[Pkg-sdl-commits] [libsdl2] 01/13: New upstream version 2.0.6+dfsg1

Manuel A. Fernandez Montecelo mafm at moszumanska.debian.org
Tue Sep 26 22:40:13 UTC 2017


This is an automated email from the git hooks/post-receive script.

mafm pushed a commit to annotated tag debian/2.0.6+dfsg1-1
in repository libsdl2.

commit 69067b1940ab7479d22e489fea6d63e77cd3b772
Author: Manuel A. Fernandez Montecelo <mafm at debian.org>
Date:   Tue Sep 26 23:19:52 2017 +0200

    New upstream version 2.0.6+dfsg1
---
 BUGS.txt                                           |     4 +-
 CMakeLists.txt                                     |   278 +-
 COPYING.txt                                        |     2 +-
 INSTALL.txt                                        |     6 +-
 Makefile.in                                        |    25 +-
 Makefile.pandora                                   |     4 +-
 README-SDL.txt                                     |     2 +-
 README.txt                                         |     2 +-
 SDL2.spec                                          |     2 +-
 SDL2Config.cmake                                   |     1 +
 WhatsNew.txt                                       |    59 +
 acinclude/libtool.m4                               |     5 +-
 autogen.sh                                         |     4 +-
 build-scripts/androidbuildlibs.sh                  |    74 +
 build-scripts/checker-buildbot.sh                  |    24 +-
 build-scripts/config.guess                         |   514 +-
 build-scripts/config.sub                           |   177 +-
 build-scripts/config.sub.patch                     |    72 +
 build-scripts/emscripten-buildbot.sh               |     8 +-
 build-scripts/iosbuild.sh                          |   413 +-
 build-scripts/nacl-buildbot.sh                     |     6 +-
 build-scripts/update-copyright.sh                  |     5 +-
 build-scripts/windows-buildbot-zipper.bat          |    13 +-
 build-scripts/winrtbuild.ps1                       |    12 +-
 cmake/sdlchecks.cmake                              |   109 +-
 configure                                          |  1027 +-
 configure.in                                       |   640 +-
 docs/README-android.md                             |    25 +-
 docs/README-emscripten.md                          |     4 +-
 docs/README-hg.md                                  |     5 +-
 docs/README-ios.md                                 |    27 +-
 docs/README-linux.md                               |     8 +-
 docs/README-macosx.md                              |     3 +
 docs/README-porting.md                             |     3 +-
 docs/README-raspberrypi.md                         |     8 +-
 docs/README-windows.md                             |    86 +-
 docs/README-winrt.md                               |    73 +-
 docs/README.md                                     |     2 +-
 include/SDL.h                                      |    11 +-
 include/SDL_assert.h                               |    20 +-
 include/SDL_atomic.h                               |    22 +-
 include/SDL_audio.h                                |    38 +-
 include/SDL_bits.h                                 |    25 +-
 include/SDL_blendmode.h                            |    67 +-
 include/SDL_clipboard.h                            |     8 +-
 include/SDL_config.h                               |    12 +-
 include/SDL_config.h.cmake                         |   114 +-
 include/SDL_config.h.in                            |   109 +-
 include/SDL_config_android.h                       |    32 +-
 include/SDL_config_iphoneos.h                      |    29 +-
 include/SDL_config_macosx.h                        |    31 +-
 include/SDL_config_minimal.h                       |     9 +-
 include/SDL_config_pandora.h                       |    35 +-
 include/SDL_config_psp.h                           |    22 +-
 include/SDL_config_windows.h                       |    29 +-
 include/SDL_config_winrt.h                         |    16 +-
 include/SDL_config_wiz.h                           |    35 +-
 include/SDL_copying.h                              |     2 +-
 include/SDL_cpuinfo.h                              |    23 +-
 include/SDL_egl.h                                  |     4 +-
 include/SDL_endian.h                               |    29 +-
 include/SDL_error.h                                |     8 +-
 include/SDL_events.h                               |    62 +-
 include/SDL_filesystem.h                           |     8 +-
 include/SDL_gamecontroller.h                       |    65 +-
 include/SDL_gesture.h                              |     8 +-
 include/SDL_haptic.h                               |    44 +-
 include/SDL_hints.h                                |   194 +-
 include/SDL_joystick.h                             |   115 +-
 include/SDL_keyboard.h                             |     8 +-
 include/SDL_keycode.h                              |    18 +-
 include/SDL_loadso.h                               |     8 +-
 include/SDL_log.h                                  |    10 +-
 include/SDL_main.h                                 |    10 +-
 include/SDL_messagebox.h                           |     8 +-
 include/SDL_mouse.h                                |    10 +-
 include/SDL_mutex.h                                |     8 +-
 include/SDL_name.h                                 |     8 +-
 include/SDL_opengl.h                               |    15 +-
 include/SDL_opengles.h                             |     2 +-
 include/SDL_opengles2.h                            |     2 +-
 include/SDL_pixels.h                               |     8 +-
 include/SDL_platform.h                             |    38 +-
 include/SDL_power.h                                |     8 +-
 include/SDL_quit.h                                 |     8 +-
 include/SDL_rect.h                                 |     8 +-
 include/SDL_render.h                               |    17 +-
 include/SDL_revision.h                             |     4 +-
 include/SDL_rwops.h                                |    43 +-
 include/SDL_scancode.h                             |    22 +-
 include/SDL_shape.h                                |    17 +-
 include/SDL_stdinc.h                               |    32 +-
 include/SDL_surface.h                              |    20 +-
 include/SDL_system.h                               |    18 +-
 include/SDL_syswm.h                                |    31 +-
 include/SDL_test.h                                 |     8 +-
 include/SDL_test_assert.h                          |    14 +-
 include/SDL_test_common.h                          |     8 +-
 include/SDL_test_compare.h                         |     8 +-
 include/SDL_test_crc32.h                           |     8 +-
 include/SDL_test_font.h                            |    17 +-
 include/SDL_test_fuzzer.h                          |    36 +-
 include/SDL_test_harness.h                         |    19 +-
 include/SDL_test_images.h                          |    30 +-
 include/SDL_test_log.h                             |     8 +-
 include/SDL_test_md5.h                             |     8 +-
 include/SDL_test_random.h                          |     8 +-
 include/SDL_thread.h                               |    36 +-
 include/SDL_timer.h                                |     8 +-
 include/SDL_touch.h                                |     8 +-
 include/SDL_types.h                                |     2 +-
 include/SDL_version.h                              |    10 +-
 include/SDL_video.h                                |    59 +-
 include/SDL_vulkan.h                               |   257 +
 include/begin_code.h                               |    25 +-
 include/close_code.h                               |     4 +-
 src/SDL.c                                          |    11 +-
 src/SDL_assert.c                                   |    75 +-
 src/SDL_assert_c.h                                 |     2 +-
 src/SDL_dataqueue.c                                |   314 +
 src/SDL_dataqueue.h                                |    54 +
 src/SDL_error.c                                    |   139 +-
 src/SDL_error_c.h                                  |     8 +-
 src/SDL_hints.c                                    |     4 +-
 src/SDL_internal.h                                 |    22 +-
 src/SDL_log.c                                      |    13 +-
 src/atomic/SDL_atomic.c                            |   101 +-
 src/atomic/SDL_spinlock.c                          |    19 +-
 src/audio/SDL_audio.c                              |   632 +-
 src/audio/SDL_audio_c.h                            |   107 +-
 src/audio/SDL_audiocvt.c                           |  2101 ++-
 src/audio/SDL_audiodev.c                           |     7 +-
 src/audio/SDL_audiodev_c.h                         |     2 +-
 src/audio/SDL_audiotypecvt.c                       | 16149 +------------------
 src/audio/SDL_mixer.c                              |     2 +-
 src/audio/SDL_sysaudio.h                           |    86 +-
 src/audio/SDL_wave.c                               |    72 +-
 src/audio/SDL_wave.h                               |    12 +-
 src/audio/alsa/SDL_alsa_audio.c                    |   143 +-
 src/audio/alsa/SDL_alsa_audio.h                    |    11 +-
 src/audio/android/SDL_androidaudio.c               |     6 +-
 src/audio/android/SDL_androidaudio.h               |    11 +-
 src/audio/arts/SDL_artsaudio.c                     |     2 +-
 src/audio/arts/SDL_artsaudio.h                     |    11 +-
 src/audio/coreaudio/SDL_coreaudio.h                |    11 +-
 src/audio/coreaudio/SDL_coreaudio.m                |    94 +-
 src/audio/directsound/SDL_directsound.c            |     7 +-
 src/audio/directsound/SDL_directsound.h            |     8 +-
 src/audio/disk/SDL_diskaudio.c                     |    14 +-
 src/audio/disk/SDL_diskaudio.h                     |     8 +-
 src/audio/dsp/SDL_dspaudio.c                       |     2 +-
 src/audio/dsp/SDL_dspaudio.h                       |     8 +-
 src/audio/dummy/SDL_dummyaudio.c                   |     2 +-
 src/audio/dummy/SDL_dummyaudio.h                   |     8 +-
 src/audio/emscripten/SDL_emscriptenaudio.c         |   214 +-
 src/audio/emscripten/SDL_emscriptenaudio.h         |    16 +-
 src/audio/esd/SDL_esdaudio.c                       |     2 +-
 src/audio/esd/SDL_esdaudio.h                       |     9 +-
 src/audio/fusionsound/SDL_fsaudio.c                |     2 +-
 src/audio/fusionsound/SDL_fsaudio.h                |     9 +-
 src/audio/haiku/SDL_haikuaudio.cc                  |    48 +-
 src/audio/haiku/SDL_haikuaudio.h                   |     8 +-
 src/audio/jack/SDL_jackaudio.c                     |   429 +
 .../SDL_haikuaudio.h => jack/SDL_jackaudio.h}      |    18 +-
 src/audio/nacl/SDL_naclaudio.c                     |    58 +-
 src/audio/nacl/SDL_naclaudio.h                     |    10 +-
 src/audio/nas/SDL_nasaudio.c                       |     4 +-
 src/audio/nas/SDL_nasaudio.h                       |     8 +-
 .../SDL_bsdaudio.c => netbsd/SDL_netbsdaudio.c}    |    66 +-
 .../SDL_bsdaudio.h => netbsd/SDL_netbsdaudio.h}    |    13 +-
 src/audio/paudio/SDL_paudio.c                      |    43 +-
 src/audio/paudio/SDL_paudio.h                      |    11 +-
 src/audio/psp/SDL_pspaudio.c                       |     3 +-
 src/audio/psp/SDL_pspaudio.h                       |    12 +-
 src/audio/pulseaudio/SDL_pulseaudio.c              |     3 +-
 src/audio/pulseaudio/SDL_pulseaudio.h              |     8 +-
 src/audio/qsa/SDL_qsa_audio.c                      |   161 +-
 src/audio/qsa/SDL_qsa_audio.h                      |     2 +-
 src/audio/sdlgenaudiocvt.pl                        |   761 -
 src/audio/sndio/SDL_sndioaudio.c                   |    75 +-
 src/audio/sndio/SDL_sndioaudio.h                   |    12 +-
 src/audio/sun/SDL_sunaudio.c                       |    18 +-
 src/audio/sun/SDL_sunaudio.h                       |     8 +-
 src/audio/wasapi/SDL_wasapi.c                      |   964 ++
 .../SDL_pulseaudio.h => wasapi/SDL_wasapi.h}       |    34 +-
 src/audio/winmm/SDL_winmm.c                        |    36 +-
 src/audio/winmm/SDL_winmm.h                        |     8 +-
 src/audio/xaudio2/SDL_xaudio2.c                    |    12 +-
 src/audio/xaudio2/SDL_xaudio2.h                    |     8 +-
 src/audio/xaudio2/SDL_xaudio2_winrthelpers.cpp     |     2 +-
 src/audio/xaudio2/SDL_xaudio2_winrthelpers.h       |     2 +-
 src/core/android/SDL_android.c                     |   652 +-
 src/core/android/SDL_android.h                     |    18 +-
 src/core/linux/SDL_dbus.c                          |   225 +-
 src/core/linux/SDL_dbus.h                          |    23 +-
 src/core/linux/SDL_evdev.c                         |   311 +-
 src/core/linux/SDL_evdev.h                         |     8 +-
 src/core/linux/SDL_evdev_kbd.c                     |   677 +
 .../linux/SDL_evdev_kbd.h}                         |    13 +-
 src/core/linux/SDL_evdev_kbd_default_accents.h     |   284 +
 src/core/linux/SDL_evdev_kbd_default_keymap.h      |  4763 ++++++
 src/core/linux/SDL_fcitx.c                         |   262 +-
 src/core/linux/SDL_fcitx.h                         |    10 +-
 src/core/linux/SDL_ibus.c                          |   163 +-
 src/core/linux/SDL_ibus.h                          |    10 +-
 src/core/linux/SDL_ime.c                           |    20 +-
 src/core/linux/SDL_ime.h                           |    18 +-
 src/core/linux/SDL_udev.c                          |    38 +-
 src/core/linux/SDL_udev.h                          |    10 +-
 src/core/unix/SDL_poll.c                           |    88 +
 .../SDL_winrtmessagebox.h => core/unix/SDL_poll.h} |    13 +-
 src/core/windows/SDL_directx.h                     |     8 +-
 src/core/windows/SDL_windows.c                     |    20 +-
 src/core/windows/SDL_windows.h                     |     9 +-
 src/core/windows/SDL_xinput.c                      |     2 +-
 src/core/windows/SDL_xinput.h                      |    13 +-
 src/core/winrt/SDL_winrtapp_common.cpp             |     2 +-
 src/core/winrt/SDL_winrtapp_common.h               |     8 +-
 src/core/winrt/SDL_winrtapp_direct3d.cpp           |     8 +-
 src/core/winrt/SDL_winrtapp_direct3d.h             |     2 +-
 src/core/winrt/SDL_winrtapp_xaml.cpp               |     2 +-
 src/core/winrt/SDL_winrtapp_xaml.h                 |     8 +-
 src/cpuinfo/SDL_cpuinfo.c                          |   350 +-
 src/dynapi/SDL_dynapi.c                            |    68 +-
 src/dynapi/SDL_dynapi.h                            |     6 +-
 src/dynapi/SDL_dynapi_overrides.h                  |    37 +-
 src/dynapi/SDL_dynapi_procs.h                      |    39 +-
 src/dynapi/gendynapi.pl                            |     2 +-
 src/events/SDL_clipboardevents.c                   |     2 +-
 src/events/SDL_clipboardevents_c.h                 |     8 +-
 src/events/SDL_dropevents.c                        |     2 +-
 src/events/SDL_dropevents_c.h                      |     8 +-
 src/events/SDL_events.c                            |   234 +-
 src/events/SDL_events_c.h                          |     2 +-
 src/events/SDL_gesture.c                           |    40 +-
 src/events/SDL_gesture_c.h                         |    11 +-
 src/events/SDL_keyboard.c                          |    39 +-
 src/events/SDL_keyboard_c.h                        |     8 +-
 src/events/SDL_mouse.c                             |   143 +-
 src/events/SDL_mouse_c.h                           |    18 +-
 src/events/SDL_quit.c                              |     2 +-
 src/events/SDL_sysevents.h                         |     2 +-
 src/events/SDL_touch.c                             |    18 +-
 src/events/SDL_touch_c.h                           |     8 +-
 src/events/SDL_windowevents.c                      |    10 +-
 src/events/SDL_windowevents_c.h                    |     8 +-
 src/events/blank_cursor.h                          |     2 +-
 src/events/default_cursor.h                        |     2 +-
 src/events/scancodes_darwin.h                      |     2 +-
 src/events/scancodes_linux.h                       |     6 +-
 src/events/scancodes_windows.h                     |     2 +-
 src/events/scancodes_xfree86.h                     |     4 +-
 src/file/SDL_rwops.c                               |   130 +-
 src/file/cocoa/SDL_rwopsbundlesupport.h            |     2 +-
 src/file/cocoa/SDL_rwopsbundlesupport.m            |     2 +-
 src/filesystem/android/SDL_sysfilesystem.c         |     4 +-
 src/filesystem/cocoa/SDL_sysfilesystem.m           |    17 +-
 src/filesystem/dummy/SDL_sysfilesystem.c           |     2 +-
 src/filesystem/emscripten/SDL_sysfilesystem.c      |    16 +-
 src/filesystem/haiku/SDL_sysfilesystem.cc          |    33 +-
 src/filesystem/nacl/SDL_sysfilesystem.c            |     3 +-
 src/filesystem/unix/SDL_sysfilesystem.c            |    29 +-
 src/filesystem/windows/SDL_sysfilesystem.c         |    16 +-
 src/filesystem/winrt/SDL_sysfilesystem.cpp         |    20 +-
 src/haptic/SDL_haptic.c                            |     5 +-
 src/haptic/SDL_haptic_c.h                          |     2 +-
 src/haptic/SDL_syshaptic.h                         |    10 +-
 src/haptic/android/SDL_syshaptic.c                 |   358 +
 src/haptic/android/SDL_syshaptic_c.h               |    12 +
 src/haptic/darwin/SDL_syshaptic.c                  |     4 +-
 src/haptic/darwin/SDL_syshaptic_c.h                |     2 +-
 src/haptic/dummy/SDL_syshaptic.c                   |     2 +-
 src/haptic/linux/SDL_syshaptic.c                   |     8 +-
 src/haptic/windows/SDL_dinputhaptic.c              |    42 +-
 src/haptic/windows/SDL_dinputhaptic_c.h            |     2 +-
 src/haptic/windows/SDL_windowshaptic.c             |     4 +-
 src/haptic/windows/SDL_windowshaptic_c.h           |     8 +-
 src/haptic/windows/SDL_xinputhaptic.c              |     7 +-
 src/haptic/windows/SDL_xinputhaptic_c.h            |     2 +-
 src/joystick/SDL_gamecontroller.c                  |  1129 +-
 src/joystick/SDL_gamecontrollerdb.h                |   162 +-
 src/joystick/SDL_joystick.c                        |   495 +-
 src/joystick/SDL_joystick_c.h                      |    16 +-
 src/joystick/SDL_sysjoystick.h                     |    28 +-
 src/joystick/android/SDL_sysjoystick.c             |    16 +-
 src/joystick/android/SDL_sysjoystick_c.h           |    10 +-
 src/joystick/bsd/SDL_sysjoystick.c                 |    24 +-
 src/joystick/darwin/SDL_sysjoystick.c              |    67 +-
 src/joystick/darwin/SDL_sysjoystick_c.h            |     5 +-
 src/joystick/dummy/SDL_sysjoystick.c               |     8 +-
 src/joystick/emscripten/SDL_sysjoystick.c          |    17 +-
 src/joystick/emscripten/SDL_sysjoystick_c.h        |     2 +-
 src/joystick/haiku/SDL_haikujoystick.cc            |    30 +-
 src/joystick/iphoneos/SDL_sysjoystick.m            |    14 +-
 src/joystick/iphoneos/SDL_sysjoystick_c.h          |     2 +-
 src/joystick/linux/SDL_sysjoystick.c               |   164 +-
 src/joystick/linux/SDL_sysjoystick_c.h             |     4 +-
 src/joystick/psp/SDL_sysjoystick.c                 |     6 +-
 src/joystick/sort_controllers.py                   |     1 +
 src/joystick/windows/SDL_dinputjoystick.c          |    92 +-
 src/joystick/windows/SDL_dinputjoystick_c.h        |     2 +-
 src/joystick/windows/SDL_mmjoystick.c              |    58 +-
 src/joystick/windows/SDL_windowsjoystick.c         |    82 +-
 src/joystick/windows/SDL_windowsjoystick_c.h       |     3 +-
 src/joystick/windows/SDL_xinputjoystick.c          |   140 +-
 src/joystick/windows/SDL_xinputjoystick_c.h        |     2 +-
 src/libm/e_rem_pio2.c                              |     9 +-
 src/libm/k_rem_pio2.c                              |     9 +-
 src/libm/math_libm.h                               |     2 +-
 src/loadso/dlopen/SDL_sysloadso.c                  |     2 +-
 src/loadso/dummy/SDL_sysloadso.c                   |     2 +-
 src/loadso/haiku/SDL_sysloadso.c                   |    71 -
 src/loadso/windows/SDL_sysloadso.c                 |     2 +-
 src/main/android/SDL_android_main.c                |    80 +-
 src/main/haiku/SDL_BApp.h                          |    13 +-
 src/main/haiku/SDL_BeApp.cc                        |    25 +-
 src/main/haiku/SDL_BeApp.h                         |     4 +-
 src/main/nacl/SDL_nacl_main.c                      |     2 +-
 src/main/windows/version.rc                        |    10 +-
 src/power/SDL_power.c                              |    16 +-
 src/power/SDL_syspower.h                           |    47 +
 src/power/android/SDL_syspower.c                   |     3 +-
 src/power/emscripten/SDL_syspower.c                |     2 +-
 src/power/haiku/SDL_syspower.c                     |     4 +-
 src/power/linux/SDL_syspower.c                     |   129 +-
 src/power/macosx/SDL_syspower.c                    |     2 +-
 src/power/psp/SDL_syspower.c                       |     2 +-
 src/power/uikit/SDL_syspower.h                     |     2 +-
 src/power/uikit/SDL_syspower.m                     |     2 +-
 src/power/windows/SDL_syspower.c                   |     2 +-
 src/power/winrt/SDL_syspower.cpp                   |     2 +-
 src/render/SDL_d3dmath.c                           |   100 +-
 src/render/SDL_d3dmath.h                           |     4 +-
 src/render/SDL_render.c                            |   347 +-
 src/render/SDL_sysrender.h                         |    37 +-
 src/render/SDL_yuv_mmx.c                           |    44 +-
 .../SDL_blit_auto.h => render/SDL_yuv_mmx_c.h}     |    12 +-
 src/render/SDL_yuv_sw.c                            |    41 +-
 src/render/SDL_yuv_sw_c.h                          |     7 +-
 src/render/direct3d/SDL_render_d3d.c               |   145 +-
 src/render/direct3d11/SDL_render_d3d11.c           |   219 +-
 src/render/direct3d11/SDL_render_winrt.cpp         |     2 +-
 src/render/direct3d11/SDL_render_winrt.h           |     2 +-
 src/render/opengl/SDL_glfuncs.h                    |     5 +-
 src/render/opengl/SDL_render_gl.c                  |   127 +-
 src/render/opengl/SDL_shaders_gl.c                 |     4 +-
 src/render/opengl/SDL_shaders_gl.h                 |     4 +-
 src/render/opengles/SDL_glesfuncs.h                |     4 +-
 src/render/opengles/SDL_render_gles.c              |   136 +-
 src/render/opengles2/SDL_gles2funcs.h              |     7 +-
 src/render/opengles2/SDL_render_gles2.c            |   187 +-
 src/render/opengles2/SDL_shaders_gles2.c           |   569 +-
 src/render/opengles2/SDL_shaders_gles2.h           |    10 +-
 src/render/psp/SDL_render_psp.c                    |     6 +-
 src/render/software/SDL_blendfillrect.c            |     4 +-
 src/render/software/SDL_blendfillrect.h            |     2 +-
 src/render/software/SDL_blendline.c                |     4 +-
 src/render/software/SDL_blendline.h                |     2 +-
 src/render/software/SDL_blendpoint.c               |    10 +-
 src/render/software/SDL_blendpoint.h               |     2 +-
 src/render/software/SDL_draw.h                     |    10 +-
 src/render/software/SDL_drawline.c                 |     2 +-
 src/render/software/SDL_drawline.h                 |     2 +-
 src/render/software/SDL_drawpoint.c                |     2 +-
 src/render/software/SDL_drawpoint.h                |     2 +-
 src/render/software/SDL_render_sw.c                |   238 +-
 src/render/software/SDL_render_sw_c.h              |     2 +-
 src/render/software/SDL_rotate.c                   |   201 +-
 src/render/software/SDL_rotate.h                   |     2 +-
 src/stdlib/SDL_getenv.c                            |     6 +-
 src/stdlib/SDL_iconv.c                             |     5 +-
 src/stdlib/SDL_malloc.c                            |     6 +-
 src/stdlib/SDL_qsort.c                             |    12 +-
 src/stdlib/SDL_stdlib.c                            |    82 +-
 src/stdlib/SDL_string.c                            |   137 +-
 src/test/SDL_test_assert.c                         |     4 +-
 src/test/SDL_test_common.c                         |   322 +-
 src/test/SDL_test_compare.c                        |     4 +-
 src/test/SDL_test_crc32.c                          |     7 +-
 src/test/SDL_test_font.c                           |    54 +-
 src/test/SDL_test_fuzzer.c                         |    29 +-
 src/test/SDL_test_harness.c                        |    56 +-
 src/test/SDL_test_imageBlit.c                      |    10 +-
 src/test/SDL_test_imageBlitBlend.c                 |    14 +-
 src/test/SDL_test_imageFace.c                      |     5 +-
 src/test/SDL_test_imagePrimitives.c                |     6 +-
 src/test/SDL_test_imagePrimitivesBlend.c           |     6 +-
 src/test/SDL_test_log.c                            |    23 +-
 src/test/SDL_test_md5.c                            |     4 +-
 src/test/SDL_test_random.c                         |     4 +-
 src/thread/SDL_systhread.h                         |    10 +-
 src/thread/SDL_thread.c                            |     6 +-
 src/thread/SDL_thread_c.h                          |    12 +-
 src/thread/generic/SDL_syscond.c                   |     2 +-
 src/thread/generic/SDL_sysmutex.c                  |     2 +-
 src/thread/generic/SDL_sysmutex_c.h                |     2 +-
 src/thread/generic/SDL_syssem.c                    |     2 +-
 src/thread/generic/SDL_systhread.c                 |     2 +-
 src/thread/generic/SDL_systhread_c.h               |     2 +-
 src/thread/generic/SDL_systls.c                    |     4 +-
 src/thread/psp/SDL_syscond.c                       |     2 +-
 src/thread/psp/SDL_sysmutex.c                      |     2 +-
 src/thread/psp/SDL_sysmutex_c.h                    |     2 +-
 src/thread/psp/SDL_syssem.c                        |     4 +-
 src/thread/psp/SDL_systhread.c                     |     2 +-
 src/thread/psp/SDL_systhread_c.h                   |     2 +-
 src/thread/pthread/SDL_syscond.c                   |     4 +-
 src/thread/pthread/SDL_sysmutex.c                  |     7 +-
 src/thread/pthread/SDL_sysmutex_c.h                |     8 +-
 src/thread/pthread/SDL_syssem.c                    |     5 +-
 src/thread/pthread/SDL_systhread.c                 |     4 +-
 src/thread/pthread/SDL_systhread_c.h               |     2 +-
 src/thread/pthread/SDL_systls.c                    |     5 +-
 src/thread/stdcpp/SDL_syscond.cpp                  |     2 +-
 src/thread/stdcpp/SDL_sysmutex.cpp                 |     2 +-
 src/thread/stdcpp/SDL_sysmutex_c.h                 |     2 +-
 src/thread/stdcpp/SDL_systhread.cpp                |     4 +-
 src/thread/stdcpp/SDL_systhread_c.h                |     2 +-
 src/thread/windows/SDL_sysmutex.c                  |     2 +-
 src/thread/windows/SDL_syssem.c                    |     2 +-
 src/thread/windows/SDL_systhread.c                 |    57 +-
 src/thread/windows/SDL_systhread_c.h               |     8 +-
 src/thread/windows/SDL_systls.c                    |     4 +-
 src/timer/SDL_timer.c                              |     5 +-
 src/timer/SDL_timer_c.h                            |     2 +-
 src/timer/dummy/SDL_systimer.c                     |     2 +-
 src/timer/haiku/SDL_systimer.c                     |     4 +-
 src/timer/psp/SDL_systimer.c                       |     2 +-
 src/timer/unix/SDL_systimer.c                      |     3 +-
 src/timer/windows/SDL_systimer.c                   |     4 +-
 src/video/SDL_RLEaccel.c                           |    16 +-
 src/video/SDL_RLEaccel_c.h                         |    10 +-
 src/video/SDL_blit.c                               |    14 +-
 src/video/SDL_blit.h                               |    49 +-
 src/video/SDL_blit_0.c                             |     2 +-
 src/video/SDL_blit_1.c                             |    16 +-
 src/video/SDL_blit_A.c                             |     6 +-
 src/video/SDL_blit_N.c                             |    36 +-
 src/video/SDL_blit_auto.c                          |     2 +-
 src/video/SDL_blit_auto.h                          |     2 +-
 src/video/SDL_blit_copy.c                          |     2 +-
 src/video/SDL_blit_copy.h                          |     2 +-
 src/video/SDL_blit_slow.c                          |     2 +-
 src/video/SDL_blit_slow.h                          |     2 +-
 src/video/SDL_bmp.c                                |     5 +-
 src/video/SDL_clipboard.c                          |     2 +-
 src/video/SDL_egl.c                                |   271 +-
 src/video/SDL_egl_c.h                              |    31 +-
 src/video/SDL_fillrect.c                           |    14 +-
 src/video/SDL_pixels.c                             |    13 +-
 src/video/SDL_pixels_c.h                           |     2 +-
 src/video/SDL_rect.c                               |    10 +-
 src/video/SDL_rect_c.h                             |     2 +-
 src/video/SDL_shape.c                              |    30 +-
 src/video/SDL_shape_internals.h                    |     6 +-
 src/video/SDL_stretch.c                            |    10 +-
 src/video/SDL_surface.c                            |    70 +-
 src/video/SDL_sysvideo.h                           |    95 +-
 src/video/SDL_video.c                              |   494 +-
 src/video/SDL_vulkan_internal.h                    |    88 +
 src/video/SDL_vulkan_utils.c                       |   177 +
 src/video/android/SDL_androidclipboard.c           |     4 +-
 src/video/android/SDL_androidclipboard.h           |     8 +-
 src/video/android/SDL_androidevents.c              |    21 +-
 src/video/android/SDL_androidevents.h              |     2 +-
 src/video/android/SDL_androidgl.c                  |     9 +-
 .../SDL_androidgl.h}                               |    15 +-
 src/video/android/SDL_androidkeyboard.c            |     8 +-
 src/video/android/SDL_androidkeyboard.h            |     2 +-
 src/video/android/SDL_androidmessagebox.c          |     6 +-
 src/video/android/SDL_androidmessagebox.h          |     2 +-
 src/video/android/SDL_androidmouse.c               |    57 +-
 src/video/android/SDL_androidmouse.h               |     8 +-
 src/video/android/SDL_androidtouch.c               |    11 +-
 src/video/android/SDL_androidtouch.h               |     2 +-
 src/video/android/SDL_androidvideo.c               |    28 +-
 src/video/android/SDL_androidvideo.h               |     8 +-
 src/video/android/SDL_androidvulkan.c              |   174 +
 .../SDL_androidvulkan.h}                           |    46 +-
 src/video/android/SDL_androidwindow.c              |    24 +-
 src/video/android/SDL_androidwindow.h              |     8 +-
 src/video/cocoa/SDL_cocoaclipboard.h               |     8 +-
 src/video/cocoa/SDL_cocoaclipboard.m               |     2 +-
 src/video/cocoa/SDL_cocoaevents.h                  |     8 +-
 src/video/cocoa/SDL_cocoaevents.m                  |    38 +-
 src/video/cocoa/SDL_cocoakeyboard.h                |     8 +-
 src/video/cocoa/SDL_cocoakeyboard.m                |    25 +-
 src/video/cocoa/SDL_cocoamessagebox.h              |     2 +-
 src/video/cocoa/SDL_cocoamessagebox.m              |    23 +-
 src/video/cocoa/SDL_cocoametalview.h               |    65 +
 src/video/cocoa/SDL_cocoametalview.m               |   128 +
 src/video/cocoa/SDL_cocoamodes.h                   |     8 +-
 src/video/cocoa/SDL_cocoamodes.m                   |    73 +-
 src/video/cocoa/SDL_cocoamouse.h                   |     8 +-
 src/video/cocoa/SDL_cocoamouse.m                   |    23 +-
 src/video/cocoa/SDL_cocoamousetap.h                |     9 +-
 src/video/cocoa/SDL_cocoamousetap.m                |    48 +-
 src/video/cocoa/SDL_cocoaopengl.h                  |    10 +-
 src/video/cocoa/SDL_cocoaopengl.m                  |     5 +-
 src/video/cocoa/SDL_cocoashape.h                   |    10 +-
 src/video/cocoa/SDL_cocoashape.m                   |     4 +-
 src/video/cocoa/SDL_cocoavideo.h                   |    61 +-
 src/video/cocoa/SDL_cocoavideo.m                   |    15 +-
 .../SDL_cocoavulkan.h}                             |    49 +-
 src/video/cocoa/SDL_cocoavulkan.m                  |   209 +
 src/video/cocoa/SDL_cocoawindow.h                  |     8 +-
 src/video/cocoa/SDL_cocoawindow.m                  |   136 +-
 src/video/directfb/SDL_DirectFB_WM.c               |     2 +-
 src/video/directfb/SDL_DirectFB_WM.h               |     8 +-
 src/video/directfb/SDL_DirectFB_dyn.c              |     2 +-
 src/video/directfb/SDL_DirectFB_dyn.h              |    10 +-
 src/video/directfb/SDL_DirectFB_events.c           |     5 +-
 src/video/directfb/SDL_DirectFB_events.h           |    10 +-
 src/video/directfb/SDL_DirectFB_modes.c            |     2 +-
 src/video/directfb/SDL_DirectFB_modes.h            |     8 +-
 src/video/directfb/SDL_DirectFB_mouse.c            |    11 +-
 src/video/directfb/SDL_DirectFB_mouse.h            |     8 +-
 src/video/directfb/SDL_DirectFB_opengl.c           |    33 +-
 src/video/directfb/SDL_DirectFB_opengl.h           |    10 +-
 src/video/directfb/SDL_DirectFB_render.c           |    23 +-
 src/video/directfb/SDL_DirectFB_render.h           |     2 +-
 src/video/directfb/SDL_DirectFB_shape.c            |    13 +-
 src/video/directfb/SDL_DirectFB_shape.h            |     9 +-
 src/video/directfb/SDL_DirectFB_video.c            |    17 +-
 src/video/directfb/SDL_DirectFB_video.h            |     8 +-
 src/video/directfb/SDL_DirectFB_window.c           |    24 +-
 src/video/directfb/SDL_DirectFB_window.h           |     8 +-
 src/video/dummy/SDL_nullevents.c                   |     2 +-
 src/video/dummy/SDL_nullevents_c.h                 |     2 +-
 src/video/dummy/SDL_nullframebuffer.c              |     2 +-
 src/video/dummy/SDL_nullframebuffer_c.h            |     2 +-
 src/video/dummy/SDL_nullvideo.c                    |     3 +-
 src/video/dummy/SDL_nullvideo.h                    |     8 +-
 src/video/emscripten/SDL_emscriptenevents.c        |   106 +-
 src/video/emscripten/SDL_emscriptenevents.h        |    11 +-
 src/video/emscripten/SDL_emscriptenframebuffer.c   |     2 +-
 src/video/emscripten/SDL_emscriptenframebuffer.h   |     8 +-
 src/video/emscripten/SDL_emscriptenmouse.c         |   112 +-
 src/video/emscripten/SDL_emscriptenmouse.h         |    11 +-
 src/video/emscripten/SDL_emscriptenopengles.c      |    12 +-
 src/video/emscripten/SDL_emscriptenopengles.h      |    10 +-
 src/video/emscripten/SDL_emscriptenvideo.c         |    15 +-
 src/video/emscripten/SDL_emscriptenvideo.h         |    12 +-
 src/video/haiku/SDL_BWin.h                         |    23 +-
 src/video/haiku/SDL_bclipboard.cc                  |    14 +-
 src/video/haiku/SDL_bclipboard.h                   |     4 +-
 src/video/haiku/SDL_bevents.cc                     |     4 +-
 src/video/haiku/SDL_bevents.h                      |     4 +-
 src/video/haiku/SDL_bframebuffer.cc                |    17 +-
 src/video/haiku/SDL_bframebuffer.h                 |     4 +-
 src/video/haiku/SDL_bkeyboard.cc                   |     6 +-
 src/video/haiku/SDL_bkeyboard.h                    |     6 +-
 src/video/haiku/SDL_bmodes.cc                      |     8 +-
 src/video/haiku/SDL_bmodes.h                       |     4 +-
 src/video/haiku/SDL_bopengl.cc                     |   199 +-
 src/video/haiku/SDL_bopengl.h                      |    10 +-
 src/video/haiku/SDL_bvideo.cc                      |    11 +-
 src/video/haiku/SDL_bvideo.h                       |     4 +-
 src/video/haiku/SDL_bwindow.cc                     |    18 +-
 src/video/haiku/SDL_bwindow.h                      |     3 +-
 src/video/khronos/EGL/egl.h                        |   303 +
 .../SDL_egl.h => src/video/khronos/EGL/eglext.h    |  1172 +-
 src/video/khronos/EGL/eglplatform.h                |   132 +
 src/video/khronos/GLES2/gl2.h                      |   675 +
 src/video/khronos/GLES2/gl2ext.h                   |  3505 ++++
 src/video/khronos/GLES2/gl2platform.h              |    38 +
 src/video/khronos/KHR/khrplatform.h                |   284 +
 src/video/khronos/vulkan/vk_platform.h             |   120 +
 src/video/khronos/vulkan/vulkan.h                  |  6458 ++++++++
 src/video/kmsdrm/SDL_kmsdrmdyn.c                   |   171 +
 .../{mir/SDL_mirdyn.h => kmsdrm/SDL_kmsdrmdyn.h}   |    30 +-
 .../SDL_rpievents.c => kmsdrm/SDL_kmsdrmevents.c}  |    15 +-
 .../kmsdrm/SDL_kmsdrmevents.h}                     |    15 +-
 src/video/kmsdrm/SDL_kmsdrmmouse.c                 |   422 +
 .../SDL_nullevents.c => kmsdrm/SDL_kmsdrmmouse.h}  |    27 +-
 src/video/kmsdrm/SDL_kmsdrmopengles.c              |   139 +
 .../SDL_kmsdrmopengles.h}                          |    30 +-
 src/video/kmsdrm/SDL_kmsdrmsym.h                   |    99 +
 src/video/kmsdrm/SDL_kmsdrmvideo.c                 |   650 +
 src/video/kmsdrm/SDL_kmsdrmvideo.h                 |   121 +
 src/video/mir/SDL_mirdyn.c                         |     2 +-
 src/video/mir/SDL_mirdyn.h                         |     8 +-
 src/video/mir/SDL_mirevents.c                      |    32 +-
 src/video/mir/SDL_mirevents.h                      |    10 +-
 src/video/mir/SDL_mirframebuffer.c                 |     6 +-
 src/video/mir/SDL_mirframebuffer.h                 |     8 +-
 src/video/mir/SDL_mirmouse.c                       |    48 +-
 src/video/mir/SDL_mirmouse.h                       |     8 +-
 src/video/mir/SDL_miropengl.c                      |    26 +-
 src/video/mir/SDL_miropengl.h                      |    19 +-
 src/video/mir/SDL_mirsym.h                         |    63 +-
 src/video/mir/SDL_mirvideo.c                       |    32 +-
 src/video/mir/SDL_mirvideo.h                       |     9 +-
 src/video/mir/SDL_mirvulkan.c                      |   175 +
 .../SDL_emscriptenvideo.h => mir/SDL_mirvulkan.h}  |    46 +-
 src/video/mir/SDL_mirwindow.c                      |   216 +-
 src/video/mir/SDL_mirwindow.h                      |    10 +-
 src/video/nacl/SDL_naclevents.c                    |    46 +-
 src/video/nacl/SDL_naclevents_c.h                  |     8 +-
 src/video/nacl/SDL_naclglue.c                      |     2 +-
 src/video/nacl/SDL_naclopengles.c                  |    11 +-
 src/video/nacl/SDL_naclopengles.h                  |    10 +-
 src/video/nacl/SDL_naclvideo.c                     |     6 +-
 src/video/nacl/SDL_naclvideo.h                     |     8 +-
 src/video/nacl/SDL_naclwindow.c                    |     2 +-
 src/video/nacl/SDL_naclwindow.h                    |     8 +-
 src/video/pandora/SDL_pandora.c                    |    20 +-
 src/video/pandora/SDL_pandora.h                    |     4 +-
 src/video/pandora/SDL_pandora_events.c             |     2 +-
 src/video/pandora/SDL_pandora_events.h             |     2 +-
 src/video/psp/SDL_pspevents.c                      |     6 +-
 src/video/psp/SDL_pspevents_c.h                    |     2 +-
 src/video/psp/SDL_pspgl.c                          |    13 +-
 src/video/psp/SDL_pspgl_c.h                        |    12 +-
 src/video/psp/SDL_pspmouse.c                       |     2 +-
 src/video/psp/SDL_pspmouse_c.h                     |     2 +-
 src/video/psp/SDL_pspvideo.c                       |    12 +-
 src/video/psp/SDL_pspvideo.h                       |    10 +-
 src/video/qnx/gl.c                                 |   285 +
 src/video/qnx/keyboard.c                           |   133 +
 .../SDL_emscriptenvideo.h => qnx/sdl_qnx.h}        |    50 +-
 src/video/qnx/video.c                              |   364 +
 src/video/raspberry/SDL_rpievents.c                |     2 +-
 src/video/raspberry/SDL_rpievents_c.h              |     8 +-
 src/video/raspberry/SDL_rpimouse.c                 |     2 +-
 src/video/raspberry/SDL_rpimouse.h                 |     8 +-
 src/video/raspberry/SDL_rpiopengles.c              |    12 +-
 src/video/raspberry/SDL_rpiopengles.h              |    11 +-
 src/video/raspberry/SDL_rpivideo.c                 |    24 +-
 src/video/raspberry/SDL_rpivideo.h                 |     6 +-
 src/video/sdlgenblit.pl                            |     2 +-
 src/video/uikit/SDL_uikitappdelegate.h             |     8 +-
 src/video/uikit/SDL_uikitappdelegate.m             |    68 +-
 src/video/uikit/SDL_uikitclipboard.h               |     8 +-
 src/video/uikit/SDL_uikitclipboard.m               |     2 +-
 src/video/uikit/SDL_uikitevents.h                  |     8 +-
 src/video/uikit/SDL_uikitevents.m                  |     2 +-
 src/video/uikit/SDL_uikitmessagebox.h              |     4 +-
 src/video/uikit/SDL_uikitmessagebox.m              |     4 +-
 src/video/uikit/SDL_uikitmetalview.h               |    55 +
 src/video/uikit/SDL_uikitmetalview.m               |   147 +
 src/video/uikit/SDL_uikitmodes.h                   |     8 +-
 src/video/uikit/SDL_uikitmodes.m                   |    43 +-
 src/video/uikit/SDL_uikitopengles.h                |    12 +-
 src/video/uikit/SDL_uikitopengles.m                |     7 +-
 src/video/uikit/SDL_uikitopenglview.h              |     2 +-
 src/video/uikit/SDL_uikitopenglview.m              |     2 +-
 src/video/uikit/SDL_uikitvideo.h                   |     8 +-
 src/video/uikit/SDL_uikitvideo.m                   |    53 +-
 src/video/uikit/SDL_uikitview.h                    |     2 +-
 src/video/uikit/SDL_uikitview.m                    |    50 +-
 src/video/uikit/SDL_uikitviewcontroller.h          |     2 +-
 src/video/uikit/SDL_uikitviewcontroller.m          |    54 +-
 .../SDL_uikitvulkan.h}                             |    46 +-
 src/video/uikit/SDL_uikitvulkan.m                  |   222 +
 src/video/uikit/SDL_uikitwindow.h                  |     8 +-
 src/video/uikit/SDL_uikitwindow.m                  |    12 +-
 src/video/uikit/keyinfotable.h                     |     2 +-
 src/video/vivante/SDL_vivanteopengles.c            |     4 +-
 src/video/vivante/SDL_vivanteopengles.h            |    10 +-
 src/video/vivante/SDL_vivanteplatform.c            |     2 +-
 src/video/vivante/SDL_vivanteplatform.h            |     8 +-
 src/video/vivante/SDL_vivantevideo.c               |     6 +-
 src/video/vivante/SDL_vivantevideo.h               |     8 +-
 src/video/wayland/SDL_waylandclipboard.c           |   123 +
 .../wayland/SDL_waylandclipboard.h}                |    14 +-
 src/video/wayland/SDL_waylanddatamanager.c         |   468 +
 src/video/wayland/SDL_waylanddatamanager.h         |   103 +
 src/video/wayland/SDL_waylanddyn.c                 |     2 +-
 src/video/wayland/SDL_waylanddyn.h                 |    12 +-
 src/video/wayland/SDL_waylandevents.c              |   492 +-
 src/video/wayland/SDL_waylandevents_c.h            |    13 +-
 src/video/wayland/SDL_waylandmouse.c               |    24 +-
 src/video/wayland/SDL_waylandmouse.h               |     2 +-
 src/video/wayland/SDL_waylandopengles.c            |    12 +-
 src/video/wayland/SDL_waylandopengles.h            |    12 +-
 src/video/wayland/SDL_waylandsym.h                 |     6 +-
 src/video/wayland/SDL_waylandtouch.c               |     2 +-
 src/video/wayland/SDL_waylandtouch.h               |     8 +-
 src/video/wayland/SDL_waylandvideo.c               |    23 +-
 src/video/wayland/SDL_waylandvideo.h               |     9 +-
 src/video/wayland/SDL_waylandvulkan.c              |   175 +
 .../SDL_waylandvulkan.h}                           |    46 +-
 src/video/wayland/SDL_waylandwindow.c              |    98 +-
 src/video/wayland/SDL_waylandwindow.h              |     8 +-
 src/video/windows/SDL_msctf.h                      |     8 +-
 src/video/windows/SDL_vkeys.h                      |     2 +-
 src/video/windows/SDL_windowsclipboard.c           |     2 +-
 src/video/windows/SDL_windowsclipboard.h           |     8 +-
 src/video/windows/SDL_windowsevents.c              |   321 +-
 src/video/windows/SDL_windowsevents.h              |     8 +-
 src/video/windows/SDL_windowsframebuffer.c         |     2 +-
 src/video/windows/SDL_windowsframebuffer.h         |     2 +-
 src/video/windows/SDL_windowskeyboard.c            |    40 +-
 src/video/windows/SDL_windowskeyboard.h            |     8 +-
 src/video/windows/SDL_windowsmessagebox.c          |    30 +-
 src/video/windows/SDL_windowsmessagebox.h          |     2 +-
 src/video/windows/SDL_windowsmodes.c               |   297 +-
 src/video/windows/SDL_windowsmodes.h               |    14 +-
 src/video/windows/SDL_windowsmouse.c               |     9 +-
 src/video/windows/SDL_windowsmouse.h               |     8 +-
 src/video/windows/SDL_windowsopengl.c              |   115 +-
 src/video/windows/SDL_windowsopengl.h              |    25 +-
 src/video/windows/SDL_windowsopengles.c            |    17 +-
 src/video/windows/SDL_windowsopengles.h            |    14 +-
 src/video/windows/SDL_windowsshape.c               |     4 +-
 src/video/windows/SDL_windowsshape.h               |     8 +-
 src/video/windows/SDL_windowsvideo.c               |    25 +-
 src/video/windows/SDL_windowsvideo.h               |     8 +-
 src/video/windows/SDL_windowsvulkan.c              |   176 +
 .../SDL_windowsvulkan.h}                           |    46 +-
 src/video/windows/SDL_windowswindow.c              |   218 +-
 src/video/windows/SDL_windowswindow.h              |    10 +-
 src/video/windows/wmmsg.h                          |     2 +-
 src/video/winrt/SDL_winrtevents.cpp                |     4 +-
 src/video/winrt/SDL_winrtevents_c.h                |     4 +-
 src/video/winrt/SDL_winrtgamebar.cpp               |     2 +-
 src/video/winrt/SDL_winrtgamebar_cpp.h             |     8 +-
 src/video/winrt/SDL_winrtkeyboard.cpp              |     4 +-
 src/video/winrt/SDL_winrtmessagebox.cpp            |     2 +-
 src/video/winrt/SDL_winrtmessagebox.h              |     2 +-
 src/video/winrt/SDL_winrtmouse.cpp                 |     2 +-
 src/video/winrt/SDL_winrtmouse_c.h                 |     8 +-
 src/video/winrt/SDL_winrtopengles.cpp              |    19 +-
 src/video/winrt/SDL_winrtopengles.h                |    10 +-
 src/video/winrt/SDL_winrtpointerinput.cpp          |    11 +-
 src/video/winrt/SDL_winrtvideo.cpp                 |    10 +-
 src/video/winrt/SDL_winrtvideo_cpp.h               |     2 +-
 src/video/x11/SDL_x11clipboard.c                   |    24 +-
 src/video/x11/SDL_x11clipboard.h                   |     8 +-
 src/video/x11/SDL_x11dyn.c                         |     2 +-
 src/video/x11/SDL_x11dyn.h                         |     8 +-
 src/video/x11/SDL_x11events.c                      |   220 +-
 src/video/x11/SDL_x11events.h                      |     8 +-
 src/video/x11/SDL_x11framebuffer.c                 |     4 +-
 src/video/x11/SDL_x11framebuffer.h                 |     2 +-
 src/video/x11/SDL_x11keyboard.c                    |    87 +-
 src/video/x11/SDL_x11keyboard.h                    |     8 +-
 src/video/x11/SDL_x11messagebox.c                  |    36 +-
 src/video/x11/SDL_x11messagebox.h                  |     2 +-
 src/video/x11/SDL_x11modes.c                       |    51 +-
 src/video/x11/SDL_x11modes.h                       |     8 +-
 src/video/x11/SDL_x11mouse.c                       |    22 +-
 src/video/x11/SDL_x11mouse.h                       |     8 +-
 src/video/x11/SDL_x11opengl.c                      |   182 +-
 src/video/x11/SDL_x11opengl.h                      |    23 +-
 src/video/x11/SDL_x11opengles.c                    |     4 +-
 src/video/x11/SDL_x11opengles.h                    |    13 +-
 src/video/x11/SDL_x11shape.c                       |     8 +-
 src/video/x11/SDL_x11shape.h                       |     9 +-
 src/video/x11/SDL_x11sym.h                         |     5 +-
 src/video/x11/SDL_x11touch.c                       |     9 +-
 src/video/x11/SDL_x11touch.h                       |     9 +-
 src/video/x11/SDL_x11video.c                       |    91 +-
 src/video/x11/SDL_x11video.h                       |    22 +-
 src/video/x11/SDL_x11vulkan.c                      |   241 +
 .../SDL_nasaudio.h => video/x11/SDL_x11vulkan.h}   |    52 +-
 src/video/x11/SDL_x11window.c                      |    59 +-
 src/video/x11/SDL_x11window.h                      |     8 +-
 src/video/x11/SDL_x11xinput2.c                     |     2 +-
 src/video/x11/SDL_x11xinput2.h                     |     8 +-
 src/video/x11/edid-parse.c                         |    92 +-
 src/video/x11/edid.h                               |     4 +-
 test/Makefile.in                                   |    23 +-
 test/axis.bmp                                      |   Bin 3746 -> 10138 bytes
 test/checkkeys.c                                   |    16 +-
 test/controllermap.c                               |   748 +-
 test/loopwave.c                                    |    90 +-
 test/loopwavequeue.c                               |     5 +-
 test/nacl/common.js                                |     7 +-
 test/testatomic.c                                  |    17 +-
 test/testaudiocapture.c                            |     2 +-
 test/testaudiohotplug.c                            |     2 +-
 test/testaudioinfo.c                               |     2 +-
 test/testautomation.c                              |     2 +-
 test/testautomation_audio.c                        |     2 +-
 test/testautomation_clipboard.c                    |     2 +-
 test/testautomation_events.c                       |     2 +-
 test/testautomation_keyboard.c                     |     2 +-
 test/testautomation_mouse.c                        |    16 +-
 test/testautomation_platform.c                     |    36 +-
 test/testautomation_rwops.c                        |    54 +-
 test/testautomation_sdltest.c                      |    72 +-
 test/testautomation_stdlib.c                       |    24 +-
 test/testautomation_timer.c                        |     2 +-
 test/testbounds.c                                  |     2 +-
 test/testcustomcursor.c                            |     2 +-
 test/testdisplayinfo.c                             |     2 +-
 test/testdraw2.c                                   |     2 +-
 test/testdrawchessboard.c                          |    22 +-
 test/testdropfile.c                                |     2 +-
 test/testerror.c                                   |     3 +-
 test/testfile.c                                    |     2 +-
 test/testfilesystem.c                              |    11 +-
 test/testgamecontroller.c                          |    44 +-
 test/testgesture.c                                 |     3 +-
 test/testgl2.c                                     |     4 +-
 test/testgles.c                                    |     2 +-
 test/testgles2.c                                   |     7 +-
 test/testhittesting.c                              |     2 +-
 test/testhotplug.c                                 |     2 +-
 test/testiconv.c                                   |     2 +-
 test/testime.c                                     |    62 +-
 test/testintersections.c                           |     2 +-
 test/testjoystick.c                                |    41 +-
 test/testkeys.c                                    |     2 +-
 test/testloadso.c                                  |     2 +-
 test/testlock.c                                    |     2 +-
 test/testmessage.c                                 |     8 +-
 test/testmultiaudio.c                              |     2 +-
 test/testnative.c                                  |     2 +-
 test/testnative.h                                  |     2 +-
 test/testnativew32.c                               |     2 +-
 test/testnativex11.c                               |     2 +-
 test/testoverlay2.c                                |   174 +-
 test/testplatform.c                                |   219 +-
 test/testpower.c                                   |     2 +-
 test/testqsort.c                                   |     2 +-
 test/testrelative.c                                |     2 +-
 test/testrendercopyex.c                            |     2 +-
 test/testrendertarget.c                            |     2 +-
 test/testresample.c                                |    16 +-
 test/testrumble.c                                  |     9 +-
 test/testscale.c                                   |     2 +-
 test/testsem.c                                     |     2 +-
 test/testshader.c                                  |     2 +-
 test/testshape.c                                   |    17 +-
 test/testsprite2.c                                 |    12 +-
 test/testspriteminimal.c                           |     2 +-
 test/teststreaming.c                               |     2 +-
 test/testthread.c                                  |     2 +-
 test/testtimer.c                                   |     2 +-
 test/testver.c                                     |     2 +-
 test/testviewport.c                                |     2 +-
 test/testvulkan.c                                  |  1201 ++
 test/testwm2.c                                     |     2 +-
 test/torturethread.c                               |     2 +-
 837 files changed, 45569 insertions(+), 28192 deletions(-)

diff --git a/BUGS.txt b/BUGS.txt
index aa52e61..57d953f 100644
--- a/BUGS.txt
+++ b/BUGS.txt
@@ -7,9 +7,9 @@ You may report bugs there, and search to see if a given issue has already
  been reported, discussed, and maybe even fixed.
 
 
-You may also find help on the SDL mailing list. Subscription information:
+You may also find help at the SDL forums/mailing list:
 
-    http://lists.libsdl.org/listinfo.cgi/sdl-libsdl.org
+    https://discourse.libsdl.org/
 
 Bug reports are welcome here, but we really appreciate if you use Bugzilla, as
  bugs discussed on the mailing list may be forgotten or missed.
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 54a23f0..8a5e592 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -2,7 +2,7 @@ if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})
   message(FATAL_ERROR "Prevented in-tree built. Please create a build directory outside of the SDL source code and call cmake from there")
 endif()
 
-cmake_minimum_required(VERSION 2.8.5)
+cmake_minimum_required(VERSION 2.8.11)
 project(SDL2 C)
 
 # !!! FIXME: this should probably do "MACOSX_RPATH ON" as a target property
@@ -20,6 +20,7 @@ include(CheckLibraryExists)
 include(CheckIncludeFiles)
 include(CheckIncludeFile)
 include(CheckSymbolExists)
+include(CheckCSourceCompiles)
 include(CheckCSourceRuns)
 include(CheckCCompilerFlag)
 include(CheckTypeSize)
@@ -41,11 +42,17 @@ include(${SDL2_SOURCE_DIR}/cmake/sdlchecks.cmake)
 # set SDL_BINARY_AGE and SDL_INTERFACE_AGE to 0.
 set(SDL_MAJOR_VERSION 2)
 set(SDL_MINOR_VERSION 0)
-set(SDL_MICRO_VERSION 5)
-set(SDL_INTERFACE_AGE 1)
-set(SDL_BINARY_AGE 5)
+set(SDL_MICRO_VERSION 6)
+set(SDL_INTERFACE_AGE 0)
+set(SDL_BINARY_AGE 6)
 set(SDL_VERSION "${SDL_MAJOR_VERSION}.${SDL_MINOR_VERSION}.${SDL_MICRO_VERSION}")
 
+# Set defaults preventing destination file conflicts
+set(CMAKE_DEBUG_POSTFIX "d"
+    CACHE STRING "Name suffix for debug builds")
+
+mark_as_advanced(CMAKE_IMPORT_LIBRARY_SUFFIX CMAKE_DEBUG_POSTFIX)
+
 # Calculate a libtool-like version number
 math(EXPR LT_CURRENT "${SDL_MICRO_VERSION} - ${SDL_INTERFACE_AGE}")
 math(EXPR LT_AGE "${SDL_BINARY_AGE} - ${SDL_INTERFACE_AGE}")
@@ -137,7 +144,9 @@ endif()
 
 # Default option knobs
 if(APPLE OR ARCH_64)
-  set(OPT_DEF_SSEMATH ON)
+  if(NOT "${CMAKE_OSX_ARCHITECTURES}" MATCHES "arm")
+    set(OPT_DEF_SSEMATH ON)
+  endif()
 endif()
 if(UNIX OR MINGW OR MSYS)
   set(OPT_DEF_LIBC ON)
@@ -157,6 +166,10 @@ else()
   set(OPT_DEF_ASM FALSE)
 endif()
 
+if(USE_GCC OR USE_CLANG)
+  set(OPT_DEF_GCC_ATOMICS ON)
+endif()
+
 # Default flags, if not set otherwise
 if("$ENV{CFLAGS}" STREQUAL "")
   if(CMAKE_BUILD_TYPE STREQUAL "")
@@ -220,6 +233,11 @@ endif()
 add_definitions(-DUSING_GENERATED_CONFIG_H)
 # General includes
 include_directories(${SDL2_BINARY_DIR}/include ${SDL2_SOURCE_DIR}/include)
+if(USE_GCC OR USE_CLANG)
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -idirafter ${SDL2_SOURCE_DIR}/src/video/khronos")
+else()
+  include_directories(${SDL2_SOURCE_DIR}/src/video/khronos)
+endif()
 
 # All these ENABLED_BY_DEFAULT vars will default to ON if not specified, so
 #  you only need to have a platform override them if they are disabling.
@@ -255,20 +273,19 @@ endforeach()
 option_string(ASSERTIONS "Enable internal sanity checks (auto/disabled/release/enabled/paranoid)" "auto")
 #set_option(DEPENDENCY_TRACKING "Use gcc -MMD -MT dependency tracking" ON)
 set_option(LIBC                "Use the system C library" ${OPT_DEF_LIBC})
-set_option(GCC_ATOMICS         "Use gcc builtin atomics" ${USE_GCC})
+set_option(GCC_ATOMICS         "Use gcc builtin atomics" ${OPT_DEF_GCC_ATOMICS})
 set_option(ASSEMBLY            "Enable assembly routines" ${OPT_DEF_ASM})
 set_option(SSEMATH             "Allow GCC to use SSE floating point math" ${OPT_DEF_SSEMATH})
 set_option(MMX                 "Use MMX assembly routines" ${OPT_DEF_ASM})
 set_option(3DNOW               "Use 3Dnow! MMX assembly routines" ${OPT_DEF_ASM})
 set_option(SSE                 "Use SSE assembly routines" ${OPT_DEF_ASM})
 set_option(SSE2                "Use SSE2 assembly routines" ${OPT_DEF_SSEMATH})
+set_option(SSE3                "Use SSE3 assembly routines" ${OPT_DEF_SSEMATH})
 set_option(ALTIVEC             "Use Altivec assembly routines" ${OPT_DEF_ASM})
 set_option(DISKAUDIO           "Support the disk writer audio driver" ON)
 set_option(DUMMYAUDIO          "Support the dummy audio driver" ON)
 set_option(VIDEO_DIRECTFB      "Use DirectFB video driver" OFF)
 dep_option(DIRECTFB_SHARED     "Dynamically load directfb support" ON "VIDEO_DIRECTFB" OFF)
-set_option(FUSIONSOUND         "Use FusionSound audio driver" OFF)
-dep_option(FUSIONSOUND_SHARED  "Dynamically load fusionsound audio support" ON "FUSIONSOUND" OFF)
 set_option(VIDEO_DUMMY         "Use dummy video driver" ON)
 set_option(VIDEO_OPENGL        "Include OpenGL support" ON)
 set_option(VIDEO_OPENGLES      "Include OpenGL ES support" ON)
@@ -278,6 +295,8 @@ set_option(SDL_DLOPEN          "Use dlopen for shared object loading" ${SDL_DLOP
 set_option(OSS                 "Support the OSS audio API" ${UNIX_SYS})
 set_option(ALSA                "Support the ALSA audio API" ${UNIX_SYS})
 dep_option(ALSA_SHARED         "Dynamically load ALSA audio support" ON "ALSA" OFF)
+set_option(JACK                "Support the JACK audio API" ${UNIX_SYS})
+dep_option(JACK_SHARED         "Dynamically load JACK audio support" ON "JACK" OFF)
 set_option(ESD                 "Support the Enlightened Sound Daemon" ${UNIX_SYS})
 dep_option(ESD_SHARED          "Dynamically load ESD audio support" ON "ESD" OFF)
 set_option(PULSEAUDIO          "Use PulseAudio" ${UNIX_SYS})
@@ -287,6 +306,10 @@ dep_option(ARTS_SHARED         "Dynamically load aRts audio support" ON "ARTS" O
 set_option(NAS                 "Support the NAS audio API" ${UNIX_SYS})
 set_option(NAS_SHARED          "Dynamically load NAS audio API" ${UNIX_SYS})
 set_option(SNDIO               "Support the sndio audio API" ${UNIX_SYS})
+set_option(FUSIONSOUND         "Use FusionSound audio driver" OFF)
+dep_option(FUSIONSOUND_SHARED  "Dynamically load fusionsound audio support" ON "FUSIONSOUND" OFF)
+set_option(LIBSAMPLERATE       "Use libsamplerate for audio rate conversion" ${UNIX_SYS})
+dep_option(LIBSAMPLERATE_SHARED "Dynamically load libsamplerate" ON "LIBSAMPLERATE" OFF)
 set_option(RPATH               "Use an rpath when linking SDL" ${UNIX_SYS})
 set_option(CLOCK_GETTIME       "Use clock_gettime() instead of gettimeofday()" OFF)
 set_option(INPUT_TSLIB         "Use the Touchscreen library for input" ${UNIX_SYS})
@@ -307,6 +330,9 @@ set_option(VIDEO_COCOA         "Use Cocoa video driver" ${APPLE})
 set_option(DIRECTX             "Use DirectX for Windows audio/video" ${WINDOWS})
 set_option(RENDER_D3D          "Enable the Direct3D render driver" ${WINDOWS})
 set_option(VIDEO_VIVANTE       "Use Vivante EGL video driver" ${UNIX_SYS})
+dep_option(VIDEO_VULKAN        "Enable Vulkan support" ON "ANDROID OR APPLE OR LINUX OR WINDOWS" OFF)
+set_option(VIDEO_KMSDRM        "Use KMS DRM video driver" ${UNIX_SYS})
+dep_option(KMSDRM_SHARED       "Dynamically load KMS DRM support" ON "VIDEO_KMSDRM" OFF)
 
 # TODO: We should (should we?) respect cmake's ${BUILD_SHARED_LIBS} flag here
 # The options below are for compatibility to configure's default behaviour.
@@ -414,11 +440,15 @@ if(USE_GCC OR USE_CLANG)
     list(APPEND EXTRA_CFLAGS "-Wshadow")
   endif()
 
-  set(CMAKE_REQUIRED_FLAGS "-Wl,--no-undefined")
-  check_c_compiler_flag("" HAVE_NO_UNDEFINED)
-  set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
-  if(HAVE_NO_UNDEFINED)
-    list(APPEND EXTRA_LDFLAGS "-Wl,--no-undefined")
+  if(APPLE)
+    list(APPEND EXTRA_LDFLAGS "-Wl,-undefined,error")
+  else()
+    set(CMAKE_REQUIRED_FLAGS "-Wl,--no-undefined")
+    check_c_compiler_flag("" HAVE_NO_UNDEFINED)
+    set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
+    if(HAVE_NO_UNDEFINED)
+      list(APPEND EXTRA_LDFLAGS "-Wl,--no-undefined")
+    endif()
   endif()
 endif()
 
@@ -514,10 +544,36 @@ if(ASSEMBLY)
       set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
     endif()
 
-    if(SSEMATH)
-      if(SSE OR SSE2)
+    if(SSE3)
+      set(CMAKE_REQUIRED_FLAGS "-msse3")
+      check_c_source_compiles("
+          #ifdef __MINGW32__
+          #include <_mingw.h>
+          #ifdef __MINGW64_VERSION_MAJOR
+          #include <intrin.h>
+          #else
+          #include <pmmintrin.h>
+          #endif
+          #else
+          #include <pmmintrin.h>
+          #endif
+          #ifndef __SSE3__
+          #error Assembler CPP flag not enabled
+          #endif
+          int main(int argc, char **argv) { }" HAVE_SSE3)
+      if(HAVE_SSE3)
+        list(APPEND EXTRA_CFLAGS "-msse3")
+      endif()
+      set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
+    endif()
+
+    if(NOT SSEMATH)
+      if(SSE OR SSE2 OR SSE3)
         if(USE_GCC)
-          list(APPEND EXTRA_CFLAGS "-mfpmath=387")
+          check_c_compiler_flag(-mfpmath=387 HAVE_FP_387)
+          if(HAVE_FP_387)
+            list(APPEND EXTRA_CFLAGS "-mfpmath=387")
+          endif()
         endif()
         set(HAVE_SSEMATH TRUE)
       endif()
@@ -555,12 +611,13 @@ if(ASSEMBLY)
     endif()
     set(HAVE_SSE TRUE)
     set(HAVE_SSE2 TRUE)
+    set(HAVE_SSE3 TRUE)
     set(SDL_ASSEMBLY_ROUTINES 1)
   endif()
 # TODO:
 #else()
 #  if(USE_GCC OR USE_CLANG)
-#    list(APPEND EXTRA_CFLAGS "-mno-sse" "-mno-sse2" "-mno-mmx")
+#    list(APPEND EXTRA_CFLAGS "-mno-sse" "-mno-sse2" "-mno-sse3" "-mno-mmx")
 #  endif()
 endif()
 
@@ -569,7 +626,7 @@ endif()
 if(LIBC)
   if(WINDOWS AND NOT MINGW)
     set(HAVE_LIBC TRUE)
-    foreach(_HEADER stdio.h string.h ctype.h math.h)
+    foreach(_HEADER stdio.h string.h wchar.h ctype.h math.h limits.h)
       string(TOUPPER "HAVE_${_HEADER}" _UPPER)
       string(REPLACE "." "_" _HAVE_H ${_UPPER})
       set(${_HAVE_H} 1)
@@ -577,6 +634,7 @@ if(LIBC)
     set(HAVE_SIGNAL_H 1)
     foreach(_FN
             malloc calloc realloc free qsort abs memset memcpy memmove memcmp
+            wcslen wcscmp
             strlen _strrev _strupr _strlwr strchr strrchr strstr itoa _ltoa
             _ultoa strtol strtoul strtoll strtod atoi atof strcmp strncmp
             _stricmp _strnicmp sscanf atan atan2 acos asin ceil copysign cos
@@ -594,8 +652,8 @@ if(LIBC)
     set(HAVE_LIBC TRUE)
     check_include_file(sys/types.h HAVE_SYS_TYPES_H)
     foreach(_HEADER
-            stdio.h stdlib.h stddef.h stdarg.h malloc.h memory.h string.h
-            strings.h inttypes.h stdint.h ctype.h math.h iconv.h signal.h)
+            stdio.h stdlib.h stddef.h stdarg.h malloc.h memory.h string.h limits.h
+            strings.h wchar.h inttypes.h stdint.h ctype.h math.h iconv.h signal.h)
       string(TOUPPER "HAVE_${_HEADER}" _UPPER)
       string(REPLACE "." "_" _HAVE_H ${_UPPER})
       check_include_file("${_HEADER}" ${_HAVE_H})
@@ -614,8 +672,8 @@ if(LIBC)
             strdup _strrev _strupr _strlwr strchr strrchr strstr itoa _ltoa
             _uitoa _ultoa strtol strtoul _i64toa _ui64toa strtoll strtoull
             atoi atof strcmp strncmp _stricmp strcasecmp _strnicmp strncasecmp
-            vsscanf vsnprintf fseeko fseeko64 sigaction setjmp
-            nanosleep sysconf sysctlbyname
+            vsscanf vsnprintf fopen64 fseeko fseeko64 sigaction setjmp
+            nanosleep sysconf sysctlbyname getauxval poll
             )
       string(TOUPPER ${_FN} _UPPER)
       set(_HAVEVAR "HAVE_${_UPPER}")
@@ -725,8 +783,19 @@ endif()
 if(ANDROID)
   file(GLOB ANDROID_CORE_SOURCES ${SDL2_SOURCE_DIR}/src/core/android/*.c)
   set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_CORE_SOURCES})
+
+  # SDL_spinlock.c Needs to be compiled in ARM mode.
+  # There seems to be no better way currently to set the ARM mode.
+  # see: https://issuetracker.google.com/issues/62264618
+  # Another option would be to set ARM mode to all compiled files
+  check_c_compiler_flag(-marm HAVE_ARM_MODE)
+  if(HAVE_ARM_MODE)
+    set_source_files_properties(${SDL2_SOURCE_DIR}/src/atomic/SDL_spinlock.c PROPERTIES COMPILE_FLAGS -marm)
+  endif()
+
   file(GLOB ANDROID_MAIN_SOURCES ${SDL2_SOURCE_DIR}/src/main/android/*.c)
-  set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_MAIN_SOURCES})
+  set(SDLMAIN_SOURCES ${SDLMAIN_SOURCES} ${ANDROID_MAIN_SOURCES})
+
   if(SDL_AUDIO)
     set(SDL_AUDIO_DRIVER_ANDROID 1)
     file(GLOB ANDROID_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/android/*.c)
@@ -739,33 +808,78 @@ if(ANDROID)
     set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_FILESYSTEM_SOURCES})
     set(HAVE_SDL_FILESYSTEM TRUE)
   endif()
+  if(SDL_HAPTIC)
+    set(SDL_HAPTIC_ANDROID 1)
+    file(GLOB ANDROID_HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/android/*.c)
+    set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_HAPTIC_SOURCES})
+    set(HAVE_SDL_HAPTIC TRUE)
+  endif()
   if(SDL_JOYSTICK)
     set(SDL_JOYSTICK_ANDROID 1)
     file(GLOB ANDROID_JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/android/*.c)
     set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_JOYSTICK_SOURCES})
     set(HAVE_SDL_JOYSTICK TRUE)
   endif()
+  if(SDL_LOADSO)
+    set(SDL_LOADSO_DLOPEN 1)
+    file(GLOB LOADSO_SOURCES ${SDL2_SOURCE_DIR}/src/loadso/dlopen/*.c)
+    set(SOURCE_FILES ${SOURCE_FILES} ${LOADSO_SOURCES})
+    set(HAVE_SDL_LOADSO TRUE)
+  endif()
   if(SDL_POWER)
     set(SDL_POWER_ANDROID 1)
     file(GLOB ANDROID_POWER_SOURCES ${SDL2_SOURCE_DIR}/src/power/android/*.c)
     set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_POWER_SOURCES})
     set(HAVE_SDL_POWER TRUE)
   endif()
+  if(SDL_TIMERS)
+    set(SDL_TIMER_UNIX 1)
+    file(GLOB TIMER_SOURCES ${SDL2_SOURCE_DIR}/src/timer/unix/*.c)
+    set(SOURCE_FILES ${SOURCE_FILES} ${TIMER_SOURCES})
+    set(HAVE_SDL_TIMERS TRUE)
+  endif()
   if(SDL_VIDEO)
     set(SDL_VIDEO_DRIVER_ANDROID 1)
     file(GLOB ANDROID_VIDEO_SOURCES ${SDL2_SOURCE_DIR}/src/video/android/*.c)
     set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_VIDEO_SOURCES})
     set(HAVE_SDL_VIDEO TRUE)
 
+    # Core stuff
+    find_library(ANDROID_DL_LIBRARY dl)
+    find_library(ANDROID_LOG_LIBRARY log)
+    find_library(ANDROID_LIBRARY_LIBRARY android)
+    list(APPEND EXTRA_LIBS ${ANDROID_DL_LIBRARY} ${ANDROID_LOG_LIBRARY} ${ANDROID_LIBRARY_LIBRARY})
+    add_definitions(-DGL_GLEXT_PROTOTYPES)
+
     #enable gles
     if(VIDEO_OPENGLES)
       set(SDL_VIDEO_OPENGL_EGL 1)
       set(HAVE_VIDEO_OPENGLES TRUE)
       set(SDL_VIDEO_OPENGL_ES2 1)
       set(SDL_VIDEO_RENDER_OGL_ES2 1)
+
+      find_library(OpenGLES1_LIBRARY GLESv1_CM)
+      find_library(OpenGLES2_LIBRARY GLESv2)
+      list(APPEND EXTRA_LIBS ${OpenGLES1_LIBRARY} ${OpenGLES2_LIBRARY})
+    endif()
+
+    CHECK_C_SOURCE_COMPILES("
+    #if defined(__ARM_ARCH) && __ARM_ARCH < 7
+    #error Vulkan doesn't work on this configuration
+    #endif
+    int main()
+    {
+        return 0;
+    }
+    " VULKAN_PASSED_ANDROID_CHECKS)
+    if(NOT VULKAN_PASSED_ANDROID_CHECKS)
+      set(VIDEO_VULKAN OFF)
+      message(STATUS "Vulkan doesn't work on this configuration")
     endif()
   endif()
-  list(APPEND EXTRA_LDFLAGS "-Wl,--undefined=Java_org_libsdl_app_SDLActivity_nativeInit")
+
+  CheckPTHREAD()
+
 endif()
 
 # Platform-specific options and settings
@@ -821,17 +935,17 @@ if(EMSCRIPTEN)
       set(SDL_VIDEO_RENDER_OGL_ES2 1)
     endif()
   endif()
-elseif(UNIX AND NOT APPLE)
+elseif(UNIX AND NOT APPLE AND NOT ANDROID)
   if(SDL_AUDIO)
     if(SYSV5 OR SOLARIS OR HPUX)
         set(SDL_AUDIO_DRIVER_SUNAUDIO 1)
         file(GLOB SUN_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/sun/*.c)
         set(SOURCE_FILES ${SOURCE_FILES} ${SUN_AUDIO_SOURCES})
         set(HAVE_SDL_AUDIO TRUE)
-    elseif(NETBSD OR OPENBSD)
-        set(SDL_AUDIO_DRIVER_BSD 1)
-        file(GLOB BSD_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/bsd/*.c)
-        set(SOURCE_FILES ${SOURCE_FILES} ${BSD_AUDIO_SOURCES})
+    elseif(NETBSD)
+        set(SDL_AUDIO_DRIVER_NETBSD 1)
+        file(GLOB NETBSD_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/netbsd/*.c)
+        set(SOURCE_FILES ${SOURCE_FILES} ${NETBSD_AUDIO_SOURCES})
         set(HAVE_SDL_AUDIO TRUE)
     elseif(AIX)
         set(SDL_AUDIO_DRIVER_PAUDIO 1)
@@ -841,12 +955,14 @@ elseif(UNIX AND NOT APPLE)
     endif()
     CheckOSS()
     CheckALSA()
+    CheckJACK()
     CheckPulseAudio()
     CheckESD()
     CheckARTS()
     CheckNAS()
     CheckSNDIO()
     CheckFusionSound()
+    CheckLibSampleRate()
   endif()
 
   if(SDL_VIDEO)
@@ -859,6 +975,12 @@ elseif(UNIX AND NOT APPLE)
     CheckOpenGLESX11()
     CheckWayland()
     CheckVivante()
+    CheckKMSDRM()
+  endif()
+
+  if(UNIX)
+    file(GLOB CORE_UNIX_SOURCES ${SDL2_SOURCE_DIR}/src/core/unix/*.c)
+    set(SOURCE_FILES ${SOURCE_FILES} ${CORE_UNIX_SOURCES})
   endif()
 
   if(LINUX)
@@ -880,8 +1002,8 @@ elseif(UNIX AND NOT APPLE)
             ioctl(0, KDGKBENT, &kbe);
         }" HAVE_INPUT_KD)
 
-    file(GLOB CORE_SOURCES ${SDL2_SOURCE_DIR}/src/core/linux/*.c)
-    set(SOURCE_FILES ${SOURCE_FILES} ${CORE_SOURCES})
+    file(GLOB CORE_LINUX_SOURCES ${SDL2_SOURCE_DIR}/src/core/linux/*.c)
+    set(SOURCE_FILES ${SOURCE_FILES} ${CORE_LINUX_SOURCES})
 
     if(HAVE_INPUT_EVENTS)
       set(SDL_INPUT_LINUXEV 1)
@@ -917,7 +1039,6 @@ elseif(UNIX AND NOT APPLE)
     endif()
 
     check_include_file("fcitx/frontend.h" HAVE_FCITX_FRONTEND_H)
-
   endif()
 
   if(INPUT_TSLIB)
@@ -1013,9 +1134,9 @@ elseif(WINDOWS)
 
   if(MSVC)
     # Prevent codegen that would use the VC runtime libraries.
-    add_definitions(/GS-)
+    set_property(DIRECTORY . APPEND PROPERTY COMPILE_OPTIONS "/GS-")
     if(NOT ARCH_64)
-      add_definitions(/arch:SSE)
+      set_property(DIRECTORY . APPEND PROPERTY COMPILE_OPTIONS "/arch:SSE")
     endif()
   endif()
 
@@ -1037,6 +1158,16 @@ elseif(WINDOWS)
         #include <windows.h>
         #include <xinput.h>
         int main(int argc, char **argv) { }" HAVE_XINPUT_H)
+      check_c_source_compiles("
+        #include <windows.h>
+        #include <xinput.h>
+        XINPUT_GAMEPAD_EX x1;
+        int main(int argc, char **argv) { }" HAVE_XINPUT_GAMEPAD_EX)
+      check_c_source_compiles("
+        #include <windows.h>
+        #include <xinput.h>
+        XINPUT_STATE_EX s1;
+        int main(int argc, char **argv) { }" HAVE_XINPUT_STATE_EX)
     else()
       check_include_file(xinput.h HAVE_XINPUT_H)
     endif()
@@ -1047,6 +1178,8 @@ elseif(WINDOWS)
     check_include_file(dsound.h HAVE_DSOUND_H)
     check_include_file(dinput.h HAVE_DINPUT_H)
     check_include_file(xaudio2.h HAVE_XAUDIO2_H)
+    check_include_file(mmdeviceapi.h HAVE_MMDEVICEAPI_H)
+    check_include_file(audioclient.h HAVE_AUDIOCLIENT_H)
     check_include_file(dxgi.h HAVE_DXGI_H)
     if(HAVE_D3D_H OR HAVE_D3D11_H OR HAVE_DDRAW_H OR HAVE_DSOUND_H OR HAVE_DINPUT_H OR HAVE_XAUDIO2_H)
       set(HAVE_DIRECTX TRUE)
@@ -1076,6 +1209,12 @@ elseif(WINDOWS)
       file(GLOB XAUDIO2_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/xaudio2/*.c)
       set(SOURCE_FILES ${SOURCE_FILES} ${XAUDIO2_AUDIO_SOURCES})
     endif()
+
+    if(HAVE_AUDIOCLIENT_H AND HAVE_MMDEVICEAPI_H)
+      set(SDL_AUDIO_DRIVER_WASAPI 1)
+      file(GLOB WASAPI_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/wasapi/*.c)
+      set(SOURCE_FILES ${SOURCE_FILES} ${WASAPI_AUDIO_SOURCES})
+    endif()
   endif()
 
   if(SDL_VIDEO)
@@ -1207,15 +1346,25 @@ elseif(WINDOWS)
     list(APPEND SDL_LIBS "-lmingw32" "-lSDL2main" "-mwindows")
   endif()
 elseif(APPLE)
-  # TODO: rework this for proper MacOS X, iOS and Darwin support
+  # TODO: rework this all for proper MacOS X, iOS and Darwin support
+
+  # We always need these libs on macOS at the moment.
+  # !!! FIXME: we need Carbon for some very old API calls in
+  # !!! FIXME:  src/video/cocoa/SDL_cocoakeyboard.c, but we should figure out
+  # !!! FIXME:  how to dump those.
+  if (APPLE AND NOT IOS)
+    set(SDL_FRAMEWORK_COCOA 1)
+    set(SDL_FRAMEWORK_CARBON 1)
+  endif()
 
   # Requires the darwin file implementation
   if(SDL_FILE)
     file(GLOB EXTRA_SOURCES ${SDL2_SOURCE_DIR}/src/file/cocoa/*.m)
     set(SOURCE_FILES ${EXTRA_SOURCES} ${SOURCE_FILES})
+    # !!! FIXME: modern CMake doesn't need "LANGUAGE C" for Objective-C.
     set_source_files_properties(${EXTRA_SOURCES} PROPERTIES LANGUAGE C)
     set(HAVE_SDL_FILE TRUE)
-    set(SDL_FRAMEWORK_COCOA 1)
+    # !!! FIXME: why is COREVIDEO inside this if() block?
     set(SDL_FRAMEWORK_COREVIDEO 1)
   else()
     message_error("SDL_FILE must be enabled to build on MacOS X")
@@ -1246,7 +1395,7 @@ elseif(APPLE)
   if(SDL_HAPTIC)
     set(SDL_HAPTIC_IOKIT 1)
     if (IOS)
-      file(GLOB POWER_SOURCES ${SDL2_SOURCE_DIR}/src/power/dummy/*.c)
+      file(GLOB HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/dummy/*.c)
       set(SDL_HAPTIC_DUMMY 1)
     else()
       file(GLOB HAPTIC_SOURCES ${SDL2_SOURCE_DIR}/src/haptic/darwin/*.c)
@@ -1269,7 +1418,6 @@ elseif(APPLE)
     endif()
     set(SOURCE_FILES ${SOURCE_FILES} ${POWER_SOURCES})
     set(HAVE_SDL_POWER TRUE)
-    set(SDL_FRAMEWORK_CARBON 1)
     set(SDL_FRAMEWORK_IOKIT 1)
   endif()
 
@@ -1283,6 +1431,7 @@ elseif(APPLE)
   if(SDL_FILESYSTEM)
     set(SDL_FILESYSTEM_COCOA 1)
     file(GLOB FILESYSTEM_SOURCES ${SDL2_SOURCE_DIR}/src/filesystem/cocoa/*.m)
+    # !!! FIXME: modern CMake doesn't need "LANGUAGE C" for Objective-C.
     set_source_files_properties(${FILESYSTEM_SOURCES} PROPERTIES LANGUAGE C)
     set(SOURCE_FILES ${SOURCE_FILES} ${FILESYSTEM_SOURCES})
     set(HAVE_SDL_FILESYSTEM TRUE)
@@ -1368,6 +1517,10 @@ elseif(HAIKU)
   CheckPTHREAD()
 endif()
 
+if(VIDEO_VULKAN)
+  set(SDL_VIDEO_VULKAN 1)
+endif()
+
 # Dummies
 # configure.in does it differently:
 # if not have X
@@ -1534,11 +1687,14 @@ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
 
 # Always build SDLmain
 add_library(SDL2main STATIC ${SDLMAIN_SOURCES})
+target_include_directories(SDL2main PUBLIC $<INSTALL_INTERFACE:include>)
 set(_INSTALL_LIBS "SDL2main")
 
 if(SDL_SHARED)
   add_library(SDL2 SHARED ${SOURCE_FILES} ${VERSION_SOURCES})
-  if(UNIX)
+  if(APPLE)
+    set_target_properties(SDL2 PROPERTIES MACOSX_RPATH 1)
+  elseif(UNIX AND NOT ANDROID)
     set_target_properties(SDL2 PROPERTIES
       VERSION ${LT_VERSION}
       SOVERSION ${LT_REVISION}
@@ -1549,7 +1705,7 @@ if(SDL_SHARED)
       SOVERSION ${LT_REVISION}
       OUTPUT_NAME "SDL2")
   endif()
-  if(MSVC)
+  if(MSVC AND NOT LIBC)
     # Don't try to link with the default set of libraries.
     set_target_properties(SDL2 PROPERTIES LINK_FLAGS_RELEASE "/NODEFAULTLIB")
     set_target_properties(SDL2 PROPERTIES LINK_FLAGS_DEBUG "/NODEFAULTLIB")
@@ -1557,14 +1713,21 @@ if(SDL_SHARED)
   endif()
   set(_INSTALL_LIBS "SDL2" ${_INSTALL_LIBS})
   target_link_libraries(SDL2 ${EXTRA_LIBS} ${EXTRA_LDFLAGS})
+  target_include_directories(SDL2 PUBLIC $<INSTALL_INTERFACE:include>)
 endif()
 
 if(SDL_STATIC)
   set (BUILD_SHARED_LIBS FALSE)
   add_library(SDL2-static STATIC ${SOURCE_FILES})
-  set_target_properties(SDL2-static PROPERTIES OUTPUT_NAME "SDL2")
+  if (NOT SDL_SHARED OR NOT WIN32)
+    set_target_properties(SDL2-static PROPERTIES OUTPUT_NAME "SDL2")
+    # Note: Apparently, OUTPUT_NAME must really be unique; even when
+    # CMAKE_IMPORT_LIBRARY_SUFFIX or the like are given. Otherwise
+    # the static build may race with the import lib and one will get
+    # clobbered, when the suffix is realized via subsequent rename.
+  endif()
   set_target_properties(SDL2-static PROPERTIES POSITION_INDEPENDENT_CODE ${SDL_STATIC_PIC})
-  if(MSVC)
+  if(MSVC AND NOT LIBC)
     set_target_properties(SDL2-static PROPERTIES LINK_FLAGS_RELEASE "/NODEFAULTLIB")
     set_target_properties(SDL2-static PROPERTIES LINK_FLAGS_DEBUG "/NODEFAULTLIB")
     set_target_properties(SDL2-static PROPERTIES STATIC_LIBRARY_FLAGS "/NODEFAULTLIB")
@@ -1573,14 +1736,43 @@ if(SDL_STATIC)
   # libraries - do we need to consider this?
   set(_INSTALL_LIBS "SDL2-static" ${_INSTALL_LIBS})
   target_link_libraries(SDL2-static ${EXTRA_LIBS} ${EXTRA_LDFLAGS})
+  target_include_directories(SDL2-static PUBLIC $<INSTALL_INTERFACE:include>)
 endif()
 
 ##### Installation targets #####
-install(TARGETS ${_INSTALL_LIBS}
+install(TARGETS ${_INSTALL_LIBS} EXPORT SDL2Targets
   LIBRARY DESTINATION "lib${LIB_SUFFIX}"
   ARCHIVE DESTINATION "lib${LIB_SUFFIX}"
   RUNTIME DESTINATION bin)
 
+##### Export files #####
+if (APPLE)
+  set(PKG_PREFIX "SDL2.framework/Resources")
+elseif (WINDOWS)
+  set(PKG_PREFIX "cmake")
+else ()
+  set(PKG_PREFIX "lib/cmake/SDL2")
+endif ()
+
+include(CMakePackageConfigHelpers)
+write_basic_package_version_file("${CMAKE_BINARY_DIR}/SDL2ConfigVersion.cmake"
+  VERSION ${SDL_VERSION}
+  COMPATIBILITY AnyNewerVersion
+)
+
+install(EXPORT SDL2Targets
+  FILE SDL2Targets.cmake
+  NAMESPACE SDL2::
+  DESTINATION ${PKG_PREFIX}
+)
+install(
+  FILES
+    ${CMAKE_SOURCE_DIR}/SDL2Config.cmake
+    ${CMAKE_BINARY_DIR}/SDL2ConfigVersion.cmake
+  DESTINATION ${PKG_PREFIX}
+  COMPONENT Devel
+)
+
 file(GLOB INCLUDE_FILES ${SDL2_SOURCE_DIR}/include/*.h)
 file(GLOB BIN_INCLUDE_FILES ${SDL2_BINARY_DIR}/include/*.h)
 foreach(_FNAME ${BIN_INCLUDE_FILES})
diff --git a/COPYING.txt b/COPYING.txt
index 04f14ee..7571fab 100644
--- a/COPYING.txt
+++ b/COPYING.txt
@@ -1,6 +1,6 @@
 
 Simple DirectMedia Layer
-Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
   
 This software is provided 'as-is', without any express or implied
 warranty.  In no event will the authors be held liable for any damages
diff --git a/INSTALL.txt b/INSTALL.txt
index 2df10bd..398fc11 100644
--- a/INSTALL.txt
+++ b/INSTALL.txt
@@ -5,7 +5,7 @@ To compile and install SDL:
         * Read VisualC.html
 
         Windows with gcc, either native or cross-compiling:
-        * Read the FAQ at http://wiki.libsdl.org/moin.fcg/FAQWindows
+        * Read the FAQ at https://wiki.libsdl.org/moin.fcg/FAQWindows
         * Run './configure; make; make install'
 
         Mac OS X with Xcode:
@@ -27,14 +27,14 @@ To compile and install SDL:
         * Read docs/README-cmake.md
 
     2.  Look at the example programs in ./test, and check out the online
-        documentation at http://wiki.libsdl.org/
+        documentation at https://wiki.libsdl.org/
 
     3.  Join the SDL developer mailing list by sending E-mail to
     	sdl-request at libsdl.org
         and put "subscribe" in the subject of the message.
 
         Or alternatively you can use the web interface:
-            http://www.libsdl.org/mailing-list.php
+            https://www.libsdl.org/mailing-list.php
 
 That's it!
 Sam Lantinga <slouken at libsdl.org>
diff --git a/Makefile.in b/Makefile.in
index a7cbddf..fe56652 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -36,15 +36,15 @@ GEN_HEADERS = @GEN_HEADERS@
 GEN_OBJECTS = @GEN_OBJECTS@
 VERSION_OBJECTS = @VERSION_OBJECTS@
 
-SDLMAIN_TARGET = libSDL2main.a
+SDLMAIN_TARGET = libSDL2main.la
 SDLMAIN_OBJECTS = @SDLMAIN_OBJECTS@
 
-SDLTEST_TARGET = libSDL2_test.a
+SDLTEST_TARGET = libSDL2_test.la
 SDLTEST_OBJECTS = @SDLTEST_OBJECTS@
 
 WAYLAND_SCANNER = @WAYLAND_SCANNER@
 
-SRC_DIST = *.txt acinclude Android.mk autogen.sh android-project build-scripts cmake cmake_uninstall.cmake.in configure configure.in debian docs include Makefile.* sdl2-config.cmake.in sdl2-config.in sdl2.m4 sdl2.pc.in SDL2.spec.in src test VisualC.html VisualC VisualC-WinRT Xcode Xcode-iOS
+SRC_DIST = *.txt acinclude Android.mk autogen.sh android-project build-scripts cmake cmake_uninstall.cmake.in configure configure.in debian docs include Makefile.* sdl2-config.cmake.in sdl2-config.in sdl2.m4 sdl2.pc.in SDL2.spec.in SDL2Config.cmake src test VisualC.html VisualC VisualC-WinRT Xcode Xcode-iOS
 GEN_DIST = SDL2.spec
 
 ifneq ($V,1)
@@ -112,6 +112,7 @@ HDRS = \
 	SDL_types.h \
 	SDL_version.h \
 	SDL_video.h \
+	SDL_vulkan.h \
 	begin_code.h \
 	close_code.h
 
@@ -121,14 +122,12 @@ LT_AGE      = @LT_AGE@
 LT_CURRENT  = @LT_CURRENT@
 LT_RELEASE  = @LT_RELEASE@
 LT_REVISION = @LT_REVISION@
-LT_LDFLAGS  = -no-undefined -rpath $(DESTDIR)$(libdir) -release $(LT_RELEASE) -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
+LT_LDFLAGS  = -no-undefined -rpath $(libdir) -release $(LT_RELEASE) -version-info $(LT_CURRENT):$(LT_REVISION):$(LT_AGE)
 
 all: $(srcdir)/configure Makefile $(objects) $(objects)/$(TARGET) $(objects)/$(SDLMAIN_TARGET) $(objects)/$(SDLTEST_TARGET)
 
 $(srcdir)/configure: $(srcdir)/configure.in
-	@echo "Warning, configure.in is out of date"
-	#(cd $(srcdir) && sh autogen.sh && sh configure)
-	@sleep 3
+	@echo "Warning, configure is out of date, please re-run autogen.sh"
 
 Makefile: $(srcdir)/Makefile.in
 	$(SHELL) config.status $@
@@ -147,12 +146,10 @@ $(objects)/$(TARGET): $(GEN_HEADERS) $(GEN_OBJECTS) $(OBJECTS) $(VERSION_OBJECTS
 	$(RUN_CMD_LTLINK)$(LIBTOOL) --tag=CC --mode=link $(CC) -o $@ $(OBJECTS) $(GEN_OBJECTS) $(VERSION_OBJECTS) $(LDFLAGS) $(EXTRA_LDFLAGS) $(LT_LDFLAGS)
 
 $(objects)/$(SDLMAIN_TARGET): $(SDLMAIN_OBJECTS)
-	$(RUN_CMD_AR)$(AR) cru $@ $(SDLMAIN_OBJECTS)
-	$(RUN_CMD_RANLIB)$(RANLIB) $@
+	$(RUN_CMD_LTLINK)$(LIBTOOL) --tag=CC --mode=link $(CC) -static -o $@ $(SDLMAIN_OBJECTS) -rpath $(libdir)
 
 $(objects)/$(SDLTEST_TARGET): $(SDLTEST_OBJECTS)
-	$(RUN_CMD_AR)$(AR) cru $@ $(SDLTEST_OBJECTS)
-	$(RUN_CMD_RANLIB)$(RANLIB) $@
+	$(RUN_CMD_LTLINK)$(LIBTOOL) --tag=CC --mode=link $(CC) -static -o $@ $(SDLTEST_OBJECTS) -rpath $(libdir)
 
 install: all install-bin install-hdrs install-lib install-data
 install-bin:
@@ -173,10 +170,8 @@ install-hdrs: update-revision
 install-lib: $(objects) $(objects)/$(TARGET) $(objects)/$(SDLMAIN_TARGET) $(objects)/$(SDLTEST_TARGET)
 	$(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(libdir)
 	$(LIBTOOL) --mode=install $(INSTALL) $(objects)/$(TARGET) $(DESTDIR)$(libdir)/$(TARGET)
-	$(INSTALL) -m 644 $(objects)/$(SDLMAIN_TARGET) $(DESTDIR)$(libdir)/$(SDLMAIN_TARGET)
-	$(RANLIB) $(DESTDIR)$(libdir)/$(SDLMAIN_TARGET)
-	$(INSTALL) -m 644 $(objects)/$(SDLTEST_TARGET) $(DESTDIR)$(libdir)/$(SDLTEST_TARGET)
-	$(RANLIB) $(DESTDIR)$(libdir)/$(SDLTEST_TARGET)
+	$(LIBTOOL) --mode=install $(INSTALL) $(objects)/$(SDLMAIN_TARGET) $(DESTDIR)$(libdir)/$(SDLMAIN_TARGET)
+	$(LIBTOOL) --mode=install $(INSTALL) $(objects)/$(SDLTEST_TARGET) $(DESTDIR)$(libdir)/$(SDLTEST_TARGET)
 install-data:
 	$(SHELL) $(auxdir)/mkinstalldirs $(DESTDIR)$(datadir)/aclocal
 	$(INSTALL) -m 644 $(srcdir)/sdl2.m4 $(DESTDIR)$(datadir)/aclocal/sdl2.m4
diff --git a/Makefile.pandora b/Makefile.pandora
index 8b78f27..56f171b 100644
--- a/Makefile.pandora
+++ b/Makefile.pandora
@@ -8,7 +8,7 @@ STRIP = arm-none-linux-gnueabi-strip
 
 CFLAGS  = -O3 -march=armv7-a -mcpu=cortex-a8 -mtune=cortex-a8 -mfloat-abi=softfp \
 	-mfpu=neon -ftree-vectorize -ffast-math -fomit-frame-pointer -fno-strict-aliasing -fsingle-precision-constant \
-	-I./include -I$(PNDSDK)/usr/include -DSDL_REVISION=0
+	-I./include -I$(PNDSDK)/usr/include
 
 TARGET  = libSDL.a
 
@@ -25,7 +25,7 @@ SOURCES = ./src/*.c ./src/audio/*.c ./src/cpuinfo/*.c ./src/events/*.c \
 
 OBJECTS = $(shell echo $(SOURCES) | sed -e 's,\.c,\.o,g')
 
-CONFIG_H = $(shell cp include/SDL_config_pandora.h include/SDL_config.h && touch include/SDL_revision.h)
+CONFIG_H = $(shell cp include/SDL_config_pandora.h include/SDL_config.h)
 
 all: $(TARGET)
 
diff --git a/README-SDL.txt b/README-SDL.txt
index c3d2d37..2984b14 100644
--- a/README-SDL.txt
+++ b/README-SDL.txt
@@ -6,7 +6,7 @@ designed to make it easy to write multi-media software, such as games
 and emulators.
 
 The Simple DirectMedia Layer library source code is available from:
-http://www.libsdl.org/
+https://www.libsdl.org/
 
 This library is distributed under the terms of the zlib license:
 http://www.zlib.net/zlib_license.html
diff --git a/README.txt b/README.txt
index 84c335c..e8630c7 100644
--- a/README.txt
+++ b/README.txt
@@ -6,7 +6,7 @@
                                 Version 2.0
 
 ---
-http://www.libsdl.org/
+https://www.libsdl.org/
 
 Simple DirectMedia Layer is a cross-platform development library designed
 to provide low level access to audio, keyboard, mouse, joystick, and graphics
diff --git a/SDL2.spec b/SDL2.spec
index 5dfda58..4aa6861 100644
--- a/SDL2.spec
+++ b/SDL2.spec
@@ -1,6 +1,6 @@
 Summary: Simple DirectMedia Layer
 Name: SDL2
-Version: 2.0.5
+Version: 2.0.6
 Release: 2
 Source: http://www.libsdl.org/release/%{name}-%{version}.tar.gz
 URL: http://www.libsdl.org/
diff --git a/SDL2Config.cmake b/SDL2Config.cmake
new file mode 100644
index 0000000..4a5f646
--- /dev/null
+++ b/SDL2Config.cmake
@@ -0,0 +1 @@
+include("${CMAKE_CURRENT_LIST_DIR}/SDL2Targets.cmake")
diff --git a/WhatsNew.txt b/WhatsNew.txt
index f8cba4e..38e0496 100644
--- a/WhatsNew.txt
+++ b/WhatsNew.txt
@@ -2,6 +2,65 @@
 This is a list of major changes in SDL's version history.
 
 ---------------------------------------------------------------------------
+2.0.6:
+---------------------------------------------------------------------------
+
+General:
+* Added cross-platform Vulkan graphics support in SDL_vulkan.h
+	SDL_Vulkan_LoadLibrary()
+	SDL_Vulkan_GetVkGetInstanceProcAddr()
+	SDL_Vulkan_GetInstanceExtensions()
+	SDL_Vulkan_CreateSurface()
+	SDL_Vulkan_GetDrawableSize()
+	SDL_Vulkan_UnloadLibrary()
+  This is all the platform-specific code you need to bring up Vulkan on all SDL platforms. You can look at an example in test/testvulkan.c
+* Added SDL_ComposeCustomBlendMode() to create custom blend modes for 2D rendering
+* Added SDL_HasNEON() which returns whether the CPU has NEON instruction support
+* Added support for many game controllers, including the Nintendo Switch Pro Controller
+* Added support for inverted axes and separate axis directions in game controller mappings
+* Added functions to return information about a joystick before it's opened:
+	SDL_JoystickGetDeviceVendor()
+	SDL_JoystickGetDeviceProduct()
+	SDL_JoystickGetDeviceProductVersion()
+	SDL_JoystickGetDeviceType()
+	SDL_JoystickGetDeviceInstanceID()
+* Added functions to return information about an open joystick:
+	SDL_JoystickGetVendor()
+	SDL_JoystickGetProduct()
+	SDL_JoystickGetProductVersion()
+	SDL_JoystickGetType()
+	SDL_JoystickGetAxisInitialState()
+* Added functions to return information about an open game controller:
+	SDL_GameControllerGetVendor()
+	SDL_GameControllerGetProduct()
+	SDL_GameControllerGetProductVersion()
+* Added SDL_GameControllerNumMappings() and SDL_GameControllerMappingForIndex() to be able to enumerate the built-in game controller mappings
+* Added SDL_LoadFile() and SDL_LoadFile_RW() to load a file into memory
+* Added SDL_DuplicateSurface() to make a copy of a surface
+* Added an experimental JACK audio driver
+* Implemented non-power-of-two audio resampling, optionally using libsamplerate to perform the resampling
+* Added the hint SDL_HINT_AUDIO_RESAMPLING_MODE to control the quality of resampling
+* Added the hint SDL_HINT_RENDER_LOGICAL_SIZE_MODE to control the scaling policy for SDL_RenderSetLogicalSize():
+	"0" or "letterbox" - Uses letterbox/sidebars to fit the entire rendering on screen (the default)
+	"1" or "overscan"  - Will zoom the rendering so it fills the entire screen, allowing edges to be drawn offscreen
+* Added the hints SDL_HINT_MOUSE_NORMAL_SPEED_SCALE and SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE to scale the mouse speed when being read from raw mouse input
+* Added the hint SDL_HINT_TOUCH_MOUSE_EVENTS to control whether SDL will synthesize mouse events from touch events
+
+Windows:
+* The new default audio driver on Windows is WASAPI and supports hot-plugging devices and changing the default audio device
+* The old XAudio2 audio driver is deprecated and will be removed in the next release
+* Added hints SDL_HINT_WINDOWS_INTRESOURCE_ICON and SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL to specify a custom icon resource ID for SDL windows
+* The hint SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING is now on by default for compatibility with .NET languages and various Windows debuggers
+* Updated the GUID format for game controller mappings, older mappings will be automatically converted on load
+* Implemented the SDL_WINDOW_ALWAYS_ON_TOP flag on Windows
+
+Linux:
+* Added an experimental KMS/DRM video driver for embedded development
+
+iOS:
+* Added a hint SDL_HINT_AUDIO_CATEGORY to control the audio category, determining whether the phone mute switch affects the audio
+
+---------------------------------------------------------------------------
 2.0.5:
 ---------------------------------------------------------------------------
 
diff --git a/acinclude/libtool.m4 b/acinclude/libtool.m4
index 0eb07c8..b8ba032 100644
--- a/acinclude/libtool.m4
+++ b/acinclude/libtool.m4
@@ -1347,7 +1347,10 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
 	  x86_64-*linux*)
 	    LD="${LD-ld} -m elf_x86_64"
 	    ;;
-	  ppc*-*linux*|powerpc*-*linux*)
+	  powerpc64le-*linux*)
+	    LD="${LD-ld} -m elf64lppc"
+	    ;;
+	  powerpc64-*linux*)
 	    LD="${LD-ld} -m elf64ppc"
 	    ;;
 	  s390*-*linux*|s390*-*tpf*)
diff --git a/autogen.sh b/autogen.sh
index 3e958e1..9edfb8a 100755
--- a/autogen.sh
+++ b/autogen.sh
@@ -5,7 +5,7 @@ echo "This may take a while ..."
 
 srcdir=`dirname $0`
 test -z "$srcdir" && srcdir=.
-pushd $srcdir
+cd "$srcdir"
 
 # Regenerate configuration files
 cat acinclude/* >aclocal.m4
@@ -19,7 +19,5 @@ if test x$found = xfalse; then
 fi
 (cd test; sh autogen.sh)
 
-popd
-
 # Run configure for this platform
 echo "Now you are ready to run ./configure"
diff --git a/build-scripts/androidbuildlibs.sh b/build-scripts/androidbuildlibs.sh
new file mode 100755
index 0000000..4a0bb2f
--- /dev/null
+++ b/build-scripts/androidbuildlibs.sh
@@ -0,0 +1,74 @@
+#!/bin/sh
+#
+# Build the Android libraries without needing a project
+# (AndroidManifest.xml, jni/{Application,Android}.mk, etc.)
+#
+# Usage: androidbuildlibs.sh [arg for ndk-build ...]"
+#
+# Useful NDK arguments:
+#
+#  NDK_DEBUG=1          - build debug version
+#  NDK_LIBS_OUT=<dest>  - specify alternate destination for installable
+#                         modules.
+#
+# Note that SDLmain is not an installable module (.so) so libSDLmain.a
+# can be found in $obj/local/<abi> along with the unstripped libSDL.so.
+#
+
+
+# Android.mk is in srcdir
+srcdir=`dirname $0`/..
+srcdir=`cd $srcdir && pwd`
+cd $srcdir
+
+
+#
+# Create the build directories
+#
+
+build=build
+buildandroid=$build/android
+obj=
+lib=
+ndk_args=
+
+# Allow an external caller to specify locations.
+for arg in $*
+do
+  if [ "${arg:0:8}" == "NDK_OUT=" ]; then
+	obj=${arg#NDK_OUT=}
+  elif [ "${arg:0:13}" == "NDK_LIBS_OUT=" ]; then
+	lib=${arg#NDK_LIBS_OUT=}
+  else
+    ndk_args="$ndk_args $arg"
+  fi
+done
+
+if [ -z $obj ]; then
+  obj=$buildandroid/obj
+fi
+if [ -z $lib ]; then
+  lib=$buildandroid/lib
+fi
+
+for dir in $build $buildandroid $obj $lib; do
+    if test -d $dir; then
+        :
+    else
+        mkdir $dir || exit 1
+    fi
+done
+
+
+# APP_* variables set in the environment here will not be seen by the
+# ndk-build makefile segments that use them, e.g., default-application.mk.
+# For consistency, pass all values on the command line.
+ndk-build \
+  NDK_PROJECT_PATH=null \
+  NDK_OUT=$obj \
+  NDK_LIBS_OUT=$lib \
+  APP_BUILD_SCRIPT=Android.mk \
+  APP_ABI="all" \
+  APP_PLATFORM=android-12 \
+  APP_MODULES="SDL2 SDL2_main" \
+  $ndk_args
diff --git a/build-scripts/checker-buildbot.sh b/build-scripts/checker-buildbot.sh
index eb01431..cc16a50 100755
--- a/build-scripts/checker-buildbot.sh
+++ b/build-scripts/checker-buildbot.sh
@@ -11,7 +11,7 @@
 
 FINALDIR="$1"
 
-CHECKERDIR="/usr/local/checker-276"
+CHECKERDIR="/usr/local/checker-279"
 if [ ! -d "$CHECKERDIR" ]; then
     echo "$CHECKERDIR not found. Trying /usr/share/clang ..." 1>&2
     CHECKERDIR="/usr/share/clang/scan-build"
@@ -46,6 +46,10 @@ fi
 
 echo "\$MAKE is '$MAKE'"
 
+# Unset $MAKE so submakes don't use it.
+MAKECOMMAND="$MAKE"
+unset MAKE
+
 set -x
 set -e
 
@@ -60,17 +64,23 @@ fi
 mkdir checker-buildbot
 cd checker-buildbot
 
+# We turn off deprecated declarations, because we don't care about these warnings during static analysis.
+# The -Wno-liblto is new since our checker-279 upgrade, I think; checker otherwise warns "libLTO.dylib relative to clang installed dir not found"
+
 # You might want to do this for CMake-backed builds instead...
-PATH="$CHECKERDIR:$PATH" scan-build -o analysis cmake -DCMAKE_BUILD_TYPE=Debug -DASSERTIONS=enabled ..
+PATH="$CHECKERDIR/bin:$PATH" scan-build -o analysis cmake -Wno-dev -DSDL_STATIC=OFF -DCMAKE_BUILD_TYPE=Debug -DASSERTIONS=enabled -DCMAKE_C_FLAGS="-Wno-deprecated-declarations" -DCMAKE_SHARED_LINKER_FLAGS="-Wno-liblto" ..
 
 # ...or run configure without the scan-build wrapper...
-#CC="$CHECKERDIR/libexec/ccc-analyzer" CFLAGS="-O0" ../configure --enable-assertions=enabled
-
-# ...but this works for our buildbots just fine (EXCEPT ON LATEST MAC OS X).
-#CFLAGS="-O0" PATH="$CHECKERDIR:$PATH" scan-build -o analysis ../configure --enable-assertions=enabled
+#CC="$CHECKERDIR/libexec/ccc-analyzer" CFLAGS="-O0 -Wno-deprecated-declarations" LDFLAGS="-Wno-liblto" ../configure --enable-assertions=enabled
 
 rm -rf analysis
-PATH="$CHECKERDIR:$PATH" scan-build -o analysis $MAKE
+PATH="$CHECKERDIR/bin:$PATH" scan-build -o analysis $MAKECOMMAND
+
+if [ `ls -A analysis |wc -l` == 0 ] ; then
+    mkdir analysis/zarro
+    echo '<html><head><title>Zarro boogs</title></head><body>Static analysis: no issues to report.</body></html>' >analysis/zarro/index.html
+fi
+
 mv analysis/* ../analysis
 rmdir analysis   # Make sure this is empty.
 cd ..
diff --git a/build-scripts/config.guess b/build-scripts/config.guess
index 68c1be3..a744844 100644
--- a/build-scripts/config.guess
+++ b/build-scripts/config.guess
@@ -1,14 +1,12 @@
 #! /bin/sh
 # Attempt to guess a canonical system name.
-#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-#   2011, 2012 Free Software Foundation, Inc.
+#   Copyright 1992-2017 Free Software Foundation, Inc.
 
-timestamp='2012-08-14'
+timestamp='2017-08-08'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
+# the Free Software Foundation; either version 3 of the License, or
 # (at your option) any later version.
 #
 # This program is distributed in the hope that it will be useful, but
@@ -22,19 +20,17 @@ timestamp='2012-08-14'
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
 # configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-
-# Originally written by Per Bothner.  Please send patches (context
-# diff format) to <config-patches at gnu.org> and include a ChangeLog
-# entry.
+# the same distribution terms that you use for the rest of that
+# program.  This Exception is an additional permission under section 7
+# of the GNU General Public License, version 3 ("GPLv3").
 #
-# This script attempts to guess a canonical system name similar to
-# config.sub.  If it succeeds, it prints the system name on stdout, and
-# exits with 0.  Otherwise, it exits with 1.
+# Originally written by Per Bothner; maintained since 2000 by Ben Elliston.
 #
 # You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess
+#
+# Please send patches to <config-patches at gnu.org>.
+
 
 me=`echo "$0" | sed -e 's,.*/,,'`
 
@@ -54,9 +50,7 @@ version="\
 GNU config.guess ($timestamp)
 
 Originally written by Per Bothner.
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
-Free Software Foundation, Inc.
+Copyright 1992-2017 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -138,6 +132,27 @@ UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
 UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
 UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
 
+case "${UNAME_SYSTEM}" in
+Linux|GNU|GNU/*)
+	# If the system lacks a compiler, then just pick glibc.
+	# We could probably try harder.
+	LIBC=gnu
+
+	eval $set_cc_for_build
+	cat <<-EOF > $dummy.c
+	#include <features.h>
+	#if defined(__UCLIBC__)
+	LIBC=uclibc
+	#elif defined(__dietlibc__)
+	LIBC=dietlibc
+	#else
+	LIBC=gnu
+	#endif
+	EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`
+	;;
+esac
+
 # Note: order is significant - the case branches are not exclusive.
 
 case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
@@ -153,19 +168,29 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	# Note: NetBSD doesn't particularly care about the vendor
 	# portion of the name.  We always set it to "unknown".
 	sysctl="sysctl -n hw.machine_arch"
-	UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
-	    /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+	UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \
+	    /sbin/$sysctl 2>/dev/null || \
+	    /usr/sbin/$sysctl 2>/dev/null || \
+	    echo unknown)`
 	case "${UNAME_MACHINE_ARCH}" in
 	    armeb) machine=armeb-unknown ;;
 	    arm*) machine=arm-unknown ;;
 	    sh3el) machine=shl-unknown ;;
 	    sh3eb) machine=sh-unknown ;;
 	    sh5el) machine=sh5le-unknown ;;
+	    earmv*)
+		arch=`echo ${UNAME_MACHINE_ARCH} | sed -e 's,^e\(armv[0-9]\).*$,\1,'`
+		endian=`echo ${UNAME_MACHINE_ARCH} | sed -ne 's,^.*\(eb\)$,\1,p'`
+		machine=${arch}${endian}-unknown
+		;;
 	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
 	esac
 	# The Operating System including object format, if it has switched
-	# to ELF recently, or will in the future.
+	# to ELF recently (or will in the future) and ABI.
 	case "${UNAME_MACHINE_ARCH}" in
+	    earm*)
+		os=netbsdelf
+		;;
 	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
 		eval $set_cc_for_build
 		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
@@ -182,6 +207,13 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 		os=netbsd
 		;;
 	esac
+	# Determine ABI tags.
+	case "${UNAME_MACHINE_ARCH}" in
+	    earm*)
+		expr='s/^earmv[0-9]/-eabi/;s/eb$//'
+		abi=`echo ${UNAME_MACHINE_ARCH} | sed -e "$expr"`
+		;;
+	esac
 	# The OS release
 	# Debian GNU/NetBSD machines have a different userland, and
 	# thus, need a distinct triplet. However, they do not need
@@ -192,13 +224,13 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 		release='-gnu'
 		;;
 	    *)
-		release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+		release=`echo ${UNAME_RELEASE} | sed -e 's/[-_].*//' | cut -d. -f1,2`
 		;;
 	esac
 	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
 	# contains redundant information, the shorter form:
 	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
-	echo "${machine}-${os}${release}"
+	echo "${machine}-${os}${release}${abi}"
 	exit ;;
     *:Bitrig:*:*)
 	UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
@@ -208,6 +240,10 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
 	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
 	exit ;;
+    *:LibertyBSD:*:*)
+	UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'`
+	echo ${UNAME_MACHINE_ARCH}-unknown-libertybsd${UNAME_RELEASE}
+	exit ;;
     *:ekkoBSD:*:*)
 	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
 	exit ;;
@@ -220,6 +256,12 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
     *:MirBSD:*:*)
 	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
 	exit ;;
+    *:Sortix:*:*)
+	echo ${UNAME_MACHINE}-unknown-sortix
+	exit ;;
+    *:Redox:*:*)
+	echo ${UNAME_MACHINE}-unknown-redox
+	exit ;;
     alpha:OSF1:*:*)
 	case $UNAME_RELEASE in
 	*4.0)
@@ -236,42 +278,42 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
 	case "$ALPHA_CPU_TYPE" in
 	    "EV4 (21064)")
-		UNAME_MACHINE="alpha" ;;
+		UNAME_MACHINE=alpha ;;
 	    "EV4.5 (21064)")
-		UNAME_MACHINE="alpha" ;;
+		UNAME_MACHINE=alpha ;;
 	    "LCA4 (21066/21068)")
-		UNAME_MACHINE="alpha" ;;
+		UNAME_MACHINE=alpha ;;
 	    "EV5 (21164)")
-		UNAME_MACHINE="alphaev5" ;;
+		UNAME_MACHINE=alphaev5 ;;
 	    "EV5.6 (21164A)")
-		UNAME_MACHINE="alphaev56" ;;
+		UNAME_MACHINE=alphaev56 ;;
 	    "EV5.6 (21164PC)")
-		UNAME_MACHINE="alphapca56" ;;
+		UNAME_MACHINE=alphapca56 ;;
 	    "EV5.7 (21164PC)")
-		UNAME_MACHINE="alphapca57" ;;
+		UNAME_MACHINE=alphapca57 ;;
 	    "EV6 (21264)")
-		UNAME_MACHINE="alphaev6" ;;
+		UNAME_MACHINE=alphaev6 ;;
 	    "EV6.7 (21264A)")
-		UNAME_MACHINE="alphaev67" ;;
+		UNAME_MACHINE=alphaev67 ;;
 	    "EV6.8CB (21264C)")
-		UNAME_MACHINE="alphaev68" ;;
+		UNAME_MACHINE=alphaev68 ;;
 	    "EV6.8AL (21264B)")
-		UNAME_MACHINE="alphaev68" ;;
+		UNAME_MACHINE=alphaev68 ;;
 	    "EV6.8CX (21264D)")
-		UNAME_MACHINE="alphaev68" ;;
+		UNAME_MACHINE=alphaev68 ;;
 	    "EV6.9A (21264/EV69A)")
-		UNAME_MACHINE="alphaev69" ;;
+		UNAME_MACHINE=alphaev69 ;;
 	    "EV7 (21364)")
-		UNAME_MACHINE="alphaev7" ;;
+		UNAME_MACHINE=alphaev7 ;;
 	    "EV7.9 (21364A)")
-		UNAME_MACHINE="alphaev79" ;;
+		UNAME_MACHINE=alphaev79 ;;
 	esac
 	# A Pn.n version is a patched version.
 	# A Vn.n version is a released version.
 	# A Tn.n version is a released field test version.
 	# A Xn.n version is an unreleased experimental baselevel.
 	# 1.2 uses "1.2" for uname -r.
-	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`
 	# Reset EXIT trap before exiting to avoid spurious non-zero exit code.
 	exitcode=$?
 	trap '' 0
@@ -306,7 +348,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
     arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
 	echo arm-acorn-riscix${UNAME_RELEASE}
 	exit ;;
-    arm:riscos:*:*|arm:RISCOS:*:*)
+    arm*:riscos:*:*|arm*:RISCOS:*:*)
 	echo arm-unknown-riscos
 	exit ;;
     SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
@@ -344,16 +386,16 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	exit ;;
     i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
 	eval $set_cc_for_build
-	SUN_ARCH="i386"
+	SUN_ARCH=i386
 	# If there is a compiler, see if it is configured for 64-bit objects.
 	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
 	# This test works for both compilers.
-	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+	if [ "$CC_FOR_BUILD" != no_compiler_found ]; then
 	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
-		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		(CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
 		grep IS_64BIT_ARCH >/dev/null
 	    then
-		SUN_ARCH="x86_64"
+		SUN_ARCH=x86_64
 	    fi
 	fi
 	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
@@ -378,7 +420,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
 	exit ;;
     sun*:*:4.2BSD:*)
 	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
-	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+	test "x${UNAME_RELEASE}" = x && UNAME_RELEASE=3
 	case "`/bin/arch`" in
 	    sun3)
 		echo m68k-sun-sunos${UNAME_RELEASE}
@@ -564,8 +606,9 @@ EOF
 	else
 		IBM_ARCH=powerpc
 	fi
-	if [ -x /usr/bin/oslevel ] ; then
-		IBM_REV=`/usr/bin/oslevel`
+	if [ -x /usr/bin/lslpp ] ; then
+		IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc |
+			   awk -F: '{ print $3 }' | sed s/[0-9]*$/0/`
 	else
 		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
 	fi
@@ -602,13 +645,13 @@ EOF
 		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
 		    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
 		    case "${sc_cpu_version}" in
-		      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
-		      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+		      523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0
+		      528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1
 		      532)                      # CPU_PA_RISC2_0
 			case "${sc_kernel_bits}" in
-			  32) HP_ARCH="hppa2.0n" ;;
-			  64) HP_ARCH="hppa2.0w" ;;
-			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
+			  32) HP_ARCH=hppa2.0n ;;
+			  64) HP_ARCH=hppa2.0w ;;
+			  '') HP_ARCH=hppa2.0 ;;   # HP-UX 10.20
 			esac ;;
 		    esac
 		fi
@@ -647,11 +690,11 @@ EOF
 		    exit (0);
 		}
 EOF
-		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+		    (CCOPTS="" $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
 		    test -z "$HP_ARCH" && HP_ARCH=hppa
 		fi ;;
 	esac
-	if [ ${HP_ARCH} = "hppa2.0w" ]
+	if [ ${HP_ARCH} = hppa2.0w ]
 	then
 	    eval $set_cc_for_build
 
@@ -664,12 +707,12 @@ EOF
 	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
 	    # => hppa64-hp-hpux11.23
 
-	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+	    if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) |
 		grep -q __LP64__
 	    then
-		HP_ARCH="hppa2.0w"
+		HP_ARCH=hppa2.0w
 	    else
-		HP_ARCH="hppa64"
+		HP_ARCH=hppa64
 	    fi
 	fi
 	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
@@ -774,14 +817,14 @@ EOF
 	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
 	exit ;;
     F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
-	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
-	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+	FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`
+	FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'`
 	FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
 	echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
 	exit ;;
     5000:UNIX_System_V:4.*:*)
-	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
-	FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+	FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'`
+	FUJITSU_REL=`echo ${UNAME_RELEASE} | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'`
 	echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
 	exit ;;
     i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
@@ -797,10 +840,11 @@ EOF
 	UNAME_PROCESSOR=`/usr/bin/uname -p`
 	case ${UNAME_PROCESSOR} in
 	    amd64)
-		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
-	    *)
-		echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+		UNAME_PROCESSOR=x86_64 ;;
+	    i386)
+		UNAME_PROCESSOR=i586 ;;
 	esac
+	echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
 	exit ;;
     i*:CYGWIN*:*)
 	echo ${UNAME_MACHINE}-pc-cygwin
@@ -811,7 +855,7 @@ EOF
     *:MINGW*:*)
 	echo ${UNAME_MACHINE}-pc-mingw32
 	exit ;;
-    i*:MSYS*:*)
+    *:MSYS*:*)
 	echo ${UNAME_MACHINE}-pc-msys
 	exit ;;
     i*:windows32*:*)
@@ -859,21 +903,21 @@ EOF
 	exit ;;
     *:GNU:*:*)
 	# the GNU system
-	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
 	exit ;;
     *:GNU/*:*:*)
 	# other systems with GNU libc and userland
-	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu
+	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
 	exit ;;
     i*86:Minix:*:*)
 	echo ${UNAME_MACHINE}-pc-minix
 	exit ;;
     aarch64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     aarch64_be:Linux:*:*)
 	UNAME_MACHINE=aarch64_be
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     alpha:Linux:*:*)
 	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
@@ -886,64 +930,60 @@ EOF
 	  EV68*) UNAME_MACHINE=alphaev68 ;;
 	esac
 	objdump --private-headers /bin/sh | grep -q ld.so.1
-	if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
-	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+	if test "$?" = 0 ; then LIBC=gnulibc1 ; fi
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    arc:Linux:*:* | arceb:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     arm*:Linux:*:*)
 	eval $set_cc_for_build
 	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
 	    | grep -q __ARM_EABI__
 	then
-	    echo ${UNAME_MACHINE}-unknown-linux-gnu
+	    echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	else
-        case `sed -n '/^Hardware/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
-        BCM2708) MANUFACTURER=raspberry;;
-        BCM2709) MANUFACTURER=raspberry;;
-        *) MANUFACTURER=unknown;;
-        esac
 	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
 		| grep -q __ARM_PCS_VFP
 	    then
-		echo ${UNAME_MACHINE}-${MANUFACTURER}-linux-gnueabi
+		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi
 	    else
-		echo ${UNAME_MACHINE}-${MANUFACTURER}-linux-gnueabihf
+		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf
 	    fi
 	fi
 	exit ;;
     avr32*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     cris:Linux:*:*)
-	echo ${UNAME_MACHINE}-axis-linux-gnu
+	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
 	exit ;;
     crisv32:Linux:*:*)
-	echo ${UNAME_MACHINE}-axis-linux-gnu
+	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
+	exit ;;
+    e2k:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     frv:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     hexagon:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     i*86:Linux:*:*)
-	LIBC=gnu
-	eval $set_cc_for_build
-	sed 's/^	//' << EOF >$dummy.c
-	#ifdef __dietlibc__
-	LIBC=dietlibc
-	#endif
-EOF
-	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
-	echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+	echo ${UNAME_MACHINE}-pc-linux-${LIBC}
 	exit ;;
     ia64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    k1om:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     m32r*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     m68*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     mips:Linux:*:* | mips64:Linux:*:*)
 	eval $set_cc_for_build
@@ -962,54 +1002,69 @@ EOF
 	#endif
 EOF
 	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
-	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; }
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
 	;;
-    or32:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+    mips64el:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    openrisc*:Linux:*:*)
+	echo or1k-unknown-linux-${LIBC}
+	exit ;;
+    or32:Linux:*:* | or1k*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     padre:Linux:*:*)
-	echo sparc-unknown-linux-gnu
+	echo sparc-unknown-linux-${LIBC}
 	exit ;;
     parisc64:Linux:*:* | hppa64:Linux:*:*)
-	echo hppa64-unknown-linux-gnu
+	echo hppa64-unknown-linux-${LIBC}
 	exit ;;
     parisc:Linux:*:* | hppa:Linux:*:*)
 	# Look for CPU level
 	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
-	  PA7*) echo hppa1.1-unknown-linux-gnu ;;
-	  PA8*) echo hppa2.0-unknown-linux-gnu ;;
-	  *)    echo hppa-unknown-linux-gnu ;;
+	  PA7*) echo hppa1.1-unknown-linux-${LIBC} ;;
+	  PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;
+	  *)    echo hppa-unknown-linux-${LIBC} ;;
 	esac
 	exit ;;
     ppc64:Linux:*:*)
-	echo powerpc64-unknown-linux-gnu
+	echo powerpc64-unknown-linux-${LIBC}
 	exit ;;
     ppc:Linux:*:*)
-	echo powerpc-unknown-linux-gnu
+	echo powerpc-unknown-linux-${LIBC}
+	exit ;;
+    ppc64le:Linux:*:*)
+	echo powerpc64le-unknown-linux-${LIBC}
+	exit ;;
+    ppcle:Linux:*:*)
+	echo powerpcle-unknown-linux-${LIBC}
+	exit ;;
+    riscv32:Linux:*:* | riscv64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     s390:Linux:*:* | s390x:Linux:*:*)
-	echo ${UNAME_MACHINE}-ibm-linux
+	echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
 	exit ;;
     sh64*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     sh*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     sparc:Linux:*:* | sparc64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     tile*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     vax:Linux:*:*)
-	echo ${UNAME_MACHINE}-dec-linux-gnu
+	echo ${UNAME_MACHINE}-dec-linux-${LIBC}
 	exit ;;
     x86_64:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-pc-linux-${LIBC}
 	exit ;;
     xtensa*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
 	exit ;;
     i*86:DYNIX/ptx:4*:*)
 	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
@@ -1085,7 +1140,7 @@ EOF
 	# uname -m prints for DJGPP always 'pc', but it prints nothing about
 	# the processor, so we play safe by assuming i586.
 	# Note: whatever this is, it MUST be the same as what config.sub
-	# prints for the "djgpp" host, or else GDB configury will decide that
+	# prints for the "djgpp" host, or else GDB configure will decide that
 	# this is a cross-build.
 	echo i586-pc-msdosdjgpp
 	exit ;;
@@ -1234,6 +1289,9 @@ EOF
     SX-8R:SUPER-UX:*:*)
 	echo sx8r-nec-superux${UNAME_RELEASE}
 	exit ;;
+    SX-ACE:SUPER-UX:*:*)
+	echo sxace-nec-superux${UNAME_RELEASE}
+	exit ;;
     Power*:Rhapsody:*:*)
 	echo powerpc-apple-rhapsody${UNAME_RELEASE}
 	exit ;;
@@ -1242,24 +1300,43 @@ EOF
 	exit ;;
     *:Darwin:*:*)
 	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
-	case $UNAME_PROCESSOR in
-	    i386)
-		eval $set_cc_for_build
-		if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
-		  if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
-		      (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
-		      grep IS_64BIT_ARCH >/dev/null
-		  then
-		      UNAME_PROCESSOR="x86_64"
-		  fi
-		fi ;;
-	    unknown) UNAME_PROCESSOR=powerpc ;;
-	esac
+	eval $set_cc_for_build
+	if test "$UNAME_PROCESSOR" = unknown ; then
+	    UNAME_PROCESSOR=powerpc
+	fi
+	if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then
+	    if [ "$CC_FOR_BUILD" != no_compiler_found ]; then
+		if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+		       (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
+		       grep IS_64BIT_ARCH >/dev/null
+		then
+		    case $UNAME_PROCESSOR in
+			i386) UNAME_PROCESSOR=x86_64 ;;
+			powerpc) UNAME_PROCESSOR=powerpc64 ;;
+		    esac
+		fi
+		# On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc
+		if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \
+		       (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
+		       grep IS_PPC >/dev/null
+		then
+		    UNAME_PROCESSOR=powerpc
+		fi
+	    fi
+	elif test "$UNAME_PROCESSOR" = i386 ; then
+	    # Avoid executing cc on OS X 10.9, as it ships with a stub
+	    # that puts up a graphical alert prompting to install
+	    # developer tools.  Any system running Mac OS X 10.7 or
+	    # later (Darwin 11 and later) is required to have a 64-bit
+	    # processor. This is not true of the ARM version of Darwin
+	    # that Apple uses in portable devices.
+	    UNAME_PROCESSOR=x86_64
+	fi
 	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
 	exit ;;
     *:procnto*:*:* | *:QNX:[0123456789]*:*)
 	UNAME_PROCESSOR=`uname -p`
-	if test "$UNAME_PROCESSOR" = "x86"; then
+	if test "$UNAME_PROCESSOR" = x86; then
 		UNAME_PROCESSOR=i386
 		UNAME_MACHINE=pc
 	fi
@@ -1268,15 +1345,18 @@ EOF
     *:QNX:*:4*)
 	echo i386-pc-qnx
 	exit ;;
-    NEO-?:NONSTOP_KERNEL:*:*)
+    NEO-*:NONSTOP_KERNEL:*:*)
 	echo neo-tandem-nsk${UNAME_RELEASE}
 	exit ;;
     NSE-*:NONSTOP_KERNEL:*:*)
 	echo nse-tandem-nsk${UNAME_RELEASE}
 	exit ;;
-    NSR-?:NONSTOP_KERNEL:*:*)
+    NSR-*:NONSTOP_KERNEL:*:*)
 	echo nsr-tandem-nsk${UNAME_RELEASE}
 	exit ;;
+    NSX-*:NONSTOP_KERNEL:*:*)
+	echo nsx-tandem-nsk${UNAME_RELEASE}
+	exit ;;
     *:NonStop-UX:*:*)
 	echo mips-compaq-nonstopux
 	exit ;;
@@ -1290,7 +1370,7 @@ EOF
 	# "uname -m" is not consistent, so use $cputype instead. 386
 	# is converted to i386 for consistency with other x86
 	# operating systems.
-	if test "$cputype" = "386"; then
+	if test "$cputype" = 386; then
 	    UNAME_MACHINE=i386
 	else
 	    UNAME_MACHINE="$cputype"
@@ -1332,7 +1412,7 @@ EOF
 	echo i386-pc-xenix
 	exit ;;
     i*86:skyos:*:*)
-	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE} | sed -e 's/ .*$//'`
 	exit ;;
     i*86:rdos:*:*)
 	echo ${UNAME_MACHINE}-pc-rdos
@@ -1343,171 +1423,25 @@ EOF
     x86_64:VMkernel:*:*)
 	echo ${UNAME_MACHINE}-unknown-esx
 	exit ;;
-esac
-
-eval $set_cc_for_build
-cat >$dummy.c <<EOF
-#ifdef _SEQUENT_
-# include <sys/types.h>
-# include <sys/utsname.h>
-#endif
-main ()
-{
-#if defined (sony)
-#if defined (MIPSEB)
-  /* BFD wants "bsd" instead of "newsos".  Perhaps BFD should be changed,
-     I don't know....  */
-  printf ("mips-sony-bsd\n"); exit (0);
-#else
-#include <sys/param.h>
-  printf ("m68k-sony-newsos%s\n",
-#ifdef NEWSOS4
-	"4"
-#else
-	""
-#endif
-	); exit (0);
-#endif
-#endif
-
-#if defined (__arm) && defined (__acorn) && defined (__unix)
-  printf ("arm-acorn-riscix\n"); exit (0);
-#endif
-
-#if defined (hp300) && !defined (hpux)
-  printf ("m68k-hp-bsd\n"); exit (0);
-#endif
-
-#if defined (NeXT)
-#if !defined (__ARCHITECTURE__)
-#define __ARCHITECTURE__ "m68k"
-#endif
-  int version;
-  version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
-  if (version < 4)
-    printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
-  else
-    printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
-  exit (0);
-#endif
-
-#if defined (MULTIMAX) || defined (n16)
-#if defined (UMAXV)
-  printf ("ns32k-encore-sysv\n"); exit (0);
-#else
-#if defined (CMU)
-  printf ("ns32k-encore-mach\n"); exit (0);
-#else
-  printf ("ns32k-encore-bsd\n"); exit (0);
-#endif
-#endif
-#endif
-
-#if defined (__386BSD__)
-  printf ("i386-pc-bsd\n"); exit (0);
-#endif
-
-#if defined (sequent)
-#if defined (i386)
-  printf ("i386-sequent-dynix\n"); exit (0);
-#endif
-#if defined (ns32000)
-  printf ("ns32k-sequent-dynix\n"); exit (0);
-#endif
-#endif
-
-#if defined (_SEQUENT_)
-    struct utsname un;
-
-    uname(&un);
-
-    if (strncmp(un.version, "V2", 2) == 0) {
-	printf ("i386-sequent-ptx2\n"); exit (0);
-    }
-    if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
-	printf ("i386-sequent-ptx1\n"); exit (0);
-    }
-    printf ("i386-sequent-ptx\n"); exit (0);
-
-#endif
-
-#if defined (vax)
-# if !defined (ultrix)
-#  include <sys/param.h>
-#  if defined (BSD)
-#   if BSD == 43
-      printf ("vax-dec-bsd4.3\n"); exit (0);
-#   else
-#    if BSD == 199006
-      printf ("vax-dec-bsd4.3reno\n"); exit (0);
-#    else
-      printf ("vax-dec-bsd\n"); exit (0);
-#    endif
-#   endif
-#  else
-    printf ("vax-dec-bsd\n"); exit (0);
-#  endif
-# else
-    printf ("vax-dec-ultrix\n"); exit (0);
-# endif
-#endif
-
-#if defined (alliant) && defined (i860)
-  printf ("i860-alliant-bsd\n"); exit (0);
-#endif
-
-  exit (1);
-}
-EOF
-
-$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
-	{ echo "$SYSTEM_NAME"; exit; }
-
-# Apollos put the system type in the environment.
-
-test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
-
-# Convex versions that predate uname can use getsysinfo(1)
-
-if [ -x /usr/convex/getsysinfo ]
-then
-    case `getsysinfo -f cpu_type` in
-    c1*)
-	echo c1-convex-bsd
-	exit ;;
-    c2*)
-	if getsysinfo -f scalar_acc
-	then echo c32-convex-bsd
-	else echo c2-convex-bsd
-	fi
-	exit ;;
-    c34*)
-	echo c34-convex-bsd
-	exit ;;
-    c38*)
-	echo c38-convex-bsd
+    amd64:Isilon\ OneFS:*:*)
+	echo x86_64-unknown-onefs
 	exit ;;
-    c4*)
-	echo c4-convex-bsd
-	exit ;;
-    esac
-fi
+esac
 
 cat >&2 <<EOF
 $0: unable to guess system type
 
-This script, last modified $timestamp, has failed to recognize
-the operating system you are using. It is advised that you
-download the most up to date version of the config scripts from
+This script (version $timestamp), has failed to recognize the
+operating system you are using. If your script is old, overwrite *all*
+copies of config.guess and config.sub with the latest versions from:
 
-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess
 and
-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub
 
-If the version you run ($0) is already up to date, please
-send the following data and any information you think might be
-pertinent to <config-patches at gnu.org> in order to provide the needed
-information to handle your system.
+If $0 has already been updated, send the following data and any
+information you think might be pertinent to config-patches at gnu.org to
+provide the necessary information to handle your system.
 
 config.guess timestamp = $timestamp
 
diff --git a/build-scripts/config.sub b/build-scripts/config.sub
index 53273f2..dcf4133 100644
--- a/build-scripts/config.sub
+++ b/build-scripts/config.sub
@@ -1,24 +1,18 @@
 #! /bin/sh
 # Configuration validation subroutine script.
-#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-#   2011, 2012 Free Software Foundation, Inc.
+#   Copyright 1992-2017 Free Software Foundation, Inc.
 
-timestamp='2012-08-18'
+timestamp='2017-04-02'
 
-# This file is (in principle) common to ALL GNU software.
-# The presence of a machine in this file suggests that SOME GNU software
-# can handle that machine.  It does not imply ALL GNU software can.
-#
-# This file is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
 # (at your option) any later version.
 #
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
 # along with this program; if not, see <http://www.gnu.org/licenses/>.
@@ -26,11 +20,12 @@ timestamp='2012-08-18'
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
 # configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
+# the same distribution terms that you use for the rest of that
+# program.  This Exception is an additional permission under section 7
+# of the GNU General Public License, version 3 ("GPLv3").
 
 
-# Please send patches to <config-patches at gnu.org>.  Submit a context
-# diff and a properly formatted GNU ChangeLog entry.
+# Please send patches to <config-patches at gnu.org>.
 #
 # Configuration subroutine to validate and canonicalize a configuration type.
 # Supply the specified configuration type as an argument.
@@ -38,7 +33,7 @@ timestamp='2012-08-18'
 # Otherwise, we print the canonical config type on stdout and succeed.
 
 # You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub
 
 # This file is supposed to be the same for all GNU packages
 # and recognize all the CPU types, system types and aliases
@@ -58,8 +53,7 @@ timestamp='2012-08-18'
 me=`echo "$0" | sed -e 's,.*/,,'`
 
 usage="\
-Usage: $0 [OPTION] CPU-MFR-OPSYS
-       $0 [OPTION] ALIAS
+Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS
 
 Canonicalize a configuration name.
 
@@ -73,9 +67,7 @@ Report bugs and patches to <config-patches at gnu.org>."
 version="\
 GNU config.sub ($timestamp)
 
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
-Free Software Foundation, Inc.
+Copyright 1992-2017 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -124,8 +116,8 @@ maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
 case $maybe_os in
   nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
   linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
-  knetbsd*-gnu* | netbsd*-gnu* | \
-  kopensolaris*-gnu* | \
+  knetbsd*-gnu* | netbsd*-gnu* | netbsd*-eabi* | \
+  kopensolaris*-gnu* | cloudabi*-eabi* | \
   storm-chaos* | os2-emx* | rtmk-nova*)
     os=-$maybe_os
     basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
@@ -156,7 +148,7 @@ case $os in
 	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
 	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
 	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
-	-apple | -axis | -knuth | -cray | -microblaze)
+	-apple | -axis | -knuth | -cray | -microblaze*)
 		os=
 		basic_machine=$1
 		;;
@@ -259,21 +251,25 @@ case $basic_machine in
 	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
 	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
 	| am33_2.0 \
-	| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \
-        | be32 | be64 \
+	| arc | arceb \
+	| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
+	| avr | avr32 \
+	| ba \
+	| be32 | be64 \
 	| bfin \
-	| c4x | clipper \
+	| c4x | c8051 | clipper \
 	| d10v | d30v | dlx | dsp16xx \
-	| epiphany \
-	| fido | fr30 | frv \
+	| e2k | epiphany \
+	| fido | fr30 | frv | ft32 \
 	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
 	| hexagon \
-	| i370 | i860 | i960 | ia64 \
+	| i370 | i860 | i960 | ia16 | ia64 \
 	| ip2k | iq2000 \
+	| k1om \
 	| le32 | le64 \
 	| lm32 \
 	| m32c | m32r | m32rle | m68000 | m68k | m88k \
-	| maxq | mb | microblaze | mcore | mep | metag \
+	| maxq | mb | microblaze | microblazeel | mcore | mep | metag \
 	| mips | mipsbe | mipseb | mipsel | mipsle \
 	| mips16 \
 	| mips64 | mips64el \
@@ -287,26 +283,30 @@ case $basic_machine in
 	| mips64vr5900 | mips64vr5900el \
 	| mipsisa32 | mipsisa32el \
 	| mipsisa32r2 | mipsisa32r2el \
+	| mipsisa32r6 | mipsisa32r6el \
 	| mipsisa64 | mipsisa64el \
 	| mipsisa64r2 | mipsisa64r2el \
+	| mipsisa64r6 | mipsisa64r6el \
 	| mipsisa64sb1 | mipsisa64sb1el \
 	| mipsisa64sr71k | mipsisa64sr71kel \
+	| mipsr5900 | mipsr5900el \
 	| mipstx39 | mipstx39el \
 	| mn10200 | mn10300 \
 	| moxie \
 	| mt \
 	| msp430 \
 	| nds32 | nds32le | nds32be \
-	| nios | nios2 \
+	| nios | nios2 | nios2eb | nios2el \
 	| ns16k | ns32k \
-	| open8 \
-	| or32 \
+	| open8 | or1k | or1knd | or32 \
 	| pdp10 | pdp11 | pj | pjl \
 	| powerpc | powerpc64 | powerpc64le | powerpcle \
+	| pru \
 	| pyramid \
+	| riscv32 | riscv64 \
 	| rl78 | rx \
 	| score \
-	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[234]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
 	| sh64 | sh64le \
 	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
 	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
@@ -314,6 +314,8 @@ case $basic_machine in
 	| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
 	| ubicom32 \
 	| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
+	| visium \
+	| wasm32 \
 	| we32k \
 	| x86 | xc16x | xstormy16 | xtensa \
 	| z8k | z80)
@@ -328,7 +330,10 @@ case $basic_machine in
 	c6x)
 		basic_machine=tic6x-unknown
 		;;
-	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip)
+	leon|leon[3-9])
+		basic_machine=sparc-$basic_machine
+		;;
+	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
 		basic_machine=$basic_machine-unknown
 		os=-none
 		;;
@@ -383,26 +388,29 @@ case $basic_machine in
 	| aarch64-* | aarch64_be-* \
 	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
 	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
-	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
 	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
 	| avr-* | avr32-* \
+	| ba-* \
 	| be32-* | be64-* \
 	| bfin-* | bs2000-* \
 	| c[123]* | c30-* | [cjt]90-* | c4x-* \
-	| clipper-* | craynv-* | cydra-* \
+	| c8051-* | clipper-* | craynv-* | cydra-* \
 	| d10v-* | d30v-* | dlx-* \
-	| elxsi-* \
+	| e2k-* | elxsi-* \
 	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
 	| h8300-* | h8500-* \
 	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
 	| hexagon-* \
-	| i*86-* | i860-* | i960-* | ia64-* \
+	| i*86-* | i860-* | i960-* | ia16-* | ia64-* \
 	| ip2k-* | iq2000-* \
+	| k1om-* \
 	| le32-* | le64-* \
 	| lm32-* \
 	| m32c-* | m32r-* | m32rle-* \
 	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
-	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \
+	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* \
+	| microblaze-* | microblazeel-* \
 	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
 	| mips16-* \
 	| mips64-* | mips64el-* \
@@ -416,28 +424,34 @@ case $basic_machine in
 	| mips64vr5900-* | mips64vr5900el-* \
 	| mipsisa32-* | mipsisa32el-* \
 	| mipsisa32r2-* | mipsisa32r2el-* \
+	| mipsisa32r6-* | mipsisa32r6el-* \
 	| mipsisa64-* | mipsisa64el-* \
 	| mipsisa64r2-* | mipsisa64r2el-* \
+	| mipsisa64r6-* | mipsisa64r6el-* \
 	| mipsisa64sb1-* | mipsisa64sb1el-* \
 	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
+	| mipsr5900-* | mipsr5900el-* \
 	| mipstx39-* | mipstx39el-* \
 	| mmix-* \
 	| mt-* \
 	| msp430-* \
 	| nds32-* | nds32le-* | nds32be-* \
-	| nios-* | nios2-* \
+	| nios-* | nios2-* | nios2eb-* | nios2el-* \
 	| none-* | np1-* | ns16k-* | ns32k-* \
 	| open8-* \
+	| or1k*-* \
 	| orion-* \
 	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
 	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
+	| pru-* \
 	| pyramid-* \
+	| riscv32-* | riscv64-* \
 	| rl78-* | romp-* | rs6000-* | rx-* \
 	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
 	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
 	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
 	| sparclite-* \
-	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
+	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx*-* \
 	| tahoe-* \
 	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
 	| tile*-* \
@@ -445,6 +459,8 @@ case $basic_machine in
 	| ubicom32-* \
 	| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
 	| vax-* \
+	| visium-* \
+	| wasm32-* \
 	| we32k-* \
 	| x86-* | x86_64-* | xc16x-* | xps100-* \
 	| xstormy16-* | xtensa*-* \
@@ -521,6 +537,9 @@ case $basic_machine in
 		basic_machine=i386-pc
 		os=-aros
 		;;
+	asmjs)
+		basic_machine=asmjs-unknown
+		;;
 	aux)
 		basic_machine=m68k-apple
 		os=-aux
@@ -641,6 +660,14 @@ case $basic_machine in
 		basic_machine=m68k-bull
 		os=-sysv3
 		;;
+	e500v[12])
+		basic_machine=powerpc-unknown
+		os=$os"spe"
+		;;
+	e500v[12]-*)
+		basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=$os"spe"
+		;;
 	ebmon29k)
 		basic_machine=a29k-amd
 		os=-ebmon
@@ -782,6 +809,9 @@ case $basic_machine in
 		basic_machine=m68k-isi
 		os=-sysv
 		;;
+	leon-*|leon[3-9]-*)
+		basic_machine=sparc-`echo $basic_machine | sed 's/-.*//'`
+		;;
 	m68knommu)
 		basic_machine=m68k-unknown
 		os=-linux
@@ -801,7 +831,7 @@ case $basic_machine in
 		basic_machine=ns32k-utek
 		os=-sysv
 		;;
-	microblaze)
+	microblaze*)
 		basic_machine=microblaze-xilinx
 		;;
 	mingw64)
@@ -809,7 +839,7 @@ case $basic_machine in
 		os=-mingw64
 		;;
 	mingw32)
-		basic_machine=i386-pc
+		basic_machine=i686-pc
 		os=-mingw32
 		;;
 	mingw32ce)
@@ -837,6 +867,10 @@ case $basic_machine in
 		basic_machine=powerpc-unknown
 		os=-morphos
 		;;
+	moxiebox)
+		basic_machine=moxie-unknown
+		os=-moxiebox
+		;;
 	msdos)
 		basic_machine=i386-pc
 		os=-msdos
@@ -845,7 +879,7 @@ case $basic_machine in
 		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
 		;;
 	msys)
-		basic_machine=i386-pc
+		basic_machine=i686-pc
 		os=-msys
 		;;
 	mvs)
@@ -933,6 +967,9 @@ case $basic_machine in
 	nsr-tandem)
 		basic_machine=nsr-tandem
 		;;
+	nsx-tandem)
+		basic_machine=nsx-tandem
+		;;
 	op50n-* | op60c-*)
 		basic_machine=hppa1.1-oki
 		os=-proelf
@@ -1017,7 +1054,7 @@ case $basic_machine in
 	ppc-* | ppcbe-*)
 		basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
-	ppcle | powerpclittle | ppc-le | powerpc-little)
+	ppcle | powerpclittle)
 		basic_machine=powerpcle-unknown
 		;;
 	ppcle-* | powerpclittle-*)
@@ -1027,7 +1064,7 @@ case $basic_machine in
 		;;
 	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
 		;;
-	ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+	ppc64le | powerpc64little)
 		basic_machine=powerpc64le-unknown
 		;;
 	ppc64le-* | powerpc64little-*)
@@ -1040,7 +1077,11 @@ case $basic_machine in
 		basic_machine=i586-unknown
 		os=-pw32
 		;;
-	rdos)
+	rdos | rdos64)
+		basic_machine=x86_64-pc
+		os=-rdos
+		;;
+	rdos32)
 		basic_machine=i386-pc
 		os=-rdos
 		;;
@@ -1224,6 +1265,9 @@ case $basic_machine in
 		basic_machine=a29k-wrs
 		os=-vxworks
 		;;
+	wasm32)
+		basic_machine=wasm32-unknown
+		;;
 	w65*)
 		basic_machine=w65-wdc
 		os=-none
@@ -1367,29 +1411,30 @@ case $os in
 	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
 	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
 	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
-	      | -sym* | -kopensolaris* \
+	      | -sym* | -kopensolaris* | -plan9* \
 	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
-	      | -aos* | -aros* \
+	      | -aos* | -aros* | -cloudabi* | -sortix* \
 	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
 	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
 	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
-	      | -bitrig* | -openbsd* | -solidbsd* \
+	      | -bitrig* | -openbsd* | -solidbsd* | -libertybsd* \
 	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
 	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
 	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
 	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
-	      | -chorusos* | -chorusrdb* | -cegcc* \
+	      | -chorusos* | -chorusrdb* | -cegcc* | -glidix* \
 	      | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
-	      | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
+	      | -midipix* | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
 	      | -linux-newlib* | -linux-musl* | -linux-uclibc* \
-	      | -uxpv* | -beos* | -mpeix* | -udk* \
+	      | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \
 	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
 	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
 	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
 	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
 	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
 	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
-	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
+	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* \
+	      | -onefs* | -tirtos* | -phoenix* | -fuchsia* | -redox*)
 	# Remember, each alternative MUST END IN *, to match a version number.
 		;;
 	-qnx*)
@@ -1437,6 +1482,9 @@ case $os in
 	-os400*)
 		os=-os400
 		;;
+	-cegcc*)
+		os=-cegcc
+		;;
 	-wince*)
 		os=-wince
 		;;
@@ -1519,9 +1567,6 @@ case $os in
 	-aros*)
 		os=-aros
 		;;
-	-kaos*)
-		os=-kaos
-		;;
 	-zvmoe)
 		os=-zvmoe
 		;;
@@ -1534,6 +1579,8 @@ case $os in
 	-pnacl*)
 		os=-pnacl
 		;;
+	-ios)
+		;;
 	-emscripten*)
 		;;
 	-none)
@@ -1576,6 +1623,9 @@ case $basic_machine in
 	c4x-* | tic4x-*)
 		os=-coff
 		;;
+	c8051-*)
+		os=-elf
+		;;
 	hexagon-*)
 		os=-elf
 		;;
@@ -1628,6 +1678,9 @@ case $basic_machine in
 	sparc-* | *-sun)
 		os=-sunos4.1.1
 		;;
+	pru-*)
+		os=-elf
+		;;
 	*-be)
 		os=-beos
 		;;
diff --git a/build-scripts/config.sub.patch b/build-scripts/config.sub.patch
new file mode 100644
index 0000000..8c09e00
--- /dev/null
+++ b/build-scripts/config.sub.patch
@@ -0,0 +1,72 @@
+--- config.sub.orig	2017-09-09 08:01:02.139023205 -0700
++++ config.sub	2017-09-09 07:59:35.798264474 -0700
+@@ -364,6 +364,19 @@
+ 	i*86 | x86_64)
+ 	  basic_machine=$basic_machine-pc
+ 	  ;;
++	nacl64*)
++		basic_machine=x86_64-pc
++		os=-nacl
++		;;
++	nacl*)
++		basic_machine=i686-pc
++		os=-nacl
++		;;
++	pnacl*)
++		# le32-unknown-pnacl comes from http://www.chromium.org/nativeclient/pnacl/stability-of-the-pnacl-bitcode-abi
++		basic_machine=le32-unknown
++		os=-pnacl
++		;;
+ 	# Object if more than one company name word.
+ 	*-*-*)
+ 		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+@@ -877,6 +890,10 @@
+ 		basic_machine=le32-unknown
+ 		os=-nacl
+ 		;;
++	pnacl)
++		basic_machine=le32-unknown
++		os=-pnacl
++		;;
+ 	ncr3000)
+ 		basic_machine=i486-ncr
+ 		os=-sysv4
+@@ -1429,6 +1446,12 @@
+ 			;;
+ 		esac
+ 		;;
++	-nacl*)
++		os=-nacl
++		;;
++	-pnacl*)
++		os=-pnacl
++		;;
+ 	-nto-qnx*)
+ 		;;
+ 	-nto*)
+@@ -1459,6 +1482,9 @@
+ 	-os400*)
+ 		os=-os400
+ 		;;
++	-cegcc*)
++		os=-cegcc
++		;;
+ 	-wince*)
+ 		os=-wince
+ 		;;
+@@ -1548,9 +1574,15 @@
+ 		os=-dicos
+ 		;;
+ 	-nacl*)
++        os=-nacl
++        ;;
++	-pnacl*)
++		os=-pnacl
+ 		;;
+ 	-ios)
+ 		;;
++	-emscripten*)
++		;;
+ 	-none)
+ 		;;
+ 	*)
diff --git a/build-scripts/emscripten-buildbot.sh b/build-scripts/emscripten-buildbot.sh
index 42eebb6..65b43e8 100755
--- a/build-scripts/emscripten-buildbot.sh
+++ b/build-scripts/emscripten-buildbot.sh
@@ -1,9 +1,13 @@
 #!/bin/bash
 
-SDKDIR="/emsdk_portable"
+if [ -z "$SDKDIR" ]; then
+    SDKDIR="/emsdk_portable"
+fi
+
 ENVSCRIPT="$SDKDIR/emsdk_env.sh"
 if [ ! -f "$ENVSCRIPT" ]; then
    echo "ERROR: This script expects the Emscripten SDK to be in '$SDKDIR'." 1>&2
+   echo "ERROR: Set the \$SDKDIR environment variable to override this." 1>&2
    exit 1
 fi
 
@@ -51,7 +55,7 @@ mkdir buildbot
 pushd buildbot
 
 echo "Configuring..."
-emconfigure ../configure --host=asmjs-unknown-emscripten --disable-assembly --disable-threads --enable-cpuinfo=false CFLAGS="-O2 -Wno-warn-absolute-paths -Wdeclaration-after-statement -Werror=declaration-after-statement" --prefix="$PWD/emscripten-sdl2-installed" || exit $?
+emconfigure ../configure --host=asmjs-unknown-emscripten --disable-assembly --disable-threads --disable-cpuinfo CFLAGS="-O2 -Wno-warn-absolute-paths -Wdeclaration-after-statement -Werror=declaration-after-statement" --prefix="$PWD/emscripten-sdl2-installed" || exit $?
 
 echo "Building..."
 emmake $MAKE || exit $?
diff --git a/build-scripts/iosbuild.sh b/build-scripts/iosbuild.sh
index eeb5716..bb0e631 100755
--- a/build-scripts/iosbuild.sh
+++ b/build-scripts/iosbuild.sh
@@ -1,7 +1,6 @@
 #!/bin/sh
 #
 # Build a fat binary for iOS
-# Based on fatbuild.sh and code from the Ignifuga Game Engine
 
 # Number of CPUs (for make -j)
 NCPU=`sysctl -n hw.ncpu`
@@ -9,269 +8,181 @@ if test x$NJOB = x; then
     NJOB=$NCPU
 fi
 
-# SDK path
-XCODE_PATH=`xcode-select --print-path`
-if [ -z "$XCODE_PATH" ]; then
-    echo "Could not find XCode location (use xcode-select -switch to set the correct path)"
-    exit 1
+SRC_DIR=$(cd `dirname $0`/..; pwd)
+if [ "$PWD" = "$SRC_DIR" ]; then
+    PREFIX=$SRC_DIR/ios-build
+    mkdir $PREFIX
+else
+    PREFIX=$PWD
 fi
 
-prepare_environment() {
-    ARCH=$1
-    
-    if test x$SDK_VERSION = x; then
-      export SDK_VERSION=`xcodebuild -showsdks | grep iphoneos | sed "s|.*iphoneos||"`
-      if [ -z "$XCODE_PATH" ]; then
-          echo "Could not find a valid iOS SDK"
-          exit 1
-      fi  
-    fi
-    
-    case $ARCH in
-        armv6)
-            DEV_PATH="$XCODE_PATH/Platforms/iPhoneOS.platform/Developer"
-            SDK_PATH="$DEV_PATH/SDKs/iPhoneOS$SDK_VERSION.sdk"
-            ;;
-        armv7)
-            DEV_PATH="$XCODE_PATH/Platforms/iPhoneOS.platform/Developer"
-            SDK_PATH="$DEV_PATH/SDKs/iPhoneOS$SDK_VERSION.sdk"
-            ;;
-        i386)
-            DEV_PATH="$XCODE_PATH/Platforms/iPhoneSimulator.platform/Developer"
-            SDK_PATH="$DEV_PATH/SDKs/iPhoneSimulator$SDK_VERSION.sdk"
-            ;;
-        *)
-            echo "Unknown Architecture $ARCH"
-            exit 1
-            ;;
-    esac
+BUILD_I386_IOSSIM=YES
+BUILD_X86_64_IOSSIM=YES
 
-    if [ ! -d "$SDK_PATH" ]; then
-        echo "Could not find iOS SDK at $SDK_PATH"
-        exit 1
-    fi
+BUILD_IOS_ARMV7=YES
+BUILD_IOS_ARMV7S=YES
+BUILD_IOS_ARM64=YES
 
-    if test x$MIN_OS_VERSION = x; then
-        export MIN_OS_VERSION="3.0"
-    fi
-    
-    # Environment flags
-    CFLAGS="-g -O2 -pipe -no-cpp-precomp -isysroot $SDK_PATH \
-            -miphoneos-version-min=$MIN_OS_VERSION -I$SDK_PATH/usr/include/"
-    LDFLAGS="-L$SDK_PATH/usr/lib/ -isysroot $SDK_PATH \
-             -miphoneos-version-min=$MIN_OS_VERSION -static-libgcc"
-    export CXXFLAGS="$CFLAGS"
-    export CXXCPP="$DEV_PATH/usr/bin/llvm-cpp-4.2"
-    export CPP="$CXXCPP"
-    export CXX="$DEV_PATH/usr/bin/llvm-g++-4.2"
-    export CC="$DEV_PATH/usr/bin/llvm-gcc-4.2"
-    export LD="$DEV_PATH/usr/bin/ld"
-    export AR="$DEV_PATH/usr/bin/ar"
-    export AS="$DEV_PATH/usr/bin/ls"
-    export NM="$DEV_PATH/usr/bin/nm"
-    export RANLIB="$DEV_PATH/usr/bin/ranlib"
-    export STRIP="$DEV_PATH/usr/bin/strip"
-    
-    # We dynamically load X11, so using the system X11 headers is fine.
-    CONFIG_FLAGS="--disable-shared --enable-static"
-    
-    case $ARCH in
-        armv6)
-            export CONFIG_FLAGS="$CONFIG_FLAGS --host=armv6-apple-darwin"
-            export CFLAGS="$CFLAGS -arch armv6"
-            export LDFLAGS="$LDFLAGS -arch armv6"
-            ;;
-        armv7)
-            export CONFIG_FLAGS="$CONFIG_FLAGS --host=armv7-apple-darwin"
-            export CFLAGS="$CFLAGS -arch armv7"
-            export LDFLAGS="$LDFLAGS -arch armv7"
-            ;;
-        i386)
-            export CONFIG_FLAGS="$CONFIG_FLAGS --host=i386-apple-darwin"
-            export CFLAGS="$CFLAGS -arch i386"
-            export LDFLAGS="$LDFLAGS -arch i386"
-            ;;
-        *)
-            echo "Unknown Architecture $ARCH"
-            exit 1
-            ;;
-    esac
-}
+# 13.4.0 - Mavericks
+# 14.0.0 - Yosemite
+# 15.0.0 - El Capitan
+DARWIN=darwin15.0.0
 
-prepare_environment "armv6"
-echo "Building with iOS SDK v$SDK_VERSION for iOS >= $MIN_OS_VERSION"
+XCODEDIR=`xcode-select --print-path`
+IOS_SDK_VERSION=`xcrun --sdk iphoneos --show-sdk-version`
+MIN_SDK_VERSION=6.0
 
-#
-# Find the configure script
-#
-srcdir=`dirname $0`/..
-srcdir=`cd $srcdir && pwd`
-auxdir=$srcdir/build-scripts
-cd $srcdir
+IPHONEOS_PLATFORM=`xcrun --sdk iphoneos --show-sdk-platform-path`
+IPHONEOS_SYSROOT=`xcrun --sdk iphoneos --show-sdk-path`
 
-#
-# Figure out which phase to build:
-# all,
-# configure, configure-armv6, configure-armv7, configure-i386
-# make, make-armv6, make-armv7, make-i386, merge
-# clean
-if test x"$1" = x; then
-    phase=all
-else
-    phase="$1"
-fi
-case $phase in
-    all)
-        configure_armv6="yes"
-        configure_armv7="yes"
-        configure_i386="yes"
-        make_armv6="yes"
-        make_armv7="yes"
-        make_i386="yes"
-        merge="yes"
-        ;;
-    configure)
-        configure_armv6="yes"
-        configure_armv7="yes"
-        configure_i386="yes"
-        ;;
-    configure-armv6)
-        configure_armv6="yes"
-        ;;
-    configure-armv7)
-        configure_armv7="yes"
-        ;;
-    configure-i386)
-        configure_i386="yes"
-        ;;
-    make)
-        make_armv6="yes"
-        make_armv7="yes"
-        make_i386="yes"
-        merge="yes"
-        ;;
-    make-armv6)
-        make_armv6="yes"
-        ;;
-    make-armv7)
-        make_armv7="yes"
-        ;;
-    make-i386)
-        make_i386="yes"
-        ;;
-    merge)
-        merge="yes"
-        ;;
-    clean)
-        clean_armv6="yes"
-        clean_armv7="yes"
-        clean_i386="yes"
-        ;;
-    clean-armv6)
-        clean_armv6="yes"
-        ;;
-    clean-armv7)
-        clean_armv7="yes"
-        ;;
-    clean-i386)
-        clean_i386="yes"
-        ;;
-    *)
-        echo "Usage: $0 [all|configure[-armv6|-armv7|-i386]|make[-armv6|-armv7|-i386]|merge|clean[-armv6|-armv7|-i386]]"
-        exit 1
-        ;;
-esac
+IPHONESIMULATOR_PLATFORM=`xcrun --sdk iphonesimulator --show-sdk-platform-path`
+IPHONESIMULATOR_SYSROOT=`xcrun --sdk iphonesimulator --show-sdk-path`
 
-#
-# Create the build directories
-#
-for dir in build build/armv6 build/armv7 build/i386; do
-    if test -d $dir; then
-        :
-    else
-        mkdir $dir || exit 1
-    fi
-done
+# Uncomment if you want to see more information about each invocation
+# of clang as the builds proceed.
+# CLANG_VERBOSE="--verbose"
 
-#
-# Build the armv6 binary
-#
-prepare_environment "armv6"
-if test x$configure_armv6 = xyes; then
-    (cd build/armv6 && \
-     sh ../../configure $CONFIG_FLAGS CC="$CC" CXX="$CXX" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS") || exit 2
-     # configure is not yet fully ready for iOS, some manual patching is required
-     cp include/* build/armv6/include
-     cp include/SDL_config_iphoneos.h build/armv6/include/SDL_config.h || exit 2
-     sed -i "" -e "s|^EXTRA_CFLAGS.*|EXTRA_CFLAGS=-I./include|g" build/armv6/Makefile || exit 2
-     sed -i "" -e "s|^EXTRA_LDFLAGS.*|EXTRA_LDFLAGS=-lm|g" build/armv6/Makefile || exit 2
-fi
-if test x$make_armv6 = xyes; then
-    (cd build/armv6 && make -j$NJOB) || exit 3
-fi
-#
-# Build the armv7 binary
-#
-prepare_environment "armv7"
-if test x$configure_armv7 = xyes; then
-    (cd build/armv7 && \
-     sh ../../configure $CONFIG_FLAGS CC="$CC" CXX="$CXX" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS") || exit 2
-     # configure is not yet fully ready for iOS, some manual patching is required
-     cp include/* build/armv7/include
-     cp include/SDL_config_iphoneos.h build/armv7/include/SDL_config.h || exit 2
-     sed -i "" -e "s|^EXTRA_CFLAGS.*|EXTRA_CFLAGS=-I./include|g" build/armv7/Makefile || exit 2
-     sed -i "" -e "s|^EXTRA_LDFLAGS.*|EXTRA_LDFLAGS=-lm|g" build/armv7/Makefile || exit 2
-fi
-if test x$make_armv7 = xyes; then
-    (cd build/armv7 && make -j$NJOB) || exit 3
-fi
-#
-# Build the i386 binary
-#
-prepare_environment "i386"
-if test x$configure_i386 = xyes; then
-    (cd build/i386 && \
-     sh ../../configure $CONFIG_FLAGS CC="$CC" CXX="$CXX" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS") || exit 2
-     # configure is not yet fully ready for iOS, some manual patching is required
-     cp include/* build/i386/include
-     cp include/SDL_config_iphoneos.h build/i386/include/SDL_config.h || exit 2
-     sed -i "" -e "s|^EXTRA_CFLAGS.*|EXTRA_CFLAGS=-I./include|g" build/i386/Makefile || exit 2
-     sed -i "" -e "s|^EXTRA_LDFLAGS.*|EXTRA_LDFLAGS=-lm|g" build/i386/Makefile || exit 2
-fi
-if test x$make_i386 = xyes; then
-    (cd build/i386 && make -j$NJOB) || exit 3
+CC=clang
+CXX=clang
+
+SILENCED_WARNINGS="-Wno-unused-local-typedef -Wno-unused-function"
+
+CFLAGS="${CLANG_VERBOSE} ${SILENCED_WARNINGS} -DNDEBUG -g -O0 -pipe -fPIC -fobjc-arc"
+
+echo "PREFIX ..................... ${PREFIX}"
+echo "BUILD_MACOSX_X86_64 ........ ${BUILD_MACOSX_X86_64}"
+echo "BUILD_I386_IOSSIM .......... ${BUILD_I386_IOSSIM}"
+echo "BUILD_X86_64_IOSSIM ........ ${BUILD_X86_64_IOSSIM}"
+echo "BUILD_IOS_ARMV7 ............ ${BUILD_IOS_ARMV7}"
+echo "BUILD_IOS_ARMV7S ........... ${BUILD_IOS_ARMV7S}"
+echo "BUILD_IOS_ARM64 ............ ${BUILD_IOS_ARM64}"
+echo "DARWIN ..................... ${DARWIN}"
+echo "XCODEDIR ................... ${XCODEDIR}"
+echo "IOS_SDK_VERSION ............ ${IOS_SDK_VERSION}"
+echo "MIN_SDK_VERSION ............ ${MIN_SDK_VERSION}"
+echo "IPHONEOS_PLATFORM .......... ${IPHONEOS_PLATFORM}"
+echo "IPHONEOS_SYSROOT ........... ${IPHONEOS_SYSROOT}"
+echo "IPHONESIMULATOR_PLATFORM ... ${IPHONESIMULATOR_PLATFORM}"
+echo "IPHONESIMULATOR_SYSROOT .... ${IPHONESIMULATOR_SYSROOT}"
+echo "CC ......................... ${CC}"
+echo "CFLAGS ..................... ${CFLAGS}"
+echo "CXX ........................ ${CXX}"
+echo "CXXFLAGS ................... ${CXXFLAGS}"
+echo "LDFLAGS .................... ${LDFLAGS}"
+
+###################################################################
+# This section contains the build commands for each of the 
+# architectures that will be included in the universal binaries.
+###################################################################
+
+echo "$(tput setaf 2)"
+echo "###########################"
+echo "# i386 for iPhone Simulator"
+echo "###########################"
+echo "$(tput sgr0)"
+
+if [ "${BUILD_I386_IOSSIM}" == "YES" ]
+then
+    (
+        cd ${PREFIX}
+        make clean
+        ../configure --build=x86_64-apple-${DARWIN} --host=i386-ios-${DARWIN} --disable-shared --prefix=${PREFIX}/platform/i386-sim "CC=${CC}" "CFLAGS=${CFLAGS} -mios-simulator-version-min=${MIN_SDK_VERSION} -arch i386 -isysroot ${IPHONESIMULATOR_SYSROOT}" "CXX=${CXX}" "CXXFLAGS=${CXXFLAGS} -mios-simulator-version-min=${MIN_SDK_VERSION} -arch i386 -isysroot ${IPHONESIMULATOR_SYSROOT}" LDFLAGS="-arch i386 -mios-simulator-version-min=${MIN_SDK_VERSION} ${LDFLAGS} -L${IPHONESIMULATOR_SYSROO [...]
+	cp $SRC_DIR/include/SDL_config_iphoneos.h include/SDL_config.h
+        make -j10 || exit 3
+        make install
+    ) || exit $?
 fi
 
-#
-# Combine into fat binary
-#
-if test x$merge = xyes; then
-    output=ios/lib
-    sh $auxdir/mkinstalldirs build/$output
-    cd build
-    target=`find . -mindepth 4 -maxdepth 4 -type f -name '*.dylib' | head -1 | sed 's|.*/||'`
-    (lipo -create -o $output/libSDL2.a armv6/build/.libs/libSDL2.a armv7/build/.libs/libSDL2.a i386/build/.libs/libSDL2.a &&
-     lipo -create -o $output/libSDL2main.a armv6/build/libSDL2main.a armv7/build/libSDL2main.a i386/build/libSDL2main.a &&
-     cp -r armv6/include ios
-     echo "Build complete!" &&
-     echo "Files can be found under the build/ios directory.") || exit 4
-    cd ..
+echo "$(tput setaf 2)"
+echo "#############################"
+echo "# x86_64 for iPhone Simulator"
+echo "#############################"
+echo "$(tput sgr0)"
+
+if [ "${BUILD_X86_64_IOSSIM}" == "YES" ]
+then
+    (
+        cd ${PREFIX}
+        make clean
+        ../configure --build=x86_64-apple-${DARWIN} --host=x86_64-ios-${DARWIN} --disable-shared --prefix=${PREFIX}/platform/x86_64-sim "CC=${CC}" "CFLAGS=${CFLAGS} -mios-simulator-version-min=${MIN_SDK_VERSION} -arch x86_64 -isysroot ${IPHONESIMULATOR_SYSROOT}" "CXX=${CXX}" "CXXFLAGS=${CXXFLAGS} -mios-simulator-version-min=${MIN_SDK_VERSION} -arch x86_64 -isysroot ${IPHONESIMULATOR_SYSROOT}" LDFLAGS="-arch x86_64 -mios-simulator-version-min=${MIN_SDK_VERSION} ${LDFLAGS} -L${IPHONESIMULA [...]
+	cp $SRC_DIR/include/SDL_config_iphoneos.h include/SDL_config.h
+        make -j$NJOB || exit 3
+        make install
+    ) || exit $?
 fi
 
-#
-# Clean up
-#
-do_clean()
-{
-    echo $*
-    $* || exit 6
-}
-if test x$clean_armv6 = xyes; then
-    do_clean rm -r build/armv6
+echo "$(tput setaf 2)"
+echo "##################"
+echo "# armv7 for iPhone"
+echo "##################"
+echo "$(tput sgr0)"
+
+if [ "${BUILD_IOS_ARMV7}" == "YES" ]
+then
+    (
+        cd ${PREFIX}
+        make clean
+        ../configure --build=x86_64-apple-${DARWIN} --host=armv7-ios-${DARWIN} --disable-shared --prefix=${PREFIX}/platform/armv7-ios "CC=${CC}" "CFLAGS=${CFLAGS} -miphoneos-version-min=${MIN_SDK_VERSION} -arch armv7 -isysroot ${IPHONEOS_SYSROOT}" "CXX=${CXX}" "CXXFLAGS=${CXXFLAGS} -arch armv7 -isysroot ${IPHONEOS_SYSROOT}" LDFLAGS="-arch armv7 -miphoneos-version-min=${MIN_SDK_VERSION} ${LDFLAGS}" || exit 2
+	cp $SRC_DIR/include/SDL_config_iphoneos.h include/SDL_config.h
+        make -j$NJOB || exit 3
+        make install
+    ) || exit $?
 fi
-if test x$clean_armv7 = xyes; then
-    do_clean rm -r build/armv7
+
+echo "$(tput setaf 2)"
+echo "###################"
+echo "# armv7s for iPhone"
+echo "###################"
+echo "$(tput sgr0)"
+
+if [ "${BUILD_IOS_ARMV7S}" == "YES" ]
+then
+    (
+        cd ${PREFIX}
+        make clean
+        ../configure --build=x86_64-apple-${DARWIN} --host=armv7s-ios-${DARWIN} --disable-shared --prefix=${PREFIX}/platform/armv7s-ios "CC=${CC}" "CFLAGS=${CFLAGS} -miphoneos-version-min=${MIN_SDK_VERSION} -arch armv7s -isysroot ${IPHONEOS_SYSROOT}" "CXX=${CXX}" "CXXFLAGS=${CXXFLAGS} -miphoneos-version-min=${MIN_SDK_VERSION} -arch armv7s -isysroot ${IPHONEOS_SYSROOT}" LDFLAGS="-arch armv7s -miphoneos-version-min=${MIN_SDK_VERSION} ${LDFLAGS}" || exit 2
+	cp $SRC_DIR/include/SDL_config_iphoneos.h include/SDL_config.h
+        make -j$NJOB || exit 3
+        make install
+    ) || exit $?
 fi
-if test x$clean_i386 = xyes; then
-    do_clean rm -r build/i386
+
+echo "$(tput setaf 2)"
+echo "##################"
+echo "# arm64 for iPhone"
+echo "##################"
+echo "$(tput sgr0)"
+
+if [ "${BUILD_IOS_ARM64}" == "YES" ]
+then
+    (
+        cd ${PREFIX}
+        make clean
+        ../configure --build=x86_64-apple-${DARWIN} --host=arm-ios-${DARWIN} --disable-shared --prefix=${PREFIX}/platform/arm64-ios "CC=${CC}" "CFLAGS=${CFLAGS} -miphoneos-version-min=${MIN_SDK_VERSION} -arch arm64 -isysroot ${IPHONEOS_SYSROOT}" "CXX=${CXX}" "CXXFLAGS=${CXXFLAGS} -miphoneos-version-min=${MIN_SDK_VERSION} -arch arm64 -isysroot ${IPHONEOS_SYSROOT}" LDFLAGS="-arch arm64 -miphoneos-version-min=${MIN_SDK_VERSION} ${LDFLAGS}" || exit 2
+	cp $SRC_DIR/include/SDL_config_iphoneos.h include/SDL_config.h
+        make -j$NJOB || exit 3
+        make install
+    ) || exit $?
 fi
+
+echo "$(tput setaf 2)"
+echo "###################################################################"
+echo "# Create Universal Libraries and Finalize the packaging"
+echo "###################################################################"
+echo "$(tput sgr0)"
+
+(
+    cd ${PREFIX}/platform
+    mkdir -p universal
+    lipo x86_64-sim/lib/libSDL2.a i386-sim/lib/libSDL2.a arm64-ios/lib/libSDL2.a armv7s-ios/lib/libSDL2.a armv7-ios/lib/libSDL2.a -create -output universal/libSDL2.a
+)
+
+(
+    cd ${PREFIX}
+    mkdir -p lib
+    cp -r platform/universal/* lib
+    #rm -rf platform
+    lipo -info lib/libSDL2.a
+)
+
+echo Done!
diff --git a/build-scripts/nacl-buildbot.sh b/build-scripts/nacl-buildbot.sh
index a72333b..73aae9e 100755
--- a/build-scripts/nacl-buildbot.sh
+++ b/build-scripts/nacl-buildbot.sh
@@ -3,7 +3,11 @@
 # This is the script buildbot.libsdl.org uses to cross-compile SDL2 from
 #  amd64 Linux to NaCl.
 
-export NACL_SDK_ROOT="/nacl_sdk/pepper_35"
+# PLEASE NOTE that we have reports that SDL built with pepper_49 (current
+#  stable release as of November 10th, 2016) is broken. Please retest
+#  when something newer becomes stable and then decide if this was SDL's
+#  bug or NaCl's bug.  --ryan.
+export NACL_SDK_ROOT="/nacl_sdk/pepper_47"
 
 TARBALL="$1"
 if [ -z $1 ]; then
diff --git a/build-scripts/update-copyright.sh b/build-scripts/update-copyright.sh
index 34864bc..5955b09 100755
--- a/build-scripts/update-copyright.sh
+++ b/build-scripts/update-copyright.sh
@@ -2,8 +2,7 @@
 
 find . -type f -exec grep -Il "Copyright" {} \;     \
 | grep -v \.hg                             \
-| while read i;                            \
+| while read file;                            \
 do \
-  LC_ALL=C sed -ie "s/\(.*Copyright.*\)[0-9]\{4\}\( *Sam Lantinga\)/\1`date +%Y`\2/" "$i"; \
-  rm "${i}e"; \
+  LC_ALL=C sed -b -i "s/\(.*Copyright.*\)[0-9]\{4\}\( *Sam Lantinga\)/\1`date +%Y`\2/" "$file"; \
 done
diff --git a/build-scripts/windows-buildbot-zipper.bat b/build-scripts/windows-buildbot-zipper.bat
index 5a1e40a..a6f5169 100644
--- a/build-scripts/windows-buildbot-zipper.bat
+++ b/build-scripts/windows-buildbot-zipper.bat
@@ -3,11 +3,16 @@ rem just a helper batch file for collecting up files and zipping them.
 rem usage: windows-buildbot-zipper.bat <zipfilename>
 rem must be run from root of SDL source tree.
 
-IF EXIST VisualC\Win32\Release GOTO okaydir
+IF EXIST VisualC\Win32\Release GOTO okaywin32dir
 echo Please run from root of source tree after doing a Release build.
 GOTO done
 
-:okaydir
+:okaywin32dir
+IF EXIST VisualC\x64\Release GOTO okaydirs
+echo Please run from root of source tree after doing a Release build.
+GOTO done
+
+:okaydirs
 erase /q /f /s zipper
 IF EXIST zipper GOTO zippermade
 mkdir zipper
@@ -18,10 +23,14 @@ cd SDL
 mkdir include
 mkdir lib
 mkdir lib\win32
+mkdir lib\win64
 copy ..\..\include\*.h include\
 copy ..\..\VisualC\Win32\Release\SDL2.dll lib\win32\
 copy ..\..\VisualC\Win32\Release\SDL2.lib lib\win32\
 copy ..\..\VisualC\Win32\Release\SDL2main.lib lib\win32\
+copy ..\..\VisualC\x64\Release\SDL2.dll lib\win64\
+copy ..\..\VisualC\x64\Release\SDL2.lib lib\win64\
+copy ..\..\VisualC\x64\Release\SDL2main.lib lib\win64\
 cd ..
 zip -9r ..\%1 SDL
 cd ..
diff --git a/build-scripts/winrtbuild.ps1 b/build-scripts/winrtbuild.ps1
index 31ac504..1fdd58a 100644
--- a/build-scripts/winrtbuild.ps1
+++ b/build-scripts/winrtbuild.ps1
@@ -220,9 +220,15 @@ if ( ! (Build-SDL-WinRT-Variant "SDL" "v120_wp81" "ARM"))   { $DidAnyDLLBuildFai
 if ( ! (Build-SDL-WinRT-Variant "SDL" "v120_wp81" "Win32")) { $DidAnyDLLBuildFail = $true }
 
 # Build for Windows 8.0 and Windows RT 8.0, via VC++ 2012:
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "ARM"))        { $DidAnyDLLBuildFail = $true }
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "Win32"))      { $DidAnyDLLBuildFail = $true }
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "x64"))        { $DidAnyDLLBuildFail = $true }
+#
+# Win 8.0 auto-building was disabled on 2017-Feb-25, by David Ludwig <dludwig at pobox.com>.
+# Steam's OS-usage surveys indicate that Windows 8.0 use is pretty much nil, plus
+# Microsoft hasn't supported Windows 8.0 development for a few years now.
+# The commented-out lines below may still work on some systems, though.
+# 
+#if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "ARM"))        { $DidAnyDLLBuildFail = $true }
+#if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "Win32"))      { $DidAnyDLLBuildFail = $true }
+#if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "x64"))        { $DidAnyDLLBuildFail = $true }
 
 # Build for Windows 8.1 and Windows RT 8.1, via VC++ 2013:
 if ( ! (Build-SDL-WinRT-Variant "SDL" "v120" "ARM"))        { $DidAnyDLLBuildFail = $true }
diff --git a/cmake/sdlchecks.cmake b/cmake/sdlchecks.cmake
index b100781..e2e89a2 100644
--- a/cmake/sdlchecks.cmake
+++ b/cmake/sdlchecks.cmake
@@ -161,6 +161,36 @@ endmacro()
 # Requires:
 # - PkgCheckModules
 # Optional:
+# - JACK_SHARED opt
+# - HAVE_DLOPEN opt
+macro(CheckJACK)
+  if(JACK)
+    pkg_check_modules(PKG_JACK jack)
+    if(PKG_JACK_FOUND)
+      set(HAVE_JACK TRUE)
+      file(GLOB JACK_SOURCES ${SDL2_SOURCE_DIR}/src/audio/jack/*.c)
+      set(SOURCE_FILES ${SOURCE_FILES} ${JACK_SOURCES})
+      set(SDL_AUDIO_DRIVER_JACK 1)
+      list(APPEND EXTRA_CFLAGS ${PKG_JACK_CFLAGS})
+      if(JACK_SHARED)
+        if(NOT HAVE_DLOPEN)
+          message_warn("You must have SDL_LoadObject() support for dynamic JACK audio loading")
+        else()
+          FindLibraryAndSONAME("jack")
+          set(SDL_AUDIO_DRIVER_JACK_DYNAMIC "\"${JACK_LIB_SONAME}\"")
+          set(HAVE_JACK_SHARED TRUE)
+        endif()
+      else()
+        list(APPEND EXTRA_LDFLAGS ${PKG_JACK_LDFLAGS})
+      endif()
+      set(HAVE_SDL_AUDIO TRUE)
+    endif()
+  endif()
+endmacro()
+
+# Requires:
+# - PkgCheckModules
+# Optional:
 # - ESD_SHARED opt
 # - HAVE_DLOPEN opt
 macro(CheckESD)
@@ -316,6 +346,29 @@ macro(CheckFusionSound)
 endmacro()
 
 # Requires:
+# - LIBSAMPLERATE
+# Optional:
+# - LIBSAMPLERATE_SHARED opt
+# - HAVE_DLOPEN opt
+macro(CheckLibSampleRate)
+  if(LIBSAMPLERATE)
+    check_include_file(samplerate.h HAVE_LIBSAMPLERATE_H)
+    if(HAVE_LIBSAMPLERATE_H)
+      if(LIBSAMPLERATE_SHARED)
+        if(NOT HAVE_DLOPEN)
+          message_warn("You must have SDL_LoadObject() support for dynamic libsamplerate loading")
+        else()
+          FindLibraryAndSONAME("samplerate")
+          set(SDL_LIBSAMPLERATE_DYNAMIC "\"${SAMPLERATE_LIB_SONAME}\"")
+        endif()
+      else()
+        list(APPEND EXTRA_LDFLAGS -lsamplerate)
+      endif()
+    endif()
+  endif()
+endmacro()
+
+# Requires:
 # - n/a
 # Optional:
 # - X11_SHARED opt
@@ -508,7 +561,7 @@ endmacro()
 macro(CheckMir)
     if(VIDEO_MIR)
         find_library(MIR_LIB mirclient mircommon egl)
-        pkg_check_modules(MIR_TOOLKIT mirclient mircommon)
+        pkg_check_modules(MIR_TOOLKIT mirclient>=0.26 mircommon)
         pkg_check_modules(EGL egl)
         pkg_check_modules(XKB xkbcommon)
 
@@ -520,7 +573,7 @@ macro(CheckMir)
             set(SOURCE_FILES ${SOURCE_FILES} ${MIR_SOURCES})
             set(SDL_VIDEO_DRIVER_MIR 1)
 
-            list(APPEND EXTRA_CFLAGS ${MIR_TOOLKIT_CFLAGS} ${EGL_CLFAGS} ${XKB_CLFLAGS})
+            list(APPEND EXTRA_CFLAGS ${MIR_TOOLKIT_CFLAGS} ${EGL_CFLAGS} ${XKB_CFLAGS})
 
             if(MIR_SHARED)
                 if(NOT HAVE_DLOPEN)
@@ -803,7 +856,10 @@ endmacro()
 # PTHREAD_LIBS
 macro(CheckPTHREAD)
   if(PTHREADS)
-    if(LINUX)
+    if(ANDROID)
+      # the android libc provides built-in support for pthreads, so no
+      # additional linking or compile flags are necessary
+    elseif(LINUX)
       set(PTHREAD_CFLAGS "-D_REENTRANT")
       set(PTHREAD_LDFLAGS "-pthread")
     elseif(BSDI)
@@ -878,7 +934,7 @@ macro(CheckPTHREAD)
             #include <pthread.h>
             int main(int argc, char **argv) {
               pthread_mutexattr_t attr;
-              pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
+              pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
               return 0;
             }" HAVE_RECURSIVE_MUTEXES_NP)
         if(HAVE_RECURSIVE_MUTEXES_NP)
@@ -907,7 +963,6 @@ macro(CheckPTHREAD)
           int main(int argc, char** argv) { return 0; }" HAVE_PTHREAD_NP_H)
       check_function_exists(pthread_setname_np HAVE_PTHREAD_SETNAME_NP)
       check_function_exists(pthread_set_name_np HAVE_PTHREAD_SET_NAME_NP)
-      set(CMAKE_REQUIRED_FLAGS "${ORIG_CMAKE_REQUIRED_FLAGS}")
 
       set(SOURCE_FILES ${SOURCE_FILES}
           ${SDL2_SOURCE_DIR}/src/thread/pthread/SDL_systhread.c
@@ -924,6 +979,7 @@ macro(CheckPTHREAD)
       endif()
       set(HAVE_SDL_THREADS TRUE)
     endif()
+    set(CMAKE_REQUIRED_FLAGS "${ORIG_CMAKE_REQUIRED_FLAGS}")
   endif()
 endmacro()
 
@@ -1096,3 +1152,46 @@ macro(CheckRPI)
     endif(SDL_VIDEO AND HAVE_VIDEO_RPI)
   endif(VIDEO_RPI)
 endmacro(CheckRPI)
+
+# Requires:
+# - EGL
+# - PkgCheckModules
+# Optional:
+# - KMSDRM_SHARED opt
+# - HAVE_DLOPEN opt
+macro(CheckKMSDRM)
+  if(VIDEO_KMSDRM)
+    pkg_check_modules(KMSDRM libdrm gbm egl)
+    if(KMSDRM_FOUND)
+      link_directories(
+        ${KMSDRM_LIBRARY_DIRS}
+      )
+      include_directories(
+        ${KMSDRM_INCLUDE_DIRS}
+      )
+      set(HAVE_VIDEO_KMSDRM TRUE)
+      set(HAVE_SDL_VIDEO TRUE)
+
+      file(GLOB KMSDRM_SOURCES ${SDL2_SOURCE_DIR}/src/video/kmsdrm/*.c)
+      set(SOURCE_FILES ${SOURCE_FILES} ${KMSDRM_SOURCES})
+
+      list(APPEND EXTRA_CFLAGS ${KMSDRM_CFLAGS})
+
+      set(SDL_VIDEO_DRIVER_KMSDRM 1)
+
+      if(KMSDRM_SHARED)
+        if(NOT HAVE_DLOPEN)
+          message_warn("You must have SDL_LoadObject() support for dynamic KMS/DRM loading")
+        else()
+          FindLibraryAndSONAME(drm)
+          FindLibraryAndSONAME(gbm)
+          set(SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC "\"${DRM_LIB_SONAME}\"")
+          set(SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM "\"${GBM_LIB_SONAME}\"")
+          set(HAVE_KMSDRM_SHARED TRUE)
+        endif()
+      else()
+        set(EXTRA_LIBS ${KMSDRM_LIBRARIES} ${EXTRA_LIBS})
+      endif()
+    endif()
+  endif()
+endmacro()
diff --git a/configure b/configure
index 5070f6e..14623c8 100755
--- a/configure
+++ b/configure
@@ -658,10 +658,10 @@ X_PRE_LIBS
 X_CFLAGS
 XMKMF
 ARTSCONFIG
-PKG_CONFIG
 ESD_LIBS
 ESD_CFLAGS
 ESD_CONFIG
+PKG_CONFIG
 ALSA_LIBS
 ALSA_CFLAGS
 POW_LIB
@@ -798,6 +798,7 @@ enable_mmx
 enable_3dnow
 enable_sse
 enable_sse2
+enable_sse3
 enable_altivec
 enable_oss
 enable_alsa
@@ -805,6 +806,8 @@ with_alsa_prefix
 with_alsa_inc_prefix
 enable_alsatest
 enable_alsa_shared
+enable_jack
+enable_jack_shared
 enable_esd
 with_esd_prefix
 with_esd_exec_prefix
@@ -818,13 +821,18 @@ enable_nas
 enable_nas_shared
 enable_sndio
 enable_sndio_shared
+enable_fusionsound
+enable_fusionsound_shared
 enable_diskaudio
 enable_dummyaudio
+enable_libsamplerate
+enable_libsamplerate_shared
 enable_video_wayland
 enable_video_wayland_qt_touch
 enable_wayland_shared
 enable_video_mir
 enable_mir_shared
+enable_video_rpi
 enable_video_x11
 with_x
 enable_x11_shared
@@ -840,13 +848,14 @@ enable_video_vivante
 enable_video_cocoa
 enable_video_directfb
 enable_directfb_shared
-enable_fusionsound
-enable_fusionsound_shared
+enable_video_kmsdrm
+enable_kmsdrm_shared
 enable_video_dummy
 enable_video_opengl
 enable_video_opengles
 enable_video_opengles1
 enable_video_opengles2
+enable_video_vulkan
 enable_libudev
 enable_dbus
 enable_ime
@@ -1521,16 +1530,19 @@ Optional Features:
   --enable-cpuinfo        Enable the cpuinfo subsystem [[default=yes]]
   --enable-assembly       Enable assembly routines [[default=yes]]
   --enable-ssemath        Allow GCC to use SSE floating point math
-                          [[default=no]]
+                          [[default=maybe]]
   --enable-mmx            use MMX assembly routines [[default=yes]]
   --enable-3dnow          use 3DNow! assembly routines [[default=yes]]
   --enable-sse            use SSE assembly routines [[default=yes]]
-  --enable-sse2           use SSE2 assembly routines [[default=no]]
+  --enable-sse2           use SSE2 assembly routines [[default=maybe]]
+  --enable-sse3           use SSE3 assembly routines [[default=maybe]]
   --enable-altivec        use Altivec assembly routines [[default=yes]]
   --enable-oss            support the OSS audio API [[default=maybe]]
   --enable-alsa           support the ALSA audio API [[default=yes]]
   --disable-alsatest      Do not try to compile and run a test Alsa program
   --enable-alsa-shared    dynamically load ALSA audio support [[default=yes]]
+  --enable-jack           use JACK audio [[default=yes]]
+  --enable-jack-shared    dynamically load JACK audio support [[default=yes]]
   --enable-esd            support the Enlightened Sound Daemon [[default=yes]]
   --disable-esdtest       Do not try to compile and run a test ESD program
   --enable-esd-shared     dynamically load ESD audio support [[default=yes]]
@@ -1544,8 +1556,16 @@ Optional Features:
   --enable-nas-shared     dynamically load NAS audio support [[default=yes]]
   --enable-sndio          support the sndio audio API [[default=yes]]
   --enable-sndio-shared   dynamically load sndio audio support [[default=yes]]
+  --enable-fusionsound    use FusionSound audio driver [[default=no]]
+  --enable-fusionsound-shared
+                          dynamically load fusionsound audio support
+                          [[default=yes]]
   --enable-diskaudio      support the disk writer audio driver [[default=yes]]
   --enable-dummyaudio     support the dummy audio driver [[default=yes]]
+  --enable-libsamplerate  use libsamplerate for audio rate conversion
+                          [[default=yes]]
+  --enable-libsamplerate-shared
+                          dynamically load libsamplerate [[default=yes]]
   --enable-video-wayland  use Wayland video driver [[default=yes]]
   --enable-video-wayland-qt-touch
                           QtWayland server support for Wayland video driver
@@ -1553,6 +1573,7 @@ Optional Features:
   --enable-wayland-shared dynamically load Wayland support [[default=maybe]]
   --enable-video-mir      use Mir video driver [[default=yes]]
   --enable-mir-shared     dynamically load Mir support [[default=maybe]]
+  --enable-video-rpi      use Raspberry Pi video driver [[default=yes]]
   --enable-video-x11      use X11 video driver [[default=yes]]
   --enable-x11-shared     dynamically load X11 support [[default=maybe]]
   --enable-video-x11-xcursor
@@ -1576,10 +1597,8 @@ Optional Features:
   --enable-video-directfb use DirectFB video driver [[default=no]]
   --enable-directfb-shared
                           dynamically load directfb support [[default=yes]]
-  --enable-fusionsound    use FusionSound audio driver [[default=no]]
-  --enable-fusionsound-shared
-                          dynamically load fusionsound audio support
-                          [[default=yes]]
+  --enable-video-kmsdrm   use KMSDRM video driver [[default=no]]
+  --enable-kmsdrm-shared  dynamically load kmsdrm support [[default=yes]]
   --enable-video-dummy    use dummy video driver [[default=yes]]
   --enable-video-opengl   include OpenGL support [[default=yes]]
   --enable-video-opengles include OpenGL ES support [[default=yes]]
@@ -1587,6 +1606,7 @@ Optional Features:
                           include OpenGL ES 1.1 support [[default=yes]]
   --enable-video-opengles2
                           include OpenGL ES 2.0 support [[default=yes]]
+  --enable-video-vulkan   include Vulkan support [[default=yes]]
   --enable-libudev        enable libudev support [[default=yes]]
   --enable-dbus           enable D-Bus support [[default=yes]]
   --enable-ime            enable IME support [[default=yes]]
@@ -2690,9 +2710,9 @@ orig_CFLAGS="$CFLAGS"
 #
 SDL_MAJOR_VERSION=2
 SDL_MINOR_VERSION=0
-SDL_MICRO_VERSION=5
-SDL_INTERFACE_AGE=1
-SDL_BINARY_AGE=5
+SDL_MICRO_VERSION=6
+SDL_INTERFACE_AGE=0
+SDL_BINARY_AGE=6
 SDL_VERSION=$SDL_MAJOR_VERSION.$SDL_MINOR_VERSION.$SDL_MICRO_VERSION
 
 
@@ -5977,7 +5997,10 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
 	  x86_64-*linux*)
 	    LD="${LD-ld} -m elf_x86_64"
 	    ;;
-	  ppc*-*linux*|powerpc*-*linux*)
+	  powerpc64le-*linux*)
+	    LD="${LD-ld} -m elf64lppc"
+	    ;;
+	  powerpc64-*linux*)
 	    LD="${LD-ld} -m elf64ppc"
 	    ;;
 	  s390*-*linux*|s390*-*tpf*)
@@ -15656,7 +15679,7 @@ case "$host" in
         ;;
 esac
 
-INCLUDE="-I$srcdir/include"
+INCLUDE="-I$srcdir/include -idirafter $srcdir/src/video/khronos"
 if test x$srcdir != x.; then
     INCLUDE="-Iinclude $INCLUDE"
 elif test -d .hg; then
@@ -16148,7 +16171,7 @@ $as_echo "#define STDC_HEADERS 1" >>confdefs.h
 
 fi
 
-    for ac_header in sys/types.h stdio.h stdlib.h stddef.h stdarg.h malloc.h memory.h string.h strings.h inttypes.h stdint.h ctype.h math.h iconv.h signal.h
+    for ac_header in sys/types.h stdio.h stdlib.h stddef.h stdarg.h malloc.h memory.h string.h strings.h wchar.h inttypes.h stdint.h limits.h ctype.h math.h float.h iconv.h signal.h
 do :
   as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
 ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"
@@ -16612,7 +16635,7 @@ fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 
-    for ac_func in malloc calloc realloc free getenv setenv putenv unsetenv qsort abs bcopy memset memcpy memmove strlen strlcpy strlcat strdup _strrev _strupr _strlwr strchr strrchr strstr itoa _ltoa _uitoa _ultoa strtol strtoul _i64toa _ui64toa strtoll strtoull atoi atof strcmp strncmp _stricmp strcasecmp _strnicmp strncasecmp vsscanf vsnprintf fseeko fseeko64 sigaction setjmp nanosleep sysconf sysctlbyname
+    for ac_func in malloc calloc realloc free getenv setenv putenv unsetenv qsort abs bcopy memset memcpy memmove wcslen wcscmp strlen strlcpy strlcat strdup _strrev _strupr _strlwr strchr strrchr strstr itoa _ltoa _uitoa _ultoa strtol strtoul _i64toa _ui64toa strtoll strtoull atoi atof strcmp strncmp _stricmp strcasecmp _strnicmp strncasecmp vsscanf vsnprintf fopen64 fseeko fseeko64 sigaction setjmp nanosleep sysconf sysctlbyname getauxval poll
 do :
   as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
 ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
@@ -16733,7 +16756,8 @@ done
     ac_fn_c_check_member "$LINENO" "struct sigaction" "sa_sigaction" "ac_cv_member_struct_sigaction_sa_sigaction" "#include <signal.h>
 "
 if test "x$ac_cv_member_struct_sigaction_sa_sigaction" = xyes; then :
-  $as_echo "#define HAVE_SA_SIGACTION 1" >>confdefs.h
+
+$as_echo "#define HAVE_SA_SIGACTION 1" >>confdefs.h
 
 fi
 
@@ -17072,7 +17096,7 @@ else
 fi
 
     if test x$enable_ssemath = xno; then
-        if test x$have_gcc_sse = xyes -o x$have_gcc_sse2 = xyes; then
+        if test x$have_gcc_sse = xyes -o x$have_gcc_sse2 = xyes -o x$have_gcc_sse3 = xyes; then
             EXTRA_CFLAGS="$EXTRA_CFLAGS -mfpmath=387"
         fi
     fi
@@ -17299,6 +17323,63 @@ $as_echo "$have_gcc_sse2" >&6; }
         fi
     fi
 
+    # Check whether --enable-sse3 was given.
+if test "${enable_sse3+set}" = set; then :
+  enableval=$enable_sse3;
+else
+  enable_sse3=$default_ssemath
+fi
+
+    if test x$enable_sse3 = xyes; then
+        save_CFLAGS="$CFLAGS"
+        have_gcc_sse3=no
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GCC -msse3 option" >&5
+$as_echo_n "checking for GCC -msse3 option... " >&6; }
+        sse3_CFLAGS="-msse3"
+        CFLAGS="$save_CFLAGS $sse3_CFLAGS"
+
+        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+        #ifdef __MINGW32__
+        #include <_mingw.h>
+        #ifdef __MINGW64_VERSION_MAJOR
+        #include <intrin.h>
+        #else
+        #include <pmmintrin.h>
+        #endif
+        #else
+        #include <pmmintrin.h>
+        #endif
+        #ifndef __SSE2__
+        #error Assembler CPP flag not enabled
+        #endif
+
+int
+main ()
+{
+
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+        have_gcc_sse3=yes
+
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_gcc_sse3" >&5
+$as_echo "$have_gcc_sse3" >&6; }
+        CFLAGS="$save_CFLAGS"
+
+        if test x$have_gcc_sse3 = xyes; then
+            EXTRA_CFLAGS="$EXTRA_CFLAGS $sse3_CFLAGS"
+            SUMMARY_math="${SUMMARY_math} sse3"
+        fi
+    fi
+
     # Check whether --enable-altivec was given.
 if test "${enable_altivec+set}" = set; then :
   enableval=$enable_altivec;
@@ -17801,6 +17882,119 @@ _ACEOF
     fi
 }
 
+CheckJACK()
+{
+    # Check whether --enable-jack was given.
+if test "${enable_jack+set}" = set; then :
+  enableval=$enable_jack;
+else
+  enable_jack=yes
+fi
+
+    if test x$enable_audio = xyes -a x$enable_jack = xyes; then
+        audio_jack=no
+
+        JACK_REQUIRED_VERSION=0.125
+
+        # Extract the first word of "pkg-config", so it can be a program name with args.
+set dummy pkg-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_PKG_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $PKG_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_path_PKG_CONFIG" && ac_cv_path_PKG_CONFIG="no"
+  ;;
+esac
+fi
+PKG_CONFIG=$ac_cv_path_PKG_CONFIG
+if test -n "$PKG_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5
+$as_echo "$PKG_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JACK $JACK_REQUIRED_VERSION support" >&5
+$as_echo_n "checking for JACK $JACK_REQUIRED_VERSION support... " >&6; }
+        if test x$PKG_CONFIG != xno; then
+        if $PKG_CONFIG --atleast-pkgconfig-version 0.7 && $PKG_CONFIG --atleast-version $JACK_REQUIRED_VERSION jack; then
+                JACK_CFLAGS=`$PKG_CONFIG --cflags jack`
+                JACK_LIBS=`$PKG_CONFIG --libs jack`
+                audio_jack=yes
+            fi
+        fi
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $audio_jack" >&5
+$as_echo "$audio_jack" >&6; }
+
+        if test x$audio_jack = xyes; then
+            # Check whether --enable-jack-shared was given.
+if test "${enable_jack_shared+set}" = set; then :
+  enableval=$enable_jack_shared;
+else
+  enable_jack_shared=yes
+fi
+
+            jack_lib=`find_lib "libjack.so.*" "$JACK_LIBS" | sed 's/.*\/\(.*\)/\1/; q'`
+
+
+$as_echo "#define SDL_AUDIO_DRIVER_JACK 1" >>confdefs.h
+
+            SOURCES="$SOURCES $srcdir/src/audio/jack/*.c"
+            EXTRA_CFLAGS="$EXTRA_CFLAGS $JACK_CFLAGS"
+            if test x$have_loadso != xyes && \
+               test x$enable_jack_shared = xyes; then
+                { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You must have SDL_LoadObject() support for dynamic JACK audio loading" >&5
+$as_echo "$as_me: WARNING: You must have SDL_LoadObject() support for dynamic JACK audio loading" >&2;}
+            fi
+            if test x$have_loadso = xyes && \
+               test x$enable_jack_shared = xyes && test x$jack_lib != x; then
+                echo "-- dynamic libjack -> $jack_lib"
+
+cat >>confdefs.h <<_ACEOF
+#define SDL_AUDIO_DRIVER_JACK_DYNAMIC "$jack_lib"
+_ACEOF
+
+                SUMMARY_audio="${SUMMARY_audio} jack(dynamic)"
+
+                case "$host" in
+                    # On Solaris, jack must be linked deferred explicitly
+                    # to prevent undefined symbol failures.
+                    *-*-solaris*)
+                        JACK_LIBS=`echo $JACK_LIBS | sed 's/\-l/-Wl,-l/g'`
+                        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-zdeferred $JACK_LIBS -Wl,-znodeferred"
+                esac
+            else
+                EXTRA_LDFLAGS="$EXTRA_LDFLAGS $JACK_LIBS"
+                SUMMARY_audio="${SUMMARY_audio} jack"
+            fi
+            have_audio=yes
+        fi
+    fi
+}
+
 CheckESD()
 {
     # Check whether --enable-esd was given.
@@ -18544,6 +18738,116 @@ $as_echo "#define SDL_AUDIO_DRIVER_SNDIO 1" >>confdefs.h
     fi
 }
 
+CheckFusionSound()
+{
+    # Check whether --enable-fusionsound was given.
+if test "${enable_fusionsound+set}" = set; then :
+  enableval=$enable_fusionsound;
+else
+  enable_fusionsound=no
+fi
+
+    if test x$enable_audio = xyes -a x$enable_fusionsound = xyes; then
+        fusionsound=no
+
+        FUSIONSOUND_REQUIRED_VERSION=1.1.1
+
+        # Extract the first word of "pkg-config", so it can be a program name with args.
+set dummy pkg-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_PKG_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $PKG_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_path_PKG_CONFIG" && ac_cv_path_PKG_CONFIG="no"
+  ;;
+esac
+fi
+PKG_CONFIG=$ac_cv_path_PKG_CONFIG
+if test -n "$PKG_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5
+$as_echo "$PKG_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for FusionSound $FUSIONSOUND_REQUIRED_VERSION support" >&5
+$as_echo_n "checking for FusionSound $FUSIONSOUND_REQUIRED_VERSION support... " >&6; }
+        if test x$PKG_CONFIG != xno; then
+            if $PKG_CONFIG --atleast-pkgconfig-version 0.7 && $PKG_CONFIG --atleast-version $FUSIONSOUND_REQUIRED_VERSION fusionsound; then
+                FUSIONSOUND_CFLAGS=`$PKG_CONFIG --cflags fusionsound`
+                FUSIONSOUND_LIBS=`$PKG_CONFIG --libs fusionsound`
+                fusionsound=yes
+            fi
+        fi
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fusionsound" >&5
+$as_echo "$fusionsound" >&6; }
+
+        if test x$fusionsound = xyes; then
+
+$as_echo "#define SDL_AUDIO_DRIVER_FUSIONSOUND 1" >>confdefs.h
+
+            SOURCES="$SOURCES $srcdir/src/audio/fusionsound/*.c"
+            EXTRA_CFLAGS="$EXTRA_CFLAGS $FUSIONSOUND_CFLAGS"
+
+            # Check whether --enable-fusionsound-shared was given.
+if test "${enable_fusionsound_shared+set}" = set; then :
+  enableval=$enable_fusionsound_shared;
+else
+  enable_fusionsound_shared=yes
+fi
+
+            fusionsound_shared=no
+            { $as_echo "$as_me:${as_lineno-$LINENO}: checking for FusionSound dynamic loading support" >&5
+$as_echo_n "checking for FusionSound dynamic loading support... " >&6; }
+            if test x$have_loadso != xyes && \
+               test x$enable_fusionsound_shared = xyes; then
+                { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You must have SDL_LoadObject() support for dynamic fusionsound loading" >&5
+$as_echo "$as_me: WARNING: You must have SDL_LoadObject() support for dynamic fusionsound loading" >&2;}
+            fi
+            if test x$have_loadso = xyes && \
+               test x$enable_fusionsound_shared = xyes; then
+
+cat >>confdefs.h <<_ACEOF
+#define SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC "libfusionsound.so"
+_ACEOF
+
+                fusionsound_shared=yes
+                SUMMARY_audio="${SUMMARY_audio} fusionsound(dynamic)"
+            else
+                EXTRA_LDFLAGS="$EXTRA_LDFLAGS $FUSIONSOUND_LIBS"
+                SUMMARY_audio="${SUMMARY_audio} fusionsound"
+            fi
+            { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fusionsound_shared" >&5
+$as_echo "$fusionsound_shared" >&6; }
+
+            have_audio=yes
+        fi
+    fi
+}
+
 CheckDiskAudio()
 {
     # Check whether --enable-diskaudio was given.
@@ -18580,19 +18884,72 @@ $as_echo "#define SDL_AUDIO_DRIVER_DUMMY 1" >>confdefs.h
     fi
 }
 
-CheckVisibilityHidden()
+CheckLibSampleRate()
 {
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GCC -fvisibility=hidden option" >&5
-$as_echo_n "checking for GCC -fvisibility=hidden option... " >&6; }
-    have_gcc_fvisibility=no
+    # Check whether --enable-libsamplerate was given.
+if test "${enable_libsamplerate+set}" = set; then :
+  enableval=$enable_libsamplerate;
+else
+  enable_libsamplerate=yes
+fi
 
-    visibility_CFLAGS="-fvisibility=hidden"
-    save_CFLAGS="$CFLAGS"
-    CFLAGS="$save_CFLAGS $visibility_CFLAGS -Werror"
-    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
+    if test x$enable_libsamplerate = xyes; then
+        ac_fn_c_check_header_mongrel "$LINENO" "samplerate.h" "ac_cv_header_samplerate_h" "$ac_includes_default"
+if test "x$ac_cv_header_samplerate_h" = xyes; then :
+  have_samplerate_h_hdr=yes
+else
+  have_samplerate_h_hdr=no
+fi
 
-    #if !defined(__GNUC__) || __GNUC__ < 4
+
+        if test x$have_samplerate_h_hdr = xyes; then
+
+$as_echo "#define HAVE_LIBSAMPLERATE_H 1" >>confdefs.h
+
+
+            # Check whether --enable-libsamplerate-shared was given.
+if test "${enable_libsamplerate_shared+set}" = set; then :
+  enableval=$enable_libsamplerate_shared;
+else
+  enable_libsamplerate_shared=yes
+fi
+
+
+            samplerate_lib=`find_lib "libsamplerate.so.*" "" | sed 's/.*\/\(.*\)/\1/; q'`
+
+            if test x$have_loadso != xyes && \
+               test x$enable_libsamplerate_shared = xyes; then
+                { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You must have SDL_LoadObject() support for dynamic libsamplerate loading" >&5
+$as_echo "$as_me: WARNING: You must have SDL_LoadObject() support for dynamic libsamplerate loading" >&2;}
+            fi
+            if test x$have_loadso = xyes && \
+               test x$enable_libsamplerate_shared = xyes && test x$samplerate_lib != x; then
+                echo "-- dynamic libsamplerate -> $samplerate_lib"
+
+cat >>confdefs.h <<_ACEOF
+#define SDL_LIBSAMPLERATE_DYNAMIC "$samplerate_lib"
+_ACEOF
+
+            else
+                EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lsamplerate"
+            fi
+        fi
+    fi
+}
+
+CheckVisibilityHidden()
+{
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GCC -fvisibility=hidden option" >&5
+$as_echo_n "checking for GCC -fvisibility=hidden option... " >&6; }
+    have_gcc_fvisibility=no
+
+    visibility_CFLAGS="-fvisibility=hidden"
+    save_CFLAGS="$CFLAGS"
+    CFLAGS="$save_CFLAGS $visibility_CFLAGS -Werror"
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+    #if !defined(__GNUC__) || __GNUC__ < 4
     #error SDL only uses visibility attributes in GCC 4 or newer
     #endif
 
@@ -18978,7 +19335,7 @@ int
 main ()
 {
 
-                    MirTouchAction actions = mir_touch_actions
+                    MirWindowAttrib attrib = mir_window_attrib_state
 
   ;
   return 0;
@@ -19073,9 +19430,11 @@ main ()
 _ACEOF
 if ac_fn_c_try_compile "$LINENO"; then :
 
-        $as_echo "#define SDL_VIDEO_DRIVER_NACL 1" >>confdefs.h
 
-        $as_echo "#define SDL_AUDIO_DRIVER_NACL 1" >>confdefs.h
+$as_echo "#define SDL_VIDEO_DRIVER_NACL 1" >>confdefs.h
+
+
+$as_echo "#define SDL_AUDIO_DRIVER_NACL 1" >>confdefs.h
 
 
 $as_echo "#define HAVE_POW 1" >>confdefs.h
@@ -19103,10 +19462,77 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 }
 
 
-CheckX11()
+CheckRPI()
+{
+    # Check whether --enable-video-rpi was given.
+if test "${enable_video_rpi+set}" = set; then :
+  enableval=$enable_video_rpi;
+else
+  enable_video_rpi=yes
+fi
+
+    if test x$enable_video = xyes -a x$enable_video_rpi = xyes; then
+        if test x$ARCH = xnetbsd; then
+            RPI_CFLAGS="-I/usr/pkg/include -I/usr/pkg/include/interface/vcos/pthreads -I/usr/pkg/include/interface/vmcs_host/linux"
+            RPI_LDFLAGS="-Wl,-R/usr/pkg/lib -L/usr/pkg/lib -lbcm_host"
+        else
+            RPI_CFLAGS="-I/opt/vc/include -I/opt/vc/include/interface/vcos/pthreads -I/opt/vc/include/interface/vmcs_host/linux"
+            RPI_LDFLAGS="-L/opt/vc/lib -lbcm_host"
+        fi
+
+        # Save the original compiler flags and libraries
+        ac_save_cflags="$CFLAGS"; ac_save_libs="$LIBS"
+
+        # Add the Raspberry Pi compiler flags and libraries
+        CFLAGS="$CFLAGS $RPI_CFLAGS"; LIBS="$LIBS $RPI_LDFLAGS"
+
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Raspberry Pi" >&5
+$as_echo_n "checking for Raspberry Pi... " >&6; }
+        have_video_rpi=no
+        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+          #include <bcm_host.h>
+
+int
+main ()
 {
 
+          bcm_host_init();
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+
+        have_video_rpi=yes
+
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_video_rpi" >&5
+$as_echo "$have_video_rpi" >&6; }
+
+        # Restore the compiler flags and libraries
+        CFLAGS="$ac_save_cflags"; LIBS="$ac_save_libs"
+
+        if test x$have_video_rpi = xyes; then
+            CFLAGS="$CFLAGS $RPI_CFLAGS"
+            SDL_CFLAGS="$SDL_CFLAGS $RPI_CFLAGS"
+            EXTRA_CFLAGS="$EXTRA_CFLAGS $RPI_CFLAGS"
+            EXTRA_LDFLAGS="$EXTRA_LDFLAGS $RPI_LDFLAGS"
+            SOURCES="$SOURCES $srcdir/src/video/raspberry/*.c"
+
+$as_echo "#define SDL_VIDEO_DRIVER_RPI 1" >>confdefs.h
+
+            SUMMARY_video="${SUMMARY_video} rpi"
+        fi
+    fi
+}
 
+CheckX11()
+{
     # Check whether --enable-video-x11 was given.
 if test "${enable_video_x11+set}" = set; then :
   enableval=$enable_video_x11;
@@ -19942,7 +20368,8 @@ _ACEOF
 if ac_fn_c_try_compile "$LINENO"; then :
 
             have_const_param_XextAddDisplay=yes
-            $as_echo "#define SDL_VIDEO_DRIVER_X11_CONST_PARAM_XEXTADDDISPLAY 1" >>confdefs.h
+
+$as_echo "#define SDL_VIDEO_DRIVER_X11_CONST_PARAM_XEXTADDDISPLAY 1" >>confdefs.h
 
 
 fi
@@ -19976,7 +20403,8 @@ _ACEOF
 if ac_fn_c_try_compile "$LINENO"; then :
 
                 have_XGenericEvent=yes
-                $as_echo "#define SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS 1" >>confdefs.h
+
+$as_echo "#define SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS 1" >>confdefs.h
 
 
 fi
@@ -20925,7 +21353,7 @@ $as_echo "#define SDL_VIDEO_RENDER_DIRECTFB 1" >>confdefs.h
             { $as_echo "$as_me:${as_lineno-$LINENO}: checking for directfb dynamic loading support" >&5
 $as_echo_n "checking for directfb dynamic loading support... " >&6; }
             directfb_shared=no
-            directfb_lib=`find_lib "libdirectfb.so.*" "$DIRECTFB_LIBS"`
+            directfb_lib=`find_lib "libdirectfb*.so.*" "$DIRECTFB_LIBS"`
             # | sed 's/.*\/\(.*\)/\1/; q'`]
 { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \"directfb $directfb_lib\"" >&5
 $as_echo "$as_me: WARNING: \"directfb $directfb_lib\"" >&2;}
@@ -20956,19 +21384,23 @@ $as_echo "$directfb_shared" >&6; }
     fi
 }
 
-CheckFusionSound()
+CheckKMSDRM()
 {
-    # Check whether --enable-fusionsound was given.
-if test "${enable_fusionsound+set}" = set; then :
-  enableval=$enable_fusionsound;
+    # Check whether --enable-video-kmsdrm was given.
+if test "${enable_video_kmsdrm+set}" = set; then :
+  enableval=$enable_video_kmsdrm;
 else
-  enable_fusionsound=no
+  enable_video_kmsdrm=no
 fi
 
-    if test x$enable_audio = xyes -a x$enable_fusionsound = xyes; then
-        fusionsound=no
 
-        FUSIONSOUND_REQUIRED_VERSION=1.1.1
+    if test x$enable_video = xyes -a x$enable_video_kmsdrm = xyes; then
+        video_kmsdrm=no
+        libdrm_avail=no
+        libgbm_avail=no
+
+        LIBDRM_REQUIRED_VERSION=2.4.46
+        LIBGBM_REQUIRED_VERSION=9.0.0
 
         # Extract the first word of "pkg-config", so it can be a program name with args.
 set dummy pkg-config; ac_word=$2
@@ -21011,57 +21443,86 @@ $as_echo "no" >&6; }
 fi
 
 
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for FusionSound $FUSIONSOUND_REQUIRED_VERSION support" >&5
-$as_echo_n "checking for FusionSound $FUSIONSOUND_REQUIRED_VERSION support... " >&6; }
         if test x$PKG_CONFIG != xno; then
-            if $PKG_CONFIG --atleast-pkgconfig-version 0.7 && $PKG_CONFIG --atleast-version $FUSIONSOUND_REQUIRED_VERSION fusionsound; then
-                FUSIONSOUND_CFLAGS=`$PKG_CONFIG --cflags fusionsound`
-                FUSIONSOUND_LIBS=`$PKG_CONFIG --libs fusionsound`
-                fusionsound=yes
-            fi
-        fi
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fusionsound" >&5
-$as_echo "$fusionsound" >&6; }
-
-        if test x$fusionsound = xyes; then
-
-$as_echo "#define SDL_AUDIO_DRIVER_FUSIONSOUND 1" >>confdefs.h
+            if $PKG_CONFIG --atleast-pkgconfig-version 0.7; then
+                if $PKG_CONFIG --atleast-version $LIBDRM_REQUIRED_VERSION libdrm; then
+                    LIBDRM_CFLAGS=`$PKG_CONFIG --cflags libdrm`
+                    LIBDRM_LIBS=`$PKG_CONFIG --libs libdrm`
+                    LIBDRM_PREFIX=`$PKG_CONFIG --variable=prefix libdrm`
+                    libdrm_avail=yes
+                fi
+                if $PKG_CONFIG --atleast-version $LIBGBM_REQUIRED_VERSION gbm; then
+                    LIBGBM_CFLAGS=`$PKG_CONFIG --cflags gbm`
+                    LIBGBM_LIBS=`$PKG_CONFIG --libs gbm`
+                    LIBGBM_PREFIX=`$PKG_CONFIG --variable=prefix gbm`
+                    libgbm_avail=yes
+                fi
+                if test x$libdrm_avail = xyes -a x$libgbm_avail = xyes; then
+                    video_kmsdrm=yes
+                fi
 
-            SOURCES="$SOURCES $srcdir/src/audio/fusionsound/*.c"
-            EXTRA_CFLAGS="$EXTRA_CFLAGS $FUSIONSOUND_CFLAGS"
+                { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libdrm $LIBDRM_REQUIRED_VERSION library for kmsdrm support" >&5
+$as_echo_n "checking for libdrm $LIBDRM_REQUIRED_VERSION library for kmsdrm support... " >&6; }
+                { $as_echo "$as_me:${as_lineno-$LINENO}: result: $libdrm_avail" >&5
+$as_echo "$libdrm_avail" >&6; }
+                { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libgbm $LIBGBM_REQUIRED_VERSION library for kmsdrm support" >&5
+$as_echo_n "checking for libgbm $LIBGBM_REQUIRED_VERSION library for kmsdrm support... " >&6; }
+                { $as_echo "$as_me:${as_lineno-$LINENO}: result: $libgbm_avail" >&5
+$as_echo "$libgbm_avail" >&6; }
 
-            # Check whether --enable-fusionsound-shared was given.
-if test "${enable_fusionsound_shared+set}" = set; then :
-  enableval=$enable_fusionsound_shared;
+                if test x$video_kmsdrm = xyes; then
+                    # Check whether --enable-kmsdrm-shared was given.
+if test "${enable_kmsdrm_shared+set}" = set; then :
+  enableval=$enable_kmsdrm_shared;
 else
-  enable_fusionsound_shared=yes
+  enable_kmsdrm_shared=yes
 fi
 
-            fusionsound_shared=no
-            { $as_echo "$as_me:${as_lineno-$LINENO}: checking for FusionSound dynamic loading support" >&5
-$as_echo_n "checking for FusionSound dynamic loading support... " >&6; }
-            if test x$have_loadso != xyes && \
-               test x$enable_fusionsound_shared = xyes; then
-                { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You must have SDL_LoadObject() support for dynamic fusionsound loading" >&5
-$as_echo "$as_me: WARNING: You must have SDL_LoadObject() support for dynamic fusionsound loading" >&2;}
-            fi
-            if test x$have_loadso = xyes && \
-               test x$enable_fusionsound_shared = xyes; then
+
+
+$as_echo "#define SDL_VIDEO_DRIVER_KMSDRM 1" >>confdefs.h
+
+                    SOURCES="$SOURCES $srcdir/src/video/kmsdrm/*.c"
+                    EXTRA_CFLAGS="$EXTRA_CFLAGS $LIBDRM_CFLAGS $LIBGBM_CFLAGS"
+
+                    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for kmsdrm dynamic loading support" >&5
+$as_echo_n "checking for kmsdrm dynamic loading support... " >&6; }
+                    kmsdrm_shared=no
+                    drm_lib=`find_lib "libdrm.so.*" "$DRM_LIBS"`
+                    gbm_lib=`find_lib "libgbm.so.*" "$DRM_LIBS"`
+                    if test x$have_loadso != xyes && \
+                       test x$enable_kmsdrm_shared = xyes; then
+                        { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: You must have SDL_LoadObject() support for dynamic kmsdrm loading" >&5
+$as_echo "$as_me: WARNING: You must have SDL_LoadObject() support for dynamic kmsdrm loading" >&2;}
+                    fi
+                    if test x$have_loadso = xyes && \
+                       test x$enable_kmsdrm_shared = xyes && test x$drm_lib != x && test x$gbm_lib != x; then
+                        kmsdrm_shared=yes
 
 cat >>confdefs.h <<_ACEOF
-#define SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC "libfusionsound.so"
+#define SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC "$drm_lib"
 _ACEOF
 
-                fusionsound_shared=yes
-                SUMMARY_audio="${SUMMARY_audio} fusionsound(dynamic)"
-            else
-                EXTRA_LDFLAGS="$EXTRA_LDFLAGS $FUSIONSOUND_LIBS"
-                SUMMARY_audio="${SUMMARY_audio} fusionsound"
-            fi
-            { $as_echo "$as_me:${as_lineno-$LINENO}: result: $fusionsound_shared" >&5
-$as_echo "$fusionsound_shared" >&6; }
 
-            have_audio=yes
+cat >>confdefs.h <<_ACEOF
+#define SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM "$gbm_lib"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_KMSDRM_SHARED "TRUE"
+_ACEOF
+
+                        SUMMARY_video="${SUMMARY_video} kmsdrm(dynamic)"
+                    else
+                        EXTRA_LDFLAGS="$EXTRA_LDFLAGS $LIBDRM_LIBS $LIBGBM_LIBS"
+                        SUMMARY_video="${SUMMARY_video} kmsdrm"
+                    fi
+                    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $kmsdrm_shared" >&5
+$as_echo "$kmsdrm_shared" >&6; }
+                    have_video=yes
+                fi
+            fi
         fi
     fi
 }
@@ -21085,6 +21546,32 @@ $as_echo "#define SDL_VIDEO_DRIVER_DUMMY 1" >>confdefs.h
     fi
 }
 
+CheckQNXVideo()
+{
+    if test x$enable_video = xyes; then
+
+$as_echo "#define SDL_VIDEO_DRIVER_QNX 1" >>confdefs.h
+
+        SOURCES="$SOURCES $srcdir/src/video/qnx/*.c"
+        have_video=yes
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lscreen -lEGL -lGLESv2"
+        SUMMARY_video="${SUMMARY_video} qnx"
+    fi
+}
+
+CheckQNXAudio()
+{
+    if test x$enable_audio = xyes; then
+
+$as_echo "#define SDL_AUDIO_DRIVER_QSA 1" >>confdefs.h
+
+        SOURCES="$SOURCES $srcdir/src/audio/qsa/*.c"
+        have_audio=yes
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lasound"
+        SUMMARY_audio="${SUMMARY_audio} qsa"
+    fi
+}
+
 # Check whether --enable-video-opengl was given.
 if test "${enable_video_opengl+set}" = set; then :
   enableval=$enable_video_opengl;
@@ -21475,6 +21962,97 @@ $as_echo "#define SDL_VIDEO_RENDER_OGL_ES2 1" >>confdefs.h
     fi
 }
 
+# Check whether --enable-video-vulkan was given.
+if test "${enable_video_vulkan+set}" = set; then :
+  enableval=$enable_video_vulkan;
+else
+  enable_video_vulkan=yes
+fi
+
+
+CheckVulkan()
+{
+    if test x$enable_video = xyes -a x$enable_video_vulkan = xyes; then
+        case "$host" in
+            *-*-androideabi*)
+                cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+                  #if defined(__ARM_ARCH) && __ARM_ARCH < 7
+                  #error Vulkan doesn't work on this configuration
+                  #endif
+
+int
+main ()
+{
+
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+
+else
+
+                    enable_video_vulkan=no
+
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+                ;;
+            *-*-darwin*)
+                save_CFLAGS="$CFLAGS"
+                                CFLAGS="$CFLAGS -x objective-c"
+                cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+                  #include <Cocoa/Cocoa.h>
+                  #include <Metal/Metal.h>
+                  #include <QuartzCore/CAMetalLayer.h>
+
+                  #if !TARGET_CPU_X86_64
+                  #error Vulkan doesn't work on this configuration
+                  #endif
+
+int
+main ()
+{
+
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+
+else
+
+                    enable_video_vulkan=no
+
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+                CFLAGS="$save_CFLAGS"
+                ;;
+            *)
+                ;;
+        esac
+        if test x$enable_video_vulkan = xno; then
+            # For reasons I am totally unable to see, I get an undefined macro error if
+            # I put this in the AC_TRY_COMPILE.
+            { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Vulkan does not work on this configuration." >&5
+$as_echo "$as_me: WARNING: Vulkan does not work on this configuration." >&2;}
+        fi
+    fi
+    if test x$enable_video_vulkan = xyes; then
+
+$as_echo "#define SDL_VIDEO_VULKAN 1" >>confdefs.h
+
+        SUMMARY_video="${SUMMARY_video} vulkan"
+    fi
+}
+
 CheckInputEvents()
 {
             { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Linux 2.4 unified input interface" >&5
@@ -21575,6 +22153,16 @@ fi
 
 $as_echo "#define HAVE_LIBUDEV_H 1" >>confdefs.h
 
+
+            udev_lib=`find_lib "libudev.so.*" "" | sed 's/.*\/\(.*\)/\1/; q'`
+            if test x$udev_lib != x; then
+                echo "-- dynamic udev -> $udev_lib"
+
+cat >>confdefs.h <<_ACEOF
+#define SDL_UDEV_DYNAMIC "$udev_lib"
+_ACEOF
+
+            fi
         fi
     fi
 }
@@ -21974,6 +22562,10 @@ fi
             pthread_cflags="-D_REENTRANT"
             pthread_lib=""
             ;;
+        *-*-nto*)
+            pthread_cflags="-D_REENTRANT"
+            pthread_lib=""
+            ;;
         *)
             pthread_cflags="-D_REENTRANT"
             pthread_lib="-lpthread"
@@ -22147,7 +22739,8 @@ _ACEOF
 if ac_fn_c_try_link "$LINENO"; then :
 
                 have_sem_timedwait=yes
-                $as_echo "#define HAVE_SEM_TIMEDWAIT 1" >>confdefs.h
+
+$as_echo "#define HAVE_SEM_TIMEDWAIT 1" >>confdefs.h
 
 
 fi
@@ -22403,6 +22996,58 @@ if test "x$ac_cv_header_xinput_h" = xyes; then :
 fi
 
 
+        ac_fn_c_check_header_mongrel "$LINENO" "mmdeviceapi.h" "ac_cv_header_mmdeviceapi_h" "$ac_includes_default"
+if test "x$ac_cv_header_mmdeviceapi_h" = xyes; then :
+  have_wasapi=yes
+fi
+
+
+        ac_fn_c_check_header_mongrel "$LINENO" "audioclient.h" "ac_cv_header_audioclient_h" "$ac_includes_default"
+if test "x$ac_cv_header_audioclient_h" = xyes; then :
+
+else
+  have_wasapi=no
+fi
+
+
+        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <windows.h>
+#include <xinput.h>
+XINPUT_GAMEPAD_EX x1;
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  have_xinput_gamepadex=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <windows.h>
+#include <xinput.h>
+XINPUT_STATE_EX s1;
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  have_xinput_stateex=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 
         if test x$have_ddraw = xyes; then
 
@@ -22429,6 +23074,16 @@ $as_echo "#define HAVE_DXGI_H 1" >>confdefs.h
 $as_echo "#define HAVE_XINPUT_H 1" >>confdefs.h
 
         fi
+        if test x$have_xinput_gamepadex = xyes; then
+
+$as_echo "#define HAVE_XINPUT_GAMEPAD_EX 1" >>confdefs.h
+
+        fi
+        if test x$have_xinput_stateex = xyes; then
+
+$as_echo "#define HAVE_XINPUT_STATE_EX 1" >>confdefs.h
+
+        fi
 
         SUMMARY_video="${SUMMARY_video} directx"
         SUMMARY_audio="${SUMMARY_audio} directx"
@@ -23052,24 +23707,8 @@ fi
 CheckWarnAll
 
 case "$host" in
-    *-*-linux*|*-*-uclinux*|*-*-gnu*|*-*-k*bsd*-gnu|*-*-bsdi*|*-*-freebsd*|*-*-dragonfly*|*-*-netbsd*|*-*-openbsd*|*-*-sysv5*|*-*-solaris*|*-*-hpux*|*-*-aix*|*-*-minix*)
+    *-*-linux*|*-*-uclinux*|*-*-gnu*|*-*-k*bsd*-gnu|*-*-bsdi*|*-*-freebsd*|*-*-dragonfly*|*-*-netbsd*|*-*-openbsd*|*-*-sysv5*|*-*-solaris*|*-*-hpux*|*-*-aix*|*-*-minix*|*-*-nto*)
         case "$host" in
-            *-raspberry-linux*)
-                # Raspberry Pi
-                ARCH=linux
-                RPI_CFLAGS="-I/opt/vc/include -I/opt/vc/include/interface/vcos/pthreads -I/opt/vc/include/interface/vmcs_host/linux"
-                CFLAGS="$CFLAGS $RPI_CFLAGS"
-                SDL_CFLAGS="$SDL_CFLAGS $RPI_CFLAGS"
-                EXTRA_CFLAGS="$EXTRA_CFLAGS $RPI_CFLAGS"
-                EXTRA_LDFLAGS="$EXTRA_LDFLAGS -L/opt/vc/lib -lbcm_host -ldl"
-
-                if test x$enable_video = xyes; then
-                    SOURCES="$SOURCES $srcdir/src/video/raspberry/*.c"
-                    # FIXME: confdefs? Not AC_DEFINE?
-                    $as_echo "#define SDL_VIDEO_DRIVER_RPI 1" >>confdefs.h
-                    SUMMARY_video="${SUMMARY_video} rpi"
-                fi
-                ;;
             *-*-androideabi*)
                 # Android
                 ARCH=android
@@ -23078,6 +23717,7 @@ case "$host" in
                 SDL_CFLAGS="$SDL_CFLAGS $ANDROID_CFLAGS"
                 EXTRA_CFLAGS="$EXTRA_CFLAGS $ANDROID_CFLAGS"
                 EXTRA_LDFLAGS="$EXTRA_LDFLAGS -ldl -lGLESv1_CM -lGLESv2 -llog -landroid"
+                SDLMAIN_SOURCES="$srcdir/src/main/android/*.c"
 
                 if test x$enable_video = xyes; then
                     SOURCES="$SOURCES $srcdir/src/core/android/*.c $srcdir/src/video/android/*.c"
@@ -23095,21 +23735,6 @@ case "$host" in
             *-*-bsdi*)          ARCH=bsdi ;;
             *-*-freebsd*)       ARCH=freebsd ;;
             *-*-dragonfly*)     ARCH=freebsd ;;
-            *-raspberry-netbsd*)
-                # Raspberry Pi
-                ARCH=netbsd
-                RPI_CFLAGS="-I/usr/pkg/include -I/usr/pkg/include/interface/vcos/pthreads -I/usr/pkg/include/interface/vmcs_host/linux"
-                CFLAGS="$CFLAGS $RPI_CFLAGS"
-                SDL_CFLAGS="$SDL_CFLAGS $RPI_CFLAGS"
-                EXTRA_CFLAGS="$EXTRA_CFLAGS $RPI_CFLAGS"
-                EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-R/usr/pkg/lib -L/usr/pkg/lib -lbcm_host -ldl"
-
-                if test x$enable_video = xyes; then
-                    SOURCES="$SOURCES $srcdir/src/video/raspberry/*.c"
-                    $as_echo "#define SDL_VIDEO_DRIVER_RPI 1" >>confdefs.h
-                    SUMMARY_video="${SUMMARY_video} raspberry"
-                fi
-                ;;
             *-*-netbsd*)        ARCH=netbsd ;;
             *-*-openbsd*)       ARCH=openbsd ;;
             *-*-sysv5*)         ARCH=sysv5 ;;
@@ -23117,6 +23742,9 @@ case "$host" in
             *-*-hpux*)          ARCH=hpux ;;
             *-*-aix*)           ARCH=aix ;;
             *-*-minix*)         ARCH=minix ;;
+            *-*-nto*)           ARCH=nto
+                CheckQNXVideo
+                ;;
         esac
         CheckVisibilityHidden
         CheckDeclarationAfterStatement
@@ -23127,15 +23755,21 @@ case "$host" in
         CheckOSS
         CheckALSA
         CheckPulseAudio
+        CheckJACK
         CheckARTSC
         CheckESD
         CheckNAS
         CheckSNDIO
+        CheckFusionSound
+        CheckLibSampleRate
+        # Need to check for Raspberry PI first and add platform specific compiler flags, otherwise the test for GLES fails!
+        CheckRPI
         CheckX11
         CheckDirectFB
-        CheckFusionSound
+        CheckKMSDRM
         CheckOpenGLX11
         CheckOpenGLESX11
+        CheckVulkan
         CheckMir
         CheckWayland
         CheckLibUDev
@@ -23156,6 +23790,7 @@ case "$host" in
         CheckLinuxVersion
         CheckRPATH
         CheckVivanteVideo
+
         # Set up files for the audio library
         if test x$enable_audio = xyes; then
           case $ARCH in
@@ -23164,13 +23799,15 @@ case "$host" in
 $as_echo "#define SDL_AUDIO_DRIVER_SUNAUDIO 1" >>confdefs.h
 
                 SOURCES="$SOURCES $srcdir/src/audio/sun/*.c"
+                SUMMARY_audio="${SUMMARY_audio} sun"
                 have_audio=yes
             ;;
             netbsd)  # Don't use this on OpenBSD, it's busted.
 
-$as_echo "#define SDL_AUDIO_DRIVER_BSD 1" >>confdefs.h
+$as_echo "#define SDL_AUDIO_DRIVER_NETBSD 1" >>confdefs.h
 
-                SOURCES="$SOURCES $srcdir/src/audio/bsd/*.c"
+                SOURCES="$SOURCES $srcdir/src/audio/netbsd/*.c"
+                SUMMARY_audio="${SUMMARY_audio} netbsd"
                 have_audio=yes
             ;;
             aix)
@@ -23178,6 +23815,7 @@ $as_echo "#define SDL_AUDIO_DRIVER_BSD 1" >>confdefs.h
 $as_echo "#define SDL_AUDIO_DRIVER_PAUDIO 1" >>confdefs.h
 
                 SOURCES="$SOURCES $srcdir/src/audio/paudio/*.c"
+                SUMMARY_audio="${SUMMARY_audio} paudio"
                 have_audio=yes
             ;;
             android)
@@ -23188,6 +23826,9 @@ $as_echo "#define SDL_AUDIO_DRIVER_ANDROID 1" >>confdefs.h
                 SUMMARY_audio="${SUMMARY_audio} android"
                 have_audio=yes
             ;;
+            nto)
+                CheckQNXAudio
+            ;;
           esac
         fi
         # Set up files for the joystick library
@@ -23275,8 +23916,10 @@ $as_echo "#define SDL_TIMER_UNIX 1" >>confdefs.h
         fi
         # Set up files for evdev input
         if test x$use_input_events = xyes; then
-            SOURCES="$SOURCES $srcdir/src/core/linux/SDL_evdev.c"
+            SOURCES="$SOURCES $srcdir/src/core/linux/SDL_evdev*.c"
         fi
+        # Set up other core UNIX files
+        SOURCES="$SOURCES $srcdir/src/core/unix/*.c"
         ;;
     *-*-cygwin* | *-*-mingw32*)
         ARCH=win32
@@ -23289,12 +23932,14 @@ $as_echo "#define SDL_TIMER_UNIX 1" >>confdefs.h
                 ac_default_prefix=$BUILD_PREFIX
             fi
         fi
+        CheckDeclarationAfterStatement
         CheckDummyVideo
         CheckDiskAudio
         CheckDummyAudio
         CheckWINDOWS
         CheckWINDOWSGL
         CheckWINDOWSGLES
+        CheckVulkan
         CheckDIRECTX
 
         # Set up the core platform files
@@ -23343,6 +23988,12 @@ $as_echo "#define SDL_AUDIO_DRIVER_XAUDIO2 1" >>confdefs.h
 
                 SOURCES="$SOURCES $srcdir/src/audio/xaudio2/*.c"
             fi
+            if test x$have_wasapi = xyes; then
+
+$as_echo "#define SDL_AUDIO_DRIVER_WASAPI 1" >>confdefs.h
+
+                SOURCES="$SOURCES $srcdir/src/audio/wasapi/*.c"
+            fi
             have_audio=yes
         fi
         # Set up files for the joystick library
@@ -23490,6 +24141,7 @@ fi
         CheckDummyVideo
         CheckDiskAudio
         CheckDummyAudio
+        CheckDLOPEN
         CheckHaikuVideo
         CheckHaikuGL
         CheckPTHREAD
@@ -23500,6 +24152,7 @@ fi
 $as_echo "#define SDL_AUDIO_DRIVER_HAIKU 1" >>confdefs.h
 
             SOURCES="$SOURCES $srcdir/src/audio/haiku/*.cc"
+            SUMMARY_audio="${SUMMARY_audio} haiku"
             have_audio=yes
         fi
         # Set up files for the joystick library
@@ -23518,14 +24171,6 @@ $as_echo "#define SDL_TIMER_HAIKU 1" >>confdefs.h
             SOURCES="$SOURCES $srcdir/src/timer/haiku/*.c"
             have_timers=yes
         fi
-        # Set up files for the shared object loading library
-        if test x$enable_loadso = xyes; then
-
-$as_echo "#define SDL_LOADSO_HAIKU 1" >>confdefs.h
-
-            SOURCES="$SOURCES $srcdir/src/loadso/haiku/*.c"
-            have_loadso=yes
-        fi
         # Set up files for the system power library
         if test x$enable_power = xyes; then
 
@@ -23545,10 +24190,33 @@ $as_echo "#define SDL_FILESYSTEM_HAIKU 1" >>confdefs.h
         # The Haiku platform requires special setup.
         SOURCES="$srcdir/src/main/haiku/*.cc $SOURCES"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lroot -lbe -lmedia -lgame -ldevice -ltextencoding"
+        # Haiku's x86 spins use libstdc++.r4.so (for binary compat?), but
+        #  other spins, like x86-64, use a more standard "libstdc++.so.*"
+        as_ac_File=`$as_echo "ac_cv_file_"/boot/system/lib/libstdc++.r4.so"" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for \"/boot/system/lib/libstdc++.r4.so\"" >&5
+$as_echo_n "checking for \"/boot/system/lib/libstdc++.r4.so\"... " >&6; }
+if eval \${$as_ac_File+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  test "$cross_compiling" = yes &&
+  as_fn_error $? "cannot check for file existence when cross compiling" "$LINENO" 5
+if test -r ""/boot/system/lib/libstdc++.r4.so""; then
+  eval "$as_ac_File=yes"
+else
+  eval "$as_ac_File=no"
+fi
+fi
+eval ac_res=\$$as_ac_File
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+if eval test \"x\$"$as_ac_File"\" = x"yes"; then :
+  EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lstdc++.r4"
+else
+  EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lstdc++"
+fi
+
         ;;
-    arm*-apple-darwin*)
-        # iOS - We are not writing anything to confdefs.h because you have to replace
-        # SDL_config.h for SDL_config_iphoneos.h anyway
+    arm*-apple-darwin*|*-ios-*)
         ARCH=ios
 
         CheckVisibilityHidden
@@ -23557,18 +24225,23 @@ $as_echo "#define SDL_FILESYSTEM_HAIKU 1" >>confdefs.h
         CheckDiskAudio
         CheckDummyAudio
         CheckDLOPEN
-        CheckCOCOA
         CheckPTHREAD
-
+        CheckVulkan
 
         # Set up files for the audio library
         if test x$enable_audio = xyes; then
+
+$as_echo "#define SDL_AUDIO_DRIVER_COREAUDIO 1" >>confdefs.h
+
             SOURCES="$SOURCES $srcdir/src/audio/coreaudio/*.m"
             SUMMARY_audio="${SUMMARY_audio} coreaudio"
             have_audio=yes
         fi
         # Set up files for the joystick library
         if test x$enable_joystick = xyes; then
+
+$as_echo "#define SDL_JOYSTICK_MFI 1" >>confdefs.h
+
             SOURCES="$SOURCES $srcdir/src/joystick/iphoneos/*.m"
             have_joystick=yes
         fi
@@ -23580,6 +24253,9 @@ $as_echo "#define SDL_FILESYSTEM_HAIKU 1" >>confdefs.h
         #fi
         # Set up files for the power library
         if test x$enable_power = xyes; then
+
+$as_echo "#define SDL_POWER_UIKIT 1" >>confdefs.h
+
             SOURCES="$SOURCES $srcdir/src/power/uikit/*.m"
             have_power=yes
         fi
@@ -23588,28 +24264,51 @@ $as_echo "#define SDL_FILESYSTEM_HAIKU 1" >>confdefs.h
             SOURCES="$SOURCES $srcdir/src/filesystem/cocoa/*.m"
             have_filesystem=yes
         fi
+        # Set up additional files for the file library
+        if test x$enable_file = xyes; then
+
+$as_echo "#define SDL_FILESYSTEM_COCOA 1" >>confdefs.h
+
+            SOURCES="$SOURCES $srcdir/src/file/cocoa/*.m"
+        fi
         # Set up files for the timer library
         if test x$enable_timers = xyes; then
+
+$as_echo "#define SDL_TIMER_UNIX 1" >>confdefs.h
+
             SOURCES="$SOURCES $srcdir/src/timer/unix/*.c"
             have_timers=yes
         fi
-        # Set up additional files for the file library
-        if test x$enable_file = xyes; then
-            SOURCES="$SOURCES $srcdir/src/file/cocoa/*.m"
-        fi
+        # Set up other core UNIX files
+        SOURCES="$SOURCES $srcdir/src/core/unix/*.c"
         # The iOS platform requires special setup.
+
+$as_echo "#define SDL_VIDEO_DRIVER_UIKIT 1" >>confdefs.h
+
+
+$as_echo "#define SDL_VIDEO_OPENGL_ES2 1" >>confdefs.h
+
+
+$as_echo "#define SDL_VIDEO_OPENGL_ES 1" >>confdefs.h
+
+
+$as_echo "#define SDL_VIDEO_RENDER_OGL_ES 1" >>confdefs.h
+
+
+$as_echo "#define SDL_VIDEO_RENDER_OGL_ES2 1" >>confdefs.h
+
         SOURCES="$SOURCES $srcdir/src/video/uikit/*.m"
-        EXTRA_CFLAGS="$EXTRA_CFLAGS -fpascal-strings"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lm -liconv -lobjc"
-        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,Foundation"
-        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,UIKit"
-        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,OpenGLES"
-        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,QuartzCore"
-        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,CoreAudio"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,AVFoundation"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,AudioToolbox"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,CoreAudio"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,CoreGraphics"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,CoreMotion"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,Foundation"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,GameController"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,OpenGLES"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,QuartzCore"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,UIKit"
         ;;
     *-*-darwin* )
         # This could be either full "Mac OS X", or plain "Darwin" which is
@@ -23631,6 +24330,7 @@ $as_echo "#define SDL_FILESYSTEM_HAIKU 1" >>confdefs.h
         CheckX11
         CheckMacGL
         CheckOpenGLX11
+        CheckVulkan
         CheckPTHREAD
 
         # Set up files for the audio library
@@ -23688,8 +24388,9 @@ $as_echo "#define SDL_TIMER_UNIX 1" >>confdefs.h
         if test x$enable_file = xyes; then
             SOURCES="$SOURCES $srcdir/src/file/cocoa/*.m"
         fi
+        # Set up other core UNIX files
+        SOURCES="$SOURCES $srcdir/src/core/unix/*.c"
         # The Mac OS X platform requires special setup.
-        EXTRA_CFLAGS="$EXTRA_CFLAGS -fpascal-strings"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lobjc"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,CoreVideo"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,Cocoa"
@@ -23706,7 +24407,8 @@ $as_echo "#define SDL_TIMER_UNIX 1" >>confdefs.h
 
         # Set up files for the timer library
         if test x$enable_timers = xyes; then
-            $as_echo "#define SDL_TIMER_UNIX 1" >>confdefs.h
+
+$as_echo "#define SDL_TIMER_UNIX 1" >>confdefs.h
 
             SOURCES="$SOURCES $srcdir/src/timer/unix/*.c"
             have_timers=yes
@@ -23916,16 +24618,16 @@ VERSION_DEPENDS=`echo "$VERSION_DEPENDS" | sed "s,\\([^ ]*\\)/\\([^ ]*\\)\\.rc,\
 
 SDLMAIN_OBJECTS=`echo $SDLMAIN_SOURCES`
 SDLMAIN_DEPENDS=`echo $SDLMAIN_SOURCES`
-SDLMAIN_OBJECTS=`echo "$SDLMAIN_OBJECTS" | sed 's,[^ ]*/\([^ ]*\)\.c,$(objects)/\1.o,g'`
+SDLMAIN_OBJECTS=`echo "$SDLMAIN_OBJECTS" | sed 's,[^ ]*/\([^ ]*\)\.c,$(objects)/\1.lo,g'`
 SDLMAIN_DEPENDS=`echo "$SDLMAIN_DEPENDS" | sed "s,\\([^ ]*\\)/\\([^ ]*\\)\\.c,\\\\
-\\$(objects)/\\2.o: \\1/\\2.c\\\\
+\\$(objects)/\\2.lo: \\1/\\2.c\\\\
 	\\$(RUN_CMD_CC)\\$(LIBTOOL) --tag=CC --mode=compile \\$(CC) \\$(CFLAGS) \\$(EXTRA_CFLAGS) $DEPENDENCY_TRACKING_OPTIONS -c \\$< -o \\$@,g"`
 
 SDLTEST_OBJECTS=`echo $SDLTEST_SOURCES`
 SDLTEST_DEPENDS=`echo $SDLTEST_SOURCES`
-SDLTEST_OBJECTS=`echo "$SDLTEST_OBJECTS" | sed 's,[^ ]*/\([^ ]*\)\.c,$(objects)/\1.o,g'`
+SDLTEST_OBJECTS=`echo "$SDLTEST_OBJECTS" | sed 's,[^ ]*/\([^ ]*\)\.c,$(objects)/\1.lo,g'`
 SDLTEST_DEPENDS=`echo "$SDLTEST_DEPENDS" | sed "s,\\([^ ]*\\)/\\([^ ]*\\)\\.c,\\\\
-\\$(objects)/\\2.o: \\1/\\2.c\\\\
+\\$(objects)/\\2.lo: \\1/\\2.c\\\\
 	\\$(RUN_CMD_CC)\\$(LIBTOOL) --tag=CC --mode=compile \\$(CC) \\$(CFLAGS) \\$(EXTRA_CFLAGS) $DEPENDENCY_TRACKING_OPTIONS -c \\$< -o \\$@,g"`
 
 # Set runtime shared library paths as needed
@@ -24045,30 +24747,35 @@ if test x$have_x = xyes; then
     SUMMARY="${SUMMARY}X11 libraries   :${SUMMARY_video_x11}\n"
 fi
 SUMMARY="${SUMMARY}Input drivers   :${SUMMARY_input}\n"
-if test x$enable_libudev = xyes; then
-    SUMMARY="${SUMMARY}Using libudev   : YES\n"
+if test x$have_samplerate_h_hdr = xyes; then
+    SUMMARY="${SUMMARY}Using libsamplerate : YES\n"
+else
+    SUMMARY="${SUMMARY}Using libsamplerate : NO\n"
+fi
+if test x$have_libudev_h_hdr = xyes; then
+    SUMMARY="${SUMMARY}Using libudev       : YES\n"
 else
-    SUMMARY="${SUMMARY}Using libudev   : NO\n"
+    SUMMARY="${SUMMARY}Using libudev       : NO\n"
 fi
 if test x$have_dbus_dbus_h_hdr = xyes; then
-    SUMMARY="${SUMMARY}Using dbus      : YES\n"
+    SUMMARY="${SUMMARY}Using dbus          : YES\n"
 else
-    SUMMARY="${SUMMARY}Using dbus      : NO\n"
+    SUMMARY="${SUMMARY}Using dbus          : NO\n"
 fi
 if test x$enable_ime = xyes; then
-    SUMMARY="${SUMMARY}Using ime       : YES\n"
+    SUMMARY="${SUMMARY}Using ime           : YES\n"
 else
-    SUMMARY="${SUMMARY}Using ime       : NO\n"
+    SUMMARY="${SUMMARY}Using ime           : NO\n"
 fi
 if test x$have_ibus_ibus_h_hdr = xyes; then
-    SUMMARY="${SUMMARY}Using ibus      : YES\n"
+    SUMMARY="${SUMMARY}Using ibus          : YES\n"
 else
-    SUMMARY="${SUMMARY}Using ibus      : NO\n"
+    SUMMARY="${SUMMARY}Using ibus          : NO\n"
 fi
 if test x$have_fcitx_frontend_h_hdr = xyes; then
-    SUMMARY="${SUMMARY}Using fcitx     : YES\n"
+    SUMMARY="${SUMMARY}Using fcitx         : YES\n"
 else
-    SUMMARY="${SUMMARY}Using fcitx     : NO\n"
+    SUMMARY="${SUMMARY}Using fcitx         : NO\n"
 fi
 ac_config_commands="$ac_config_commands summary"
 
diff --git a/configure.in b/configure.in
index 37c57e2..e91851e 100644
--- a/configure.in
+++ b/configure.in
@@ -20,9 +20,9 @@ dnl Set various version strings - taken gratefully from the GTk sources
 #
 SDL_MAJOR_VERSION=2
 SDL_MINOR_VERSION=0
-SDL_MICRO_VERSION=5
-SDL_INTERFACE_AGE=1
-SDL_BINARY_AGE=5
+SDL_MICRO_VERSION=6
+SDL_INTERFACE_AGE=0
+SDL_BINARY_AGE=6
 SDL_VERSION=$SDL_MAJOR_VERSION.$SDL_MINOR_VERSION.$SDL_MICRO_VERSION
 
 AC_SUBST(SDL_MAJOR_VERSION)
@@ -68,7 +68,7 @@ case "$host" in
 esac
 
 dnl Set up the compiler and linker flags
-INCLUDE="-I$srcdir/include"
+INCLUDE="-I$srcdir/include -idirafter $srcdir/src/video/khronos"
 if test x$srcdir != x.; then
     INCLUDE="-Iinclude $INCLUDE"
 elif test -d .hg; then
@@ -234,7 +234,7 @@ if test x$enable_libc = xyes; then
 
     dnl Check for C library headers
     AC_HEADER_STDC
-    AC_CHECK_HEADERS(sys/types.h stdio.h stdlib.h stddef.h stdarg.h malloc.h memory.h string.h strings.h inttypes.h stdint.h ctype.h math.h iconv.h signal.h)
+    AC_CHECK_HEADERS(sys/types.h stdio.h stdlib.h stddef.h stdarg.h malloc.h memory.h string.h strings.h wchar.h inttypes.h stdint.h limits.h ctype.h math.h float.h iconv.h signal.h)
 
     dnl Check for typedefs, structures, etc.
     AC_TYPE_SIZE_T
@@ -268,7 +268,7 @@ if test x$enable_libc = xyes; then
         AC_DEFINE(HAVE_MPROTECT, 1, [ ])
         ]),
     )
-    AC_CHECK_FUNCS(malloc calloc realloc free getenv setenv putenv unsetenv qsort abs bcopy memset memcpy memmove strlen strlcpy strlcat strdup _strrev _strupr _strlwr strchr strrchr strstr itoa _ltoa _uitoa _ultoa strtol strtoul _i64toa _ui64toa strtoll strtoull atoi atof strcmp strncmp _stricmp strcasecmp _strnicmp strncasecmp vsscanf vsnprintf fseeko fseeko64 sigaction setjmp nanosleep sysconf sysctlbyname)
+    AC_CHECK_FUNCS(malloc calloc realloc free getenv setenv putenv unsetenv qsort abs bcopy memset memcpy memmove wcslen wcscmp strlen strlcpy strlcat strdup _strrev _strupr _strlwr strchr strrchr strstr itoa _ltoa _uitoa _ultoa strtol strtoul _i64toa _ui64toa strtoll strtoull atoi atof strcmp strncmp _stricmp strcasecmp _strnicmp strncasecmp vsscanf vsnprintf fopen64 fseeko fseeko64 sigaction setjmp nanosleep sysconf sysctlbyname getauxval poll)
 
     AC_CHECK_LIB(m, pow, [LIBS="$LIBS -lm"; EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lm"])
     AC_CHECK_FUNCS(atan atan2 acos asin ceil copysign cos cosf fabs floor log pow scalbn sin sinf sqrt sqrtf tan tanf)
@@ -276,7 +276,7 @@ if test x$enable_libc = xyes; then
     AC_CHECK_LIB(iconv, iconv_open, [LIBS="$LIBS -liconv"; EXTRA_LDFLAGS="$EXTRA_LDFLAGS -liconv"])
     AC_CHECK_FUNCS(iconv)
 
-    AC_CHECK_MEMBER(struct sigaction.sa_sigaction,[AC_DEFINE(HAVE_SA_SIGACTION)], ,[#include <signal.h>])
+    AC_CHECK_MEMBER(struct sigaction.sa_sigaction,[AC_DEFINE([HAVE_SA_SIGACTION], 1, [ ])], ,[#include <signal.h>])
 fi
 
 dnl AC_CHECK_SIZEOF(void*)
@@ -479,10 +479,10 @@ if test x$enable_assembly = xyes; then
             ;;
     esac
     AC_ARG_ENABLE(ssemath,
-AC_HELP_STRING([--enable-ssemath], [Allow GCC to use SSE floating point math [[default=no]]]),
+AC_HELP_STRING([--enable-ssemath], [Allow GCC to use SSE floating point math [[default=maybe]]]),
                   , enable_ssemath=$default_ssemath)
     if test x$enable_ssemath = xno; then
-        if test x$have_gcc_sse = xyes -o x$have_gcc_sse2 = xyes; then
+        if test x$have_gcc_sse = xyes -o x$have_gcc_sse2 = xyes -o x$have_gcc_sse3 = xyes; then
             EXTRA_CFLAGS="$EXTRA_CFLAGS -mfpmath=387"
         fi
     fi
@@ -593,7 +593,7 @@ AC_HELP_STRING([--enable-sse], [use SSE assembly routines [[default=yes]]]),
     fi
 
     AC_ARG_ENABLE(sse2,
-AC_HELP_STRING([--enable-sse2], [use SSE2 assembly routines [[default=no]]]),
+AC_HELP_STRING([--enable-sse2], [use SSE2 assembly routines [[default=maybe]]]),
                   , enable_sse2=$default_ssemath)
     if test x$enable_sse2 = xyes; then
         save_CFLAGS="$CFLAGS"
@@ -629,6 +629,43 @@ AC_HELP_STRING([--enable-sse2], [use SSE2 assembly routines [[default=no]]]),
         fi
     fi
 
+    AC_ARG_ENABLE(sse3,
+AC_HELP_STRING([--enable-sse3], [use SSE3 assembly routines [[default=maybe]]]),
+                  , enable_sse3=$default_ssemath)
+    if test x$enable_sse3 = xyes; then
+        save_CFLAGS="$CFLAGS"
+        have_gcc_sse3=no
+        AC_MSG_CHECKING(for GCC -msse3 option)
+        sse3_CFLAGS="-msse3"
+        CFLAGS="$save_CFLAGS $sse3_CFLAGS"
+
+        AC_TRY_COMPILE([
+        #ifdef __MINGW32__
+        #include <_mingw.h>
+        #ifdef __MINGW64_VERSION_MAJOR
+        #include <intrin.h>
+        #else
+        #include <pmmintrin.h>
+        #endif
+        #else
+        #include <pmmintrin.h>
+        #endif
+        #ifndef __SSE2__
+        #error Assembler CPP flag not enabled
+        #endif
+        ],[
+        ],[
+        have_gcc_sse3=yes
+        ])
+        AC_MSG_RESULT($have_gcc_sse3)
+        CFLAGS="$save_CFLAGS"
+
+        if test x$have_gcc_sse3 = xyes; then
+            EXTRA_CFLAGS="$EXTRA_CFLAGS $sse3_CFLAGS"
+            SUMMARY_math="${SUMMARY_math} sse3"
+        fi
+    fi
+
     AC_ARG_ENABLE(altivec,
 AC_HELP_STRING([--enable-altivec], [use Altivec assembly routines [[default=yes]]]),
                   , enable_altivec=yes)
@@ -802,6 +839,63 @@ AC_HELP_STRING([--enable-alsa-shared], [dynamically load ALSA audio support [[de
     fi
 }
 
+dnl Find JACK Audio
+CheckJACK()
+{
+    AC_ARG_ENABLE(jack,
+AC_HELP_STRING([--enable-jack], [use JACK audio [[default=yes]]]),
+                  , enable_jack=yes)
+    if test x$enable_audio = xyes -a x$enable_jack = xyes; then
+        audio_jack=no
+
+        JACK_REQUIRED_VERSION=0.125
+
+        AC_PATH_PROG(PKG_CONFIG, pkg-config, no)
+        AC_MSG_CHECKING(for JACK $JACK_REQUIRED_VERSION support)
+        if test x$PKG_CONFIG != xno; then
+        if $PKG_CONFIG --atleast-pkgconfig-version 0.7 && $PKG_CONFIG --atleast-version $JACK_REQUIRED_VERSION jack; then
+                JACK_CFLAGS=`$PKG_CONFIG --cflags jack`
+                JACK_LIBS=`$PKG_CONFIG --libs jack`
+                audio_jack=yes
+            fi
+        fi
+        AC_MSG_RESULT($audio_jack)
+
+        if test x$audio_jack = xyes; then
+            AC_ARG_ENABLE(jack-shared,
+AC_HELP_STRING([--enable-jack-shared], [dynamically load JACK audio support [[default=yes]]]),
+                          , enable_jack_shared=yes)
+            jack_lib=[`find_lib "libjack.so.*" "$JACK_LIBS" | sed 's/.*\/\(.*\)/\1/; q'`]
+
+            AC_DEFINE(SDL_AUDIO_DRIVER_JACK, 1, [ ])
+            SOURCES="$SOURCES $srcdir/src/audio/jack/*.c"
+            EXTRA_CFLAGS="$EXTRA_CFLAGS $JACK_CFLAGS"
+            if test x$have_loadso != xyes && \
+               test x$enable_jack_shared = xyes; then
+                AC_MSG_WARN([You must have SDL_LoadObject() support for dynamic JACK audio loading])
+            fi
+            if test x$have_loadso = xyes && \
+               test x$enable_jack_shared = xyes && test x$jack_lib != x; then
+                echo "-- dynamic libjack -> $jack_lib"
+                AC_DEFINE_UNQUOTED(SDL_AUDIO_DRIVER_JACK_DYNAMIC, "$jack_lib", [ ])
+                SUMMARY_audio="${SUMMARY_audio} jack(dynamic)"
+
+                case "$host" in
+                    # On Solaris, jack must be linked deferred explicitly
+                    # to prevent undefined symbol failures.
+                    *-*-solaris*)
+                        JACK_LIBS=`echo $JACK_LIBS | sed 's/\-l/-Wl,-l/g'`
+                        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-zdeferred $JACK_LIBS -Wl,-znodeferred"
+                esac
+            else
+                EXTRA_LDFLAGS="$EXTRA_LDFLAGS $JACK_LIBS"
+                SUMMARY_audio="${SUMMARY_audio} jack"
+            fi
+            have_audio=yes
+        fi
+    fi
+}
+
 dnl Find the ESD includes and libraries
 CheckESD()
 {
@@ -1049,6 +1143,58 @@ AC_HELP_STRING([--enable-sndio-shared], [dynamically load sndio audio support [[
     fi
 }
 
+dnl Find FusionSound
+CheckFusionSound()
+{
+    AC_ARG_ENABLE(fusionsound,
+AC_HELP_STRING([--enable-fusionsound], [use FusionSound audio driver [[default=no]]]),
+                  , enable_fusionsound=no)
+    if test x$enable_audio = xyes -a x$enable_fusionsound = xyes; then
+        fusionsound=no
+
+        FUSIONSOUND_REQUIRED_VERSION=1.1.1
+
+        AC_PATH_PROG(PKG_CONFIG, pkg-config, no)
+        AC_MSG_CHECKING(for FusionSound $FUSIONSOUND_REQUIRED_VERSION support)
+        if test x$PKG_CONFIG != xno; then
+            if $PKG_CONFIG --atleast-pkgconfig-version 0.7 && $PKG_CONFIG --atleast-version $FUSIONSOUND_REQUIRED_VERSION fusionsound; then
+                FUSIONSOUND_CFLAGS=`$PKG_CONFIG --cflags fusionsound`
+                FUSIONSOUND_LIBS=`$PKG_CONFIG --libs fusionsound`
+                fusionsound=yes
+            fi
+        fi
+        AC_MSG_RESULT($fusionsound)
+
+        if test x$fusionsound = xyes; then
+            AC_DEFINE(SDL_AUDIO_DRIVER_FUSIONSOUND, 1, [ ])
+            SOURCES="$SOURCES $srcdir/src/audio/fusionsound/*.c"
+            EXTRA_CFLAGS="$EXTRA_CFLAGS $FUSIONSOUND_CFLAGS"
+            
+            AC_ARG_ENABLE(fusionsound-shared,
+AC_HELP_STRING([--enable-fusionsound-shared], [dynamically load fusionsound audio support [[default=yes]]]),
+                          , enable_fusionsound_shared=yes)
+            fusionsound_shared=no
+            AC_MSG_CHECKING(for FusionSound dynamic loading support)
+            if test x$have_loadso != xyes && \
+               test x$enable_fusionsound_shared = xyes; then
+                AC_MSG_WARN([You must have SDL_LoadObject() support for dynamic fusionsound loading])
+            fi
+            if test x$have_loadso = xyes && \
+               test x$enable_fusionsound_shared = xyes; then
+                AC_DEFINE_UNQUOTED(SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC, "libfusionsound.so", [ ])
+                fusionsound_shared=yes
+                SUMMARY_audio="${SUMMARY_audio} fusionsound(dynamic)"
+            else
+                EXTRA_LDFLAGS="$EXTRA_LDFLAGS $FUSIONSOUND_LIBS"
+                SUMMARY_audio="${SUMMARY_audio} fusionsound"
+            fi
+            AC_MSG_RESULT($fusionsound_shared)
+            
+            have_audio=yes
+        fi
+    fi
+}
+
 dnl rcg07142001 See if the user wants the disk writer audio driver...
 CheckDiskAudio()
 {
@@ -1075,6 +1221,40 @@ AC_HELP_STRING([--enable-dummyaudio], [support the dummy audio driver [[default=
     fi
 }
 
+dnl See if libsamplerate is available
+CheckLibSampleRate()
+{
+    AC_ARG_ENABLE(libsamplerate,
+AC_HELP_STRING([--enable-libsamplerate], [use libsamplerate for audio rate conversion [[default=yes]]]),
+                  , enable_libsamplerate=yes)
+    if test x$enable_libsamplerate = xyes; then
+        AC_CHECK_HEADER(samplerate.h,
+                        have_samplerate_h_hdr=yes,
+                        have_samplerate_h_hdr=no)
+        if test x$have_samplerate_h_hdr = xyes; then
+            AC_DEFINE(HAVE_LIBSAMPLERATE_H, 1, [ ])
+
+            AC_ARG_ENABLE(libsamplerate-shared,
+AC_HELP_STRING([--enable-libsamplerate-shared], [dynamically load libsamplerate [[default=yes]]]),
+                          , enable_libsamplerate_shared=yes)
+
+            samplerate_lib=[`find_lib "libsamplerate.so.*" "" | sed 's/.*\/\(.*\)/\1/; q'`]
+
+            if test x$have_loadso != xyes && \
+               test x$enable_libsamplerate_shared = xyes; then
+                AC_MSG_WARN([You must have SDL_LoadObject() support for dynamic libsamplerate loading])
+            fi
+            if test x$have_loadso = xyes && \
+               test x$enable_libsamplerate_shared = xyes && test x$samplerate_lib != x; then
+                echo "-- dynamic libsamplerate -> $samplerate_lib"
+                AC_DEFINE_UNQUOTED(SDL_LIBSAMPLERATE_DYNAMIC, "$samplerate_lib", [ ])
+            else
+                EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lsamplerate"
+            fi
+        fi
+    fi
+}
+
 dnl See if GCC's -fvisibility=hidden is supported (gcc4 and later, usually).
 dnl  Details of this flag are here: http://gcc.gnu.org/wiki/Visibility
 CheckVisibilityHidden()
@@ -1291,11 +1471,11 @@ AC_HELP_STRING([--enable-video-mir], [use Mir video driver [[default=yes]]]),
                 save_CFLAGS="$CFLAGS"
                 CFLAGS="$save_CFLAGS $MIR_CFLAGS"
 
-                dnl This will disable Mir if >= v0.25 is not available
+                dnl This will disable Mir if >= v0.26 is not available
                 AC_TRY_COMPILE([
                 #include <mir_toolkit/mir_client_library.h>
                 ],[
-                    MirTouchAction actions = mir_touch_actions
+                    MirWindowAttrib attrib = mir_window_attrib_state
                 ],[
                 video_mir=yes
                 ])
@@ -1356,8 +1536,8 @@ CheckNativeClient()
           #endif
         ],[
         ],[
-        AC_DEFINE(SDL_VIDEO_DRIVER_NACL)
-        AC_DEFINE(SDL_AUDIO_DRIVER_NACL)
+        AC_DEFINE(SDL_VIDEO_DRIVER_NACL, 1, [ ])
+        AC_DEFINE(SDL_AUDIO_DRIVER_NACL, 1, [ ])
         AC_DEFINE(HAVE_POW, 1, [ ])
         AC_DEFINE(HAVE_OPENGLES2, 1, [ ])
         AC_DEFINE(SDL_VIDEO_OPENGL_ES2, 1, [ ])
@@ -1374,11 +1554,56 @@ CheckNativeClient()
 }
 
 
-dnl Find the X11 include and library directories
-CheckX11()
+CheckRPI()
 {
+    AC_ARG_ENABLE(video-rpi,
+AC_HELP_STRING([--enable-video-rpi], [use Raspberry Pi video driver [[default=yes]]]),
+                  , enable_video_rpi=yes)
+    if test x$enable_video = xyes -a x$enable_video_rpi = xyes; then
+        if test x$ARCH = xnetbsd; then
+            RPI_CFLAGS="-I/usr/pkg/include -I/usr/pkg/include/interface/vcos/pthreads -I/usr/pkg/include/interface/vmcs_host/linux"
+            RPI_LDFLAGS="-Wl,-R/usr/pkg/lib -L/usr/pkg/lib -lbcm_host"
+        else
+            RPI_CFLAGS="-I/opt/vc/include -I/opt/vc/include/interface/vcos/pthreads -I/opt/vc/include/interface/vmcs_host/linux"
+            RPI_LDFLAGS="-L/opt/vc/lib -lbcm_host"
+        fi
+
+        # Save the original compiler flags and libraries
+        ac_save_cflags="$CFLAGS"; ac_save_libs="$LIBS"
 
+        # Add the Raspberry Pi compiler flags and libraries
+        CFLAGS="$CFLAGS $RPI_CFLAGS"; LIBS="$LIBS $RPI_LDFLAGS"
 
+        AC_MSG_CHECKING(for Raspberry Pi)
+        have_video_rpi=no
+        AC_TRY_LINK([
+          #include <bcm_host.h>
+        ],[
+          bcm_host_init();
+        ],[
+        have_video_rpi=yes
+        ],[
+        ])
+        AC_MSG_RESULT($have_video_rpi)
+
+        # Restore the compiler flags and libraries
+        CFLAGS="$ac_save_cflags"; LIBS="$ac_save_libs"
+        
+        if test x$have_video_rpi = xyes; then
+            CFLAGS="$CFLAGS $RPI_CFLAGS"
+            SDL_CFLAGS="$SDL_CFLAGS $RPI_CFLAGS"
+            EXTRA_CFLAGS="$EXTRA_CFLAGS $RPI_CFLAGS"
+            EXTRA_LDFLAGS="$EXTRA_LDFLAGS $RPI_LDFLAGS"
+            SOURCES="$SOURCES $srcdir/src/video/raspberry/*.c"
+            AC_DEFINE(SDL_VIDEO_DRIVER_RPI, 1, [ ])
+            SUMMARY_video="${SUMMARY_video} rpi"
+        fi
+    fi
+}
+
+dnl Find the X11 include and library directories
+CheckX11()
+{
     AC_ARG_ENABLE(video-x11,
 AC_HELP_STRING([--enable-video-x11], [use X11 video driver [[default=yes]]]),
                   , enable_video_x11=yes)
@@ -1496,7 +1721,7 @@ AC_HELP_STRING([--enable-x11-shared], [dynamically load X11 support [[default=ma
             ],[
             ],[
             have_const_param_XextAddDisplay=yes
-            AC_DEFINE(SDL_VIDEO_DRIVER_X11_CONST_PARAM_XEXTADDDISPLAY)
+            AC_DEFINE([SDL_VIDEO_DRIVER_X11_CONST_PARAM_XEXTADDDISPLAY], 1, [ ])
             ])
             AC_MSG_RESULT($have_const_param_XextAddDisplay)
 
@@ -1514,7 +1739,7 @@ XGetEventData(display, cookie);
 XFreeEventData(display, cookie);
             ],[
                 have_XGenericEvent=yes
-                AC_DEFINE(SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS)
+                AC_DEFINE([SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS], 1, [ ])
             ])
             AC_MSG_RESULT($have_XGenericEvent)
 
@@ -1628,7 +1853,7 @@ int event_type = XI_TouchBegin;
 XITouchClassInfo *t;
             	],[
             	have_xinput2_multitouch=yes
-            	AC_DEFINE(SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH)
+            	AC_DEFINE([SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH], 1, [])
                 SUMMARY_video_x11="${SUMMARY_video_x11} xinput2_multitouch"
             	])
             	AC_MSG_RESULT($have_xinput2_multitouch)
@@ -1803,7 +2028,7 @@ AC_HELP_STRING([--enable-video-cocoa], [use Cocoa video driver [[default=yes]]])
                   , enable_video_cocoa=yes)
     if test x$enable_video = xyes -a x$enable_video_cocoa = xyes; then
         save_CFLAGS="$CFLAGS"
-        dnl work around that we don't have Objective-C support in autoconf
+        dnl Work around that we don't have Objective-C support in autoconf
         CFLAGS="$CFLAGS -x objective-c"
         AC_MSG_CHECKING(for Cocoa framework)
         have_cocoa=no
@@ -1880,7 +2105,7 @@ AC_HELP_STRING([--enable-directfb-shared], [dynamically load directfb support [[
 
             AC_MSG_CHECKING(for directfb dynamic loading support)
             directfb_shared=no
-            directfb_lib=[`find_lib "libdirectfb.so.*" "$DIRECTFB_LIBS"`]
+            directfb_lib=[`find_lib "libdirectfb*.so.*" "$DIRECTFB_LIBS"`]
             # | sed 's/.*\/\(.*\)/\1/; q'`]
 AC_MSG_WARN("directfb $directfb_lib")
             if test x$have_loadso != xyes && \
@@ -1904,54 +2129,77 @@ AC_MSG_WARN("directfb $directfb_lib")
     fi
 }
 
-dnl Find FusionSound
-CheckFusionSound()
+dnl Find KMSDRM
+CheckKMSDRM()
 {
-    AC_ARG_ENABLE(fusionsound,
-AC_HELP_STRING([--enable-fusionsound], [use FusionSound audio driver [[default=no]]]),
-                  , enable_fusionsound=no)
-    if test x$enable_audio = xyes -a x$enable_fusionsound = xyes; then
-        fusionsound=no
+    AC_ARG_ENABLE(video-kmsdrm,
+AC_HELP_STRING([--enable-video-kmsdrm], [use KMSDRM video driver [[default=no]]]),
+                  , enable_video_kmsdrm=no)
 
-        FUSIONSOUND_REQUIRED_VERSION=1.1.1
+    if test x$enable_video = xyes -a x$enable_video_kmsdrm = xyes; then
+        video_kmsdrm=no
+        libdrm_avail=no
+        libgbm_avail=no
+
+        LIBDRM_REQUIRED_VERSION=2.4.46
+        LIBGBM_REQUIRED_VERSION=9.0.0
 
         AC_PATH_PROG(PKG_CONFIG, pkg-config, no)
-        AC_MSG_CHECKING(for FusionSound $FUSIONSOUND_REQUIRED_VERSION support)
         if test x$PKG_CONFIG != xno; then
-            if $PKG_CONFIG --atleast-pkgconfig-version 0.7 && $PKG_CONFIG --atleast-version $FUSIONSOUND_REQUIRED_VERSION fusionsound; then
-                FUSIONSOUND_CFLAGS=`$PKG_CONFIG --cflags fusionsound`
-                FUSIONSOUND_LIBS=`$PKG_CONFIG --libs fusionsound`
-                fusionsound=yes
-            fi
-        fi
-        AC_MSG_RESULT($fusionsound)
-
-        if test x$fusionsound = xyes; then
-            AC_DEFINE(SDL_AUDIO_DRIVER_FUSIONSOUND, 1, [ ])
-            SOURCES="$SOURCES $srcdir/src/audio/fusionsound/*.c"
-            EXTRA_CFLAGS="$EXTRA_CFLAGS $FUSIONSOUND_CFLAGS"
-            
-            AC_ARG_ENABLE(fusionsound-shared,
-AC_HELP_STRING([--enable-fusionsound-shared], [dynamically load fusionsound audio support [[default=yes]]]),
-                          , enable_fusionsound_shared=yes)
-            fusionsound_shared=no
-            AC_MSG_CHECKING(for FusionSound dynamic loading support)
-            if test x$have_loadso != xyes && \
-               test x$enable_fusionsound_shared = xyes; then
-                AC_MSG_WARN([You must have SDL_LoadObject() support for dynamic fusionsound loading])
-            fi
-            if test x$have_loadso = xyes && \
-               test x$enable_fusionsound_shared = xyes; then
-                AC_DEFINE_UNQUOTED(SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC, "libfusionsound.so", [ ])
-                fusionsound_shared=yes
-                SUMMARY_audio="${SUMMARY_audio} fusionsound(dynamic)"
-            else
-                EXTRA_LDFLAGS="$EXTRA_LDFLAGS $FUSIONSOUND_LIBS"
-                SUMMARY_audio="${SUMMARY_audio} fusionsound"
+            if $PKG_CONFIG --atleast-pkgconfig-version 0.7; then
+                if $PKG_CONFIG --atleast-version $LIBDRM_REQUIRED_VERSION libdrm; then
+                    LIBDRM_CFLAGS=`$PKG_CONFIG --cflags libdrm`
+                    LIBDRM_LIBS=`$PKG_CONFIG --libs libdrm`
+                    LIBDRM_PREFIX=`$PKG_CONFIG --variable=prefix libdrm`
+                    libdrm_avail=yes
+                fi
+                if $PKG_CONFIG --atleast-version $LIBGBM_REQUIRED_VERSION gbm; then
+                    LIBGBM_CFLAGS=`$PKG_CONFIG --cflags gbm`
+                    LIBGBM_LIBS=`$PKG_CONFIG --libs gbm`
+                    LIBGBM_PREFIX=`$PKG_CONFIG --variable=prefix gbm`
+                    libgbm_avail=yes
+                fi
+                if test x$libdrm_avail = xyes -a x$libgbm_avail = xyes; then
+                    video_kmsdrm=yes
+                fi
+ 
+                AC_MSG_CHECKING(for libdrm $LIBDRM_REQUIRED_VERSION library for kmsdrm support)
+                AC_MSG_RESULT($libdrm_avail)
+                AC_MSG_CHECKING(for libgbm $LIBGBM_REQUIRED_VERSION library for kmsdrm support)
+                AC_MSG_RESULT($libgbm_avail)
+
+                if test x$video_kmsdrm = xyes; then
+                    AC_ARG_ENABLE(kmsdrm-shared,
+AC_HELP_STRING([--enable-kmsdrm-shared], [dynamically load kmsdrm support [[default=yes]]]),
+                              , enable_kmsdrm_shared=yes)
+
+                    AC_DEFINE(SDL_VIDEO_DRIVER_KMSDRM, 1, [ ])
+                    SOURCES="$SOURCES $srcdir/src/video/kmsdrm/*.c"
+                    EXTRA_CFLAGS="$EXTRA_CFLAGS $LIBDRM_CFLAGS $LIBGBM_CFLAGS"
+
+                    AC_MSG_CHECKING(for kmsdrm dynamic loading support)
+                    kmsdrm_shared=no
+                    drm_lib=[`find_lib "libdrm.so.*" "$DRM_LIBS"`]
+                    gbm_lib=[`find_lib "libgbm.so.*" "$DRM_LIBS"`]
+                    if test x$have_loadso != xyes && \
+                       test x$enable_kmsdrm_shared = xyes; then
+                        AC_MSG_WARN([You must have SDL_LoadObject() support for dynamic kmsdrm loading])
+                    fi
+                    if test x$have_loadso = xyes && \
+                       test x$enable_kmsdrm_shared = xyes && test x$drm_lib != x && test x$gbm_lib != x; then
+                        kmsdrm_shared=yes
+                        AC_DEFINE_UNQUOTED(SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC, "$drm_lib", [ ])
+                        AC_DEFINE_UNQUOTED(SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM, "$gbm_lib", [ ])
+                        AC_DEFINE_UNQUOTED(HAVE_KMSDRM_SHARED, "TRUE", [ ])
+                        SUMMARY_video="${SUMMARY_video} kmsdrm(dynamic)"
+                    else
+                        EXTRA_LDFLAGS="$EXTRA_LDFLAGS $LIBDRM_LIBS $LIBGBM_LIBS"
+                        SUMMARY_video="${SUMMARY_video} kmsdrm"
+                    fi
+                    AC_MSG_RESULT($kmsdrm_shared)
+                    have_video=yes
+                fi
             fi
-            AC_MSG_RESULT($fusionsound_shared)
-            
-            have_audio=yes
         fi
     fi
 }
@@ -1970,6 +2218,30 @@ AC_HELP_STRING([--enable-video-dummy], [use dummy video driver [[default=yes]]])
     fi
 }
 
+dnl Set up the QNX video driver if enabled
+CheckQNXVideo()
+{
+    if test x$enable_video = xyes; then
+        AC_DEFINE(SDL_VIDEO_DRIVER_QNX, 1, [ ])
+        SOURCES="$SOURCES $srcdir/src/video/qnx/*.c"
+        have_video=yes
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lscreen -lEGL -lGLESv2"
+        SUMMARY_video="${SUMMARY_video} qnx"
+    fi
+}
+
+dnl Set up the QNX audio driver if enabled
+CheckQNXAudio()
+{
+    if test x$enable_audio = xyes; then
+        AC_DEFINE(SDL_AUDIO_DRIVER_QSA, 1, [ ])
+        SOURCES="$SOURCES $srcdir/src/audio/qsa/*.c"
+        have_audio=yes
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lasound"
+        SUMMARY_audio="${SUMMARY_audio} qsa"
+    fi
+}
+
 dnl Check to see if OpenGL support is desired
 AC_ARG_ENABLE(video-opengl,
 AC_HELP_STRING([--enable-video-opengl], [include OpenGL support [[default=yes]]]),
@@ -2174,6 +2446,61 @@ CheckEmscriptenGLES()
     fi
 }
 
+dnl Check to see if Vulkan support is desired
+AC_ARG_ENABLE(video-vulkan,
+AC_HELP_STRING([--enable-video-vulkan], [include Vulkan support [[default=yes]]]),
+              , enable_video_vulkan=yes)
+
+dnl Find Vulkan Header
+CheckVulkan()
+{
+    if test x$enable_video = xyes -a x$enable_video_vulkan = xyes; then
+        case "$host" in
+            *-*-androideabi*)
+                AC_TRY_COMPILE([
+                  #if defined(__ARM_ARCH) && __ARM_ARCH < 7
+                  #error Vulkan doesn't work on this configuration
+                  #endif
+                ],[
+                ],[
+                ],[
+                    enable_video_vulkan=no
+                ])
+                ;;
+            *-*-darwin*)
+                save_CFLAGS="$CFLAGS"
+                dnl Work around that we don't have Objective-C support in autoconf
+                CFLAGS="$CFLAGS -x objective-c"
+                AC_TRY_COMPILE([
+                  #include <Cocoa/Cocoa.h>
+                  #include <Metal/Metal.h>
+                  #include <QuartzCore/CAMetalLayer.h>
+
+                  #if !TARGET_CPU_X86_64
+                  #error Vulkan doesn't work on this configuration
+                  #endif
+                ],[
+                ],[
+                ],[
+                    enable_video_vulkan=no
+                ])
+                CFLAGS="$save_CFLAGS"
+                ;;
+            *)
+                ;;
+        esac
+        if test x$enable_video_vulkan = xno; then
+            # For reasons I am totally unable to see, I get an undefined macro error if
+            # I put this in the AC_TRY_COMPILE.
+            AC_MSG_WARN([Vulkan does not work on this configuration.])
+        fi
+    fi
+    if test x$enable_video_vulkan = xyes; then
+        AC_DEFINE(SDL_VIDEO_VULKAN, 1, [ ])
+        SUMMARY_video="${SUMMARY_video} vulkan"
+    fi
+}
+
 dnl See if we can use the new unified event interface in Linux 2.4
 CheckInputEvents()
 {
@@ -2231,6 +2558,12 @@ AC_HELP_STRING([--enable-libudev], [enable libudev support [[default=yes]]]),
                         have_libudev_h_hdr=no)
         if test x$have_libudev_h_hdr = xyes; then
             AC_DEFINE(HAVE_LIBUDEV_H, 1, [ ])
+
+            udev_lib=[`find_lib "libudev.so.*" "" | sed 's/.*\/\(.*\)/\1/; q'`]
+            if test x$udev_lib != x; then
+                echo "-- dynamic udev -> $udev_lib"
+                AC_DEFINE_UNQUOTED(SDL_UDEV_DYNAMIC, "$udev_lib", [ ])
+            fi
         fi
     fi
 }
@@ -2439,6 +2772,10 @@ AC_HELP_STRING([--enable-pthread-sem], [use pthread semaphores [[default=yes]]])
             pthread_cflags="-D_REENTRANT"
             pthread_lib=""
             ;;
+        *-*-nto*)
+            pthread_cflags="-D_REENTRANT"
+            pthread_lib=""
+            ;;
         *)
             pthread_cflags="-D_REENTRANT"
             pthread_lib="-lpthread"
@@ -2528,7 +2865,7 @@ AC_HELP_STRING([--enable-pthread-sem], [use pthread semaphores [[default=yes]]])
                   sem_timedwait(NULL, NULL);
                 ],[
                 have_sem_timedwait=yes
-                AC_DEFINE(HAVE_SEM_TIMEDWAIT)
+                AC_DEFINE([HAVE_SEM_TIMEDWAIT], 1, [ ])
                 ])
                 AC_MSG_RESULT($have_sem_timedwait)
             fi
@@ -2639,6 +2976,18 @@ AC_HELP_STRING([--enable-directx], [use DirectX for Windows audio/video [[defaul
         AC_CHECK_HEADER(dxgi.h, have_dxgi=yes)
         AC_CHECK_HEADER(xaudio2.h, have_xaudio2=yes)
         AC_CHECK_HEADER(xinput.h, have_xinput=yes)
+        AC_CHECK_HEADER(mmdeviceapi.h, have_wasapi=yes)
+        AC_CHECK_HEADER(audioclient.h,,have_wasapi=no)
+        AC_TRY_COMPILE([
+#include <windows.h>
+#include <xinput.h>
+XINPUT_GAMEPAD_EX x1;
+        ],[],[have_xinput_gamepadex=yes])
+        AC_TRY_COMPILE([
+#include <windows.h>
+#include <xinput.h>
+XINPUT_STATE_EX s1;
+        ],[],[have_xinput_stateex=yes])
 
         if test x$have_ddraw = xyes; then
             AC_DEFINE(HAVE_DDRAW_H, 1, [ ])
@@ -2655,6 +3004,12 @@ AC_HELP_STRING([--enable-directx], [use DirectX for Windows audio/video [[defaul
         if test x$have_xinput = xyes; then
             AC_DEFINE(HAVE_XINPUT_H, 1, [ ])
         fi
+        if test x$have_xinput_gamepadex = xyes; then
+            AC_DEFINE(HAVE_XINPUT_GAMEPAD_EX, 1, [ ])
+        fi
+        if test x$have_xinput_stateex = xyes; then
+            AC_DEFINE(HAVE_XINPUT_STATE_EX, 1, [ ])
+        fi
 
         SUMMARY_video="${SUMMARY_video} directx"
         SUMMARY_audio="${SUMMARY_audio} directx"
@@ -2883,24 +3238,8 @@ CheckWarnAll
 
 dnl Set up the configuration based on the host platform!
 case "$host" in
-    *-*-linux*|*-*-uclinux*|*-*-gnu*|*-*-k*bsd*-gnu|*-*-bsdi*|*-*-freebsd*|*-*-dragonfly*|*-*-netbsd*|*-*-openbsd*|*-*-sysv5*|*-*-solaris*|*-*-hpux*|*-*-aix*|*-*-minix*)
+    *-*-linux*|*-*-uclinux*|*-*-gnu*|*-*-k*bsd*-gnu|*-*-bsdi*|*-*-freebsd*|*-*-dragonfly*|*-*-netbsd*|*-*-openbsd*|*-*-sysv5*|*-*-solaris*|*-*-hpux*|*-*-aix*|*-*-minix*|*-*-nto*)
         case "$host" in
-            *-raspberry-linux*)
-                # Raspberry Pi
-                ARCH=linux
-                RPI_CFLAGS="-I/opt/vc/include -I/opt/vc/include/interface/vcos/pthreads -I/opt/vc/include/interface/vmcs_host/linux"
-                CFLAGS="$CFLAGS $RPI_CFLAGS"
-                SDL_CFLAGS="$SDL_CFLAGS $RPI_CFLAGS"
-                EXTRA_CFLAGS="$EXTRA_CFLAGS $RPI_CFLAGS"
-                EXTRA_LDFLAGS="$EXTRA_LDFLAGS -L/opt/vc/lib -lbcm_host -ldl"
-
-                if test x$enable_video = xyes; then
-                    SOURCES="$SOURCES $srcdir/src/video/raspberry/*.c"
-                    # FIXME: confdefs? Not AC_DEFINE?
-                    $as_echo "#define SDL_VIDEO_DRIVER_RPI 1" >>confdefs.h
-                    SUMMARY_video="${SUMMARY_video} rpi"
-                fi
-                ;;
             *-*-androideabi*)
                 # Android
                 ARCH=android
@@ -2909,6 +3248,7 @@ case "$host" in
                 SDL_CFLAGS="$SDL_CFLAGS $ANDROID_CFLAGS"
                 EXTRA_CFLAGS="$EXTRA_CFLAGS $ANDROID_CFLAGS"
                 EXTRA_LDFLAGS="$EXTRA_LDFLAGS -ldl -lGLESv1_CM -lGLESv2 -llog -landroid"
+                SDLMAIN_SOURCES="$srcdir/src/main/android/*.c"
 
                 if test x$enable_video = xyes; then
                     SOURCES="$SOURCES $srcdir/src/core/android/*.c $srcdir/src/video/android/*.c"
@@ -2926,21 +3266,6 @@ case "$host" in
             *-*-bsdi*)          ARCH=bsdi ;;
             *-*-freebsd*)       ARCH=freebsd ;;
             *-*-dragonfly*)     ARCH=freebsd ;;
-            *-raspberry-netbsd*)
-                # Raspberry Pi
-                ARCH=netbsd
-                RPI_CFLAGS="-I/usr/pkg/include -I/usr/pkg/include/interface/vcos/pthreads -I/usr/pkg/include/interface/vmcs_host/linux"
-                CFLAGS="$CFLAGS $RPI_CFLAGS"
-                SDL_CFLAGS="$SDL_CFLAGS $RPI_CFLAGS"
-                EXTRA_CFLAGS="$EXTRA_CFLAGS $RPI_CFLAGS"
-                EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-R/usr/pkg/lib -L/usr/pkg/lib -lbcm_host -ldl"
-
-                if test x$enable_video = xyes; then
-                    SOURCES="$SOURCES $srcdir/src/video/raspberry/*.c"
-                    $as_echo "#define SDL_VIDEO_DRIVER_RPI 1" >>confdefs.h
-                    SUMMARY_video="${SUMMARY_video} raspberry"
-                fi
-                ;;
             *-*-netbsd*)        ARCH=netbsd ;;
             *-*-openbsd*)       ARCH=openbsd ;;
             *-*-sysv5*)         ARCH=sysv5 ;;
@@ -2948,6 +3273,9 @@ case "$host" in
             *-*-hpux*)          ARCH=hpux ;;
             *-*-aix*)           ARCH=aix ;;
             *-*-minix*)         ARCH=minix ;;
+            *-*-nto*)           ARCH=nto
+                CheckQNXVideo
+                ;;
         esac
         CheckVisibilityHidden
         CheckDeclarationAfterStatement
@@ -2958,15 +3286,21 @@ case "$host" in
         CheckOSS
         CheckALSA
         CheckPulseAudio
+        CheckJACK
         CheckARTSC
         CheckESD
         CheckNAS
         CheckSNDIO
+        CheckFusionSound
+        CheckLibSampleRate
+        # Need to check for Raspberry PI first and add platform specific compiler flags, otherwise the test for GLES fails!
+        CheckRPI
         CheckX11
         CheckDirectFB
-        CheckFusionSound
+        CheckKMSDRM
         CheckOpenGLX11
         CheckOpenGLESX11
+        CheckVulkan
         CheckMir
         CheckWayland
         CheckLibUDev
@@ -2987,22 +3321,26 @@ case "$host" in
         CheckLinuxVersion
         CheckRPATH
         CheckVivanteVideo
+
         # Set up files for the audio library
         if test x$enable_audio = xyes; then
           case $ARCH in
             sysv5|solaris|hpux)
                 AC_DEFINE(SDL_AUDIO_DRIVER_SUNAUDIO, 1, [ ])
                 SOURCES="$SOURCES $srcdir/src/audio/sun/*.c"
+                SUMMARY_audio="${SUMMARY_audio} sun"
                 have_audio=yes
             ;;
             netbsd)  # Don't use this on OpenBSD, it's busted.
-                AC_DEFINE(SDL_AUDIO_DRIVER_BSD, 1, [ ])
-                SOURCES="$SOURCES $srcdir/src/audio/bsd/*.c"
+                AC_DEFINE(SDL_AUDIO_DRIVER_NETBSD, 1, [ ])
+                SOURCES="$SOURCES $srcdir/src/audio/netbsd/*.c"
+                SUMMARY_audio="${SUMMARY_audio} netbsd"
                 have_audio=yes
             ;;
             aix)
                 AC_DEFINE(SDL_AUDIO_DRIVER_PAUDIO, 1, [ ])
                 SOURCES="$SOURCES $srcdir/src/audio/paudio/*.c"
+                SUMMARY_audio="${SUMMARY_audio} paudio"
                 have_audio=yes
             ;;
             android)
@@ -3011,6 +3349,9 @@ case "$host" in
                 SUMMARY_audio="${SUMMARY_audio} android"
                 have_audio=yes
             ;;
+            nto)
+                CheckQNXAudio
+            ;;
           esac
         fi
         # Set up files for the joystick library
@@ -3082,8 +3423,10 @@ case "$host" in
         fi
         # Set up files for evdev input
         if test x$use_input_events = xyes; then
-            SOURCES="$SOURCES $srcdir/src/core/linux/SDL_evdev.c"
+            SOURCES="$SOURCES $srcdir/src/core/linux/SDL_evdev*.c"
         fi       
+        # Set up other core UNIX files
+        SOURCES="$SOURCES $srcdir/src/core/unix/*.c"
         ;;
     *-*-cygwin* | *-*-mingw32*)
         ARCH=win32
@@ -3096,12 +3439,14 @@ case "$host" in
                 ac_default_prefix=$BUILD_PREFIX
             fi
         fi
+        CheckDeclarationAfterStatement
         CheckDummyVideo
         CheckDiskAudio
         CheckDummyAudio
         CheckWINDOWS
         CheckWINDOWSGL
         CheckWINDOWSGLES
+        CheckVulkan
         CheckDIRECTX
 
         # Set up the core platform files
@@ -3134,6 +3479,10 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
                 AC_DEFINE(SDL_AUDIO_DRIVER_XAUDIO2, 1, [ ])
                 SOURCES="$SOURCES $srcdir/src/audio/xaudio2/*.c"
             fi
+            if test x$have_wasapi = xyes; then
+                AC_DEFINE(SDL_AUDIO_DRIVER_WASAPI, 1, [ ])
+                SOURCES="$SOURCES $srcdir/src/audio/wasapi/*.c"
+            fi
             have_audio=yes
         fi
         # Set up files for the joystick library
@@ -3229,6 +3578,7 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
         CheckDummyVideo
         CheckDiskAudio
         CheckDummyAudio
+        CheckDLOPEN
         CheckHaikuVideo
         CheckHaikuGL
         CheckPTHREAD
@@ -3237,6 +3587,7 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
         if test x$enable_audio = xyes; then
             AC_DEFINE(SDL_AUDIO_DRIVER_HAIKU, 1, [ ])
             SOURCES="$SOURCES $srcdir/src/audio/haiku/*.cc"
+            SUMMARY_audio="${SUMMARY_audio} haiku"
             have_audio=yes
         fi
         # Set up files for the joystick library
@@ -3251,12 +3602,6 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
             SOURCES="$SOURCES $srcdir/src/timer/haiku/*.c"
             have_timers=yes
         fi
-        # Set up files for the shared object loading library
-        if test x$enable_loadso = xyes; then
-            AC_DEFINE(SDL_LOADSO_HAIKU, 1, [ ])
-            SOURCES="$SOURCES $srcdir/src/loadso/haiku/*.c"
-            have_loadso=yes
-        fi
         # Set up files for the system power library
         if test x$enable_power = xyes; then
             AC_DEFINE(SDL_POWER_HAIKU, 1, [ ])
@@ -3272,10 +3617,11 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
         # The Haiku platform requires special setup.
         SOURCES="$srcdir/src/main/haiku/*.cc $SOURCES"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lroot -lbe -lmedia -lgame -ldevice -ltextencoding"
+        # Haiku's x86 spins use libstdc++.r4.so (for binary compat?), but
+        #  other spins, like x86-64, use a more standard "libstdc++.so.*"
+        AC_CHECK_FILE("/boot/system/lib/libstdc++.r4.so", EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lstdc++.r4", EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lstdc++")
         ;;
-    arm*-apple-darwin*)
-        # iOS - We are not writing anything to confdefs.h because you have to replace
-        # SDL_config.h for SDL_config_iphoneos.h anyway
+    arm*-apple-darwin*|*-ios-*)
         ARCH=ios
 
         CheckVisibilityHidden
@@ -3284,18 +3630,19 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
         CheckDiskAudio
         CheckDummyAudio
         CheckDLOPEN
-        CheckCOCOA
         CheckPTHREAD
-
+        CheckVulkan
 
         # Set up files for the audio library
         if test x$enable_audio = xyes; then
+            AC_DEFINE(SDL_AUDIO_DRIVER_COREAUDIO, 1, [ ])
             SOURCES="$SOURCES $srcdir/src/audio/coreaudio/*.m"
             SUMMARY_audio="${SUMMARY_audio} coreaudio"
             have_audio=yes
         fi
         # Set up files for the joystick library
         if test x$enable_joystick = xyes; then
+            AC_DEFINE(SDL_JOYSTICK_MFI, 1, [ ])
             SOURCES="$SOURCES $srcdir/src/joystick/iphoneos/*.m"
             have_joystick=yes
         fi
@@ -3307,6 +3654,7 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
         #fi
         # Set up files for the power library
         if test x$enable_power = xyes; then
+            AC_DEFINE(SDL_POWER_UIKIT, 1, [ ])
             SOURCES="$SOURCES $srcdir/src/power/uikit/*.m"
             have_power=yes
         fi
@@ -3315,28 +3663,37 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
             SOURCES="$SOURCES $srcdir/src/filesystem/cocoa/*.m"
             have_filesystem=yes
         fi
+        # Set up additional files for the file library
+        if test x$enable_file = xyes; then
+            AC_DEFINE(SDL_FILESYSTEM_COCOA, 1, [ ])
+            SOURCES="$SOURCES $srcdir/src/file/cocoa/*.m"
+        fi
         # Set up files for the timer library
         if test x$enable_timers = xyes; then
+            AC_DEFINE(SDL_TIMER_UNIX, 1, [ ])
             SOURCES="$SOURCES $srcdir/src/timer/unix/*.c"
             have_timers=yes
         fi
-        # Set up additional files for the file library
-        if test x$enable_file = xyes; then
-            SOURCES="$SOURCES $srcdir/src/file/cocoa/*.m"
-        fi
+        # Set up other core UNIX files
+        SOURCES="$SOURCES $srcdir/src/core/unix/*.c"
         # The iOS platform requires special setup.
+        AC_DEFINE(SDL_VIDEO_DRIVER_UIKIT, 1, [ ])
+        AC_DEFINE(SDL_VIDEO_OPENGL_ES2, 1, [ ])
+        AC_DEFINE(SDL_VIDEO_OPENGL_ES, 1, [ ])
+        AC_DEFINE(SDL_VIDEO_RENDER_OGL_ES, 1, [ ])
+        AC_DEFINE(SDL_VIDEO_RENDER_OGL_ES2, 1, [ ])
         SOURCES="$SOURCES $srcdir/src/video/uikit/*.m"
-        EXTRA_CFLAGS="$EXTRA_CFLAGS -fpascal-strings"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lm -liconv -lobjc"
-        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,Foundation"
-        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,UIKit"
-        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,OpenGLES"
-        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,QuartzCore"
-        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,CoreAudio"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,AVFoundation"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,AudioToolbox"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,CoreAudio"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,CoreGraphics"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,CoreMotion"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,Foundation"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,GameController"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,OpenGLES"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,QuartzCore"
+        EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,UIKit"
         ;;
     *-*-darwin* )
         # This could be either full "Mac OS X", or plain "Darwin" which is
@@ -3358,6 +3715,7 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
         CheckX11
         CheckMacGL
         CheckOpenGLX11
+        CheckVulkan
         CheckPTHREAD
 
         # Set up files for the audio library
@@ -3403,8 +3761,9 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
         if test x$enable_file = xyes; then
             SOURCES="$SOURCES $srcdir/src/file/cocoa/*.m"
         fi
+        # Set up other core UNIX files
+        SOURCES="$SOURCES $srcdir/src/core/unix/*.c"
         # The Mac OS X platform requires special setup.
-        EXTRA_CFLAGS="$EXTRA_CFLAGS -fpascal-strings"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lobjc"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,CoreVideo"
         EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-framework,Cocoa"
@@ -3421,7 +3780,7 @@ AC_HELP_STRING([--enable-render-d3d], [enable the Direct3D render driver [[defau
         
         # Set up files for the timer library
         if test x$enable_timers = xyes; then
-            AC_DEFINE(SDL_TIMER_UNIX)
+            AC_DEFINE(SDL_TIMER_UNIX, 1, [ ])
             SOURCES="$SOURCES $srcdir/src/timer/unix/*.c"
             have_timers=yes
         fi
@@ -3604,16 +3963,16 @@ VERSION_DEPENDS=`echo "$VERSION_DEPENDS" | sed "s,\\([[^ ]]*\\)/\\([[^ ]]*\\)\\.
 
 SDLMAIN_OBJECTS=`echo $SDLMAIN_SOURCES`
 SDLMAIN_DEPENDS=`echo $SDLMAIN_SOURCES`
-SDLMAIN_OBJECTS=`echo "$SDLMAIN_OBJECTS" | sed 's,[[^ ]]*/\([[^ ]]*\)\.c,$(objects)/\1.o,g'`
+SDLMAIN_OBJECTS=`echo "$SDLMAIN_OBJECTS" | sed 's,[[^ ]]*/\([[^ ]]*\)\.c,$(objects)/\1.lo,g'`
 SDLMAIN_DEPENDS=`echo "$SDLMAIN_DEPENDS" | sed "s,\\([[^ ]]*\\)/\\([[^ ]]*\\)\\.c,\\\\
-\\$(objects)/\\2.o: \\1/\\2.c\\\\
+\\$(objects)/\\2.lo: \\1/\\2.c\\\\
 	\\$(RUN_CMD_CC)\\$(LIBTOOL) --tag=CC --mode=compile \\$(CC) \\$(CFLAGS) \\$(EXTRA_CFLAGS) $DEPENDENCY_TRACKING_OPTIONS -c \\$< -o \\$@,g"`
 
 SDLTEST_OBJECTS=`echo $SDLTEST_SOURCES`
 SDLTEST_DEPENDS=`echo $SDLTEST_SOURCES`
-SDLTEST_OBJECTS=`echo "$SDLTEST_OBJECTS" | sed 's,[[^ ]]*/\([[^ ]]*\)\.c,$(objects)/\1.o,g'`
+SDLTEST_OBJECTS=`echo "$SDLTEST_OBJECTS" | sed 's,[[^ ]]*/\([[^ ]]*\)\.c,$(objects)/\1.lo,g'`
 SDLTEST_DEPENDS=`echo "$SDLTEST_DEPENDS" | sed "s,\\([[^ ]]*\\)/\\([[^ ]]*\\)\\.c,\\\\
-\\$(objects)/\\2.o: \\1/\\2.c\\\\
+\\$(objects)/\\2.lo: \\1/\\2.c\\\\
 	\\$(RUN_CMD_CC)\\$(LIBTOOL) --tag=CC --mode=compile \\$(CC) \\$(CFLAGS) \\$(EXTRA_CFLAGS) $DEPENDENCY_TRACKING_OPTIONS -c \\$< -o \\$@,g"`
 
 # Set runtime shared library paths as needed
@@ -3718,30 +4077,35 @@ if test x$have_x = xyes; then
     SUMMARY="${SUMMARY}X11 libraries   :${SUMMARY_video_x11}\n"
 fi
 SUMMARY="${SUMMARY}Input drivers   :${SUMMARY_input}\n"
-if test x$enable_libudev = xyes; then
-    SUMMARY="${SUMMARY}Using libudev   : YES\n"
+if test x$have_samplerate_h_hdr = xyes; then
+    SUMMARY="${SUMMARY}Using libsamplerate : YES\n"
+else
+    SUMMARY="${SUMMARY}Using libsamplerate : NO\n"
+fi
+if test x$have_libudev_h_hdr = xyes; then
+    SUMMARY="${SUMMARY}Using libudev       : YES\n"
 else
-    SUMMARY="${SUMMARY}Using libudev   : NO\n"
+    SUMMARY="${SUMMARY}Using libudev       : NO\n"
 fi
 if test x$have_dbus_dbus_h_hdr = xyes; then
-    SUMMARY="${SUMMARY}Using dbus      : YES\n"
+    SUMMARY="${SUMMARY}Using dbus          : YES\n"
 else
-    SUMMARY="${SUMMARY}Using dbus      : NO\n"
+    SUMMARY="${SUMMARY}Using dbus          : NO\n"
 fi
 if test x$enable_ime = xyes; then
-    SUMMARY="${SUMMARY}Using ime       : YES\n"
+    SUMMARY="${SUMMARY}Using ime           : YES\n"
 else
-    SUMMARY="${SUMMARY}Using ime       : NO\n"
+    SUMMARY="${SUMMARY}Using ime           : NO\n"
 fi
 if test x$have_ibus_ibus_h_hdr = xyes; then
-    SUMMARY="${SUMMARY}Using ibus      : YES\n"
+    SUMMARY="${SUMMARY}Using ibus          : YES\n"
 else
-    SUMMARY="${SUMMARY}Using ibus      : NO\n"
+    SUMMARY="${SUMMARY}Using ibus          : NO\n"
 fi
 if test x$have_fcitx_frontend_h_hdr = xyes; then
-    SUMMARY="${SUMMARY}Using fcitx     : YES\n"
+    SUMMARY="${SUMMARY}Using fcitx         : YES\n"
 else
-    SUMMARY="${SUMMARY}Using fcitx     : NO\n"
+    SUMMARY="${SUMMARY}Using fcitx         : NO\n"
 fi
 AC_CONFIG_COMMANDS([summary], [echo -en "$SUMMARY"], [SUMMARY="$SUMMARY"])
 
diff --git a/docs/README-android.md b/docs/README-android.md
index ad42756..747bf72 100644
--- a/docs/README-android.md
+++ b/docs/README-android.md
@@ -1,16 +1,23 @@
 Android
 ================================================================================
 
-Requirements:
+Matt Styles wrote a tutorial on building SDL for Android with Visual Studio:
+http://trederia.blogspot.de/2017/03/building-sdl2-for-android-with-visual.html
 
-Android SDK (version 12 or later)
-http://developer.android.com/sdk/index.html
+The rest of this README covers the old style build process.
+
+================================================================================
+ Requirements
+================================================================================
+
+Android SDK (version 16 or later)
+https://developer.android.com/sdk/index.html
 
 Android NDK r7 or later
-http://developer.android.com/tools/sdk/ndk/index.html
+https://developer.android.com/tools/sdk/ndk/index.html
 
 Minimum API level supported by SDL: 10 (Android 2.3.3)
-Joystick support is available for API level >=12 devices.
+Joystick support is available for API level >= 12 devices.
 
 ================================================================================
  How the port works
@@ -229,7 +236,7 @@ under iOS, if the OS can not restore your GL context it will just kill your app)
 ================================================================================
 
 For a quick tour on how Linux native threads interoperate with the Java VM, take
-a look here: http://developer.android.com/guide/practices/jni.html
+a look here: https://developer.android.com/guide/practices/jni.html
 
 If you want to use threads in your SDL app, it's strongly recommended that you
 do so by creating them using SDL functions. This way, the required attach/detach
@@ -265,7 +272,7 @@ The best place to start is with docs/OVERVIEW.TXT
 ================================================================================
 
 First make sure that you've installed Eclipse and the Android extensions as described here:
-	http://developer.android.com/tools/sdk/eclipse-adt.html
+	https://developer.android.com/tools/sdk/eclipse-adt.html
 
 Once you've copied the SDL android project and customized it, you can create an Eclipse project from it:
  * File -> New -> Other
@@ -281,7 +288,7 @@ Once you've copied the SDL android project and customized it, you can create an
 ================================================================================
 
 There are some good tips and tricks for getting the most out of the
-emulator here: http://developer.android.com/tools/devices/emulator.html
+emulator here: https://developer.android.com/tools/devices/emulator.html
 
 Especially useful is the info on setting up OpenGL ES 2.0 emulation.
 
@@ -446,7 +453,7 @@ Support for native OpenGL ES and ES2 applications was introduced in the NDK for
 API level 4 and 8. EGL was made a stable API in the NDK for API level 9, which
 has since then been obsoleted, with the recommendation to developers to bump the
 required API level to 10.
-As of this writing, according to http://developer.android.com/about/dashboards/index.html
+As of this writing, according to https://developer.android.com/about/dashboards/index.html
 about 90% of the Android devices accessing Google Play support API level 10 or
 higher (March 2013).
 
diff --git a/docs/README-emscripten.md b/docs/README-emscripten.md
index 1f445f5..b535cc6 100644
--- a/docs/README-emscripten.md
+++ b/docs/README-emscripten.md
@@ -5,7 +5,7 @@ Build:
 
     $ mkdir build
     $ cd build
-    $ emconfigure ../configure --host=asmjs-unknown-emscripten --disable-assembly --disable-threads --enable-cpuinfo=false CFLAGS="-O2"
+    $ emconfigure ../configure --host=asmjs-unknown-emscripten --disable-assembly --disable-threads --disable-cpuinfo CFLAGS="-O2"
     $ emmake make
 
 Or with cmake:
@@ -22,8 +22,6 @@ To build one of the tests:
 
 Uses GLES2 renderer or software
 
-tests: https://dl.dropboxusercontent.com/u/17360362/SDL2-em/index.html
-
 Some other SDL2 libraries can be easily built (assuming SDL2 is installed somewhere):
 
 SDL_mixer (http://www.libsdl.org/projects/SDL_mixer/):
diff --git a/docs/README-hg.md b/docs/README-hg.md
index 67bf98f..5f3d259 100644
--- a/docs/README-hg.md
+++ b/docs/README-hg.md
@@ -5,15 +5,12 @@ The latest development version of SDL is available via Mercurial.
 Mercurial allows you to get up-to-the-minute fixes and enhancements;
 as a developer works on a source tree, you can use "hg" to mirror that
 source tree instead of waiting for an official release. Please look
-at the Mercurial website ( http://mercurial.selenic.com/ ) for more
+at the Mercurial website ( https://www.mercurial-scm.org/ ) for more
 information on using hg, where you can also download software for
 Mac OS X, Windows, and Unix systems.
 
     hg clone http://hg.libsdl.org/SDL
 
-If you are building SDL with an IDE, you will need to copy the file
-include/SDL_config.h.default to include/SDL_config.h before building.
-
 If you are building SDL via configure, you will need to run autogen.sh
 before running configure.
 
diff --git a/docs/README-ios.md b/docs/README-ios.md
index 29f4170..18c4bc0 100644
--- a/docs/README-ios.md
+++ b/docs/README-ios.md
@@ -8,8 +8,9 @@ Building the Simple DirectMedia Layer for iOS 5.1+
 Requirements: Mac OS X 10.8 or later and the iOS 7+ SDK.
 
 Instructions:
-1.  Open SDL.xcodeproj (located in Xcode-iOS/SDL) in Xcode.
-2.  Select your desired target, and hit build.
+
+2.  Open SDL.xcodeproj (located in Xcode-iOS/SDL) in Xcode.
+4.  Select your desired target, and hit build.
 
 There are three build targets:
 - libSDL.a:
@@ -24,8 +25,9 @@ There are three build targets:
 Build SDL for iOS from the command line
 ==============================================================================
 
-1. cd (PATH WHERE THE SDL CODE IS)/build-scripts
-2. ./iosbuild.sh
+1. Follow step 1 above.
+2. cd (PATH WHERE THE SDL CODE IS)/build-scripts
+3. ./iosbuild.sh
 
 If everything goes fine, you should see a build/ios directory, inside there's
 two directories "lib" and "include". 
@@ -264,3 +266,20 @@ e.g.
     #endif
         return 0;
     }
+
+==============================================================================
+Deploying to older versions of iOS
+==============================================================================
+
+SDL supports deploying to older versions of iOS than are supported by the latest version of Xcode, all the way back to iOS 6.1
+
+In order to do that you need to download an older version of Xcode:
+https://developer.apple.com/download/more/?name=Xcode
+
+Open the package contents of the older Xcode and your newer version of Xcode and copy over the folders in Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
+
+Then open the file Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/SDKSettings.plist and add the versions of iOS you want to deploy to the key Root/DefaultProperties/DEPLOYMENT_TARGET_SUGGESTED_VALUES
+
+Open your project and set your deployment target to the desired version of iOS
+
+Finally, remove GameController from the list of frameworks linked by your application and edit the build settings for "Other Linker Flags" and add -weak_framework GameController
diff --git a/docs/README-linux.md b/docs/README-linux.md
index 30c5efc..fdc06a0 100644
--- a/docs/README-linux.md
+++ b/docs/README-linux.md
@@ -20,9 +20,9 @@ libtool libasound2-dev libpulse-dev libaudio-dev libx11-dev libxext-dev \
 libxrandr-dev libxcursor-dev libxi-dev libxinerama-dev libxxf86vm-dev \
 libxss-dev libgl1-mesa-dev libesd0-dev libdbus-1-dev libudev-dev \
 libgles1-mesa-dev libgles2-mesa-dev libegl1-mesa-dev libibus-1.0-dev \
-fcitx-libs-dev
+fcitx-libs-dev libsamplerate0-dev libsndio-dev
 
-Ubuntu 16.04 can also add "libwayland-dev libxkbcommon-dev wayland-protocols"
+Ubuntu 16.04+ can also add "libwayland-dev libxkbcommon-dev wayland-protocols"
 to that command line for Wayland support.
 
 Ubuntu 16.10 can also add "libmirclient-dev libxkbcommon-dev" to that command
@@ -31,6 +31,10 @@ line for Mir support.
 NOTES:
 - This includes all the audio targets except arts, because Ubuntu pulled the 
   artsc0-dev package, but in theory SDL still supports it.
+- libsamplerate0-dev lets SDL optionally link to libresamplerate at runtime
+  for higher-quality audio resampling. SDL will work without it if the library
+  is missing, so it's safe to build in support even if the end user doesn't
+  have this library installed.
 - DirectFB isn't included because the configure script (currently) fails to find
   it at all. You can do "sudo apt-get install libdirectfb-dev" and fix the 
   configure script to include DirectFB support. Send patches.  :)
diff --git a/docs/README-macosx.md b/docs/README-macosx.md
index 869de2e..15ab39e 100644
--- a/docs/README-macosx.md
+++ b/docs/README-macosx.md
@@ -8,6 +8,9 @@ From the developer's point of view, OS X is a sort of hybrid Mac and
 Unix system, and you have the option of using either traditional
 command line tools or Apple's IDE Xcode.
 
+Command Line Build
+==================
+
 To build SDL using the command line, use the standard configure and make
 process:
 
diff --git a/docs/README-porting.md b/docs/README-porting.md
index f06f274..86243f6 100644
--- a/docs/README-porting.md
+++ b/docs/README-porting.md
@@ -25,7 +25,7 @@ There are two basic ways of building SDL at the moment:
    If you're using an IDE or other non-configure build system, you'll probably
    want to create a custom SDL_config.h for your platform.  Edit SDL_config.h,
    add a section for your platform, and create a custom SDL_config_{platform}.h,
-   based on SDL_config.h.minimal and SDL_config.h.in
+   based on SDL_config_minimal.h and SDL_config.h.in
 
    Add the top level include directory to the header search path, and then add
    the following sources to the project:
@@ -40,6 +40,7 @@ There are two basic ways of building SDL at the moment:
 	src/joystick/*.c
 	src/power/*.c
 	src/render/*.c
+	src/render/software/*.c
 	src/stdlib/*.c
 	src/thread/*.c
 	src/timer/*.c
diff --git a/docs/README-raspberrypi.md b/docs/README-raspberrypi.md
index 6b6b785..fbcffa1 100644
--- a/docs/README-raspberrypi.md
+++ b/docs/README-raspberrypi.md
@@ -23,7 +23,7 @@ Raspbian (other Linux distros may work as well).
 sudo apt-get install libudev-dev libasound2-dev libdbus-1-dev
 
 You also need the VideoCore binary stuff that ships in /opt/vc for EGL and 
-OpenGL ES 2.x, it usually comes pre installed, but in any case:
+OpenGL ES 2.x, it usually comes pre-installed, but in any case:
     
 sudo apt-get install libraspberrypi0 libraspberrypi-bin libraspberrypi-dev
 
@@ -37,7 +37,7 @@ will be placed in /opt/rpi-tools
 
     sudo git clone --depth 1 https://github.com/raspberrypi/tools /opt/rpi-tools
 
-You'll also need a Rasbian binary image.
+You'll also need a Raspbian binary image.
 Get it from: http://downloads.raspberrypi.org/raspbian_latest 
 After unzipping, you'll get file with a name like: "<date>-wheezy-raspbian.img"
 Let's assume the sysroot will be built in /opt/rpi-sysroot.
@@ -136,9 +136,9 @@ your app has read access to one of the following:
 This is usually not a problem if you run from the physical terminal (as opposed
 to running from a pseudo terminal, such as via SSH). If running from a PTS, a 
 quick workaround is to run your app as root or add yourself to the tty group,
-then re login to the system.
+then re-login to the system.
 
-   sudo usermod -aG tty `whoami`
+    sudo usermod -aG tty `whoami`
     
 The keyboard layout used by SDL is the same as the one the kernel uses.
 To configure the layout on Raspbian:
diff --git a/docs/README-windows.md b/docs/README-windows.md
index de6e606..71f968e 100644
--- a/docs/README-windows.md
+++ b/docs/README-windows.md
@@ -1,41 +1,45 @@
-Windows
-================================================================================
-
-================================================================================
-OpenGL ES 2.x support
-================================================================================
-
-SDL has support for OpenGL ES 2.x under Windows via two alternative 
-implementations. 
-The most straightforward method consists in running your app in a system with 
-a graphic card paired with a relatively recent (as of November of 2013) driver 
-which supports the WGL_EXT_create_context_es2_profile extension. Vendors known 
-to ship said extension on Windows currently include nVidia and Intel.
-
-The other method involves using the ANGLE library (https://code.google.com/p/angleproject/)
-If an OpenGL ES 2.x context is requested and no WGL_EXT_create_context_es2_profile
-extension is found, SDL will try to load the libEGL.dll library provided by
-ANGLE.
-To obtain the ANGLE binaries, you can either compile from source from
-https://chromium.googlesource.com/angle/angle or copy the relevant binaries from
-a recent Chrome/Chromium install for Windows. The files you need are:
-    
-    * libEGL.dll
-    * libGLESv2.dll
-    * d3dcompiler_46.dll (supports Windows Vista or later, better shader compiler)
-    or...
-    * d3dcompiler_43.dll (supports Windows XP or later)
-    
-If you compile ANGLE from source, you can configure it so it does not need the
-d3dcompiler_* DLL at all (for details on this, see their documentation). 
-However, by default SDL will try to preload the d3dcompiler_46.dll to
-comply with ANGLE's requirements. If you wish SDL to preload d3dcompiler_43.dll (to
-support Windows XP) or to skip this step at all, you can use the 
-SDL_HINT_VIDEO_WIN_D3DCOMPILER hint (see SDL_hints.h for more details).
-
-Known Bugs:
-    
-    * SDL_GL_SetSwapInterval is currently a no op when using ANGLE. It appears
-      that there's a bug in the library which prevents the window contents from
-      refreshing if this is set to anything other than the default value.
-      
+Windows
+================================================================================
+
+================================================================================
+OpenGL ES 2.x support
+================================================================================
+
+SDL has support for OpenGL ES 2.x under Windows via two alternative 
+implementations. 
+The most straightforward method consists in running your app in a system with 
+a graphic card paired with a relatively recent (as of November of 2013) driver 
+which supports the WGL_EXT_create_context_es2_profile extension. Vendors known 
+to ship said extension on Windows currently include nVidia and Intel.
+
+The other method involves using the ANGLE library (https://code.google.com/p/angleproject/)
+If an OpenGL ES 2.x context is requested and no WGL_EXT_create_context_es2_profile
+extension is found, SDL will try to load the libEGL.dll library provided by
+ANGLE.
+To obtain the ANGLE binaries, you can either compile from source from
+https://chromium.googlesource.com/angle/angle or copy the relevant binaries from
+a recent Chrome/Chromium install for Windows. The files you need are:
+    
+    * libEGL.dll
+    * libGLESv2.dll
+    * d3dcompiler_46.dll (supports Windows Vista or later, better shader compiler)
+    or...
+    * d3dcompiler_43.dll (supports Windows XP or later)
+    
+If you compile ANGLE from source, you can configure it so it does not need the
+d3dcompiler_* DLL at all (for details on this, see their documentation). 
+However, by default SDL will try to preload the d3dcompiler_46.dll to
+comply with ANGLE's requirements. If you wish SDL to preload d3dcompiler_43.dll (to
+support Windows XP) or to skip this step at all, you can use the 
+SDL_HINT_VIDEO_WIN_D3DCOMPILER hint (see SDL_hints.h for more details).
+
+Known Bugs:
+    
+    * SDL_GL_SetSwapInterval is currently a no op when using ANGLE. It appears
+      that there's a bug in the library which prevents the window contents from
+      refreshing if this is set to anything other than the default value.
+     
+Vulkan Surface Support
+==============
+
+Support for creating Vulkan surfaces is configured on by default. To disable it change the value of `SDL_VIDEO_VULKAN` to 0 in `SDL_config_windows.h`. You must install the [Vulkan SDK](https://www.lunarg.com/vulkan-sdk/) in order to use Vulkan graphics in your application.
diff --git a/docs/README-winrt.md b/docs/README-winrt.md
index 8c92d7d..5ec4732 100644
--- a/docs/README-winrt.md
+++ b/docs/README-winrt.md
@@ -16,13 +16,22 @@ Some of the operating systems that include WinRT, are:
 Requirements
 ------------
 
-* Microsoft Visual C++ (aka Visual Studio), either 2015, 2013, or 2012
+* Microsoft Visual C++ (aka Visual Studio), either 2017, 2015, 2013, or 2012
   - Free, "Community" or "Express" editions may be used, so long as they
     include  support for either "Windows Store" or "Windows Phone" apps.
     "Express" versions marked as supporting "Windows Desktop" development
     typically do not include support for creating WinRT apps, to note.
     (The "Community" editions of Visual C++ do, however, support both
     desktop/Win32 and WinRT development).
+  - Visual Studio 2017 can be used, however it is recommented that you install
+    the Visual C++ 2015 build tools.  These build tools can be installed
+    using VS 2017's installer.  Be sure to also install the workload for
+    "Universal Windows Platform development", its optional component, the
+    "C++ Universal Windows Platform tools", and for UWP / Windows 10
+    development, the "Windows 10 SDK (10.0.10240.0)".  Please note that
+    targeting UWP / Windows 10 apps from development machine(s) running
+    earlier versions of Windows, such as Windows 7, is not always supported
+    by Visual Studio, and you may get error(s) when attempting to do so.
   - Visual C++ 2012 can only build apps that target versions 8.0 of Windows,
     or  Windows Phone.  8.0-targetted apps will run on devices running 8.1
     editions of Windows, however they will not be able to take advantage of
@@ -66,7 +75,10 @@ Here is a rough list of what works, and what doens't:
     anything outside of the app is not supported.
   * system path retrieval via SDL's filesystem APIs
   * game controllers.  Support is provided via the SDL_Joystick and
-    SDL_GameController APIs, and is backed by Microsoft's XInput API.
+    SDL_GameController APIs, and is backed by Microsoft's XInput API.  Please
+    note, however, that Windows limits game-controller support in UWP apps to,
+    "Xbox compatible controllers" (many controllers that work in Win32 apps,
+    do not work in UWP, due to restrictions in UWP itself.) 
   * multi-touch input
   * app events.  SDL_APP_WILLENTER* and SDL_APP_DIDENTER* events get sent out as
     appropriate.
@@ -81,7 +93,7 @@ Here is a rough list of what works, and what doens't:
   * keyboard input.  Most of WinRT's documented virtual keys are supported, as
     well as many keys with documented hardware scancodes.  Converting
     SDL_Scancodes to or from SDL_Keycodes may not work, due to missing APIs
-    (MapVirualKey()) in Microsoft's Windows Store / UWP APIs.
+    (MapVirtualKey()) in Microsoft's Windows Store / UWP APIs.
   * SDLmain.  WinRT uses a different signature for each app's main() function.
     SDL-based apps that use this port must compile in SDL_winrt_main_NonXAML.cpp
     (in `SDL\src\main\winrt\`) directly in order for their C-style main()
@@ -94,8 +106,10 @@ Here is a rough list of what works, and what doens't:
     SDL_CreateSystemCursor() (unsupported on Windows Phone)
   * SDL_WarpMouseInWindow() or SDL_WarpMouseGlobal().  This are not currently
     supported by WinRT itself.
-  * joysticks and game controllers that aren't supported by Microsoft's XInput
-    API.
+  * joysticks and game controllers that either are not supported by
+    Microsoft's XInput API, or are not supported within UWP apps (many
+    controllers that work in Win32, do not work in UWP, due to restrictions in
+    UWP itself).
   * turning off VSync when rendering on Windows Phone.  Attempts to turn VSync
     off on Windows Phone result either in Direct3D not drawing anything, or it
     forcing VSync back on.  As such, SDL_RENDERER_PRESENTVSYNC will always get
@@ -476,3 +490,52 @@ SDL provides a workaround for this, but it requires that an app links to a
 set of Win32-style cursor image-resource files.  A copy of suitable resource
 files can be found in `src/main/winrt/`.  Adding them to an app's Visual C++
 project file should be sufficient to get the app to use them.
+
+
+#### SDL's Visual Studio project file fails to open, with message, "The system can't find the file specified."
+
+This can be caused for any one of a few reasons, which Visual Studio can
+report, but won't always do so in an up-front manner.
+
+To help determine why this error comes up:
+
+1. open a copy of Visual Studio without opening a project file.  This can be
+   accomplished via Windows' Start Menu, among other means.
+2. show Visual Studio's Output window.  This can be done by going to VS'
+   menu bar, then to View, and then to Output.
+3. try opening the SDL project file directly by going to VS' menu bar, then
+   to File, then to Open, then to Project/Solution.  When a File-Open dialog
+   appears, open the SDL project (such as the one in SDL's source code, in its
+   directory, VisualC-WinRT/UWP_VS2015/).
+4. after attempting to open SDL's Visual Studio project file, additional error
+   information will be output to the Output window.
+
+If Visual Studio reports (via its Output window) that the project:
+
+"could not be loaded because it's missing install components. To fix this launch Visual Studio setup with the following selections:
+Microsoft.VisualStudio.ComponentGroup.UWP.VC"
+
+... then you will need to re-launch Visual Studio's installer, and make sure that
+the workflow for "Universal Windows Platform development" is checked, and that its
+optional component, "C++ Universal Windows Platform tools" is also checked.  While
+you are there, if you are planning on targeting UWP / Windows 10, also make sure
+that you check the optional component, "Windows 10 SDK (10.0.10240.0)".  After
+making sure these items are checked as-appropriate, install them.
+
+Once you install these components, try re-launching Visual Studio, and re-opening
+the SDL project file.  If you still get the error dialog, try using the Output
+window, again, seeing what Visual Studio says about it.
+
+
+#### Game controllers / joysticks aren't working!
+
+Windows only permits certain game controllers and joysticks to work within
+WinRT / UWP apps.  Even if a game controller or joystick works in a Win32
+app, that device is not guaranteed to work inside a WinRT / UWP app.
+
+According to Microsoft, "Xbox compatible controllers" should work inside
+UWP apps, potentially with more working in the future.  This includes, but
+may not be limited to, Microsoft-made Xbox controllers and USB adapters.
+(Source: https://social.msdn.microsoft.com/Forums/en-US/9064838b-e8c3-4c18-8a83-19bf0dfe150d/xinput-fails-to-detect-game-controllers?forum=wpdevelop)
+
+
diff --git a/docs/README.md b/docs/README.md
index e0aa33f..7e2c151 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -54,7 +54,7 @@ If you need help with the library, or just want to discuss SDL related
 issues, you can join the [developers mailing list](http://www.libsdl.org/mailing-list.php)
 
 If you want to report bugs or contribute patches, please submit them to
-[bugzilla](http://bugzilla.libsdl.org/)
+[bugzilla](https://bugzilla.libsdl.org/)
 
 Enjoy!
 
diff --git a/include/SDL.h b/include/SDL.h
index 1a3fa28..366d50f 100644
--- a/include/SDL.h
+++ b/include/SDL.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -26,8 +26,8 @@
  */
 
 
-#ifndef _SDL_H
-#define _SDL_H
+#ifndef SDL_h_
+#define SDL_h_
 
 #include "SDL_main.h"
 #include "SDL_stdinc.h"
@@ -40,10 +40,10 @@
 #include "SDL_error.h"
 #include "SDL_events.h"
 #include "SDL_filesystem.h"
-#include "SDL_joystick.h"
 #include "SDL_gamecontroller.h"
 #include "SDL_haptic.h"
 #include "SDL_hints.h"
+#include "SDL_joystick.h"
 #include "SDL_loadso.h"
 #include "SDL_log.h"
 #include "SDL_messagebox.h"
@@ -51,6 +51,7 @@
 #include "SDL_power.h"
 #include "SDL_render.h"
 #include "SDL_rwops.h"
+#include "SDL_shape.h"
 #include "SDL_system.h"
 #include "SDL_thread.h"
 #include "SDL_timer.h"
@@ -127,6 +128,6 @@ extern DECLSPEC void SDLCALL SDL_Quit(void);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_H */
+#endif /* SDL_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_assert.h b/include/SDL_assert.h
index 402981f..90abbe3 100644
--- a/include/SDL_assert.h
+++ b/include/SDL_assert.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_assert_h
-#define _SDL_assert_h
+#ifndef SDL_assert_h_
+#define SDL_assert_h_
 
 #include "SDL_config.h"
 
@@ -51,9 +51,11 @@ assert can have unique static variables associated with it.
 /* Don't include intrin.h here because it contains C++ code */
     extern void __cdecl __debugbreak(void);
     #define SDL_TriggerBreakpoint() __debugbreak()
-#elif (!defined(__NACL__) && defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))
+#elif ( (!defined(__NACL__)) && ((defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))) )
     #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "int $3\n\t" )
-#elif defined(HAVE_SIGNAL_H)
+#elif defined(__386__) && defined(__WATCOMC__)
+    #define SDL_TriggerBreakpoint() { _asm { int 0x03 } }
+#elif defined(HAVE_SIGNAL_H) && !defined(__WATCOMC__)
     #include <signal.h>
     #define SDL_TriggerBreakpoint() raise(SIGTRAP)
 #else
@@ -63,7 +65,7 @@ assert can have unique static variables associated with it.
 
 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 supports __func__ as a standard. */
 #   define SDL_FUNCTION __func__
-#elif ((__GNUC__ >= 2) || defined(_MSC_VER))
+#elif ((__GNUC__ >= 2) || defined(_MSC_VER) || defined (__WATCOMC__))
 #   define SDL_FUNCTION __FUNCTION__
 #else
 #   define SDL_FUNCTION "???"
@@ -201,7 +203,7 @@ typedef SDL_AssertState (SDLCALL *SDL_AssertionHandler)(
  *
  *  This callback is NOT reset to SDL's internal handler upon SDL_Quit()!
  *
- *  \return SDL_AssertState value of how to handle the assertion failure.
+ *  Return SDL_AssertState value of how to handle the assertion failure.
  *
  *  \param handler Callback function, called when an assertion fails.
  *  \param userdata A pointer passed to the callback as-is.
@@ -250,7 +252,7 @@ extern DECLSPEC SDL_AssertionHandler SDLCALL SDL_GetAssertionHandler(void **puse
  *  <code>
  *  const SDL_AssertData *item = SDL_GetAssertionReport();
  *  while (item) {
- *      printf("'%s', %s (%s:%d), triggered %u times, always ignore: %s.\n",
+ *      printf("'%s', %s (%s:%d), triggered %u times, always ignore: %s.\\n",
  *             item->condition, item->function, item->filename,
  *             item->linenum, item->trigger_count,
  *             item->always_ignore ? "yes" : "no");
@@ -284,6 +286,6 @@ extern DECLSPEC void SDLCALL SDL_ResetAssertionReport(void);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_assert_h */
+#endif /* SDL_assert_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_atomic.h b/include/SDL_atomic.h
index 56aa81d..36e37f3 100644
--- a/include/SDL_atomic.h
+++ b/include/SDL_atomic.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -56,8 +56,8 @@
  * All of the atomic operations that modify memory are full memory barriers.
  */
 
-#ifndef _SDL_atomic_h_
-#define _SDL_atomic_h_
+#ifndef SDL_atomic_h_
+#define SDL_atomic_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_platform.h"
@@ -118,13 +118,16 @@ extern DECLSPEC void SDLCALL SDL_AtomicUnlock(SDL_SpinLock *lock);
  * The compiler barrier prevents the compiler from reordering
  * reads and writes to globally visible variables across the call.
  */
-#if defined(_MSC_VER) && (_MSC_VER > 1200)
+#if defined(_MSC_VER) && (_MSC_VER > 1200) && !defined(__clang__)
 void _ReadWriteBarrier(void);
 #pragma intrinsic(_ReadWriteBarrier)
 #define SDL_CompilerBarrier()   _ReadWriteBarrier()
 #elif (defined(__GNUC__) && !defined(__EMSCRIPTEN__)) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5120))
 /* This is correct for all CPUs when using GCC or Solaris Studio 12.1+. */
 #define SDL_CompilerBarrier()   __asm__ __volatile__ ("" : : : "memory")
+#elif defined(__WATCOMC__)
+extern _inline void SDL_CompilerBarrier (void);
+#pragma aux SDL_CompilerBarrier = "" parm [] modify exact [];
 #else
 #define SDL_CompilerBarrier()   \
 { SDL_SpinLock _tmp = 0; SDL_AtomicLock(&_tmp); SDL_AtomicUnlock(&_tmp); }
@@ -149,6 +152,9 @@ void _ReadWriteBarrier(void);
  * For more information on these semantics, take a look at the blog post:
  * http://preshing.com/20120913/acquire-and-release-semantics
  */
+extern DECLSPEC void SDLCALL SDL_MemoryBarrierReleaseFunction(void);
+extern DECLSPEC void SDLCALL SDL_MemoryBarrierAcquireFunction(void);
+
 #if defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__))
 #define SDL_MemoryBarrierRelease()   __asm__ __volatile__ ("lwsync" : : : "memory")
 #define SDL_MemoryBarrierAcquire()   __asm__ __volatile__ ("lwsync" : : : "memory")
@@ -156,11 +162,11 @@ void _ReadWriteBarrier(void);
 #if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__)
 #define SDL_MemoryBarrierRelease()   __asm__ __volatile__ ("dmb ish" : : : "memory")
 #define SDL_MemoryBarrierAcquire()   __asm__ __volatile__ ("dmb ish" : : : "memory")
-#elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__)
+#elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_5TE__)
 #ifdef __thumb__
 /* The mcr instruction isn't available in thumb mode, use real functions */
-extern DECLSPEC void SDLCALL SDL_MemoryBarrierRelease();
-extern DECLSPEC void SDLCALL SDL_MemoryBarrierAcquire();
+#define SDL_MemoryBarrierRelease()   SDL_MemoryBarrierReleaseFunction()
+#define SDL_MemoryBarrierAcquire()   SDL_MemoryBarrierAcquireFunction()
 #else
 #define SDL_MemoryBarrierRelease()   __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory")
 #define SDL_MemoryBarrierAcquire()   __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory")
@@ -263,6 +269,6 @@ extern DECLSPEC void* SDLCALL SDL_AtomicGetPtr(void **a);
 
 #include "close_code.h"
 
-#endif /* _SDL_atomic_h_ */
+#endif /* SDL_atomic_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_audio.h b/include/SDL_audio.h
index d51f0d1..53277cb 100644
--- a/include/SDL_audio.h
+++ b/include/SDL_audio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Access to the raw audio mixing buffer for the SDL library.
  */
 
-#ifndef _SDL_audio_h
-#define _SDL_audio_h
+#ifndef SDL_audio_h_
+#define SDL_audio_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -171,7 +171,7 @@ typedef struct SDL_AudioSpec
     SDL_AudioFormat format;     /**< Audio data format */
     Uint8 channels;             /**< Number of channels: 1 mono, 2 stereo */
     Uint8 silence;              /**< Audio buffer silence value (calculated) */
-    Uint16 samples;             /**< Audio buffer size in samples (power of 2) */
+    Uint16 samples;             /**< Audio buffer size in sample FRAMES (total samples divided by channel count) */
     Uint16 padding;             /**< Necessary for some compile environments */
     Uint32 size;                /**< Audio buffer size in bytes (calculated) */
     SDL_AudioCallback callback; /**< Callback that feeds the audio device (NULL to use SDL_QueueAudio()). */
@@ -184,7 +184,23 @@ typedef void (SDLCALL * SDL_AudioFilter) (struct SDL_AudioCVT * cvt,
                                           SDL_AudioFormat format);
 
 /**
- *  A structure to hold a set of audio conversion filters and buffers.
+ *  \brief Upper limit of filters in SDL_AudioCVT
+ *
+ *  The maximum number of SDL_AudioFilter functions in SDL_AudioCVT is
+ *  currently limited to 9. The SDL_AudioCVT.filters array has 10 pointers,
+ *  one of which is the terminating NULL pointer.
+ */
+#define SDL_AUDIOCVT_MAX_FILTERS 9
+
+/**
+ *  \struct SDL_AudioCVT
+ *  \brief A structure to hold a set of audio conversion filters and buffers.
+ *
+ *  Note that various parts of the conversion pipeline can take advantage
+ *  of SIMD operations (like SSE2, for example). SDL_AudioCVT doesn't require
+ *  you to pass it aligned data, but can possibly run much faster if you
+ *  set both its (buf) field to a pointer that is aligned to 16 bytes, and its
+ *  (len) field to something that's a multiple of 16, if possible.
  */
 #ifdef __GNUC__
 /* This structure is 84 bytes on 32-bit architectures, make sure GCC doesn't
@@ -208,7 +224,7 @@ typedef struct SDL_AudioCVT
     int len_cvt;                /**< Length of converted audio buffer */
     int len_mult;               /**< buffer must be len*len_mult big */
     double len_ratio;           /**< Given len, final size is len*len_ratio */
-    SDL_AudioFilter filters[10];        /**< Filter list */
+    SDL_AudioFilter filters[SDL_AUDIOCVT_MAX_FILTERS + 1]; /**< NULL-terminated list of filter functions */
     int filter_index;           /**< Current audio conversion function */
 } SDL_AUDIOCVT_PACKED SDL_AudioCVT;
 
@@ -434,10 +450,10 @@ extern DECLSPEC void SDLCALL SDL_FreeWAV(Uint8 * audio_buf);
  *  This function takes a source format and rate and a destination format
  *  and rate, and initializes the \c cvt structure with information needed
  *  by SDL_ConvertAudio() to convert a buffer of audio data from one format
- *  to the other.
+ *  to the other. An unsupported format causes an error and -1 will be returned.
  *
- *  \return -1 if the format conversion is not supported, 0 if there's
- *  no conversion needed, or 1 if the audio filter is set up.
+ *  \return 0 if no conversion is needed, 1 if the audio filter is set up,
+ *  or -1 on error.
  */
 extern DECLSPEC int SDLCALL SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
                                               SDL_AudioFormat src_format,
@@ -456,6 +472,8 @@ extern DECLSPEC int SDLCALL SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
  *  The data conversion may expand the size of the audio data, so the buffer
  *  \c cvt->buf should be allocated after the \c cvt structure is initialized by
  *  SDL_BuildAudioCVT(), and should be \c cvt->len*cvt->len_mult bytes long.
+ *
+ *  \return 0 on success or -1 if \c cvt->buf is NULL.
  */
 extern DECLSPEC int SDLCALL SDL_ConvertAudio(SDL_AudioCVT * cvt);
 
@@ -667,6 +685,6 @@ extern DECLSPEC void SDLCALL SDL_CloseAudioDevice(SDL_AudioDeviceID dev);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_audio_h */
+#endif /* SDL_audio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_bits.h b/include/SDL_bits.h
index 528da2e..bc28572 100644
--- a/include/SDL_bits.h
+++ b/include/SDL_bits.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Functions for fiddling with bits and bitmasks.
  */
 
-#ifndef _SDL_bits_h
-#define _SDL_bits_h
+#ifndef SDL_bits_h_
+#define SDL_bits_h_
 
 #include "SDL_stdinc.h"
 
@@ -47,10 +47,20 @@ extern "C" {
  *
  *  \return Index of the most significant bit, or -1 if the value is 0.
  */
+#if defined(__WATCOMC__) && defined(__386__)
+extern _inline int _SDL_clz_watcom (Uint32);
+#pragma aux _SDL_clz_watcom = \
+    "bsr eax, eax" \
+    "xor eax, 31" \
+    parm [eax] nomemory \
+    value [eax] \
+    modify exact [eax] nomemory;
+#endif
+
 SDL_FORCE_INLINE int
 SDL_MostSignificantBitIndex32(Uint32 x)
 {
-#if defined(__GNUC__) && __GNUC__ >= 4
+#if defined(__GNUC__) && (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
     /* Count Leading Zeroes builtin in GCC.
      * http://gcc.gnu.org/onlinedocs/gcc-4.3.4/gcc/Other-Builtins.html
      */
@@ -58,6 +68,11 @@ SDL_MostSignificantBitIndex32(Uint32 x)
         return -1;
     }
     return 31 - __builtin_clz(x);
+#elif defined(__WATCOMC__) && defined(__386__)
+    if (x == 0) {
+        return -1;
+    }
+    return 31 - _SDL_clz_watcom(x);
 #else
     /* Based off of Bit Twiddling Hacks by Sean Eron Anderson
      * <seander at cs.stanford.edu>, released in the public domain.
@@ -92,6 +107,6 @@ SDL_MostSignificantBitIndex32(Uint32 x)
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_bits_h */
+#endif /* SDL_bits_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_blendmode.h b/include/SDL_blendmode.h
index 56d8ad6..9abd0bd 100644
--- a/include/SDL_blendmode.h
+++ b/include/SDL_blendmode.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Header file declaring the SDL_BlendMode enumeration
  */
 
-#ifndef _SDL_blendmode_h
-#define _SDL_blendmode_h
+#ifndef SDL_blendmode_h_
+#define SDL_blendmode_h_
 
 #include "begin_code.h"
 /* Set up for C function definitions, even when using C++ */
@@ -47,17 +47,74 @@ typedef enum
     SDL_BLENDMODE_ADD = 0x00000002,      /**< additive blending
                                               dstRGB = (srcRGB * srcA) + dstRGB
                                               dstA = dstA */
-    SDL_BLENDMODE_MOD = 0x00000004       /**< color modulate
+    SDL_BLENDMODE_MOD = 0x00000004,      /**< color modulate
                                               dstRGB = srcRGB * dstRGB
                                               dstA = dstA */
+    SDL_BLENDMODE_INVALID = 0x7FFFFFFF
+
+    /* Additional custom blend modes can be returned by SDL_ComposeCustomBlendMode() */
+
 } SDL_BlendMode;
 
+/**
+ *  \brief The blend operation used when combining source and destination pixel components
+ */
+typedef enum
+{
+    SDL_BLENDOPERATION_ADD              = 0x1,  /**< dst + src: supported by all renderers */
+    SDL_BLENDOPERATION_SUBTRACT         = 0x2,  /**< dst - src : supported by D3D9, D3D11, OpenGL, OpenGLES */
+    SDL_BLENDOPERATION_REV_SUBTRACT     = 0x3,  /**< src - dst : supported by D3D9, D3D11, OpenGL, OpenGLES */
+    SDL_BLENDOPERATION_MINIMUM          = 0x4,  /**< min(dst, src) : supported by D3D11 */
+    SDL_BLENDOPERATION_MAXIMUM          = 0x5   /**< max(dst, src) : supported by D3D11 */
+
+} SDL_BlendOperation;
+
+/**
+ *  \brief The normalized factor used to multiply pixel components
+ */
+typedef enum
+{
+    SDL_BLENDFACTOR_ZERO                = 0x1,  /**< 0, 0, 0, 0 */
+    SDL_BLENDFACTOR_ONE                 = 0x2,  /**< 1, 1, 1, 1 */
+    SDL_BLENDFACTOR_SRC_COLOR           = 0x3,  /**< srcR, srcG, srcB, srcA */
+    SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = 0x4,  /**< 1-srcR, 1-srcG, 1-srcB, 1-srcA */
+    SDL_BLENDFACTOR_SRC_ALPHA           = 0x5,  /**< srcA, srcA, srcA, srcA */
+    SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = 0x6,  /**< 1-srcA, 1-srcA, 1-srcA, 1-srcA */
+    SDL_BLENDFACTOR_DST_COLOR           = 0x7,  /**< dstR, dstG, dstB, dstA */
+    SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = 0x8,  /**< 1-dstR, 1-dstG, 1-dstB, 1-dstA */
+    SDL_BLENDFACTOR_DST_ALPHA           = 0x9,  /**< dstA, dstA, dstA, dstA */
+    SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = 0xA   /**< 1-dstA, 1-dstA, 1-dstA, 1-dstA */
+
+} SDL_BlendFactor;
+
+/**
+ *  \brief Create a custom blend mode, which may or may not be supported by a given renderer
+ *
+ *  \param srcColorFactor
+ *  \param dstColorFactor
+ *  \param colorOperation
+ *  \param srcAlphaFactor
+ *  \param dstAlphaFactor
+ *  \param alphaOperation
+ *
+ *  The result of the blend mode operation will be:
+ *      dstRGB = dstRGB * dstColorFactor colorOperation srcRGB * srcColorFactor
+ *  and
+ *      dstA = dstA * dstAlphaFactor alphaOperation srcA * srcAlphaFactor
+ */
+extern DECLSPEC SDL_BlendMode SDLCALL SDL_ComposeCustomBlendMode(SDL_BlendFactor srcColorFactor,
+                                                                 SDL_BlendFactor dstColorFactor,
+                                                                 SDL_BlendOperation colorOperation,
+                                                                 SDL_BlendFactor srcAlphaFactor,
+                                                                 SDL_BlendFactor dstAlphaFactor,
+                                                                 SDL_BlendOperation alphaOperation);
+
 /* Ends C function definitions when using C++ */
 #ifdef __cplusplus
 }
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_blendmode_h */
+#endif /* SDL_blendmode_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_clipboard.h b/include/SDL_clipboard.h
index a5556f2..341f4ba 100644
--- a/include/SDL_clipboard.h
+++ b/include/SDL_clipboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  * Include file for SDL clipboard handling
  */
 
-#ifndef _SDL_clipboard_h
-#define _SDL_clipboard_h
+#ifndef SDL_clipboard_h_
+#define SDL_clipboard_h_
 
 #include "SDL_stdinc.h"
 
@@ -66,6 +66,6 @@ extern DECLSPEC SDL_bool SDLCALL SDL_HasClipboardText(void);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_clipboard_h */
+#endif /* SDL_clipboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_config.h b/include/SDL_config.h
index 4270c78..41f5baa 100644
--- a/include/SDL_config.h
+++ b/include/SDL_config.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_h
-#define _SDL_config_h
+#ifndef SDL_config_h_
+#define SDL_config_h_
 
 #include "SDL_platform.h"
 
@@ -29,9 +29,7 @@
  */
 
 /* Add any platform that doesn't build using the configure system. */
-#ifdef USING_PREMAKE_CONFIG_H
-#include "SDL_config_premake.h"
-#elif defined(__WIN32__)
+#if defined(__WIN32__)
 #include "SDL_config_windows.h"
 #elif defined(__WINRT__)
 #include "SDL_config_winrt.h"
@@ -52,4 +50,4 @@
 #error Wrong SDL_config.h, check your include path?
 #endif
 
-#endif /* _SDL_config_h */
+#endif /* SDL_config_h_ */
diff --git a/include/SDL_config.h.cmake b/include/SDL_config.h.cmake
index 98c62a9..9befa42 100644
--- a/include/SDL_config.h.cmake
+++ b/include/SDL_config.h.cmake
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_h
-#define _SDL_config_h
+#ifndef SDL_config_h_
+#define SDL_config_h_
 
 /**
  *  \file SDL_config.h.in
@@ -47,42 +47,31 @@
 #cmakedefine HAVE_GCC_ATOMICS @HAVE_GCC_ATOMICS@
 #cmakedefine HAVE_GCC_SYNC_LOCK_TEST_AND_SET @HAVE_GCC_SYNC_LOCK_TEST_AND_SET@
 
-#cmakedefine HAVE_D3D_H @HAVE_D3D_H@
-#cmakedefine HAVE_D3D11_H @HAVE_D3D11_H@
-#cmakedefine HAVE_DDRAW_H @HAVE_DDRAW_H@
-#cmakedefine HAVE_DSOUND_H @HAVE_DSOUND_H@
-#cmakedefine HAVE_DINPUT_H @HAVE_DINPUT_H@
-#cmakedefine HAVE_XAUDIO2_H @HAVE_XAUDIO2_H@
-#cmakedefine HAVE_XINPUT_H @HAVE_XINPUT_H@
-#cmakedefine HAVE_DXGI_H @HAVE_DXGI_H@
-
 /* Comment this if you want to build without any C library requirements */
 #cmakedefine HAVE_LIBC 1
 #if HAVE_LIBC
 
 /* Useful headers */
-#cmakedefine HAVE_ALLOCA_H 1
-#cmakedefine HAVE_SYS_TYPES_H 1
-#cmakedefine HAVE_STDIO_H 1
 #cmakedefine STDC_HEADERS 1
-#cmakedefine HAVE_STDLIB_H 1
-#cmakedefine HAVE_STDARG_H 1
-#cmakedefine HAVE_MALLOC_H 1
-#cmakedefine HAVE_MEMORY_H 1
-#cmakedefine HAVE_STRING_H 1
-#cmakedefine HAVE_STRINGS_H 1
-#cmakedefine HAVE_INTTYPES_H 1
-#cmakedefine HAVE_STDINT_H 1
+#cmakedefine HAVE_ALLOCA_H 1
 #cmakedefine HAVE_CTYPE_H 1
-#cmakedefine HAVE_MATH_H 1
+#cmakedefine HAVE_FLOAT_H 1
 #cmakedefine HAVE_ICONV_H 1
+#cmakedefine HAVE_INTTYPES_H 1
+#cmakedefine HAVE_LIMITS_H 1
+#cmakedefine HAVE_MALLOC_H 1
+#cmakedefine HAVE_MATH_H 1
+#cmakedefine HAVE_MEMORY_H 1
 #cmakedefine HAVE_SIGNAL_H 1
-#cmakedefine HAVE_ALTIVEC_H 1
+#cmakedefine HAVE_STDARG_H 1
+#cmakedefine HAVE_STDINT_H 1
+#cmakedefine HAVE_STDIO_H 1
+#cmakedefine HAVE_STDLIB_H 1
+#cmakedefine HAVE_STRINGS_H 1
+#cmakedefine HAVE_STRING_H 1
+#cmakedefine HAVE_SYS_TYPES_H 1
+#cmakedefine HAVE_WCHAR_H 1
 #cmakedefine HAVE_PTHREAD_NP_H 1
-#cmakedefine HAVE_LIBUDEV_H 1
-#cmakedefine HAVE_DBUS_DBUS_H 1
-#cmakedefine HAVE_IBUS_IBUS_H 1
-#cmakedefine HAVE_FCITX_FRONTEND_H 1
 
 /* C library functions */
 #cmakedefine HAVE_MALLOC 1
@@ -103,6 +92,10 @@
 #cmakedefine HAVE_MEMCPY 1
 #cmakedefine HAVE_MEMMOVE 1
 #cmakedefine HAVE_MEMCMP 1
+#cmakedefine HAVE_WCSLEN 1
+#cmakedefine HAVE_WCSLCPY 1
+#cmakedefine HAVE_WCSLCAT 1
+#cmakedefine HAVE_WCSCMP 1
 #cmakedefine HAVE_STRLEN 1
 #cmakedefine HAVE_STRLCPY 1
 #cmakedefine HAVE_STRLCAT 1
@@ -156,6 +149,7 @@
 #cmakedefine HAVE_SQRTF 1
 #cmakedefine HAVE_TAN 1
 #cmakedefine HAVE_TANF 1
+#cmakedefine HAVE_FOPEN64 1
 #cmakedefine HAVE_FSEEKO 1
 #cmakedefine HAVE_FSEEKO64 1
 #cmakedefine HAVE_SIGACTION 1
@@ -171,14 +165,36 @@
 #cmakedefine HAVE_PTHREAD_SETNAME_NP 1
 #cmakedefine HAVE_PTHREAD_SET_NAME_NP 1
 #cmakedefine HAVE_SEM_TIMEDWAIT 1
+#cmakedefine HAVE_GETAUXVAL 1
+#cmakedefine HAVE_POLL 1
+
 #elif __WIN32__
 #cmakedefine HAVE_STDARG_H 1
 #cmakedefine HAVE_STDDEF_H 1
+#cmakedefine HAVE_FLOAT_H 1
 #else
 /* We may need some replacement for stdarg.h here */
 #include <stdarg.h>
 #endif /* HAVE_LIBC */
 
+#cmakedefine HAVE_ALTIVEC_H 1
+#cmakedefine HAVE_LIBUDEV_H 1
+#cmakedefine HAVE_DBUS_DBUS_H 1
+#cmakedefine HAVE_IBUS_IBUS_H 1
+#cmakedefine HAVE_FCITX_FRONTEND_H 1
+#cmakedefine HAVE_LIBSAMPLERATE_H 1
+
+#cmakedefine HAVE_D3D_H @HAVE_D3D_H@
+#cmakedefine HAVE_D3D11_H @HAVE_D3D11_H@
+#cmakedefine HAVE_DDRAW_H @HAVE_DDRAW_H@
+#cmakedefine HAVE_DSOUND_H @HAVE_DSOUND_H@
+#cmakedefine HAVE_DINPUT_H @HAVE_DINPUT_H@
+#cmakedefine HAVE_XAUDIO2_H @HAVE_XAUDIO2_H@
+#cmakedefine HAVE_XINPUT_H @HAVE_XINPUT_H@
+#cmakedefine HAVE_DXGI_H @HAVE_DXGI_H@
+#cmakedefine HAVE_XINPUT_GAMEPAD_EX @HAVE_XINPUT_GAMEPAD_EX@
+#cmakedefine HAVE_XINPUT_STATE_EX @HAVE_XINPUT_STATE_EX@
+
 /* SDL internal assertion support */
 #cmakedefine SDL_DEFAULT_ASSERT_LEVEL @SDL_DEFAULT_ASSERT_LEVEL@
 
@@ -199,35 +215,38 @@
 #cmakedefine SDL_FILESYSTEM_DISABLED @SDL_FILESYSTEM_DISABLED@
 
 /* Enable various audio drivers */
-#cmakedefine SDL_AUDIO_DRIVER_ANDROID @SDL_AUDIO_DRIVER_ANDROID@
 #cmakedefine SDL_AUDIO_DRIVER_ALSA @SDL_AUDIO_DRIVER_ALSA@
 #cmakedefine SDL_AUDIO_DRIVER_ALSA_DYNAMIC @SDL_AUDIO_DRIVER_ALSA_DYNAMIC@
+#cmakedefine SDL_AUDIO_DRIVER_ANDROID @SDL_AUDIO_DRIVER_ANDROID@
 #cmakedefine SDL_AUDIO_DRIVER_ARTS @SDL_AUDIO_DRIVER_ARTS@
 #cmakedefine SDL_AUDIO_DRIVER_ARTS_DYNAMIC @SDL_AUDIO_DRIVER_ARTS_DYNAMIC@
-#cmakedefine SDL_AUDIO_DRIVER_PULSEAUDIO @SDL_AUDIO_DRIVER_PULSEAUDIO@
-#cmakedefine SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC @SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC@
-#cmakedefine SDL_AUDIO_DRIVER_HAIKU @SDL_AUDIO_DRIVER_HAIKU@
-#cmakedefine SDL_AUDIO_DRIVER_BSD @SDL_AUDIO_DRIVER_BSD@
 #cmakedefine SDL_AUDIO_DRIVER_COREAUDIO @SDL_AUDIO_DRIVER_COREAUDIO@
 #cmakedefine SDL_AUDIO_DRIVER_DISK @SDL_AUDIO_DRIVER_DISK@
-#cmakedefine SDL_AUDIO_DRIVER_DUMMY @SDL_AUDIO_DRIVER_DUMMY@
-#cmakedefine SDL_AUDIO_DRIVER_XAUDIO2 @SDL_AUDIO_DRIVER_XAUDIO2@
 #cmakedefine SDL_AUDIO_DRIVER_DSOUND @SDL_AUDIO_DRIVER_DSOUND@
+#cmakedefine SDL_AUDIO_DRIVER_DUMMY @SDL_AUDIO_DRIVER_DUMMY@
+#cmakedefine SDL_AUDIO_DRIVER_EMSCRIPTEN @SDL_AUDIO_DRIVER_EMSCRIPTEN@
 #cmakedefine SDL_AUDIO_DRIVER_ESD @SDL_AUDIO_DRIVER_ESD@
 #cmakedefine SDL_AUDIO_DRIVER_ESD_DYNAMIC @SDL_AUDIO_DRIVER_ESD_DYNAMIC@
+#cmakedefine SDL_AUDIO_DRIVER_FUSIONSOUND @SDL_AUDIO_DRIVER_FUSIONSOUND@
+#cmakedefine SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC @SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC@
+#cmakedefine SDL_AUDIO_DRIVER_HAIKU @SDL_AUDIO_DRIVER_HAIKU@
+#cmakedefine SDL_AUDIO_DRIVER_JACK @SDL_AUDIO_DRIVER_JACK@
+#cmakedefine SDL_AUDIO_DRIVER_JACK_DYNAMIC @SDL_AUDIO_DRIVER_JACK_DYNAMIC@
 #cmakedefine SDL_AUDIO_DRIVER_NAS @SDL_AUDIO_DRIVER_NAS@
 #cmakedefine SDL_AUDIO_DRIVER_NAS_DYNAMIC @SDL_AUDIO_DRIVER_NAS_DYNAMIC@
-#cmakedefine SDL_AUDIO_DRIVER_SNDIO @SDL_AUDIO_DRIVER_SNDIO@
-#cmakedefine SDL_AUDIO_DRIVER_SNDIO_DYNAMIC @SDL_AUDIO_DRIVER_SNDIO_DYNAMIC@
+#cmakedefine SDL_AUDIO_DRIVER_NETBSD @SDL_AUDIO_DRIVER_NETBSD@
 #cmakedefine SDL_AUDIO_DRIVER_OSS @SDL_AUDIO_DRIVER_OSS@
 #cmakedefine SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H @SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H@
 #cmakedefine SDL_AUDIO_DRIVER_PAUDIO @SDL_AUDIO_DRIVER_PAUDIO@
+#cmakedefine SDL_AUDIO_DRIVER_PULSEAUDIO @SDL_AUDIO_DRIVER_PULSEAUDIO@
+#cmakedefine SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC @SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC@
 #cmakedefine SDL_AUDIO_DRIVER_QSA @SDL_AUDIO_DRIVER_QSA@
+#cmakedefine SDL_AUDIO_DRIVER_SNDIO @SDL_AUDIO_DRIVER_SNDIO@
+#cmakedefine SDL_AUDIO_DRIVER_SNDIO_DYNAMIC @SDL_AUDIO_DRIVER_SNDIO_DYNAMIC@
 #cmakedefine SDL_AUDIO_DRIVER_SUNAUDIO @SDL_AUDIO_DRIVER_SUNAUDIO@
+#cmakedefine SDL_AUDIO_DRIVER_WASAPI @SDL_AUDIO_DRIVER_WASAPI@
 #cmakedefine SDL_AUDIO_DRIVER_WINMM @SDL_AUDIO_DRIVER_WINMM@
-#cmakedefine SDL_AUDIO_DRIVER_FUSIONSOUND @SDL_AUDIO_DRIVER_FUSIONSOUND@
-#cmakedefine SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC @SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC@
-#cmakedefine SDL_AUDIO_DRIVER_EMSCRIPTEN @SDL_AUDIO_DRIVER_EMSCRIPTEN@
+#cmakedefine SDL_AUDIO_DRIVER_XAUDIO2 @SDL_AUDIO_DRIVER_XAUDIO2@
 
 /* Enable various input drivers */
 #cmakedefine SDL_INPUT_LINUXEV @SDL_INPUT_LINUXEV@
@@ -250,9 +269,9 @@
 #cmakedefine SDL_HAPTIC_IOKIT @SDL_HAPTIC_IOKIT@
 #cmakedefine SDL_HAPTIC_DINPUT @SDL_HAPTIC_DINPUT@
 #cmakedefine SDL_HAPTIC_XINPUT @SDL_HAPTIC_XINPUT@
+#cmakedefine SDL_HAPTIC_ANDROID @SDL_HAPTIC_ANDROID@
 
 /* Enable various shared object loading systems */
-#cmakedefine SDL_LOADSO_HAIKU @SDL_LOADSO_HAIKU@
 #cmakedefine SDL_LOADSO_DLOPEN @SDL_LOADSO_DLOPEN@
 #cmakedefine SDL_LOADSO_DUMMY @SDL_LOADSO_DUMMY@
 #cmakedefine SDL_LOADSO_LDG @SDL_LOADSO_LDG@
@@ -284,6 +303,10 @@
 #cmakedefine SDL_VIDEO_DRIVER_VIVANTE @SDL_VIDEO_DRIVER_VIVANTE@
 #cmakedefine SDL_VIDEO_DRIVER_VIVANTE_VDK @SDL_VIDEO_DRIVER_VIVANTE_VDK@
 
+#cmakedefine SDL_VIDEO_DRIVER_KMSDRM @SDL_VIDEO_DRIVER_KMSDRM@
+#cmakedefine SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC @SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC@
+#cmakedefine SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM @SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM@
+
 #cmakedefine SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH @SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH@
 #cmakedefine SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC @SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC@
 #cmakedefine SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL @SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL@
@@ -335,6 +358,9 @@
 #cmakedefine SDL_VIDEO_OPENGL_OSMESA @SDL_VIDEO_OPENGL_OSMESA@
 #cmakedefine SDL_VIDEO_OPENGL_OSMESA_DYNAMIC @SDL_VIDEO_OPENGL_OSMESA_DYNAMIC@
 
+/* Enable Vulkan support */
+#cmakedefine SDL_VIDEO_VULKAN @SDL_VIDEO_VULKAN@
+
 /* Enable system power support */
 #cmakedefine SDL_POWER_ANDROID @SDL_POWER_ANDROID@
 #cmakedefine SDL_POWER_LINUX @SDL_POWER_LINUX@
@@ -357,6 +383,8 @@
 #cmakedefine SDL_ASSEMBLY_ROUTINES @SDL_ASSEMBLY_ROUTINES@
 #cmakedefine SDL_ALTIVEC_BLITTERS @SDL_ALTIVEC_BLITTERS@
 
+/* Enable dynamic libsamplerate support */
+#cmakedefine SDL_LIBSAMPLERATE_DYNAMIC @SDL_LIBSAMPLERATE_DYNAMIC@
 
 /* Platform specific definitions */
 #if !defined(__WIN32__)
@@ -418,4 +446,4 @@ typedef unsigned int uintptr_t;
 #  endif /* !_STDINT_H_ && !HAVE_STDINT_H */
 #endif /* __WIN32__ */
 
-#endif /* _SDL_config_h */
+#endif /* SDL_config_h_ */
diff --git a/include/SDL_config.h.in b/include/SDL_config.h.in
index d610cd6..988d3d9 100644
--- a/include/SDL_config.h.in
+++ b/include/SDL_config.h.in
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_h
-#define _SDL_config_h
+#ifndef SDL_config_h_
+#define SDL_config_h_
 
 /**
  *  \file SDL_config.h.in
@@ -50,39 +50,31 @@
 #undef HAVE_GCC_ATOMICS
 #undef HAVE_GCC_SYNC_LOCK_TEST_AND_SET
 
-#undef HAVE_DDRAW_H
-#undef HAVE_DINPUT_H
-#undef HAVE_DSOUND_H
-#undef HAVE_DXGI_H
-#undef HAVE_XINPUT_H
-
 /* Comment this if you want to build without any C library requirements */
 #undef HAVE_LIBC
 #if HAVE_LIBC
 
 /* Useful headers */
-#undef HAVE_ALLOCA_H
-#undef HAVE_SYS_TYPES_H
-#undef HAVE_STDIO_H
 #undef STDC_HEADERS
-#undef HAVE_STDLIB_H
-#undef HAVE_STDARG_H
-#undef HAVE_MALLOC_H
-#undef HAVE_MEMORY_H
-#undef HAVE_STRING_H
-#undef HAVE_STRINGS_H
-#undef HAVE_INTTYPES_H
-#undef HAVE_STDINT_H
+#undef HAVE_ALLOCA_H
 #undef HAVE_CTYPE_H
-#undef HAVE_MATH_H
+#undef HAVE_FLOAT_H
 #undef HAVE_ICONV_H
+#undef HAVE_INTTYPES_H
+#undef HAVE_LIMITS_H
+#undef HAVE_MALLOC_H
+#undef HAVE_MATH_H
+#undef HAVE_MEMORY_H
 #undef HAVE_SIGNAL_H
-#undef HAVE_ALTIVEC_H
+#undef HAVE_STDARG_H
+#undef HAVE_STDINT_H
+#undef HAVE_STDIO_H
+#undef HAVE_STDLIB_H
+#undef HAVE_STRINGS_H
+#undef HAVE_STRING_H
+#undef HAVE_SYS_TYPES_H
+#undef HAVE_WCHAR_H
 #undef HAVE_PTHREAD_NP_H
-#undef HAVE_LIBUDEV_H
-#undef HAVE_DBUS_DBUS_H
-#undef HAVE_IBUS_IBUS_H
-#undef HAVE_FCITX_FRONTEND_H
 
 /* C library functions */
 #undef HAVE_MALLOC
@@ -103,6 +95,10 @@
 #undef HAVE_MEMCPY
 #undef HAVE_MEMMOVE
 #undef HAVE_MEMCMP
+#undef HAVE_WCSLEN
+#undef HAVE_WCSLCPY
+#undef HAVE_WCSLCAT
+#undef HAVE_WCSCMP
 #undef HAVE_STRLEN
 #undef HAVE_STRLCPY
 #undef HAVE_STRLCAT
@@ -158,6 +154,7 @@
 #undef HAVE_SQRTF
 #undef HAVE_TAN
 #undef HAVE_TANF
+#undef HAVE_FOPEN64
 #undef HAVE_FSEEKO
 #undef HAVE_FSEEKO64
 #undef HAVE_SIGACTION
@@ -173,6 +170,8 @@
 #undef HAVE_PTHREAD_SETNAME_NP
 #undef HAVE_PTHREAD_SET_NAME_NP
 #undef HAVE_SEM_TIMEDWAIT
+#undef HAVE_GETAUXVAL
+#undef HAVE_POLL
 
 #else
 #define HAVE_STDARG_H   1
@@ -180,6 +179,21 @@
 #define HAVE_STDINT_H   1
 #endif /* HAVE_LIBC */
 
+#undef HAVE_ALTIVEC_H
+#undef HAVE_LIBUDEV_H
+#undef HAVE_DBUS_DBUS_H
+#undef HAVE_IBUS_IBUS_H
+#undef HAVE_FCITX_FRONTEND_H
+#undef HAVE_LIBSAMPLERATE_H
+
+#undef HAVE_DDRAW_H
+#undef HAVE_DINPUT_H
+#undef HAVE_DSOUND_H
+#undef HAVE_DXGI_H
+#undef HAVE_XINPUT_H
+#undef HAVE_XINPUT_GAMEPAD_EX
+#undef HAVE_XINPUT_STATE_EX
+
 /* SDL internal assertion support */
 #undef SDL_DEFAULT_ASSERT_LEVEL
 
@@ -202,34 +216,37 @@
 /* Enable various audio drivers */
 #undef SDL_AUDIO_DRIVER_ALSA
 #undef SDL_AUDIO_DRIVER_ALSA_DYNAMIC
+#undef SDL_AUDIO_DRIVER_ANDROID
 #undef SDL_AUDIO_DRIVER_ARTS
 #undef SDL_AUDIO_DRIVER_ARTS_DYNAMIC
-#undef SDL_AUDIO_DRIVER_PULSEAUDIO
-#undef SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC
-#undef SDL_AUDIO_DRIVER_HAIKU
-#undef SDL_AUDIO_DRIVER_BSD
 #undef SDL_AUDIO_DRIVER_COREAUDIO
 #undef SDL_AUDIO_DRIVER_DISK
-#undef SDL_AUDIO_DRIVER_DUMMY
-#undef SDL_AUDIO_DRIVER_ANDROID
-#undef SDL_AUDIO_DRIVER_XAUDIO2
 #undef SDL_AUDIO_DRIVER_DSOUND
+#undef SDL_AUDIO_DRIVER_DUMMY
+#undef SDL_AUDIO_DRIVER_EMSCRIPTEN
 #undef SDL_AUDIO_DRIVER_ESD
 #undef SDL_AUDIO_DRIVER_ESD_DYNAMIC
+#undef SDL_AUDIO_DRIVER_FUSIONSOUND
+#undef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC
+#undef SDL_AUDIO_DRIVER_HAIKU
+#undef SDL_AUDIO_DRIVER_JACK
+#undef SDL_AUDIO_DRIVER_JACK_DYNAMIC
 #undef SDL_AUDIO_DRIVER_NACL
 #undef SDL_AUDIO_DRIVER_NAS
 #undef SDL_AUDIO_DRIVER_NAS_DYNAMIC
-#undef SDL_AUDIO_DRIVER_SNDIO
-#undef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
+#undef SDL_AUDIO_DRIVER_NETBSD
 #undef SDL_AUDIO_DRIVER_OSS
 #undef SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H
 #undef SDL_AUDIO_DRIVER_PAUDIO
+#undef SDL_AUDIO_DRIVER_PULSEAUDIO
+#undef SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC
 #undef SDL_AUDIO_DRIVER_QSA
+#undef SDL_AUDIO_DRIVER_SNDIO
+#undef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
 #undef SDL_AUDIO_DRIVER_SUNAUDIO
+#undef SDL_AUDIO_DRIVER_WASAPI
 #undef SDL_AUDIO_DRIVER_WINMM
-#undef SDL_AUDIO_DRIVER_FUSIONSOUND
-#undef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC
-#undef SDL_AUDIO_DRIVER_EMSCRIPTEN
+#undef SDL_AUDIO_DRIVER_XAUDIO2
 
 /* Enable various input drivers */
 #undef SDL_INPUT_LINUXEV
@@ -253,7 +270,6 @@
 #undef SDL_HAPTIC_XINPUT
 
 /* Enable various shared object loading systems */
-#undef SDL_LOADSO_HAIKU
 #undef SDL_LOADSO_DLOPEN
 #undef SDL_LOADSO_DUMMY
 #undef SDL_LOADSO_LDG
@@ -289,6 +305,9 @@
 #undef SDL_VIDEO_DRIVER_MIR_DYNAMIC_XKBCOMMON
 #undef SDL_VIDEO_DRIVER_X11
 #undef SDL_VIDEO_DRIVER_RPI
+#undef SDL_VIDEO_DRIVER_KMSDRM
+#undef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC
+#undef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM
 #undef SDL_VIDEO_DRIVER_ANDROID
 #undef SDL_VIDEO_DRIVER_EMSCRIPTEN
 #undef SDL_VIDEO_DRIVER_X11_DYNAMIC
@@ -314,6 +333,7 @@
 #undef SDL_VIDEO_DRIVER_NACL
 #undef SDL_VIDEO_DRIVER_VIVANTE
 #undef SDL_VIDEO_DRIVER_VIVANTE_VDK
+#undef SDL_VIDEO_DRIVER_QNX
 
 #undef SDL_VIDEO_RENDER_D3D
 #undef SDL_VIDEO_RENDER_D3D11
@@ -334,6 +354,9 @@
 #undef SDL_VIDEO_OPENGL_OSMESA
 #undef SDL_VIDEO_OPENGL_OSMESA_DYNAMIC
 
+/* Enable Vulkan support */
+#undef SDL_VIDEO_VULKAN
+
 /* Enable system power support */
 #undef SDL_POWER_LINUX
 #undef SDL_POWER_WINDOWS
@@ -360,4 +383,10 @@
 /* Enable ime support */
 #undef SDL_USE_IME
 
-#endif /* _SDL_config_h */
+/* Enable dynamic udev support */
+#undef SDL_UDEV_DYNAMIC
+
+/* Enable dynamic libsamplerate support */
+#undef SDL_LIBSAMPLERATE_DYNAMIC
+
+#endif /* SDL_config_h_ */
diff --git a/include/SDL_config_android.h b/include/SDL_config_android.h
index 996cf76..c3169e5 100644
--- a/include/SDL_config_android.h
+++ b/include/SDL_config_android.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,9 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_android_h
-#define _SDL_config_android_h
+#ifndef SDL_config_android_h_
+#define SDL_config_android_h_
+#define SDL_config_h_
 
 #include "SDL_platform.h"
 
@@ -34,16 +35,17 @@
 
 #define HAVE_GCC_ATOMICS    1
 
-#define HAVE_ALLOCA_H       1
-#define HAVE_SYS_TYPES_H    1
-#define HAVE_STDIO_H    1
 #define STDC_HEADERS    1
-#define HAVE_STRING_H   1
-#define HAVE_INTTYPES_H 1
-#define HAVE_STDINT_H   1
+#define HAVE_ALLOCA_H       1
 #define HAVE_CTYPE_H    1
+#define HAVE_INTTYPES_H 1
+#define HAVE_LIMITS_H   1
 #define HAVE_MATH_H 1
 #define HAVE_SIGNAL_H 1
+#define HAVE_STDINT_H   1
+#define HAVE_STDIO_H    1
+#define HAVE_STRING_H   1
+#define HAVE_SYS_TYPES_H    1
 
 /* C library functions */
 #define HAVE_MALLOC 1
@@ -117,7 +119,7 @@
 
 /* Enable various input drivers */
 #define SDL_JOYSTICK_ANDROID    1
-#define SDL_HAPTIC_DUMMY    1
+#define SDL_HAPTIC_ANDROID    1
 
 /* Enable various shared object loading systems */
 #define SDL_LOADSO_DLOPEN   1
@@ -139,10 +141,18 @@
 #define SDL_VIDEO_RENDER_OGL_ES 1
 #define SDL_VIDEO_RENDER_OGL_ES2    1
 
+/* Enable Vulkan support */
+/* Android does not support Vulkan in native code using the "armeabi" ABI. */
+#if defined(__ARM_ARCH) && __ARM_ARCH < 7
+#define SDL_VIDEO_VULKAN 0
+#else
+#define SDL_VIDEO_VULKAN 1
+#endif
+
 /* Enable system power support */
 #define SDL_POWER_ANDROID 1
 
 /* Enable the filesystem driver */
 #define SDL_FILESYSTEM_ANDROID   1
 
-#endif /* _SDL_config_android_h */
+#endif /* SDL_config_android_h_ */
diff --git a/include/SDL_config_iphoneos.h b/include/SDL_config_iphoneos.h
index 470985f..94ab693 100644
--- a/include/SDL_config_iphoneos.h
+++ b/include/SDL_config_iphoneos.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,9 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_iphoneos_h
-#define _SDL_config_iphoneos_h
+#ifndef SDL_config_iphoneos_h_
+#define SDL_config_iphoneos_h_
+#define SDL_config_h_
 
 #include "SDL_platform.h"
 
@@ -32,16 +33,17 @@
 
 #define HAVE_GCC_ATOMICS    1
 
-#define HAVE_ALLOCA_H       1
-#define HAVE_SYS_TYPES_H    1
-#define HAVE_STDIO_H    1
 #define STDC_HEADERS    1
-#define HAVE_STRING_H   1
-#define HAVE_INTTYPES_H 1
-#define HAVE_STDINT_H   1
+#define HAVE_ALLOCA_H       1
 #define HAVE_CTYPE_H    1
+#define HAVE_INTTYPES_H 1
+#define HAVE_LIMITS_H   1
 #define HAVE_MATH_H 1
 #define HAVE_SIGNAL_H   1
+#define HAVE_STDINT_H   1
+#define HAVE_STDIO_H    1
+#define HAVE_STRING_H   1
+#define HAVE_SYS_TYPES_H    1
 
 /* C library functions */
 #define HAVE_MALLOC 1
@@ -138,6 +140,13 @@
 #define SDL_VIDEO_RENDER_OGL_ES 1
 #define SDL_VIDEO_RENDER_OGL_ES2    1
 
+/* Enable Vulkan support on 64-bit devices when an iOS 8+ SDK is used. */
+#if !TARGET_OS_SIMULATOR && !TARGET_CPU_ARM && defined(__IPHONE_8_0)
+#define SDL_VIDEO_VULKAN 1
+#else
+#define SDL_VIDEO_VULKAN 0
+#endif
+
 /* Enable system power support */
 #define SDL_POWER_UIKIT 1
 
@@ -155,4 +164,4 @@
 /* enable filesystem support */
 #define SDL_FILESYSTEM_COCOA   1
 
-#endif /* _SDL_config_iphoneos_h */
+#endif /* SDL_config_iphoneos_h_ */
diff --git a/include/SDL_config_macosx.h b/include/SDL_config_macosx.h
index 5c8b7e0..67f879a 100644
--- a/include/SDL_config_macosx.h
+++ b/include/SDL_config_macosx.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,9 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_macosx_h
-#define _SDL_config_macosx_h
+#ifndef SDL_config_macosx_h_
+#define SDL_config_macosx_h_
+#define SDL_config_h_
 
 #include "SDL_platform.h"
 
@@ -36,16 +37,18 @@
 #endif
 
 /* Useful headers */
-#define HAVE_ALLOCA_H       1
-#define HAVE_SYS_TYPES_H    1
-#define HAVE_STDIO_H    1
 #define STDC_HEADERS    1
-#define HAVE_STRING_H   1
-#define HAVE_INTTYPES_H 1
-#define HAVE_STDINT_H   1
+#define HAVE_ALLOCA_H       1
 #define HAVE_CTYPE_H    1
+#define HAVE_FLOAT_H    1
+#define HAVE_INTTYPES_H 1
+#define HAVE_LIMITS_H   1
 #define HAVE_MATH_H 1
 #define HAVE_SIGNAL_H   1
+#define HAVE_STDINT_H   1
+#define HAVE_STDIO_H    1
+#define HAVE_STRING_H   1
+#define HAVE_SYS_TYPES_H    1
 
 /* C library functions */
 #define HAVE_MALLOC 1
@@ -173,6 +176,14 @@
 #define SDL_VIDEO_OPENGL_GLX    1
 #endif
 
+/* Enable Vulkan support */
+/* Metal/MoltenVK/Vulkan only supported on 64-bit architectures with 10.11+ */
+#if TARGET_CPU_X86_64 && (MAC_OS_X_VERSION_MAX_ALLOWED >= 101100)
+#define SDL_VIDEO_VULKAN 1
+#else
+#define  SDL_VIDEO_VULKAN 0
+#endif
+
 /* Enable system power support */
 #define SDL_POWER_MACOSX 1
 
@@ -185,4 +196,4 @@
 #define SDL_ALTIVEC_BLITTERS    1
 #endif
 
-#endif /* _SDL_config_macosx_h */
+#endif /* SDL_config_macosx_h_ */
diff --git a/include/SDL_config_minimal.h b/include/SDL_config_minimal.h
index 3c9d09a..3112700 100644
--- a/include/SDL_config_minimal.h
+++ b/include/SDL_config_minimal.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,9 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_minimal_h
-#define _SDL_config_minimal_h
+#ifndef SDL_config_minimal_h_
+#define SDL_config_minimal_h_
+#define SDL_config_h_
 
 #include "SDL_platform.h"
 
@@ -78,4 +79,4 @@ typedef unsigned long uintptr_t;
 /* Enable the dummy filesystem driver (src/filesystem/dummy/\*.c) */
 #define SDL_FILESYSTEM_DUMMY  1
 
-#endif /* _SDL_config_minimal_h */
+#endif /* SDL_config_minimal_h_ */
diff --git a/include/SDL_config_pandora.h b/include/SDL_config_pandora.h
index 7b51e57..f6f52fc 100644
--- a/include/SDL_config_pandora.h
+++ b/include/SDL_config_pandora.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,9 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_h
-#define _SDL_config_h
+#ifndef SDL_config_pandora_h_
+#define SDL_config_pandora_h_
+#define SDL_config_h_
 
 /* This is a set of defines to configure the SDL features */
 
@@ -35,22 +36,24 @@
 
 #define SDL_BYTEORDER 1234
 
-#define HAVE_ALLOCA_H 1
-#define HAVE_SYS_TYPES_H 1
-#define HAVE_STDIO_H 1
 #define STDC_HEADERS 1
-#define HAVE_STDLIB_H 1
-#define HAVE_STDARG_H 1
-#define HAVE_MALLOC_H 1
-#define HAVE_MEMORY_H 1
-#define HAVE_STRING_H 1
-#define HAVE_STRINGS_H 1
-#define HAVE_INTTYPES_H 1
-#define HAVE_STDINT_H 1
+#define HAVE_ALLOCA_H 1
 #define HAVE_CTYPE_H 1
-#define HAVE_MATH_H 1
 #define HAVE_ICONV_H 1
+#define HAVE_INTTYPES_H 1
+#define HAVE_LIMITS_H 1
+#define HAVE_MALLOC_H 1
+#define HAVE_MATH_H 1
+#define HAVE_MEMORY_H 1
 #define HAVE_SIGNAL_H 1
+#define HAVE_STDARG_H 1
+#define HAVE_STDINT_H 1
+#define HAVE_STDIO_H 1
+#define HAVE_STDLIB_H 1
+#define HAVE_STRINGS_H 1
+#define HAVE_STRING_H 1
+#define HAVE_SYS_TYPES_H 1
+
 #define HAVE_MALLOC 1
 #define HAVE_CALLOC 1
 #define HAVE_REALLOC 1
@@ -124,4 +127,4 @@
 #define SDL_VIDEO_RENDER_OGL_ES 1
 #define SDL_VIDEO_OPENGL_ES 1
 
-#endif /* _SDL_config_h */
+#endif /* SDL_config_pandora_h_ */
diff --git a/include/SDL_config_psp.h b/include/SDL_config_psp.h
index a6e4960..0e61979 100644
--- a/include/SDL_config_psp.h
+++ b/include/SDL_config_psp.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,9 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_psp_h
-#define _SDL_config_psp_h
+#ifndef SDL_config_psp_h_
+#define SDL_config_psp_h_
+#define SDL_config_h_
 
 #include "SDL_platform.h"
 
@@ -32,16 +33,17 @@
 
 #define HAVE_GCC_ATOMICS    1
 
-#define HAVE_ALLOCA_H       1
-#define HAVE_SYS_TYPES_H    1
-#define HAVE_STDIO_H    1
 #define STDC_HEADERS    1
-#define HAVE_STRING_H   1
-#define HAVE_INTTYPES_H 1
-#define HAVE_STDINT_H   1
+#define HAVE_ALLOCA_H       1
 #define HAVE_CTYPE_H    1
+#define HAVE_INTTYPES_H 1
+#define HAVE_LIMITS_H   1
 #define HAVE_MATH_H 1
 #define HAVE_SIGNAL_H   1
+#define HAVE_STDINT_H   1
+#define HAVE_STDIO_H    1
+#define HAVE_STRING_H   1
+#define HAVE_SYS_TYPES_H    1
 
 /* C library functions */
 #define HAVE_MALLOC 1
@@ -140,4 +142,4 @@
 #define SDL_LOADSO_DISABLED    1
 
 
-#endif /* _SDL_config_psp_h */
+#endif /* SDL_config_psp_h_ */
diff --git a/include/SDL_config_windows.h b/include/SDL_config_windows.h
index 890986c..1bbb838 100644
--- a/include/SDL_config_windows.h
+++ b/include/SDL_config_windows.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,9 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_windows_h
-#define _SDL_config_windows_h
+#ifndef SDL_config_windows_h_
+#define SDL_config_windows_h_
+#define SDL_config_h_
 
 #include "SDL_platform.h"
 
@@ -85,12 +86,14 @@ typedef unsigned int uintptr_t;
 /* This is disabled by default to avoid C runtime dependencies and manifest requirements */
 #ifdef HAVE_LIBC
 /* Useful headers */
-#define HAVE_STDIO_H 1
 #define STDC_HEADERS 1
-#define HAVE_STRING_H 1
 #define HAVE_CTYPE_H 1
+#define HAVE_FLOAT_H 1
+#define HAVE_LIMITS_H 1
 #define HAVE_MATH_H 1
 #define HAVE_SIGNAL_H 1
+#define HAVE_STDIO_H 1
+#define HAVE_STRING_H 1
 
 /* C library functions */
 #define HAVE_MALLOC 1
@@ -139,12 +142,19 @@ typedef unsigned int uintptr_t;
 #define HAVE_SQRTF 1
 #define HAVE_TAN 1
 #define HAVE_TANF 1
+#define HAVE__COPYSIGN 1
+#if defined(_MSC_VER)
+/* These functions were added with the VC++ 2013 C runtime library */
 #if _MSC_VER >= 1800
 #define HAVE_STRTOLL 1
 #define HAVE_VSSCANF 1
-#define HAVE_COPYSIGN 1
 #define HAVE_SCALBN 1
 #endif
+/* This function is available with at least the VC++ 2008 C runtime library */
+#if _MSC_VER >= 1400
+#define HAVE__FSEEKI64 1
+#endif
+#endif
 #if !defined(_MSC_VER) || defined(_USE_MATH_DEFINES)
 #define HAVE_M_PI 1
 #endif
@@ -154,8 +164,9 @@ typedef unsigned int uintptr_t;
 #endif
 
 /* Enable various audio drivers */
+#define SDL_AUDIO_DRIVER_WASAPI 1
 #define SDL_AUDIO_DRIVER_DSOUND 1
-#define SDL_AUDIO_DRIVER_XAUDIO2    1
+#define SDL_AUDIO_DRIVER_XAUDIO2    0
 #define SDL_AUDIO_DRIVER_WINMM  1
 #define SDL_AUDIO_DRIVER_DISK   1
 #define SDL_AUDIO_DRIVER_DUMMY  1
@@ -206,6 +217,8 @@ typedef unsigned int uintptr_t;
 #define SDL_VIDEO_OPENGL_EGL    1
 #endif
 
+/* Enable Vulkan support */
+#define SDL_VIDEO_VULKAN 1
 
 /* Enable system power support */
 #define SDL_POWER_WINDOWS 1
@@ -218,4 +231,4 @@ typedef unsigned int uintptr_t;
 #define SDL_ASSEMBLY_ROUTINES   1
 #endif
 
-#endif /* _SDL_config_windows_h */
+#endif /* SDL_config_windows_h_ */
diff --git a/include/SDL_config_winrt.h b/include/SDL_config_winrt.h
index e392f77..93d7ae1 100644
--- a/include/SDL_config_winrt.h
+++ b/include/SDL_config_winrt.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,9 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_winrt_h
-#define _SDL_config_winrt_h
+#ifndef SDL_config_winrt_h_
+#define SDL_config_winrt_h_
+#define SDL_config_h_
 
 #include "SDL_platform.h"
 
@@ -97,13 +98,14 @@ typedef unsigned int uintptr_t;
 #define HAVE_XINPUT_H 1
 #endif
 #define HAVE_LIBC 1
-#define HAVE_STDIO_H 1
 #define STDC_HEADERS 1
-#define HAVE_STRING_H 1
 #define HAVE_CTYPE_H 1
-#define HAVE_MATH_H 1
 #define HAVE_FLOAT_H 1
+#define HAVE_LIMITS_H 1
+#define HAVE_MATH_H 1
 #define HAVE_SIGNAL_H 1
+#define HAVE_STDIO_H 1
+#define HAVE_STRING_H 1
 
 /* C library functions */
 #define HAVE_MALLOC 1
@@ -211,4 +213,4 @@ typedef unsigned int uintptr_t;
 #define SDL_ASSEMBLY_ROUTINES	1
 #endif
 
-#endif /* _SDL_config_winrt_h */
+#endif /* SDL_config_winrt_h_ */
diff --git a/include/SDL_config_wiz.h b/include/SDL_config_wiz.h
index e090a1a..3afd8d8 100644
--- a/include/SDL_config_wiz.h
+++ b/include/SDL_config_wiz.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,9 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_config_h
-#define _SDL_config_h
+#ifndef SDL_config_wiz_h_
+#define SDL_config_wiz_h_
+#define SDL_config_h_
 
 /* This is a set of defines to configure the SDL features */
 
@@ -29,22 +30,24 @@
 
 #define SDL_BYTEORDER 1234
 
-#define HAVE_ALLOCA_H 1
-#define HAVE_SYS_TYPES_H 1
-#define HAVE_STDIO_H 1
 #define STDC_HEADERS 1
-#define HAVE_STDLIB_H 1
-#define HAVE_STDARG_H 1
-#define HAVE_MALLOC_H 1
-#define HAVE_MEMORY_H 1
-#define HAVE_STRING_H 1
-#define HAVE_STRINGS_H 1
-#define HAVE_INTTYPES_H 1
-#define HAVE_STDINT_H 1
+#define HAVE_ALLOCA_H 1
 #define HAVE_CTYPE_H 1
-#define HAVE_MATH_H 1
 #define HAVE_ICONV_H 1
+#define HAVE_INTTYPES_H 1
+#define HAVE_LIMITS_H 1
+#define HAVE_MALLOC_H 1
+#define HAVE_MATH_H 1
+#define HAVE_MEMORY_H 1
 #define HAVE_SIGNAL_H 1
+#define HAVE_STDARG_H 1
+#define HAVE_STDINT_H 1
+#define HAVE_STDIO_H 1
+#define HAVE_STDLIB_H 1
+#define HAVE_STRINGS_H 1
+#define HAVE_STRING_H 1
+#define HAVE_SYS_TYPES_H 1
+
 #define HAVE_MALLOC 1
 #define HAVE_CALLOC 1
 #define HAVE_REALLOC 1
@@ -117,4 +120,4 @@
 #define SDL_VIDEO_RENDER_OGL_ES 1
 #define SDL_VIDEO_OPENGL_ES 1
 
-#endif /* _SDL_config_h */
+#endif /* SDL_config_wiz_h_ */
diff --git a/include/SDL_copying.h b/include/SDL_copying.h
index 212da0e..8f60af6 100644
--- a/include/SDL_copying.h
+++ b/include/SDL_copying.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/include/SDL_cpuinfo.h b/include/SDL_cpuinfo.h
index d0ba47b..94b64b0 100644
--- a/include/SDL_cpuinfo.h
+++ b/include/SDL_cpuinfo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,14 +25,20 @@
  *  CPU feature detection for SDL.
  */
 
-#ifndef _SDL_cpuinfo_h
-#define _SDL_cpuinfo_h
+#ifndef SDL_cpuinfo_h_
+#define SDL_cpuinfo_h_
 
 #include "SDL_stdinc.h"
 
 /* Need to do this here because intrin.h has C++ code in it */
 /* Visual Studio 2005 has a bug where intrin.h conflicts with winnt.h */
 #if defined(_MSC_VER) && (_MSC_VER >= 1500) && (defined(_M_IX86) || defined(_M_X64))
+#ifdef __clang__
+/* Many of the intrinsics SDL uses are not implemented by clang with Visual Studio */
+#undef __MMX__
+#undef __SSE__
+#undef __SSE2__
+#else
 #include <intrin.h>
 #ifndef _WIN64
 #define __MMX__
@@ -40,6 +46,7 @@
 #endif
 #define __SSE__
 #define __SSE2__
+#endif /* __clang__ */
 #elif defined(__MINGW64_VERSION_MAJOR)
 #include <intrin.h>
 #else
@@ -61,6 +68,9 @@
 #ifdef __SSE2__
 #include <emmintrin.h>
 #endif
+#ifdef __SSE3__
+#include <pmmintrin.h>
+#endif
 #endif
 
 #include "begin_code.h"
@@ -145,6 +155,11 @@ extern DECLSPEC SDL_bool SDLCALL SDL_HasAVX(void);
 extern DECLSPEC SDL_bool SDLCALL SDL_HasAVX2(void);
 
 /**
+ *  This function returns true if the CPU has NEON (ARM SIMD) features.
+ */
+extern DECLSPEC SDL_bool SDLCALL SDL_HasNEON(void);
+
+/**
  *  This function returns the amount of RAM configured in the system, in MB.
  */
 extern DECLSPEC int SDLCALL SDL_GetSystemRAM(void);
@@ -156,6 +171,6 @@ extern DECLSPEC int SDLCALL SDL_GetSystemRAM(void);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_cpuinfo_h */
+#endif /* SDL_cpuinfo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_egl.h b/include/SDL_egl.h
index bea2a6c..e47fbe8 100644
--- a/include/SDL_egl.h
+++ b/include/SDL_egl.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -132,7 +132,7 @@
 *-------------------------------------------------------------------------
 * This precedes the return type of the function in the function prototype.
 */
-#if defined(_WIN32) && !defined(__SCITECH_SNAP__)
+#if defined(_WIN32) && !defined(__SCITECH_SNAP__) && !defined(SDL_VIDEO_STATIC_ANGLE)
 #   define KHRONOS_APICALL __declspec(dllimport)
 #elif defined (__SYMBIAN32__)
 #   define KHRONOS_APICALL IMPORT_C
diff --git a/include/SDL_endian.h b/include/SDL_endian.h
index 9100b10..3eda7f2 100644
--- a/include/SDL_endian.h
+++ b/include/SDL_endian.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Functions for reading and writing endian-specific values
  */
 
-#ifndef _SDL_endian_h
-#define _SDL_endian_h
+#ifndef SDL_endian_h_
+#define SDL_endian_h_
 
 #include "SDL_stdinc.h"
 
@@ -96,6 +96,12 @@ SDL_Swap16(Uint16 x)
   __asm__("rorw #8,%0": "=d"(x): "0"(x):"cc");
     return x;
 }
+#elif defined(__WATCOMC__) && defined(__386__)
+extern _inline Uint16 SDL_Swap16(Uint16);
+#pragma aux SDL_Swap16 = \
+  "xchg al, ah" \
+  parm   [ax]   \
+  modify [ax];
 #else
 SDL_FORCE_INLINE Uint16
 SDL_Swap16(Uint16 x)
@@ -136,6 +142,21 @@ SDL_Swap32(Uint32 x)
   __asm__("rorw #8,%0\n\tswap %0\n\trorw #8,%0": "=d"(x): "0"(x):"cc");
     return x;
 }
+#elif defined(__WATCOMC__) && defined(__386__)
+extern _inline Uint32 SDL_Swap32(Uint32);
+#ifndef __SW_3 /* 486+ */
+#pragma aux SDL_Swap32 = \
+  "bswap eax"  \
+  parm   [eax] \
+  modify [eax];
+#else  /* 386-only */
+#pragma aux SDL_Swap32 = \
+  "xchg al, ah"  \
+  "ror  eax, 16" \
+  "xchg al, ah"  \
+  parm   [eax]   \
+  modify [eax];
+#endif
 #else
 SDL_FORCE_INLINE Uint32
 SDL_Swap32(Uint32 x)
@@ -234,6 +255,6 @@ SDL_SwapFloat(float x)
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_endian_h */
+#endif /* SDL_endian_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_error.h b/include/SDL_error.h
index 2f3b4b5..49be982 100644
--- a/include/SDL_error.h
+++ b/include/SDL_error.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Simple error message routines for SDL.
  */
 
-#ifndef _SDL_error_h
-#define _SDL_error_h
+#ifndef SDL_error_h_
+#define SDL_error_h_
 
 #include "SDL_stdinc.h"
 
@@ -71,6 +71,6 @@ extern DECLSPEC int SDLCALL SDL_Error(SDL_errorcode code);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_error_h */
+#endif /* SDL_error_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_events.h b/include/SDL_events.h
index edb89ef..0fc09bc 100644
--- a/include/SDL_events.h
+++ b/include/SDL_events.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Include file for SDL event handling.
  */
 
-#ifndef _SDL_events_h
-#define _SDL_events_h
+#ifndef SDL_events_h_
+#define SDL_events_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -165,7 +165,7 @@ typedef enum
 typedef struct SDL_CommonEvent
 {
     Uint32 type;
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
 } SDL_CommonEvent;
 
 /**
@@ -174,7 +174,7 @@ typedef struct SDL_CommonEvent
 typedef struct SDL_WindowEvent
 {
     Uint32 type;        /**< ::SDL_WINDOWEVENT */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     Uint32 windowID;    /**< The associated window */
     Uint8 event;        /**< ::SDL_WindowEventID */
     Uint8 padding1;
@@ -190,7 +190,7 @@ typedef struct SDL_WindowEvent
 typedef struct SDL_KeyboardEvent
 {
     Uint32 type;        /**< ::SDL_KEYDOWN or ::SDL_KEYUP */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     Uint32 windowID;    /**< The window with keyboard focus, if any */
     Uint8 state;        /**< ::SDL_PRESSED or ::SDL_RELEASED */
     Uint8 repeat;       /**< Non-zero if this is a key repeat */
@@ -206,7 +206,7 @@ typedef struct SDL_KeyboardEvent
 typedef struct SDL_TextEditingEvent
 {
     Uint32 type;                                /**< ::SDL_TEXTEDITING */
-    Uint32 timestamp;
+    Uint32 timestamp;                           /**< In milliseconds, populated using SDL_GetTicks() */
     Uint32 windowID;                            /**< The window with keyboard focus, if any */
     char text[SDL_TEXTEDITINGEVENT_TEXT_SIZE];  /**< The editing text */
     Sint32 start;                               /**< The start cursor of selected editing text */
@@ -221,7 +221,7 @@ typedef struct SDL_TextEditingEvent
 typedef struct SDL_TextInputEvent
 {
     Uint32 type;                              /**< ::SDL_TEXTINPUT */
-    Uint32 timestamp;
+    Uint32 timestamp;                         /**< In milliseconds, populated using SDL_GetTicks() */
     Uint32 windowID;                          /**< The window with keyboard focus, if any */
     char text[SDL_TEXTINPUTEVENT_TEXT_SIZE];  /**< The input text */
 } SDL_TextInputEvent;
@@ -232,7 +232,7 @@ typedef struct SDL_TextInputEvent
 typedef struct SDL_MouseMotionEvent
 {
     Uint32 type;        /**< ::SDL_MOUSEMOTION */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     Uint32 windowID;    /**< The window with mouse focus, if any */
     Uint32 which;       /**< The mouse instance id, or SDL_TOUCH_MOUSEID */
     Uint32 state;       /**< The current button state */
@@ -248,7 +248,7 @@ typedef struct SDL_MouseMotionEvent
 typedef struct SDL_MouseButtonEvent
 {
     Uint32 type;        /**< ::SDL_MOUSEBUTTONDOWN or ::SDL_MOUSEBUTTONUP */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     Uint32 windowID;    /**< The window with mouse focus, if any */
     Uint32 which;       /**< The mouse instance id, or SDL_TOUCH_MOUSEID */
     Uint8 button;       /**< The mouse button index */
@@ -265,7 +265,7 @@ typedef struct SDL_MouseButtonEvent
 typedef struct SDL_MouseWheelEvent
 {
     Uint32 type;        /**< ::SDL_MOUSEWHEEL */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     Uint32 windowID;    /**< The window with mouse focus, if any */
     Uint32 which;       /**< The mouse instance id, or SDL_TOUCH_MOUSEID */
     Sint32 x;           /**< The amount scrolled horizontally, positive to the right and negative to the left */
@@ -279,7 +279,7 @@ typedef struct SDL_MouseWheelEvent
 typedef struct SDL_JoyAxisEvent
 {
     Uint32 type;        /**< ::SDL_JOYAXISMOTION */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     SDL_JoystickID which; /**< The joystick instance id */
     Uint8 axis;         /**< The joystick axis index */
     Uint8 padding1;
@@ -295,7 +295,7 @@ typedef struct SDL_JoyAxisEvent
 typedef struct SDL_JoyBallEvent
 {
     Uint32 type;        /**< ::SDL_JOYBALLMOTION */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     SDL_JoystickID which; /**< The joystick instance id */
     Uint8 ball;         /**< The joystick trackball index */
     Uint8 padding1;
@@ -311,7 +311,7 @@ typedef struct SDL_JoyBallEvent
 typedef struct SDL_JoyHatEvent
 {
     Uint32 type;        /**< ::SDL_JOYHATMOTION */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     SDL_JoystickID which; /**< The joystick instance id */
     Uint8 hat;          /**< The joystick hat index */
     Uint8 value;        /**< The hat position value.
@@ -331,7 +331,7 @@ typedef struct SDL_JoyHatEvent
 typedef struct SDL_JoyButtonEvent
 {
     Uint32 type;        /**< ::SDL_JOYBUTTONDOWN or ::SDL_JOYBUTTONUP */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     SDL_JoystickID which; /**< The joystick instance id */
     Uint8 button;       /**< The joystick button index */
     Uint8 state;        /**< ::SDL_PRESSED or ::SDL_RELEASED */
@@ -345,7 +345,7 @@ typedef struct SDL_JoyButtonEvent
 typedef struct SDL_JoyDeviceEvent
 {
     Uint32 type;        /**< ::SDL_JOYDEVICEADDED or ::SDL_JOYDEVICEREMOVED */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     Sint32 which;       /**< The joystick device index for the ADDED event, instance id for the REMOVED event */
 } SDL_JoyDeviceEvent;
 
@@ -356,7 +356,7 @@ typedef struct SDL_JoyDeviceEvent
 typedef struct SDL_ControllerAxisEvent
 {
     Uint32 type;        /**< ::SDL_CONTROLLERAXISMOTION */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     SDL_JoystickID which; /**< The joystick instance id */
     Uint8 axis;         /**< The controller axis (SDL_GameControllerAxis) */
     Uint8 padding1;
@@ -373,7 +373,7 @@ typedef struct SDL_ControllerAxisEvent
 typedef struct SDL_ControllerButtonEvent
 {
     Uint32 type;        /**< ::SDL_CONTROLLERBUTTONDOWN or ::SDL_CONTROLLERBUTTONUP */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     SDL_JoystickID which; /**< The joystick instance id */
     Uint8 button;       /**< The controller button (SDL_GameControllerButton) */
     Uint8 state;        /**< ::SDL_PRESSED or ::SDL_RELEASED */
@@ -388,7 +388,7 @@ typedef struct SDL_ControllerButtonEvent
 typedef struct SDL_ControllerDeviceEvent
 {
     Uint32 type;        /**< ::SDL_CONTROLLERDEVICEADDED, ::SDL_CONTROLLERDEVICEREMOVED, or ::SDL_CONTROLLERDEVICEREMAPPED */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     Sint32 which;       /**< The joystick device index for the ADDED event, instance id for the REMOVED or REMAPPED event */
 } SDL_ControllerDeviceEvent;
 
@@ -398,7 +398,7 @@ typedef struct SDL_ControllerDeviceEvent
 typedef struct SDL_AudioDeviceEvent
 {
     Uint32 type;        /**< ::SDL_AUDIODEVICEADDED, or ::SDL_AUDIODEVICEREMOVED */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     Uint32 which;       /**< The audio device index for the ADDED event (valid until next SDL_GetNumAudioDevices() call), SDL_AudioDeviceID for the REMOVED event */
     Uint8 iscapture;    /**< zero if an output device, non-zero if a capture device. */
     Uint8 padding1;
@@ -413,7 +413,7 @@ typedef struct SDL_AudioDeviceEvent
 typedef struct SDL_TouchFingerEvent
 {
     Uint32 type;        /**< ::SDL_FINGERMOTION or ::SDL_FINGERDOWN or ::SDL_FINGERUP */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     SDL_TouchID touchId; /**< The touch device id */
     SDL_FingerID fingerId;
     float x;            /**< Normalized in the range 0...1 */
@@ -430,8 +430,8 @@ typedef struct SDL_TouchFingerEvent
 typedef struct SDL_MultiGestureEvent
 {
     Uint32 type;        /**< ::SDL_MULTIGESTURE */
-    Uint32 timestamp;
-    SDL_TouchID touchId; /**< The touch device index */
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
+    SDL_TouchID touchId; /**< The touch device id */
     float dTheta;
     float dDist;
     float x;
@@ -447,7 +447,7 @@ typedef struct SDL_MultiGestureEvent
 typedef struct SDL_DollarGestureEvent
 {
     Uint32 type;        /**< ::SDL_DOLLARGESTURE or ::SDL_DOLLARRECORD */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     SDL_TouchID touchId; /**< The touch device id */
     SDL_GestureID gestureId;
     Uint32 numFingers;
@@ -465,7 +465,7 @@ typedef struct SDL_DollarGestureEvent
 typedef struct SDL_DropEvent
 {
     Uint32 type;        /**< ::SDL_DROPBEGIN or ::SDL_DROPFILE or ::SDL_DROPTEXT or ::SDL_DROPCOMPLETE */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     char *file;         /**< The file name, which should be freed with SDL_free(), is NULL on begin/complete */
     Uint32 windowID;    /**< The window that was dropped on, if any */
 } SDL_DropEvent;
@@ -477,7 +477,7 @@ typedef struct SDL_DropEvent
 typedef struct SDL_QuitEvent
 {
     Uint32 type;        /**< ::SDL_QUIT */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
 } SDL_QuitEvent;
 
 /**
@@ -486,7 +486,7 @@ typedef struct SDL_QuitEvent
 typedef struct SDL_OSEvent
 {
     Uint32 type;        /**< ::SDL_QUIT */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
 } SDL_OSEvent;
 
 /**
@@ -495,7 +495,7 @@ typedef struct SDL_OSEvent
 typedef struct SDL_UserEvent
 {
     Uint32 type;        /**< ::SDL_USEREVENT through ::SDL_LASTEVENT-1 */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     Uint32 windowID;    /**< The associated window if any */
     Sint32 code;        /**< User defined event code */
     void *data1;        /**< User defined data pointer */
@@ -515,7 +515,7 @@ typedef struct SDL_SysWMmsg SDL_SysWMmsg;
 typedef struct SDL_SysWMEvent
 {
     Uint32 type;        /**< ::SDL_SYSWMEVENT */
-    Uint32 timestamp;
+    Uint32 timestamp;   /**< In milliseconds, populated using SDL_GetTicks() */
     SDL_SysWMmsg *msg;  /**< driver dependent data, defined in SDL_syswm.h */
 } SDL_SysWMEvent;
 
@@ -724,7 +724,7 @@ extern DECLSPEC void SDLCALL SDL_FilterEvents(SDL_EventFilter filter,
 /**
  *  This function allows you to set the state of processing certain events.
  *   - If \c state is set to ::SDL_IGNORE, that event will be automatically
- *     dropped from the event queue and will not event be filtered.
+ *     dropped from the event queue and will not be filtered.
  *   - If \c state is set to ::SDL_ENABLE, that event will be processed
  *     normally.
  *   - If \c state is set to ::SDL_QUERY, SDL_EventState() will return the
@@ -749,6 +749,6 @@ extern DECLSPEC Uint32 SDLCALL SDL_RegisterEvents(int numevents);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_events_h */
+#endif /* SDL_events_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_filesystem.h b/include/SDL_filesystem.h
index 02999ed..a1c846a 100644
--- a/include/SDL_filesystem.h
+++ b/include/SDL_filesystem.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  \brief Include file for filesystem SDL API functions
  */
 
-#ifndef _SDL_filesystem_h
-#define _SDL_filesystem_h
+#ifndef SDL_filesystem_h_
+#define SDL_filesystem_h_
 
 #include "SDL_stdinc.h"
 
@@ -131,6 +131,6 @@ extern DECLSPEC char *SDLCALL SDL_GetPrefPath(const char *org, const char *app);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_filesystem_h */
+#endif /* SDL_filesystem_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_gamecontroller.h b/include/SDL_gamecontroller.h
index e67fd9f..c921513 100644
--- a/include/SDL_gamecontroller.h
+++ b/include/SDL_gamecontroller.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Include file for SDL game controller event handling
  */
 
-#ifndef _SDL_gamecontroller_h
-#define _SDL_gamecontroller_h
+#ifndef SDL_gamecontroller_h_
+#define SDL_gamecontroller_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -51,7 +51,9 @@ extern "C" {
  *  SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS
  */
 
-/* The gamecontroller structure used to identify an SDL game controller */
+/**
+ * The gamecontroller structure used to identify an SDL game controller
+ */
 struct _SDL_GameController;
 typedef struct _SDL_GameController SDL_GameController;
 
@@ -87,8 +89,8 @@ typedef struct SDL_GameControllerButtonBind
  *  To count the number of game controllers in the system for the following:
  *  int nJoysticks = SDL_NumJoysticks();
  *  int nGameControllers = 0;
- *  for ( int i = 0; i < nJoysticks; i++ ) {
- *      if ( SDL_IsGameController(i) ) {
+ *  for (int i = 0; i < nJoysticks; i++) {
+ *      if (SDL_IsGameController(i)) {
  *          nGameControllers++;
  *      }
  *  }
@@ -105,7 +107,7 @@ typedef struct SDL_GameControllerButtonBind
  *  Buttons can be used as a controller axis and vice versa.
  *
  *  This string shows an example of a valid mapping for a controller
- *  "341a3608000000000000504944564944,Afterglow PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7",
+ *  "03000000341a00003608000000000000,PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7",
  *
  */
 
@@ -117,7 +119,7 @@ typedef struct SDL_GameControllerButtonBind
  * 
  * \return number of mappings added, -1 on error
  */
-extern DECLSPEC int SDLCALL SDL_GameControllerAddMappingsFromRW( SDL_RWops * rw, int freerw );
+extern DECLSPEC int SDLCALL SDL_GameControllerAddMappingsFromRW(SDL_RWops * rw, int freerw);
 
 /**
  *  Load a set of mappings from a file, filtered by the current SDL_GetPlatform()
@@ -131,28 +133,41 @@ extern DECLSPEC int SDLCALL SDL_GameControllerAddMappingsFromRW( SDL_RWops * rw,
  *
  * \return 1 if mapping is added, 0 if updated, -1 on error
  */
-extern DECLSPEC int SDLCALL SDL_GameControllerAddMapping( const char* mappingString );
+extern DECLSPEC int SDLCALL SDL_GameControllerAddMapping(const char* mappingString);
+
+/**
+ *  Get the number of mappings installed
+ *
+ *  \return the number of mappings
+ */
+extern DECLSPEC int SDLCALL SDL_GameControllerNumMappings(void);
+
+/**
+ *  Get the mapping at a particular index.
+ *
+ *  \return the mapping string.  Must be freed with SDL_free().  Returns NULL if the index is out of range.
+ */
+extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForIndex(int mapping_index);
 
 /**
  *  Get a mapping string for a GUID
  *
  *  \return the mapping string.  Must be freed with SDL_free().  Returns NULL if no mapping is available
  */
-extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForGUID( SDL_JoystickGUID guid );
+extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForGUID(SDL_JoystickGUID guid);
 
 /**
  *  Get a mapping string for an open GameController
  *
  *  \return the mapping string.  Must be freed with SDL_free().  Returns NULL if no mapping is available
  */
-extern DECLSPEC char * SDLCALL SDL_GameControllerMapping( SDL_GameController * gamecontroller );
+extern DECLSPEC char * SDLCALL SDL_GameControllerMapping(SDL_GameController * gamecontroller);
 
 /**
  *  Is the joystick on this index supported by the game controller interface?
  */
 extern DECLSPEC SDL_bool SDLCALL SDL_IsGameController(int joystick_index);
 
-
 /**
  *  Get the implementation dependent name of a game controller.
  *  This can be called before any controllers are opened.
@@ -182,6 +197,24 @@ extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerFromInstanceID(SDL
 extern DECLSPEC const char *SDLCALL SDL_GameControllerName(SDL_GameController *gamecontroller);
 
 /**
+ *  Get the USB vendor ID of an opened controller, if available.
+ *  If the vendor ID isn't available this function returns 0.
+ */
+extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetVendor(SDL_GameController * gamecontroller);
+
+/**
+ *  Get the USB product ID of an opened controller, if available.
+ *  If the product ID isn't available this function returns 0.
+ */
+extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetProduct(SDL_GameController * gamecontroller);
+
+/**
+ *  Get the product version of an opened controller, if available.
+ *  If the product version isn't available this function returns 0.
+ */
+extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetProductVersion(SDL_GameController * gamecontroller);
+
+/**
  *  Returns SDL_TRUE if the controller has been opened and currently connected,
  *  or SDL_FALSE if it has not.
  */
@@ -214,6 +247,12 @@ extern DECLSPEC void SDLCALL SDL_GameControllerUpdate(void);
 
 /**
  *  The list of axes available from a controller
+ *
+ *  Thumbstick axis values range from SDL_JOYSTICK_AXIS_MIN to SDL_JOYSTICK_AXIS_MAX,
+ *  and are centered within ~8000 of zero, though advanced UI will allow users to set
+ *  or autodetect the dead zone, which varies between controllers.
+ *
+ *  Trigger axis values range from 0 to SDL_JOYSTICK_AXIS_MAX.
  */
 typedef enum
 {
@@ -318,6 +357,6 @@ extern DECLSPEC void SDLCALL SDL_GameControllerClose(SDL_GameController *gamecon
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_gamecontroller_h */
+#endif /* SDL_gamecontroller_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_gesture.h b/include/SDL_gesture.h
index 3c29ca7..2bba6a7 100644
--- a/include/SDL_gesture.h
+++ b/include/SDL_gesture.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Include file for SDL gesture event handling.
  */
 
-#ifndef _SDL_gesture_h
-#define _SDL_gesture_h
+#ifndef SDL_gesture_h_
+#define SDL_gesture_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -82,6 +82,6 @@ extern DECLSPEC int SDLCALL SDL_LoadDollarTemplates(SDL_TouchID touchId, SDL_RWo
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_gesture_h */
+#endif /* SDL_gesture_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_haptic.h b/include/SDL_haptic.h
index 9421c8f..60daefa 100644
--- a/include/SDL_haptic.h
+++ b/include/SDL_haptic.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,12 +22,12 @@
 /**
  *  \file SDL_haptic.h
  *
- *  \brief The SDL Haptic subsystem allows you to control haptic (force feedback)
+ *  \brief The SDL haptic subsystem allows you to control haptic (force feedback)
  *         devices.
  *
  *  The basic usage is as follows:
- *   - Initialize the Subsystem (::SDL_INIT_HAPTIC).
- *   - Open a Haptic Device.
+ *   - Initialize the subsystem (::SDL_INIT_HAPTIC).
+ *   - Open a haptic device.
  *    - SDL_HapticOpen() to open from index.
  *    - SDL_HapticOpenFromJoystick() to open from an existing joystick.
  *   - Create an effect (::SDL_HapticEffect).
@@ -104,8 +104,8 @@
  * \endcode
  */
 
-#ifndef _SDL_haptic_h
-#define _SDL_haptic_h
+#ifndef SDL_haptic_h_
+#define SDL_haptic_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -282,7 +282,7 @@ typedef struct _SDL_Haptic SDL_Haptic;
 /**
  *  \brief Device can be queried for effect status.
  *
- *  Device can be queried for effect status.
+ *  Device supports querying effect status.
  *
  *  \sa SDL_HapticGetEffectStatus
  */
@@ -291,6 +291,8 @@ typedef struct _SDL_Haptic SDL_Haptic;
 /**
  *  \brief Device can be paused.
  *
+ *  Devices supports being paused.
+ *
  *  \sa SDL_HapticPause
  *  \sa SDL_HapticUnpause
  */
@@ -444,7 +446,7 @@ typedef struct SDL_HapticDirection
 /**
  *  \brief A structure containing a template for a Constant effect.
  *
- *  The struct is exclusive to the ::SDL_HAPTIC_CONSTANT effect.
+ *  This struct is exclusively for the ::SDL_HAPTIC_CONSTANT effect.
  *
  *  A constant effect applies a constant force in the specified direction
  *  to the joystick.
@@ -676,6 +678,8 @@ typedef struct SDL_HapticLeftRight
 /**
  *  \brief A structure containing a template for the ::SDL_HAPTIC_CUSTOM effect.
  *
+ *  This struct is exclusively for the ::SDL_HAPTIC_CUSTOM effect.
+ *
  *  A custom force feedback effect is much like a periodic effect, where the
  *  application can define its exact shape.  You will have to allocate the
  *  data yourself.  Data should consist of channels * samples Uint16 samples.
@@ -804,7 +808,7 @@ typedef union SDL_HapticEffect
 extern DECLSPEC int SDLCALL SDL_NumHaptics(void);
 
 /**
- *  \brief Get the implementation dependent name of a Haptic device.
+ *  \brief Get the implementation dependent name of a haptic device.
  *
  *  This can be called before any joysticks are opened.
  *  If no name can be found, this function returns NULL.
@@ -817,9 +821,9 @@ extern DECLSPEC int SDLCALL SDL_NumHaptics(void);
 extern DECLSPEC const char *SDLCALL SDL_HapticName(int device_index);
 
 /**
- *  \brief Opens a Haptic device for usage.
+ *  \brief Opens a haptic device for use.
  *
- *  The index passed as an argument refers to the N'th Haptic device on this
+ *  The index passed as an argument refers to the N'th haptic device on this
  *  system.
  *
  *  When opening a haptic device, its gain will be set to maximum and
@@ -885,15 +889,15 @@ extern DECLSPEC SDL_Haptic *SDLCALL SDL_HapticOpenFromMouse(void);
  *  \brief Checks to see if a joystick has haptic features.
  *
  *  \param joystick Joystick to test for haptic capabilities.
- *  \return 1 if the joystick is haptic, 0 if it isn't
- *          or -1 if an error ocurred.
+ *  \return SDL_TRUE if the joystick is haptic, SDL_FALSE if it isn't
+ *          or -1 if an error occurred.
  *
  *  \sa SDL_HapticOpenFromJoystick
  */
 extern DECLSPEC int SDLCALL SDL_JoystickIsHaptic(SDL_Joystick * joystick);
 
 /**
- *  \brief Opens a Haptic device for usage from a Joystick device.
+ *  \brief Opens a haptic device for use from a joystick device.
  *
  *  You must still close the haptic device separately.  It will not be closed
  *  with the joystick.
@@ -913,7 +917,7 @@ extern DECLSPEC SDL_Haptic *SDLCALL SDL_HapticOpenFromJoystick(SDL_Joystick *
                                                                joystick);
 
 /**
- *  \brief Closes a Haptic device previously opened with SDL_HapticOpen().
+ *  \brief Closes a haptic device previously opened with SDL_HapticOpen().
  *
  *  \param haptic Haptic device to close.
  */
@@ -957,7 +961,7 @@ extern DECLSPEC int SDLCALL SDL_HapticNumEffectsPlaying(SDL_Haptic * haptic);
  *  Example:
  *  \code
  *  if (SDL_HapticQuery(haptic) & SDL_HAPTIC_CONSTANT) {
- *      printf("We have constant haptic effect!");
+ *      printf("We have constant haptic effect!\n");
  *  }
  *  \endcode
  *
@@ -996,7 +1000,7 @@ extern DECLSPEC int SDLCALL SDL_HapticEffectSupported(SDL_Haptic * haptic,
  *
  *  \param haptic Haptic device to create the effect on.
  *  \param effect Properties of the effect to create.
- *  \return The id of the effect on success or -1 on error.
+ *  \return The identifier of the effect on success or -1 on error.
  *
  *  \sa SDL_HapticUpdateEffect
  *  \sa SDL_HapticRunEffect
@@ -1008,13 +1012,13 @@ extern DECLSPEC int SDLCALL SDL_HapticNewEffect(SDL_Haptic * haptic,
 /**
  *  \brief Updates the properties of an effect.
  *
- *  Can be used dynamically, although behaviour when dynamically changing
+ *  Can be used dynamically, although behavior when dynamically changing
  *  direction may be strange.  Specifically the effect may reupload itself
  *  and start playing from the start.  You cannot change the type either when
  *  running SDL_HapticUpdateEffect().
  *
  *  \param haptic Haptic device that has the effect.
- *  \param effect Effect to update.
+ *  \param effect Identifier of the effect to update.
  *  \param data New effect properties to use.
  *  \return 0 on success or -1 on error.
  *
@@ -1218,6 +1222,6 @@ extern DECLSPEC int SDLCALL SDL_HapticRumbleStop(SDL_Haptic * haptic);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_haptic_h */
+#endif /* SDL_haptic_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_hints.h b/include/SDL_hints.h
index dd15464..007a4be 100644
--- a/include/SDL_hints.h
+++ b/include/SDL_hints.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -36,8 +36,8 @@
  *  to how they would like the library to work.
  */
 
-#ifndef _SDL_hints_h
-#define _SDL_hints_h
+#ifndef SDL_hints_h_
+#define SDL_hints_h_
 
 #include "SDL_stdinc.h"
 
@@ -119,6 +119,17 @@ extern "C" {
 #define SDL_HINT_RENDER_DIRECT3D11_DEBUG    "SDL_RENDER_DIRECT3D11_DEBUG"
 
 /**
+ *  \brief  A variable controlling the scaling policy for SDL_RenderSetLogicalSize.
+ *
+ *  This variable can be set to the following values:
+ *    "0" or "letterbox" - Uses letterbox/sidebars to fit the entire rendering on screen
+ *    "1" or "overscan"  - Will zoom the rendering so it fills the entire screen, allowing edges to be drawn offscreen
+ *
+ *  By default letterbox is used
+ */
+#define SDL_HINT_RENDER_LOGICAL_SIZE_MODE       "SDL_RENDER_LOGICAL_SIZE_MODE"
+
+/**
  *  \brief  A variable controlling the scaling quality
  *
  *  This variable can be set to the following values:
@@ -211,6 +222,12 @@ extern "C" {
 #define SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN    "SDL_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN"
 
 /**
+ * \brief A variable to specify custom icon resource id from RC file on Windows platform 
+ */
+#define SDL_HINT_WINDOWS_INTRESOURCE_ICON       "SDL_WINDOWS_INTRESOURCE_ICON"
+#define SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL "SDL_WINDOWS_INTRESOURCE_ICON_SMALL"
+
+/**
  *  \brief  A variable controlling whether the windows message loop is processed by SDL 
  *
  *  This variable can be set to the following values:
@@ -233,6 +250,16 @@ extern "C" {
 #define SDL_HINT_GRAB_KEYBOARD              "SDL_GRAB_KEYBOARD"
 
 /**
+ *  \brief  A variable setting the speed scale for mouse motion, in floating point, when the mouse is not in relative mode
+ */
+#define SDL_HINT_MOUSE_NORMAL_SPEED_SCALE    "SDL_MOUSE_NORMAL_SPEED_SCALE"
+
+/**
+ *  \brief  A variable setting the scale for mouse motion, in floating point, when the mouse is in relative mode
+ */
+#define SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE    "SDL_MOUSE_RELATIVE_SPEED_SCALE"
+
+/**
  *  \brief  A variable controlling whether relative mouse mode is implemented using mouse warping
  *
  *  This variable can be set to the following values:
@@ -255,6 +282,17 @@ extern "C" {
 #define SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH "SDL_MOUSE_FOCUS_CLICKTHROUGH"
 
 /**
+ *  \brief  A variable controlling whether touch events should generate synthetic mouse events
+ *
+ *  This variable can be set to the following values:
+ *    "0"       - Touch events will not generate mouse events
+ *    "1"       - Touch events will generate mouse events
+ *
+ *  By default SDL will generate mouse events for touch events
+ */
+#define SDL_HINT_TOUCH_MOUSE_EVENTS    "SDL_TOUCH_MOUSE_EVENTS"
+
+/**
  *  \brief Minimize your SDL_Window if it loses key focus when in fullscreen mode. Defaults to true.
  *
  */
@@ -327,7 +365,6 @@ extern "C" {
  */
 #define SDL_HINT_ACCELEROMETER_AS_JOYSTICK "SDL_ACCELEROMETER_AS_JOYSTICK"
 
-
 /**
  *  \brief  A variable that lets you disable the detection and use of Xinput gamepad devices
  *
@@ -337,7 +374,6 @@ extern "C" {
  */
 #define SDL_HINT_XINPUT_ENABLED "SDL_XINPUT_ENABLED"
 
-
 /**
  *  \brief  A variable that causes SDL to use the old axis and button mapping for XInput devices.
  *
@@ -347,9 +383,8 @@ extern "C" {
  */
 #define SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING "SDL_XINPUT_USE_OLD_JOYSTICK_MAPPING"
 
-
 /**
- *  \brief  A variable that lets you manually hint extra gamecontroller db entries
+ *  \brief  A variable that lets you manually hint extra gamecontroller db entries.
  *
  *  The variable should be newline delimited rows of gamecontroller config data, see SDL_gamecontroller.h
  *
@@ -358,6 +393,31 @@ extern "C" {
  */
 #define SDL_HINT_GAMECONTROLLERCONFIG "SDL_GAMECONTROLLERCONFIG"
 
+/**
+ *  \brief  A variable containing a list of devices to skip when scanning for game controllers.
+ *
+ *  The format of the string is a comma separated list of USB VID/PID pairs
+ *  in hexadecimal form, e.g.
+ *
+ *      0xAAAA/0xBBBB,0xCCCC/0xDDDD
+ *
+ *  The variable can also take the form of @file, in which case the named
+ *  file will be loaded and interpreted as the value of the variable.
+ */
+#define SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES "SDL_GAMECONTROLLER_IGNORE_DEVICES"
+
+/**
+ *  \brief  If set, all devices will be skipped when scanning for game controllers except for the ones listed in this variable.
+ *
+ *  The format of the string is a comma separated list of USB VID/PID pairs
+ *  in hexadecimal form, e.g.
+ *
+ *      0xAAAA/0xBBBB,0xCCCC/0xDDDD
+ *
+ *  The variable can also take the form of @file, in which case the named
+ *  file will be loaded and interpreted as the value of the variable.
+ */
+#define SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT "SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT"
 
 /**
  *  \brief  A variable that lets you enable joystick (and gamecontroller) events even when your app is in the background.
@@ -372,7 +432,6 @@ extern "C" {
  */
 #define SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS "SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS"
 
-
 /**
  *  \brief If set to "0" then never set the top most bit on a SDL Window, even if the video mode expects it.
  *      This is a debugging aid for developers and not expected to be used by end users. The default is "1"
@@ -383,7 +442,6 @@ extern "C" {
  */
 #define SDL_HINT_ALLOW_TOPMOST "SDL_ALLOW_TOPMOST"
 
-
 /**
  *  \brief A variable that controls the timer resolution, in milliseconds.
  *
@@ -401,6 +459,33 @@ extern "C" {
 #define SDL_HINT_TIMER_RESOLUTION "SDL_TIMER_RESOLUTION"
 
 
+/**
+ *  \brief  A variable describing the content orientation on QtWayland-based platforms.
+ *
+ *  On QtWayland platforms, windows are rotated client-side to allow for custom
+ *  transitions. In order to correctly position overlays (e.g. volume bar) and
+ *  gestures (e.g. events view, close/minimize gestures), the system needs to
+ *  know in which orientation the application is currently drawing its contents.
+ *
+ *  This does not cause the window to be rotated or resized, the application
+ *  needs to take care of drawing the content in the right orientation (the
+ *  framebuffer is always in portrait mode).
+ *
+ *  This variable can be one of the following values:
+ *    "primary" (default), "portrait", "landscape", "inverted-portrait", "inverted-landscape"
+ */
+#define SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION "SDL_QTWAYLAND_CONTENT_ORIENTATION"
+
+/**
+ *  \brief  Flags to set on QtWayland windows to integrate with the native window manager.
+ *
+ *  On QtWayland platforms, this hint controls the flags to set on the windows.
+ *  For example, on Sailfish OS "OverridesSystemGestures" disables swipe gestures.
+ *
+ *  This variable is a space-separated list of the following values (empty = no flags):
+ *    "OverridesSystemGestures", "StaysOnTop", "BypassWindowManager"
+ */
+#define SDL_HINT_QTWAYLAND_WINDOW_FLAGS "SDL_QTWAYLAND_WINDOW_FLAGS"
 
 /**
 *  \brief  A string specifying SDL's threads stack size in bytes or "0" for the backend's default size
@@ -689,13 +774,18 @@ extern "C" {
 #define SDL_HINT_BMP_SAVE_LEGACY_FORMAT "SDL_BMP_SAVE_LEGACY_FORMAT"
 
 /**
- * \brief Tell SDL not to name threads on Windows.
+ * \brief Tell SDL not to name threads on Windows with the 0x406D1388 Exception.
+ *        The 0x406D1388 Exception is a trick used to inform Visual Studio of a
+ *        thread's name, but it tends to cause problems with other debuggers,
+ *        and the .NET runtime. Note that SDL 2.0.6 and later will still use
+ *        the (safer) SetThreadDescription API, introduced in the Windows 10
+ *        Creators Update, if available.
  *
  * The variable can be set to the following values:
  *   "0"       - SDL will raise the 0x406D1388 Exception to name threads.
- *               This is the default behavior of SDL <= 2.0.4. (default)
- *   "1"       - SDL will not raise this exception, and threads will be unnamed.
- *               For .NET languages this is required when running under a debugger.
+ *               This is the default behavior of SDL <= 2.0.4.
+ *   "1"       - SDL will not raise this exception, and threads will be unnamed. (default)
+ *               This is necessary with .NET languages or debuggers that aren't Visual Studio.
  */
 #define SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING "SDL_WINDOWS_DISABLE_THREAD_NAMING"
 
@@ -708,6 +798,76 @@ extern "C" {
 #define SDL_HINT_RPI_VIDEO_LAYER           "SDL_RPI_VIDEO_LAYER"
 
 /**
+ *  \brief  A variable controlling what driver to use for OpenGL ES contexts.
+ *
+ *  On some platforms, currently Windows and X11, OpenGL drivers may support
+ *  creating contexts with an OpenGL ES profile. By default SDL uses these
+ *  profiles, when available, otherwise it attempts to load an OpenGL ES
+ *  library, e.g. that provided by the ANGLE project. This variable controls
+ *  whether SDL follows this default behaviour or will always load an
+ *  OpenGL ES library.
+ *
+ *  Circumstances where this is useful include
+ *  - Testing an app with a particular OpenGL ES implementation, e.g ANGLE,
+ *    or emulator, e.g. those from ARM, Imagination or Qualcomm.
+ *  - Resolving OpenGL ES function addresses at link time by linking with
+ *    the OpenGL ES library instead of querying them at run time with
+ *    SDL_GL_GetProcAddress().
+ *
+ *  Caution: for an application to work with the default behaviour across
+ *  different OpenGL drivers it must query the OpenGL ES function
+ *  addresses at run time using SDL_GL_GetProcAddress().
+ *
+ *  This variable is ignored on most platforms because OpenGL ES is native
+ *  or not supported.
+ *
+ *  This variable can be set to the following values:
+ *    "0"       - Use ES profile of OpenGL, if available. (Default when not set.)
+ *    "1"       - Load OpenGL ES library using the default library names.
+ *
+ */
+#define SDL_HINT_OPENGL_ES_DRIVER   "SDL_OPENGL_ES_DRIVER"
+
+/**
+ *  \brief  A variable controlling speed/quality tradeoff of audio resampling.
+ *
+ *  If available, SDL can use libsamplerate ( http://www.mega-nerd.com/SRC/ )
+ *  to handle audio resampling. There are different resampling modes available
+ *  that produce different levels of quality, using more CPU.
+ *
+ *  If this hint isn't specified to a valid setting, or libsamplerate isn't
+ *  available, SDL will use the default, internal resampling algorithm.
+ *
+ *  Note that this is currently only applicable to resampling audio that is
+ *  being written to a device for playback or audio being read from a device
+ *  for capture. SDL_AudioCVT always uses the default resampler (although this
+ *  might change for SDL 2.1).
+ *
+ *  This hint is currently only checked at audio subsystem initialization.
+ *
+ *  This variable can be set to the following values:
+ *
+ *    "0" or "default" - Use SDL's internal resampling (Default when not set - low quality, fast)
+ *    "1" or "fast"    - Use fast, slightly higher quality resampling, if available
+ *    "2" or "medium"  - Use medium quality resampling, if available
+ *    "3" or "best"    - Use high quality resampling, if available
+ */
+#define SDL_HINT_AUDIO_RESAMPLING_MODE   "SDL_AUDIO_RESAMPLING_MODE"
+
+/**
+ *  \brief  A variable controlling the audio category on iOS and Mac OS X
+ *
+ *  This variable can be set to the following values:
+ *
+ *    "ambient"     - Use the AVAudioSessionCategoryAmbient audio category, will be muted by the phone mute switch (default)
+ *    "playback"    - Use the AVAudioSessionCategoryPlayback category
+ *
+ *  For more information, see Apple's documentation:
+ *  https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionCategoriesandModes/AudioSessionCategoriesandModes.html
+ */
+#define SDL_HINT_AUDIO_CATEGORY   "SDL_AUDIO_CATEGORY"
+
+/**
  *  \brief  An enumeration of hint priorities
  */
 typedef enum
@@ -754,13 +914,17 @@ extern DECLSPEC const char * SDLCALL SDL_GetHint(const char *name);
 extern DECLSPEC SDL_bool SDLCALL SDL_GetHintBoolean(const char *name, SDL_bool default_value);
 
 /**
+ * \brief type definition of the hint callback function.
+ */
+typedef void (SDLCALL *SDL_HintCallback)(void *userdata, const char *name, const char *oldValue, const char *newValue);
+
+/**
  *  \brief Add a function to watch a particular hint
  *
  *  \param name The hint to watch
  *  \param callback The function to call when the hint value changes
  *  \param userdata A pointer to pass to the callback function
  */
-typedef void (*SDL_HintCallback)(void *userdata, const char *name, const char *oldValue, const char *newValue);
 extern DECLSPEC void SDLCALL SDL_AddHintCallback(const char *name,
                                                  SDL_HintCallback callback,
                                                  void *userdata);
@@ -790,6 +954,6 @@ extern DECLSPEC void SDLCALL SDL_ClearHints(void);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_hints_h */
+#endif /* SDL_hints_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_joystick.h b/include/SDL_joystick.h
index f5dbc94..698b09c 100644
--- a/include/SDL_joystick.h
+++ b/include/SDL_joystick.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -36,8 +36,8 @@
  *
  */
 
-#ifndef _SDL_joystick_h
-#define _SDL_joystick_h
+#ifndef SDL_joystick_h_
+#define SDL_joystick_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -60,7 +60,9 @@ extern "C" {
  *  SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS
  */
 
-/* The joystick structure used to identify an SDL joystick */
+/**
+ * The joystick structure used to identify an SDL joystick
+ */
 struct _SDL_Joystick;
 typedef struct _SDL_Joystick SDL_Joystick;
 
@@ -69,10 +71,31 @@ typedef struct {
     Uint8 data[16];
 } SDL_JoystickGUID;
 
+/**
+ * This is a unique ID for a joystick for the time it is connected to the system,
+ * and is never reused for the lifetime of the application. If the joystick is
+ * disconnected and reconnected, it will get a new ID.
+ *
+ * The ID value starts at 0 and increments from there. The value -1 is an invalid ID.
+ */
 typedef Sint32 SDL_JoystickID;
 
 typedef enum
 {
+    SDL_JOYSTICK_TYPE_UNKNOWN,
+    SDL_JOYSTICK_TYPE_GAMECONTROLLER,
+    SDL_JOYSTICK_TYPE_WHEEL,
+    SDL_JOYSTICK_TYPE_ARCADE_STICK,
+    SDL_JOYSTICK_TYPE_FLIGHT_STICK,
+    SDL_JOYSTICK_TYPE_DANCE_PAD,
+    SDL_JOYSTICK_TYPE_GUITAR,
+    SDL_JOYSTICK_TYPE_DRUM_KIT,
+    SDL_JOYSTICK_TYPE_ARCADE_PAD,
+    SDL_JOYSTICK_TYPE_THROTTLE
+} SDL_JoystickType;
+
+typedef enum
+{
     SDL_JOYSTICK_POWER_UNKNOWN = -1,
     SDL_JOYSTICK_POWER_EMPTY,
     SDL_JOYSTICK_POWER_LOW,
@@ -96,6 +119,46 @@ extern DECLSPEC int SDLCALL SDL_NumJoysticks(void);
 extern DECLSPEC const char *SDLCALL SDL_JoystickNameForIndex(int device_index);
 
 /**
+ *  Return the GUID for the joystick at this index
+ *  This can be called before any joysticks are opened.
+ */
+extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetDeviceGUID(int device_index);
+
+/**
+ *  Get the USB vendor ID of a joystick, if available.
+ *  This can be called before any joysticks are opened.
+ *  If the vendor ID isn't available this function returns 0.
+ */
+extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceVendor(int device_index);
+
+/**
+ *  Get the USB product ID of a joystick, if available.
+ *  This can be called before any joysticks are opened.
+ *  If the product ID isn't available this function returns 0.
+ */
+extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceProduct(int device_index);
+
+/**
+ *  Get the product version of a joystick, if available.
+ *  This can be called before any joysticks are opened.
+ *  If the product version isn't available this function returns 0.
+ */
+extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceProductVersion(int device_index);
+
+/**
+ *  Get the type of a joystick, if available.
+ *  This can be called before any joysticks are opened.
+ */
+extern DECLSPEC SDL_JoystickType SDLCALL SDL_JoystickGetDeviceType(int device_index);
+
+/**
+ *  Get the instance ID of a joystick.
+ *  This can be called before any joysticks are opened.
+ *  If the index is out of range, this function will return -1.
+ */
+extern DECLSPEC SDL_JoystickID SDLCALL SDL_JoystickGetDeviceInstanceID(int device_index);
+
+/**
  *  Open a joystick for use.
  *  The index passed as an argument refers to the N'th joystick on the system.
  *  This index is not the value which will identify this joystick in future
@@ -118,14 +181,32 @@ extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickFromInstanceID(SDL_JoystickID
 extern DECLSPEC const char *SDLCALL SDL_JoystickName(SDL_Joystick * joystick);
 
 /**
- *  Return the GUID for the joystick at this index
+ *  Return the GUID for this opened joystick
  */
-extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetDeviceGUID(int device_index);
+extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUID(SDL_Joystick * joystick);
 
 /**
- *  Return the GUID for this opened joystick
+ *  Get the USB vendor ID of an opened joystick, if available.
+ *  If the vendor ID isn't available this function returns 0.
  */
-extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUID(SDL_Joystick * joystick);
+extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetVendor(SDL_Joystick * joystick);
+
+/**
+ *  Get the USB product ID of an opened joystick, if available.
+ *  If the product ID isn't available this function returns 0.
+ */
+extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetProduct(SDL_Joystick * joystick);
+
+/**
+ *  Get the product version of an opened joystick, if available.
+ *  If the product version isn't available this function returns 0.
+ */
+extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetProductVersion(SDL_Joystick * joystick);
+
+/**
+ *  Get the type of an opened joystick.
+ */
+extern DECLSPEC SDL_JoystickType SDLCALL SDL_JoystickGetType(SDL_Joystick * joystick);
 
 /**
  *  Return a string representation for this guid. pszGUID must point to at least 33 bytes
@@ -134,7 +215,7 @@ extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUID(SDL_Joystick * joys
 extern DECLSPEC void SDLCALL SDL_JoystickGetGUIDString(SDL_JoystickGUID guid, char *pszGUID, int cbGUID);
 
 /**
- *  convert a string into a joystick formatted guid
+ *  Convert a string into a joystick guid
  */
 extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUIDFromString(const char *pchGUID);
 
@@ -190,6 +271,8 @@ extern DECLSPEC void SDLCALL SDL_JoystickUpdate(void);
  */
 extern DECLSPEC int SDLCALL SDL_JoystickEventState(int state);
 
+#define SDL_JOYSTICK_AXIS_MAX   32767
+#define SDL_JOYSTICK_AXIS_MIN   -32768
 /**
  *  Get the current state of an axis control on a joystick.
  *
@@ -201,6 +284,18 @@ extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick * joystick,
                                                    int axis);
 
 /**
+ *  Get the initial state of an axis control on a joystick.
+ *
+ *  The state is a value ranging from -32768 to 32767.
+ *
+ *  The axis indices start at index 0.
+ *
+ *  \return SDL_TRUE if this axis has any initial value, or SDL_FALSE if not.
+ */
+extern DECLSPEC SDL_bool SDLCALL SDL_JoystickGetAxisInitialState(SDL_Joystick * joystick,
+                                                   int axis, Sint16 *state);
+
+/**
  *  \name Hat positions
  */
 /* @{ */
@@ -268,6 +363,6 @@ extern DECLSPEC SDL_JoystickPowerLevel SDLCALL SDL_JoystickCurrentPowerLevel(SDL
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_joystick_h */
+#endif /* SDL_joystick_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_keyboard.h b/include/SDL_keyboard.h
index f80b6d2..e78ca46 100644
--- a/include/SDL_keyboard.h
+++ b/include/SDL_keyboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Include file for SDL keyboard event handling
  */
 
-#ifndef _SDL_keyboard_h
-#define _SDL_keyboard_h
+#ifndef SDL_keyboard_h_
+#define SDL_keyboard_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -212,6 +212,6 @@ extern DECLSPEC SDL_bool SDLCALL SDL_IsScreenKeyboardShown(SDL_Window *window);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_keyboard_h */
+#endif /* SDL_keyboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_keycode.h b/include/SDL_keycode.h
index 7be9635..c41e45f 100644
--- a/include/SDL_keycode.h
+++ b/include/SDL_keycode.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Defines constants which identify keyboard keys and modifiers.
  */
 
-#ifndef _SDL_keycode_h
-#define _SDL_keycode_h
+#ifndef SDL_keycode_h_
+#define SDL_keycode_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_scancode.h"
@@ -38,6 +38,9 @@
  *  layout of the keyboard.  These values include Unicode values representing
  *  the unmodified character that would be generated by pressing the key, or
  *  an SDLK_* constant for those keys that do not generate characters.
+ *
+ *  A special exception is the number keys at the top of the keyboard which
+ *  always map to SDLK_0...SDLK_9, regardless of layout.
  */
 typedef Sint32 SDL_Keycode;
 
@@ -308,7 +311,12 @@ enum
     SDLK_KBDILLUMDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMDOWN),
     SDLK_KBDILLUMUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMUP),
     SDLK_EJECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EJECT),
-    SDLK_SLEEP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SLEEP)
+    SDLK_SLEEP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SLEEP),
+    SDLK_APP1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APP1),
+    SDLK_APP2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APP2),
+
+    SDLK_AUDIOREWIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOREWIND),
+    SDLK_AUDIOFASTFORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOFASTFORWARD)
 };
 
 /**
@@ -336,6 +344,6 @@ typedef enum
 #define KMOD_ALT    (KMOD_LALT|KMOD_RALT)
 #define KMOD_GUI    (KMOD_LGUI|KMOD_RGUI)
 
-#endif /* _SDL_keycode_h */
+#endif /* SDL_keycode_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_loadso.h b/include/SDL_loadso.h
index 3d540bd..6ea256c 100644
--- a/include/SDL_loadso.h
+++ b/include/SDL_loadso.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -38,8 +38,8 @@
  *      the results you expect. :)
  */
 
-#ifndef _SDL_loadso_h
-#define _SDL_loadso_h
+#ifndef SDL_loadso_h_
+#define SDL_loadso_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -76,6 +76,6 @@ extern DECLSPEC void SDLCALL SDL_UnloadObject(void *handle);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_loadso_h */
+#endif /* SDL_loadso_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_log.h b/include/SDL_log.h
index 09be110..356d0e1 100644
--- a/include/SDL_log.h
+++ b/include/SDL_log.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -34,8 +34,8 @@
  *      Others: standard error output (stderr)
  */
 
-#ifndef _SDL_log_h
-#define _SDL_log_h
+#ifndef SDL_log_h_
+#define SDL_log_h_
 
 #include "SDL_stdinc.h"
 
@@ -186,7 +186,7 @@ extern DECLSPEC void SDLCALL SDL_LogMessageV(int category,
 /**
  *  \brief The prototype for the log output function
  */
-typedef void (*SDL_LogOutputFunction)(void *userdata, int category, SDL_LogPriority priority, const char *message);
+typedef void (SDLCALL *SDL_LogOutputFunction)(void *userdata, int category, SDL_LogPriority priority, const char *message);
 
 /**
  *  \brief Get the current log output function.
@@ -206,6 +206,6 @@ extern DECLSPEC void SDLCALL SDL_LogSetOutputFunction(SDL_LogOutputFunction call
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_log_h */
+#endif /* SDL_log_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_main.h b/include/SDL_main.h
index 67afea5..2af3236 100644
--- a/include/SDL_main.h
+++ b/include/SDL_main.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_main_h
-#define _SDL_main_h
+#ifndef SDL_main_h_
+#define SDL_main_h_
 
 #include "SDL_stdinc.h"
 
@@ -107,7 +107,7 @@
 /**
  *  The prototype for the application's main() function
  */
-extern C_LINKAGE int SDL_main(int argc, char *argv[]);
+extern C_LINKAGE DECLSPEC int SDL_main(int argc, char *argv[]);
 
 
 #include "begin_code.h"
@@ -156,6 +156,6 @@ extern DECLSPEC int SDLCALL SDL_WinRTRunApp(int (*mainFunction)(int, char **), v
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_main_h */
+#endif /* SDL_main_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_messagebox.h b/include/SDL_messagebox.h
index ec370db..c326d8f 100644
--- a/include/SDL_messagebox.h
+++ b/include/SDL_messagebox.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_messagebox_h
-#define _SDL_messagebox_h
+#ifndef SDL_messagebox_h_
+#define SDL_messagebox_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_video.h"      /* For SDL_Window */
@@ -139,6 +139,6 @@ extern DECLSPEC int SDLCALL SDL_ShowSimpleMessageBox(Uint32 flags, const char *t
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_messagebox_h */
+#endif /* SDL_messagebox_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_mouse.h b/include/SDL_mouse.h
index 46f046d..6001bd4 100644
--- a/include/SDL_mouse.h
+++ b/include/SDL_mouse.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Include file for SDL mouse event handling.
  */
 
-#ifndef _SDL_mouse_h
-#define _SDL_mouse_h
+#ifndef SDL_mouse_h_
+#define SDL_mouse_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -38,7 +38,7 @@
 extern "C" {
 #endif
 
-typedef struct SDL_Cursor SDL_Cursor;   /* Implementation dependent */
+typedef struct SDL_Cursor SDL_Cursor;   /**< Implementation dependent */
 
 /**
  * \brief Cursor types for SDL_CreateSystemCursor().
@@ -297,6 +297,6 @@ extern DECLSPEC int SDLCALL SDL_ShowCursor(int toggle);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_mouse_h */
+#endif /* SDL_mouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_mutex.h b/include/SDL_mutex.h
index b7e3973..0272379 100644
--- a/include/SDL_mutex.h
+++ b/include/SDL_mutex.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_mutex_h
-#define _SDL_mutex_h
+#ifndef SDL_mutex_h_
+#define SDL_mutex_h_
 
 /**
  *  \file SDL_mutex.h
@@ -246,6 +246,6 @@ extern DECLSPEC int SDLCALL SDL_CondWaitTimeout(SDL_cond * cond,
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_mutex_h */
+#endif /* SDL_mutex_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_name.h b/include/SDL_name.h
index 06cd4a5..8095ed3 100644
--- a/include/SDL_name.h
+++ b/include/SDL_name.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDLname_h_
-#define _SDLname_h_
+#ifndef SDLname_h_
+#define SDLname_h_
 
 #if defined(__STDC__) || defined(__cplusplus)
 #define NeedFunctionPrototypes 1
@@ -28,6 +28,6 @@
 
 #define SDL_NAME(X) SDL_##X
 
-#endif /* _SDLname_h_ */
+#endif /* SDLname_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_opengl.h b/include/SDL_opengl.h
index 780919b..314dd57 100644
--- a/include/SDL_opengl.h
+++ b/include/SDL_opengl.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -32,8 +32,8 @@
  *  version included in SDL_opengl.h.
  */
 
-#ifndef _SDL_opengl_h
-#define _SDL_opengl_h
+#ifndef SDL_opengl_h_
+#define SDL_opengl_h_
 
 #include "SDL_config.h"
 
@@ -97,6 +97,13 @@
 #elif defined(__CYGWIN__) && defined(USE_OPENGL32) /* use native windows opengl32 */
 #  define GLAPI extern
 #  define GLAPIENTRY __stdcall
+#elif defined(__OS2__) || defined(__EMX__) /* native os/2 opengl */
+#  define GLAPI extern
+#  define GLAPIENTRY _System
+#  define APIENTRY _System
+#  if defined(__GNUC__) && !defined(_System)
+#    define _System
+#  endif
 #elif (defined(__GNUC__) && __GNUC__ >= 4) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590))
 #  define GLAPI __attribute__((visibility("default")))
 #  define GLAPIENTRY
@@ -2171,6 +2178,6 @@ typedef void (APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum t
 
 #endif /* !__IPHONEOS__ */
 
-#endif /* _SDL_opengl_h */
+#endif /* SDL_opengl_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_opengles.h b/include/SDL_opengles.h
index 15abee7..800c593 100644
--- a/include/SDL_opengles.h
+++ b/include/SDL_opengles.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/include/SDL_opengles2.h b/include/SDL_opengles2.h
index c961f0f..102f2f3 100644
--- a/include/SDL_opengles2.h
+++ b/include/SDL_opengles2.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/include/SDL_pixels.h b/include/SDL_pixels.h
index cf6a33f..0424668 100644
--- a/include/SDL_pixels.h
+++ b/include/SDL_pixels.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Header for the enumerated pixel format definitions.
  */
 
-#ifndef _SDL_pixels_h
-#define _SDL_pixels_h
+#ifndef SDL_pixels_h_
+#define SDL_pixels_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_endian.h"
@@ -463,6 +463,6 @@ extern DECLSPEC void SDLCALL SDL_CalculateGammaRamp(float gamma, Uint16 * ramp);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_pixels_h */
+#endif /* SDL_pixels_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_platform.h b/include/SDL_platform.h
index 03cf170..9dde385 100644
--- a/include/SDL_platform.h
+++ b/include/SDL_platform.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Try to get a standard set of platform defines.
  */
 
-#ifndef _SDL_platform_h
-#define _SDL_platform_h
+#ifndef SDL_platform_h_
+#define SDL_platform_h_
 
 #if defined(_AIX)
 #undef __AIX__
@@ -97,7 +97,7 @@
 #undef __OPENBSD__
 #define __OPENBSD__ 1
 #endif
-#if defined(__OS2__)
+#if defined(__OS2__) || defined(__EMX__)
 #undef __OS2__
 #define __OS2__     1
 #endif
@@ -120,21 +120,29 @@
 
 #if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
 /* Try to find out if we're compiling for WinRT or non-WinRT */
-/* If _USING_V110_SDK71_ is defined it means we are using the v110_xp or v120_xp toolset. */
-#if (defined(_MSC_VER) && (_MSC_VER >= 1700) && !_USING_V110_SDK71_)	/* _MSC_VER==1700 for MSVC 2012 */
+#if defined(_MSC_VER) && defined(__has_include)
+#define HAVE_WINAPIFAMILY_H __has_include(<winapifamily.h>)
+/* If _USING_V110_SDK71_ is defined it means we are using the Windows XP toolset. */
+#elif defined(_MSC_VER) && (_MSC_VER >= 1700 && !_USING_V110_SDK71_)    /* _MSC_VER == 1700 for Visual Studio 2012 */
+#define HAVE_WINAPIFAMILY_H 1
+#else
+#define HAVE_WINAPIFAMILY_H 0
+#endif
+
+#if HAVE_WINAPIFAMILY_H
 #include <winapifamily.h>
-#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
-#undef __WINDOWS__
-#define __WINDOWS__   1
-/* See if we're compiling for WinRT: */
-#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
+#define WINAPI_FAMILY_WINRT (!WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP))
+#else
+#define WINAPI_FAMILY_WINRT 0
+#endif /* HAVE_WINAPIFAMILY_H */
+
+#if WINAPI_FAMILY_WINRT
 #undef __WINRT__
 #define __WINRT__ 1
-#endif
 #else
 #undef __WINDOWS__
-#define __WINDOWS__   1
-#endif /* _MSC_VER < 1700 */
+#define __WINDOWS__ 1
+#endif
 #endif /* defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) */
 
 #if defined(__WINDOWS__)
@@ -180,6 +188,6 @@ extern DECLSPEC const char * SDLCALL SDL_GetPlatform (void);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_platform_h */
+#endif /* SDL_platform_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_power.h b/include/SDL_power.h
index 24c0501..d48e8a3 100644
--- a/include/SDL_power.h
+++ b/include/SDL_power.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_power_h
-#define _SDL_power_h
+#ifndef SDL_power_h_
+#define SDL_power_h_
 
 /**
  *  \file SDL_power.h
@@ -70,6 +70,6 @@ extern DECLSPEC SDL_PowerState SDLCALL SDL_GetPowerInfo(int *secs, int *pct);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_power_h */
+#endif /* SDL_power_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_quit.h b/include/SDL_quit.h
index cc06f28..9283c38 100644
--- a/include/SDL_quit.h
+++ b/include/SDL_quit.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Include file for SDL quit event handling.
  */
 
-#ifndef _SDL_quit_h
-#define _SDL_quit_h
+#ifndef SDL_quit_h_
+#define SDL_quit_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -55,4 +55,4 @@
 #define SDL_QuitRequested() \
         (SDL_PumpEvents(), (SDL_PeepEvents(NULL,0,SDL_PEEKEVENT,SDL_QUIT,SDL_QUIT) > 0))
 
-#endif /* _SDL_quit_h */
+#endif /* SDL_quit_h_ */
diff --git a/include/SDL_rect.h b/include/SDL_rect.h
index bbcb9a3..c4f6d74 100644
--- a/include/SDL_rect.h
+++ b/include/SDL_rect.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Header file for SDL_rect definition and management functions.
  */
 
-#ifndef _SDL_rect_h
-#define _SDL_rect_h
+#ifndef SDL_rect_h_
+#define SDL_rect_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -143,6 +143,6 @@ extern DECLSPEC SDL_bool SDLCALL SDL_IntersectRectAndLine(const SDL_Rect *
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_rect_h */
+#endif /* SDL_rect_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_render.h b/include/SDL_render.h
index 60c87b6..ea6ef9f 100644
--- a/include/SDL_render.h
+++ b/include/SDL_render.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -45,8 +45,8 @@
  *  See this bug for details: http://bugzilla.libsdl.org/show_bug.cgi?id=1995
  */
 
-#ifndef _SDL_render_h
-#define _SDL_render_h
+#ifndef SDL_render_h_
+#define SDL_render_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_rect.h"
@@ -233,6 +233,8 @@ extern DECLSPEC int SDLCALL SDL_GetRendererOutputSize(SDL_Renderer * renderer,
  *          active,  the format was unsupported, or the width or height were out
  *          of range.
  *
+ *  \note The contents of the texture are not defined at creation.
+ *
  *  \sa SDL_QueryTexture()
  *  \sa SDL_UpdateTexture()
  *  \sa SDL_DestroyTexture()
@@ -370,9 +372,12 @@ extern DECLSPEC int SDLCALL SDL_GetTextureBlendMode(SDL_Texture * texture,
  *  \param texture   The texture to update
  *  \param rect      A pointer to the rectangle of pixels to update, or NULL to
  *                   update the entire texture.
- *  \param pixels    The raw pixel data.
+ *  \param pixels    The raw pixel data in the format of the texture.
  *  \param pitch     The number of bytes in a row of pixel data, including padding between lines.
  *
+ *  The pixel data must be in the format of the texture. The pixel format can be
+ *  queried with SDL_QueryTexture.
+ *
  *  \return 0 on success, or -1 if the texture is not valid.
  *
  *  \note This is a fairly slow function.
@@ -816,7 +821,7 @@ extern DECLSPEC int SDLCALL SDL_RenderCopy(SDL_Renderer * renderer,
  *                   texture.
  *  \param dstrect   A pointer to the destination rectangle, or NULL for the
  *                   entire rendering target.
- *  \param angle    An angle in degrees that indicates the rotation that will be applied to dstrect
+ *  \param angle    An angle in degrees that indicates the rotation that will be applied to dstrect, rotating it in a clockwise direction
  *  \param center   A pointer to a point indicating the point around which dstrect will be rotated (if NULL, rotation will be done around dstrect.w/2, dstrect.h/2).
  *  \param flip     An SDL_RendererFlip value stating which flipping actions should be performed on the texture
  *
@@ -900,6 +905,6 @@ extern DECLSPEC int SDLCALL SDL_GL_UnbindTexture(SDL_Texture *texture);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_render_h */
+#endif /* SDL_render_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_revision.h b/include/SDL_revision.h
index 341dc5c..98fd5af 100644
--- a/include/SDL_revision.h
+++ b/include/SDL_revision.h
@@ -1,2 +1,2 @@
-#define SDL_REVISION "hg-10556:007dfe83abf8"
-#define SDL_REVISION_NUMBER 10556
+#define SDL_REVISION "hg-11524:8df7a59b5528"
+#define SDL_REVISION_NUMBER 11524
diff --git a/include/SDL_rwops.h b/include/SDL_rwops.h
index 1ad3ac4..7f0cbdf 100644
--- a/include/SDL_rwops.h
+++ b/include/SDL_rwops.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -26,8 +26,8 @@
  *  data streams.  It can easily be extended to files, memory, etc.
  */
 
-#ifndef _SDL_rwops_h
-#define _SDL_rwops_h
+#ifndef SDL_rwops_h_
+#define SDL_rwops_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -39,12 +39,12 @@ extern "C" {
 #endif
 
 /* RWops Types */
-#define SDL_RWOPS_UNKNOWN   0U  /* Unknown stream type */
-#define SDL_RWOPS_WINFILE   1U  /* Win32 file */
-#define SDL_RWOPS_STDFILE   2U  /* Stdio file */
-#define SDL_RWOPS_JNIFILE   3U  /* Android asset */
-#define SDL_RWOPS_MEMORY    4U  /* Memory stream */
-#define SDL_RWOPS_MEMORY_RO 5U  /* Read-Only memory stream */
+#define SDL_RWOPS_UNKNOWN   0U  /**< Unknown stream type */
+#define SDL_RWOPS_WINFILE   1U  /**< Win32 file */
+#define SDL_RWOPS_STDFILE   2U  /**< Stdio file */
+#define SDL_RWOPS_JNIFILE   3U  /**< Android asset */
+#define SDL_RWOPS_MEMORY    4U  /**< Memory stream */
+#define SDL_RWOPS_MEMORY_RO 5U  /**< Read-Only memory stream */
 
 /**
  * This is the read/write operation structure -- very basic.
@@ -191,6 +191,29 @@ extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops * area);
 
 
 /**
+ *  Load all the data from an SDL data stream.
+ *
+ *  The data is allocated with a zero byte at the end (null terminated)
+ *
+ *  If \c datasize is not NULL, it is filled with the size of the data read.
+ *
+ *  If \c freesrc is non-zero, the stream will be closed after being read.
+ *
+ *  The data should be freed with SDL_free().
+ *
+ *  \return the data, or NULL if there was an error.
+ */
+extern DECLSPEC void *SDLCALL SDL_LoadFile_RW(SDL_RWops * src, size_t *datasize,
+                                                    int freesrc);
+
+/**
+ *  Load an entire file.
+ *
+ *  Convenience macro.
+ */
+#define SDL_LoadFile(file, datasize)   SDL_LoadFile_RW(SDL_RWFromFile(file, "rb"), datasize, 1)
+
+/**
  *  \name Read endian functions
  *
  *  Read an item of the specified endianness and return in native format.
@@ -226,6 +249,6 @@ extern DECLSPEC size_t SDLCALL SDL_WriteBE64(SDL_RWops * dst, Uint64 value);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_rwops_h */
+#endif /* SDL_rwops_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_scancode.h b/include/SDL_scancode.h
index 0af1dd5..1d55212 100644
--- a/include/SDL_scancode.h
+++ b/include/SDL_scancode.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Defines keyboard scancodes.
  */
 
-#ifndef _SDL_scancode_h
-#define _SDL_scancode_h
+#ifndef SDL_scancode_h_
+#define SDL_scancode_h_
 
 #include "SDL_stdinc.h"
 
@@ -38,7 +38,7 @@
  *  SDL_Event structure.
  *
  *  The values in this enumeration are based on the USB usage page standard:
- *  http://www.usb.org/developers/devclass_docs/Hut1_12v2.pdf
+ *  http://www.usb.org/developers/hidpage/Hut1_12v2.pdf
  */
 typedef enum
 {
@@ -390,12 +390,24 @@ typedef enum
 
     /* @} *//* Walther keys */
 
+    /**
+     *  \name Usage page 0x0C (additional media keys)
+     *
+     *  These values are mapped from usage page 0x0C (USB consumer page).
+     */
+    /* @{ */
+
+    SDL_SCANCODE_AUDIOREWIND = 285,
+    SDL_SCANCODE_AUDIOFASTFORWARD = 286,
+
+    /* @} *//* Usage page 0x0C (additional media keys) */
+
     /* Add any other keys here. */
 
     SDL_NUM_SCANCODES = 512 /**< not a key, just marks the number of scancodes
                                  for array bounds */
 } SDL_Scancode;
 
-#endif /* _SDL_scancode_h */
+#endif /* SDL_scancode_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_shape.h b/include/SDL_shape.h
index db10a8f..9e492d9 100644
--- a/include/SDL_shape.h
+++ b/include/SDL_shape.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_shape_h
-#define _SDL_shape_h
+#ifndef SDL_shape_h_
+#define SDL_shape_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_pixels.h"
@@ -71,6 +71,7 @@ extern DECLSPEC SDL_Window * SDLCALL SDL_CreateShapedWindow(const char *title,un
  * \param window The window to query for being shaped.
  *
  * \return SDL_TRUE if the window is a window that can be shaped, SDL_FALSE if the window is unshaped or NULL.
+ *
  * \sa SDL_CreateShapedWindow
  */
 extern DECLSPEC SDL_bool SDLCALL SDL_IsShapedWindow(const SDL_Window *window);
@@ -91,7 +92,7 @@ typedef enum {
 
 /** \brief A union containing parameters for shaped windows. */
 typedef union {
-    /** \brief a cutoff alpha value for binarization of the window shape's alpha channel. */
+    /** \brief A cutoff alpha value for binarization of the window shape's alpha channel. */
     Uint8 binarizationCutoff;
     SDL_Color colorKey;
 } SDL_WindowShapeParams;
@@ -111,8 +112,8 @@ typedef struct SDL_WindowShapeMode {
  * \param shape A surface encoding the desired shape for the window.
  * \param shape_mode The parameters to set for the shaped window.
  *
- * \return 0 on success, SDL_INVALID_SHAPE_ARGUMENT on invalid an invalid shape argument, or SDL_NONSHAPEABLE_WINDOW
- *           if the SDL_Window* given does not reference a valid shaped window.
+ * \return 0 on success, SDL_INVALID_SHAPE_ARGUMENT on an invalid shape argument, or SDL_NONSHAPEABLE_WINDOW
+ *           if the SDL_Window given does not reference a valid shaped window.
  *
  * \sa SDL_WindowShapeMode
  * \sa SDL_GetShapedWindowMode.
@@ -127,7 +128,7 @@ extern DECLSPEC int SDLCALL SDL_SetWindowShape(SDL_Window *window,SDL_Surface *s
  *
  * \return 0 if the window has a shape and, provided shape_mode was not NULL, shape_mode has been filled with the mode
  *           data, SDL_NONSHAPEABLE_WINDOW if the SDL_Window given is not a shaped window, or SDL_WINDOW_LACKS_SHAPE if
- *           the SDL_Window* given is a shapeable window currently lacking a shape.
+ *           the SDL_Window given is a shapeable window currently lacking a shape.
  *
  * \sa SDL_WindowShapeMode
  * \sa SDL_SetWindowShape
@@ -140,4 +141,4 @@ extern DECLSPEC int SDLCALL SDL_GetShapedWindowMode(SDL_Window *window,SDL_Windo
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_shape_h */
+#endif /* SDL_shape_h_ */
diff --git a/include/SDL_stdinc.h b/include/SDL_stdinc.h
index fdf9641..546544f 100644
--- a/include/SDL_stdinc.h
+++ b/include/SDL_stdinc.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  This is a general header that includes C language support.
  */
 
-#ifndef _SDL_stdinc_h
-#define _SDL_stdinc_h
+#ifndef SDL_stdinc_h_
+#define SDL_stdinc_h_
 
 #include "SDL_config.h"
 
@@ -62,6 +62,9 @@
 #ifdef HAVE_STRINGS_H
 # include <strings.h>
 #endif
+#ifdef HAVE_WCHAR_H
+# include <wchar.h>
+#endif
 #if defined(HAVE_INTTYPES_H)
 # include <inttypes.h>
 #elif defined(HAVE_STDINT_H)
@@ -127,11 +130,18 @@
  */
 /* @{ */
 
+#ifdef __CC_ARM
+/* ARM's compiler throws warnings if we use an enum: like "SDL_bool x = a < b;" */
+#define SDL_FALSE 0
+#define SDL_TRUE 1
+typedef int SDL_bool;
+#else
 typedef enum
 {
     SDL_FALSE = 0,
     SDL_TRUE = 1
 } SDL_bool;
+#endif
 
 /**
  * \brief A signed 8-bit integer type.
@@ -262,7 +272,7 @@ typedef uint64_t Uint64;
 #endif /* SDL_DISABLE_ANALYZE_MACROS */
 
 #define SDL_COMPILE_TIME_ASSERT(name, x)               \
-       typedef int SDL_dummy_ ## name[(x) * 2 - 1]
+       typedef int SDL_compile_time_assert_ ## name[(x) * 2 - 1]
 /** \cond */
 #ifndef DOXYGEN_SHOULD_IGNORE_THIS
 SDL_COMPILE_TIME_ASSERT(uint8, sizeof(Uint8) == 1);
@@ -379,10 +389,10 @@ SDL_FORCE_INLINE void SDL_memset4(void *dst, Uint32 val, size_t dwords)
         return;
     switch (dwords % 4)
     {
-        case 0: do {    *_p++ = _val;
-        case 3:         *_p++ = _val;
-        case 2:         *_p++ = _val;
-        case 1:         *_p++ = _val;
+        case 0: do {    *_p++ = _val;   /* fallthrough */
+        case 3:         *_p++ = _val;   /* fallthrough */
+        case 2:         *_p++ = _val;   /* fallthrough */
+        case 1:         *_p++ = _val;   /* fallthrough */
         } while ( --_n );
     }
 #endif
@@ -397,6 +407,7 @@ extern DECLSPEC int SDLCALL SDL_memcmp(const void *s1, const void *s2, size_t le
 extern DECLSPEC size_t SDLCALL SDL_wcslen(const wchar_t *wstr);
 extern DECLSPEC size_t SDLCALL SDL_wcslcpy(SDL_OUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t maxlen);
 extern DECLSPEC size_t SDLCALL SDL_wcslcat(SDL_INOUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t maxlen);
+extern DECLSPEC int SDLCALL SDL_wcscmp(const wchar_t *str1, const wchar_t *str2);
 
 extern DECLSPEC size_t SDLCALL SDL_strlen(const char *str);
 extern DECLSPEC size_t SDLCALL SDL_strlcpy(SDL_OUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen);
@@ -409,6 +420,7 @@ extern DECLSPEC char *SDLCALL SDL_strlwr(char *str);
 extern DECLSPEC char *SDLCALL SDL_strchr(const char *str, int c);
 extern DECLSPEC char *SDLCALL SDL_strrchr(const char *str, int c);
 extern DECLSPEC char *SDLCALL SDL_strstr(const char *haystack, const char *needle);
+extern DECLSPEC size_t SDLCALL SDL_utf8strlen(const char *str);
 
 extern DECLSPEC char *SDLCALL SDL_itoa(int value, char *str, int radix);
 extern DECLSPEC char *SDLCALL SDL_uitoa(unsigned int value, char *str, int radix);
@@ -437,7 +449,7 @@ extern DECLSPEC int SDLCALL SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size
 
 #ifndef HAVE_M_PI
 #ifndef M_PI
-#define M_PI    3.14159265358979323846264338327950288   /* pi */
+#define M_PI    3.14159265358979323846264338327950288   /**< pi */
 #endif
 #endif
 
@@ -526,6 +538,6 @@ SDL_FORCE_INLINE void *SDL_memcpy4(SDL_OUT_BYTECAP(dwords*4) void *dst, SDL_IN_B
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_stdinc_h */
+#endif /* SDL_stdinc_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_surface.h b/include/SDL_surface.h
index e4a06a2..510690c 100644
--- a/include/SDL_surface.h
+++ b/include/SDL_surface.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Header file for ::SDL_Surface definition and management functions.
  */
 
-#ifndef _SDL_surface_h
-#define _SDL_surface_h
+#ifndef SDL_surface_h_
+#define SDL_surface_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_pixels.h"
@@ -94,8 +94,8 @@ typedef struct SDL_Surface
 /**
  * \brief The type of function used for surface blitting functions.
  */
-typedef int (*SDL_blit) (struct SDL_Surface * src, SDL_Rect * srcrect,
-                         struct SDL_Surface * dst, SDL_Rect * dstrect);
+typedef int (SDLCALL *SDL_blit) (struct SDL_Surface * src, SDL_Rect * srcrect,
+                                 struct SDL_Surface * dst, SDL_Rect * dstrect);
 
 /**
  *  Allocate and free an RGB surface.
@@ -118,8 +118,11 @@ typedef int (*SDL_blit) (struct SDL_Surface * src, SDL_Rect * srcrect,
 extern DECLSPEC SDL_Surface *SDLCALL SDL_CreateRGBSurface
     (Uint32 flags, int width, int height, int depth,
      Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask);
+
+/* !!! FIXME for 2.1: why does this ask for depth? Format provides that. */
 extern DECLSPEC SDL_Surface *SDLCALL SDL_CreateRGBSurfaceWithFormat
     (Uint32 flags, int width, int height, int depth, Uint32 format);
+
 extern DECLSPEC SDL_Surface *SDLCALL SDL_CreateRGBSurfaceFrom(void *pixels,
                                                               int width,
                                                               int height,
@@ -356,6 +359,11 @@ extern DECLSPEC SDL_bool SDLCALL SDL_SetClipRect(SDL_Surface * surface,
 extern DECLSPEC void SDLCALL SDL_GetClipRect(SDL_Surface * surface,
                                              SDL_Rect * rect);
 
+/*
+ * Creates a new surface identical to the existing surface
+ */
+extern DECLSPEC SDL_Surface *SDLCALL SDL_DuplicateSurface(SDL_Surface * surface);
+
 /**
  *  Creates a new surface of the specified format, and then copies and maps
  *  the given surface to it so the blit of the converted surface will be as
@@ -508,6 +516,6 @@ extern DECLSPEC int SDLCALL SDL_LowerBlitScaled
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_surface_h */
+#endif /* SDL_surface_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_system.h b/include/SDL_system.h
index 5da9adb..eb069b3 100644
--- a/include/SDL_system.h
+++ b/include/SDL_system.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Include file for platform specific SDL API functions
  */
 
-#ifndef _SDL_system_h
-#define _SDL_system_h
+#ifndef SDL_system_h_
+#define SDL_system_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_keyboard.h"
@@ -96,7 +96,7 @@ extern DECLSPEC void SDLCALL SDL_iPhoneSetEventPump(SDL_bool enabled);
 
    This returns JNIEnv*, but the prototype is void* so we don't need jni.h
  */
-extern DECLSPEC void * SDLCALL SDL_AndroidGetJNIEnv();
+extern DECLSPEC void * SDLCALL SDL_AndroidGetJNIEnv(void);
 
 /**
    \brief Get the SDL Activity object for the application
@@ -106,7 +106,7 @@ extern DECLSPEC void * SDLCALL SDL_AndroidGetJNIEnv();
    It is the caller's responsibility to properly release it
    (using env->Push/PopLocalFrame or manually with env->DeleteLocalRef)
  */
-extern DECLSPEC void * SDLCALL SDL_AndroidGetActivity();
+extern DECLSPEC void * SDLCALL SDL_AndroidGetActivity(void);
 
 /**
    See the official Android developer guide for more information:
@@ -121,7 +121,7 @@ extern DECLSPEC void * SDLCALL SDL_AndroidGetActivity();
    This path is unique to your application and cannot be written to
    by other applications.
  */
-extern DECLSPEC const char * SDLCALL SDL_AndroidGetInternalStoragePath();
+extern DECLSPEC const char * SDLCALL SDL_AndroidGetInternalStoragePath(void);
 
 /**
    \brief Get the current state of external storage, a bitmask of these values:
@@ -130,7 +130,7 @@ extern DECLSPEC const char * SDLCALL SDL_AndroidGetInternalStoragePath();
 
    If external storage is currently unavailable, this will return 0.
 */
-extern DECLSPEC int SDLCALL SDL_AndroidGetExternalStorageState();
+extern DECLSPEC int SDLCALL SDL_AndroidGetExternalStorageState(void);
 
 /**
    \brief Get the path used for external storage for this application.
@@ -138,7 +138,7 @@ extern DECLSPEC int SDLCALL SDL_AndroidGetExternalStorageState();
    This path is unique to your application, but is public and can be
    written to by other applications.
  */
-extern DECLSPEC const char * SDLCALL SDL_AndroidGetExternalStoragePath();
+extern DECLSPEC const char * SDLCALL SDL_AndroidGetExternalStoragePath(void);
 
 #endif /* __ANDROID__ */
 
@@ -211,6 +211,6 @@ extern DECLSPEC const char * SDLCALL SDL_WinRTGetFSPathUTF8(SDL_WinRT_Path pathT
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_system_h */
+#endif /* SDL_system_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_syswm.h b/include/SDL_syswm.h
index 71ba5f1..2d18afb 100644
--- a/include/SDL_syswm.h
+++ b/include/SDL_syswm.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Include file for SDL custom system window manager hooks.
  */
 
-#ifndef _SDL_syswm_h
-#define _SDL_syswm_h
+#ifndef SDL_syswm_h_
+#define SDL_syswm_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -125,7 +125,8 @@ typedef enum
     SDL_SYSWM_MIR,
     SDL_SYSWM_WINRT,
     SDL_SYSWM_ANDROID,
-    SDL_SYSWM_VIVANTE
+    SDL_SYSWM_VIVANTE,
+    SDL_SYSWM_OS2
 } SDL_SYSWM_TYPE;
 
 /**
@@ -201,6 +202,7 @@ struct SDL_SysWMinfo
         {
             HWND window;                /**< The window handle */
             HDC hdc;                    /**< The window device context */
+            HINSTANCE hinstance;        /**< The instance handle */
         } win;
 #endif
 #if defined(SDL_VIDEO_DRIVER_WINRT)
@@ -228,9 +230,9 @@ struct SDL_SysWMinfo
         struct
         {
 #if defined(__OBJC__) && defined(__has_feature) && __has_feature(objc_arc)
-            NSWindow __unsafe_unretained *window; /* The Cocoa window */
+            NSWindow __unsafe_unretained *window; /**< The Cocoa window */
 #else
-            NSWindow *window;                     /* The Cocoa window */
+            NSWindow *window;                     /**< The Cocoa window */
 #endif
         } cocoa;
 #endif
@@ -238,13 +240,13 @@ struct SDL_SysWMinfo
         struct
         {
 #if defined(__OBJC__) && defined(__has_feature) && __has_feature(objc_arc)
-            UIWindow __unsafe_unretained *window; /* The UIKit window */
+            UIWindow __unsafe_unretained *window; /**< The UIKit window */
 #else
-            UIWindow *window;                     /* The UIKit window */
+            UIWindow *window;                     /**< The UIKit window */
 #endif
-            GLuint framebuffer; /* The GL view's Framebuffer Object. It must be bound when rendering to the screen using GL. */
-            GLuint colorbuffer; /* The GL view's color Renderbuffer Object. It must be bound when SDL_GL_SwapWindow is called. */
-            GLuint resolveFramebuffer; /* The Framebuffer Object which holds the resolve color Renderbuffer, when MSAA is used. */
+            GLuint framebuffer; /**< The GL view's Framebuffer Object. It must be bound when rendering to the screen using GL. */
+            GLuint colorbuffer; /**< The GL view's color Renderbuffer Object. It must be bound when SDL_GL_SwapWindow is called. */
+            GLuint resolveFramebuffer; /**< The Framebuffer Object which holds the resolve color Renderbuffer, when MSAA is used. */
         } uikit;
 #endif
 #if defined(SDL_VIDEO_DRIVER_WAYLAND)
@@ -279,8 +281,9 @@ struct SDL_SysWMinfo
         } vivante;
 #endif
 
-        /* Can't have an empty union */
-        int dummy;
+        /* Make sure this union is always 64 bytes (8 64-bit pointers). */
+        /* Be careful not to overflow this if you add a new target! */
+        Uint8 dummy[64];
     } info;
 };
 
@@ -316,6 +319,6 @@ extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowWMInfo(SDL_Window * window,
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_syswm_h */
+#endif /* SDL_syswm_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test.h b/include/SDL_test.h
index 217847b..62c1be3 100644
--- a/include/SDL_test.h
+++ b/include/SDL_test.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,8 +27,8 @@
  *  This code is a part of the SDL2_test library, not the main SDL library.
  */
 
-#ifndef _SDL_test_h
-#define _SDL_test_h
+#ifndef SDL_test_h_
+#define SDL_test_h_
 
 #include "SDL.h"
 #include "SDL_test_common.h"
@@ -63,6 +63,6 @@ extern "C" {
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_h */
+#endif /* SDL_test_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_assert.h b/include/SDL_test_assert.h
index 29277e1..11d8363 100644
--- a/include/SDL_test_assert.h
+++ b/include/SDL_test_assert.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,8 +33,8 @@
  *
  */
 
-#ifndef _SDL_test_assert_h
-#define _SDL_test_assert_h
+#ifndef SDL_test_assert_h_
+#define SDL_test_assert_h_
 
 #include "begin_code.h"
 /* Set up for C function definitions, even when using C++ */
@@ -80,12 +80,12 @@ void SDLTest_AssertPass(SDL_PRINTF_FORMAT_STRING const char *assertDescription,
 /**
  * \brief Resets the assert summary counters to zero.
  */
-void SDLTest_ResetAssertSummary();
+void SDLTest_ResetAssertSummary(void);
 
 /**
  * \brief Logs summary of all assertions (total, pass, fail) since last reset as INFO or ERROR.
  */
-void SDLTest_LogAssertSummary();
+void SDLTest_LogAssertSummary(void);
 
 
 /**
@@ -93,13 +93,13 @@ void SDLTest_LogAssertSummary();
  *
  * \returns TEST_RESULT_PASSED, TEST_RESULT_FAILED, or TEST_RESULT_NO_ASSERT
  */
-int SDLTest_AssertSummaryToTestResult();
+int SDLTest_AssertSummaryToTestResult(void);
 
 #ifdef __cplusplus
 }
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_assert_h */
+#endif /* SDL_test_assert_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_common.h b/include/SDL_test_common.h
index 0ebf31c..24eeb32 100644
--- a/include/SDL_test_common.h
+++ b/include/SDL_test_common.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -29,8 +29,8 @@
 
 /* Ported from original test\common.h file. */
 
-#ifndef _SDL_test_common_h
-#define _SDL_test_common_h
+#ifndef SDL_test_common_h_
+#define SDL_test_common_h_
 
 #include "SDL.h"
 
@@ -183,6 +183,6 @@ void SDLTest_CommonQuit(SDLTest_CommonState * state);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_common_h */
+#endif /* SDL_test_common_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_compare.h b/include/SDL_test_compare.h
index 772cf9f..9f4c458 100644
--- a/include/SDL_test_compare.h
+++ b/include/SDL_test_compare.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,8 +33,8 @@
 
 */
 
-#ifndef _SDL_test_compare_h
-#define _SDL_test_compare_h
+#ifndef SDL_test_compare_h_
+#define SDL_test_compare_h_
 
 #include "SDL.h"
 
@@ -64,6 +64,6 @@ int SDLTest_CompareSurfaces(SDL_Surface *surface, SDL_Surface *referenceSurface,
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_compare_h */
+#endif /* SDL_test_compare_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_crc32.h b/include/SDL_test_crc32.h
index 572a3d9..65aa64e 100644
--- a/include/SDL_test_crc32.h
+++ b/include/SDL_test_crc32.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,8 +33,8 @@
 
 */
 
-#ifndef _SDL_test_crc32_h
-#define _SDL_test_crc32_h
+#ifndef SDL_test_crc32_h_
+#define SDL_test_crc32_h_
 
 #include "begin_code.h"
 /* Set up for C function definitions, even when using C++ */
@@ -119,6 +119,6 @@ int SDLTest_Crc32Done(SDLTest_Crc32Context * crcContext);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_crc32_h */
+#endif /* SDL_test_crc32_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_font.h b/include/SDL_test_font.h
index 3378ea8..58c9f9d 100644
--- a/include/SDL_test_font.h
+++ b/include/SDL_test_font.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,8 +27,8 @@
  *  This code is a part of the SDL2_test library, not the main SDL library.
  */
 
-#ifndef _SDL_test_font_h
-#define _SDL_test_font_h
+#ifndef SDL_test_font_h_
+#define SDL_test_font_h_
 
 #include "begin_code.h"
 /* Set up for C function definitions, even when using C++ */
@@ -50,7 +50,7 @@ extern "C" {
  *
  *  \returns Returns 0 on success, -1 on failure.
  */
-int SDLTest_DrawCharacter( SDL_Renderer *renderer, int x, int y, char c );
+int SDLTest_DrawCharacter(SDL_Renderer *renderer, int x, int y, char c);
 
 /**
  *  \brief Draw a string in the currently set font.
@@ -62,15 +62,20 @@ int SDLTest_DrawCharacter( SDL_Renderer *renderer, int x, int y, char c );
  *
  *  \returns Returns 0 on success, -1 on failure.
  */
-int SDLTest_DrawString( SDL_Renderer * renderer, int x, int y, const char *s );
+int SDLTest_DrawString(SDL_Renderer *renderer, int x, int y, const char *s);
 
 
+/**
+ *  \brief Cleanup textures used by font drawing functions.
+ */
+void SDLTest_CleanupTextDrawing(void);
+
 /* Ends C function definitions when using C++ */
 #ifdef __cplusplus
 }
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_font_h */
+#endif /* SDL_test_font_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_fuzzer.h b/include/SDL_test_fuzzer.h
index 9603652..6cf0574 100644
--- a/include/SDL_test_fuzzer.h
+++ b/include/SDL_test_fuzzer.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,8 +33,8 @@
 
 */
 
-#ifndef _SDL_test_fuzzer_h
-#define _SDL_test_fuzzer_h
+#ifndef SDL_test_fuzzer_h_
+#define SDL_test_fuzzer_h_
 
 #include "begin_code.h"
 /* Set up for C function definitions, even when using C++ */
@@ -68,14 +68,14 @@ void SDLTest_FuzzerInit(Uint64 execKey);
  *
  * \returns Generated integer
  */
-Uint8 SDLTest_RandomUint8();
+Uint8 SDLTest_RandomUint8(void);
 
 /**
  * Returns a random Sint8
  *
  * \returns Generated signed integer
  */
-Sint8 SDLTest_RandomSint8();
+Sint8 SDLTest_RandomSint8(void);
 
 
 /**
@@ -83,14 +83,14 @@ Sint8 SDLTest_RandomSint8();
  *
  * \returns Generated integer
  */
-Uint16 SDLTest_RandomUint16();
+Uint16 SDLTest_RandomUint16(void);
 
 /**
  * Returns a random Sint16
  *
  * \returns Generated signed integer
  */
-Sint16 SDLTest_RandomSint16();
+Sint16 SDLTest_RandomSint16(void);
 
 
 /**
@@ -98,7 +98,7 @@ Sint16 SDLTest_RandomSint16();
  *
  * \returns Generated integer
  */
-Sint32 SDLTest_RandomSint32();
+Sint32 SDLTest_RandomSint32(void);
 
 
 /**
@@ -106,14 +106,14 @@ Sint32 SDLTest_RandomSint32();
  *
  * \returns Generated integer
  */
-Uint32 SDLTest_RandomUint32();
+Uint32 SDLTest_RandomUint32(void);
 
 /**
  * Returns random Uint64.
  *
  * \returns Generated integer
  */
-Uint64 SDLTest_RandomUint64();
+Uint64 SDLTest_RandomUint64(void);
 
 
 /**
@@ -121,29 +121,29 @@ Uint64 SDLTest_RandomUint64();
  *
  * \returns Generated signed integer
  */
-Sint64 SDLTest_RandomSint64();
+Sint64 SDLTest_RandomSint64(void);
 
 /**
  * \returns random float in range [0.0 - 1.0[
  */
-float SDLTest_RandomUnitFloat();
+float SDLTest_RandomUnitFloat(void);
 
 /**
  * \returns random double in range [0.0 - 1.0[
  */
-double SDLTest_RandomUnitDouble();
+double SDLTest_RandomUnitDouble(void);
 
 /**
  * \returns random float.
  *
  */
-float SDLTest_RandomFloat();
+float SDLTest_RandomFloat(void);
 
 /**
  * \returns random double.
  *
  */
-double SDLTest_RandomDouble();
+double SDLTest_RandomDouble(void);
 
 /**
  * Returns a random boundary value for Uint8 within the given boundaries.
@@ -338,7 +338,7 @@ Sint32 SDLTest_RandomIntegerInRange(Sint32 min, Sint32 max);
  *
  * \returns Newly allocated random string; or NULL if length was invalid or string could not be allocated.
  */
-char * SDLTest_RandomAsciiString();
+char * SDLTest_RandomAsciiString(void);
 
 
 /**
@@ -371,7 +371,7 @@ char * SDLTest_RandomAsciiStringOfSize(int size);
 /**
  * Returns the invocation count for the fuzzer since last ...FuzzerInit.
  */
-int SDLTest_GetFuzzerInvocationCount();
+int SDLTest_GetFuzzerInvocationCount(void);
 
 /* Ends C function definitions when using C++ */
 #ifdef __cplusplus
@@ -379,6 +379,6 @@ int SDLTest_GetFuzzerInvocationCount();
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_fuzzer_h */
+#endif /* SDL_test_fuzzer_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_harness.h b/include/SDL_test_harness.h
index 74c0950..68c4bcb 100644
--- a/include/SDL_test_harness.h
+++ b/include/SDL_test_harness.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,8 +33,8 @@
   Based on original GSOC code by Markus Kauppila <markus.kauppila at gmail.com>
 */
 
-#ifndef _SDL_test_harness_h
-#define _SDL_test_harness_h
+#ifndef SDL_test_h_arness_h
+#define SDL_test_h_arness_h
 
 #include "begin_code.h"
 /* Set up for C function definitions, even when using C++ */
@@ -99,6 +99,17 @@ typedef struct SDLTest_TestSuiteReference {
 
 
 /**
+ * \brief Generates a random run seed string for the harness. The generated seed will contain alphanumeric characters (0-9A-Z).
+ *
+ * Note: The returned string needs to be deallocated by the caller.
+ *
+ * \param length The length of the seed string to generate
+ *
+ * \returns The generated seed string
+ */
+char *SDLTest_GenerateRunSeed(const int length);
+
+/**
  * \brief Execute a test suite using the given run seed and execution key.
  *
  * \param testSuites Suites containing the test case.
@@ -118,6 +129,6 @@ int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *user
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_harness_h */
+#endif /* SDL_test_h_arness_h */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_images.h b/include/SDL_test_images.h
index 8c64b4f..683d2f8 100644
--- a/include/SDL_test_images.h
+++ b/include/SDL_test_images.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,8 +33,8 @@
 
 */
 
-#ifndef _SDL_test_images_h
-#define _SDL_test_images_h
+#ifndef SDL_test_images_h_
+#define SDL_test_images_h_
 
 #include "SDL.h"
 
@@ -55,17 +55,17 @@ typedef struct SDLTest_SurfaceImage_s {
 } SDLTest_SurfaceImage_t;
 
 /* Test images */
-SDL_Surface *SDLTest_ImageBlit();
-SDL_Surface *SDLTest_ImageBlitColor();
-SDL_Surface *SDLTest_ImageBlitAlpha();
-SDL_Surface *SDLTest_ImageBlitBlendAdd();
-SDL_Surface *SDLTest_ImageBlitBlend();
-SDL_Surface *SDLTest_ImageBlitBlendMod();
-SDL_Surface *SDLTest_ImageBlitBlendNone();
-SDL_Surface *SDLTest_ImageBlitBlendAll();
-SDL_Surface *SDLTest_ImageFace();
-SDL_Surface *SDLTest_ImagePrimitives();
-SDL_Surface *SDLTest_ImagePrimitivesBlend();
+SDL_Surface *SDLTest_ImageBlit(void);
+SDL_Surface *SDLTest_ImageBlitColor(void);
+SDL_Surface *SDLTest_ImageBlitAlpha(void);
+SDL_Surface *SDLTest_ImageBlitBlendAdd(void);
+SDL_Surface *SDLTest_ImageBlitBlend(void);
+SDL_Surface *SDLTest_ImageBlitBlendMod(void);
+SDL_Surface *SDLTest_ImageBlitBlendNone(void);
+SDL_Surface *SDLTest_ImageBlitBlendAll(void);
+SDL_Surface *SDLTest_ImageFace(void);
+SDL_Surface *SDLTest_ImagePrimitives(void);
+SDL_Surface *SDLTest_ImagePrimitivesBlend(void);
 
 /* Ends C function definitions when using C++ */
 #ifdef __cplusplus
@@ -73,6 +73,6 @@ SDL_Surface *SDLTest_ImagePrimitivesBlend();
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_images_h */
+#endif /* SDL_test_images_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_log.h b/include/SDL_test_log.h
index 73a5c01..9f993fb 100644
--- a/include/SDL_test_log.h
+++ b/include/SDL_test_log.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,8 +33,8 @@
  *
  */
 
-#ifndef _SDL_test_log_h
-#define _SDL_test_log_h
+#ifndef SDL_test_log_h_
+#define SDL_test_log_h_
 
 #include "begin_code.h"
 /* Set up for C function definitions, even when using C++ */
@@ -62,6 +62,6 @@ void SDLTest_LogError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_log_h */
+#endif /* SDL_test_log_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_md5.h b/include/SDL_test_md5.h
index f2d9a7d..67ca7d1 100644
--- a/include/SDL_test_md5.h
+++ b/include/SDL_test_md5.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -53,8 +53,8 @@
  ***********************************************************************
 */
 
-#ifndef _SDL_test_md5_h
-#define _SDL_test_md5_h
+#ifndef SDL_test_md5_h_
+#define SDL_test_md5_h_
 
 #include "begin_code.h"
 /* Set up for C function definitions, even when using C++ */
@@ -124,6 +124,6 @@ extern "C" {
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_md5_h */
+#endif /* SDL_test_md5_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_test_random.h b/include/SDL_test_random.h
index 91c3652..2b01922 100644
--- a/include/SDL_test_random.h
+++ b/include/SDL_test_random.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -37,8 +37,8 @@
 
 */
 
-#ifndef _SDL_test_random_h
-#define _SDL_test_random_h
+#ifndef SDL_test_random_h_
+#define SDL_test_random_h_
 
 #include "begin_code.h"
 /* Set up for C function definitions, even when using C++ */
@@ -110,6 +110,6 @@ extern "C" {
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_test_random_h */
+#endif /* SDL_test_random_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_thread.h b/include/SDL_thread.h
index 377e6c7..cf1ce49 100644
--- a/include/SDL_thread.h
+++ b/include/SDL_thread.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_thread_h
-#define _SDL_thread_h
+#ifndef SDL_thread_h_
+#define SDL_thread_h_
 
 /**
  *  \file SDL_thread.h
@@ -74,15 +74,15 @@ typedef int (SDLCALL * SDL_ThreadFunction) (void *data);
  *
  *  We compile SDL into a DLL. This means, that it's the DLL which
  *  creates a new thread for the calling process with the SDL_CreateThread()
- *  API. There is a problem with this, that only the RTL of the SDL.DLL will
+ *  API. There is a problem with this, that only the RTL of the SDL2.DLL will
  *  be initialized for those threads, and not the RTL of the calling
  *  application!
  *
  *  To solve this, we make a little hack here.
  *
  *  We'll always use the caller's _beginthread() and _endthread() APIs to
- *  start a new thread. This way, if it's the SDL.DLL which uses this API,
- *  then the RTL of SDL.DLL will be used to create the new thread, and if it's
+ *  start a new thread. This way, if it's the SDL2.DLL which uses this API,
+ *  then the RTL of SDL2.DLL will be used to create the new thread, and if it's
  *  the application, then the RTL of the application will be used.
  *
  *  So, in short:
@@ -118,6 +118,26 @@ SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data,
 #define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthreadex, (pfnSDL_CurrentEndThread)_endthreadex)
 #endif
 
+#elif defined(__OS2__)
+/*
+ * just like the windows case above:  We compile SDL2
+ * into a dll with Watcom's runtime statically linked.
+ */
+#define SDL_PASSED_BEGINTHREAD_ENDTHREAD
+#include <process.h>
+typedef int (*pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void * /*arg*/);
+typedef void (*pfnSDL_CurrentEndThread)(void);
+extern DECLSPEC SDL_Thread *SDLCALL
+SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data,
+                 pfnSDL_CurrentBeginThread pfnBeginThread,
+                 pfnSDL_CurrentEndThread pfnEndThread);
+#if defined(SDL_CreateThread) && SDL_DYNAMIC_API
+#undef SDL_CreateThread
+#define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthread, (pfnSDL_CurrentEndThread)_endthread)
+#else
+#define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthread, (pfnSDL_CurrentEndThread)_endthread)
+#endif
+
 #else
 
 /**
@@ -273,7 +293,7 @@ extern DECLSPEC void * SDLCALL SDL_TLSGet(SDL_TLSID id);
  *  \sa SDL_TLSCreate()
  *  \sa SDL_TLSGet()
  */
-extern DECLSPEC int SDLCALL SDL_TLSSet(SDL_TLSID id, const void *value, void (*destructor)(void*));
+extern DECLSPEC int SDLCALL SDL_TLSSet(SDL_TLSID id, const void *value, void (SDLCALL *destructor)(void*));
 
 
 /* Ends C function definitions when using C++ */
@@ -282,6 +302,6 @@ extern DECLSPEC int SDLCALL SDL_TLSSet(SDL_TLSID id, const void *value, void (*d
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_thread_h */
+#endif /* SDL_thread_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_timer.h b/include/SDL_timer.h
index e0d3785..282625d 100644
--- a/include/SDL_timer.h
+++ b/include/SDL_timer.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_timer_h
-#define _SDL_timer_h
+#ifndef SDL_timer_h_
+#define SDL_timer_h_
 
 /**
  *  \file SDL_timer.h
@@ -110,6 +110,6 @@ extern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID id);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_timer_h */
+#endif /* SDL_timer_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_touch.h b/include/SDL_touch.h
index 2643e36..db9e25e 100644
--- a/include/SDL_touch.h
+++ b/include/SDL_touch.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Include file for SDL touch event handling.
  */
 
-#ifndef _SDL_touch_h
-#define _SDL_touch_h
+#ifndef SDL_touch_h_
+#define SDL_touch_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_error.h"
@@ -81,6 +81,6 @@ extern DECLSPEC SDL_Finger * SDLCALL SDL_GetTouchFinger(SDL_TouchID touchID, int
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_touch_h */
+#endif /* SDL_touch_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_types.h b/include/SDL_types.h
index 5118af2..06ee80c 100644
--- a/include/SDL_types.h
+++ b/include/SDL_types.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/include/SDL_version.h b/include/SDL_version.h
index 1700efd..8471b65 100644
--- a/include/SDL_version.h
+++ b/include/SDL_version.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  This header defines the current SDL version.
  */
 
-#ifndef _SDL_version_h
-#define _SDL_version_h
+#ifndef SDL_version_h_
+#define SDL_version_h_
 
 #include "SDL_stdinc.h"
 
@@ -59,7 +59,7 @@ typedef struct SDL_version
 */
 #define SDL_MAJOR_VERSION   2
 #define SDL_MINOR_VERSION   0
-#define SDL_PATCHLEVEL      5
+#define SDL_PATCHLEVEL      6
 
 /**
  *  \brief Macro to determine SDL version program was compiled against.
@@ -157,6 +157,6 @@ extern DECLSPEC int SDLCALL SDL_GetRevisionNumber(void);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_version_h */
+#endif /* SDL_version_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_video.h b/include/SDL_video.h
index 73c33eb..6f6cda8 100644
--- a/include/SDL_video.h
+++ b/include/SDL_video.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,8 @@
  *  Header file for SDL video functions.
  */
 
-#ifndef _SDL_video_h
-#define _SDL_video_h
+#ifndef SDL_video_h_
+#define SDL_video_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_pixels.h"
@@ -116,7 +116,8 @@ typedef enum
     SDL_WINDOW_SKIP_TASKBAR  = 0x00010000,      /**< window should not be added to the taskbar */
     SDL_WINDOW_UTILITY       = 0x00020000,      /**< window should be treated as a utility window */
     SDL_WINDOW_TOOLTIP       = 0x00040000,      /**< window should be treated as a tooltip */
-    SDL_WINDOW_POPUP_MENU    = 0x00080000       /**< window should be treated as a popup menu */
+    SDL_WINDOW_POPUP_MENU    = 0x00080000,      /**< window should be treated as a popup menu */
+    SDL_WINDOW_VULKAN        = 0x10000000       /**< window usable for Vulkan surface */
 } SDL_WindowFlags;
 
 /**
@@ -200,14 +201,16 @@ typedef enum
     SDL_GL_CONTEXT_PROFILE_MASK,
     SDL_GL_SHARE_WITH_CURRENT_CONTEXT,
     SDL_GL_FRAMEBUFFER_SRGB_CAPABLE,
-    SDL_GL_CONTEXT_RELEASE_BEHAVIOR
+    SDL_GL_CONTEXT_RELEASE_BEHAVIOR,
+    SDL_GL_CONTEXT_RESET_NOTIFICATION,
+    SDL_GL_CONTEXT_NO_ERROR
 } SDL_GLattr;
 
 typedef enum
 {
     SDL_GL_CONTEXT_PROFILE_CORE           = 0x0001,
     SDL_GL_CONTEXT_PROFILE_COMPATIBILITY  = 0x0002,
-    SDL_GL_CONTEXT_PROFILE_ES             = 0x0004 /* GLX_CONTEXT_ES2_PROFILE_BIT_EXT */
+    SDL_GL_CONTEXT_PROFILE_ES             = 0x0004 /**< GLX_CONTEXT_ES2_PROFILE_BIT_EXT */
 } SDL_GLprofile;
 
 typedef enum
@@ -224,6 +227,11 @@ typedef enum
     SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH  = 0x0001
 } SDL_GLcontextReleaseFlag;
 
+typedef enum
+{
+    SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = 0x0000,
+    SDL_GL_CONTEXT_RESET_LOSE_CONTEXT    = 0x0001
+} SDL_GLContextResetNotification;
 
 /* Function prototypes */
 
@@ -448,17 +456,32 @@ extern DECLSPEC Uint32 SDLCALL SDL_GetWindowPixelFormat(SDL_Window * window);
  *               ::SDL_WINDOW_HIDDEN,        ::SDL_WINDOW_BORDERLESS,
  *               ::SDL_WINDOW_RESIZABLE,     ::SDL_WINDOW_MAXIMIZED,
  *               ::SDL_WINDOW_MINIMIZED,     ::SDL_WINDOW_INPUT_GRABBED,
- *               ::SDL_WINDOW_ALLOW_HIGHDPI.
+ *               ::SDL_WINDOW_ALLOW_HIGHDPI, ::SDL_WINDOW_VULKAN.
  *
  *  \return The created window, or NULL if window creation failed.
  *
  *  If the window is created with the SDL_WINDOW_ALLOW_HIGHDPI flag, its size
  *  in pixels may differ from its size in screen coordinates on platforms with
  *  high-DPI support (e.g. iOS and Mac OS X). Use SDL_GetWindowSize() to query
- *  the client area's size in screen coordinates, and SDL_GL_GetDrawableSize()
- *  or SDL_GetRendererOutputSize() to query the drawable size in pixels.
+ *  the client area's size in screen coordinates, and SDL_GL_GetDrawableSize(),
+ *  SDL_Vulkan_GetDrawableSize(), or SDL_GetRendererOutputSize() to query the
+ *  drawable size in pixels.
+ *
+ *  If the window is created with any of the SDL_WINDOW_OPENGL or
+ *  SDL_WINDOW_VULKAN flags, then the corresponding LoadLibrary function
+ *  (SDL_GL_LoadLibrary or SDL_Vulkan_LoadLibrary) is called and the
+ *  corrensponding UnloadLibrary function is called by SDL_DestroyWindow().
+ *
+ *  If SDL_WINDOW_VULKAN is specified and there isn't a working Vulkan driver,
+ *  SDL_CreateWindow() will fail because SDL_Vulkan_LoadLibrary() will fail.
+ *
+ *  \note On non-Apple devices, SDL requires you to either not link to the
+ *        Vulkan loader or link to a dynamic library version. This limitation
+ *        may be removed in a future version of SDL.
  *
  *  \sa SDL_DestroyWindow()
+ *  \sa SDL_GL_LoadLibrary()
+ *  \sa SDL_Vulkan_LoadLibrary()
  */
 extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindow(const char *title,
                                                       int x, int y, int w,
@@ -581,8 +604,8 @@ extern DECLSPEC void SDLCALL SDL_GetWindowPosition(SDL_Window * window,
  *  \param w        The width of the window, in screen coordinates. Must be >0.
  *  \param h        The height of the window, in screen coordinates. Must be >0.
  *
- *  \note You can't change the size of a fullscreen window, it automatically
- *        matches the size of the display mode.
+ *  \note Fullscreen windows automatically match the size of the display mode,
+ *        and you should use SDL_SetWindowDisplayMode() to change their size.
  *
  *  The window size in screen coordinates may differ from the size in pixels, if
  *  the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a platform with
@@ -590,6 +613,7 @@ extern DECLSPEC void SDLCALL SDL_GetWindowPosition(SDL_Window * window,
  *  SDL_GetRendererOutputSize() to get the real client area size in pixels.
  *
  *  \sa SDL_GetWindowSize()
+ *  \sa SDL_SetWindowDisplayMode()
  */
 extern DECLSPEC void SDLCALL SDL_SetWindowSize(SDL_Window * window, int w,
                                                int h);
@@ -870,7 +894,7 @@ extern DECLSPEC float SDLCALL SDL_GetWindowBrightness(SDL_Window * window);
  *  \param window The window which will be made transparent or opaque
  *  \param opacity Opacity (0.0f - transparent, 1.0f - opaque) This will be
  *                 clamped internally between 0.0f and 1.0f.
- * 
+ *
  *  \return 0 on success, or -1 if setting the opacity isn't supported.
  *
  *  \sa SDL_GetWindowOpacity()
@@ -897,7 +921,7 @@ extern DECLSPEC int SDLCALL SDL_GetWindowOpacity(SDL_Window * window, float * ou
  *
  *  \param modal_window The window that should be modal
  *  \param parent_window The parent window
- * 
+ *
  *  \return 0 on success, or -1 otherwise.
  */
 extern DECLSPEC int SDLCALL SDL_SetWindowModalFor(SDL_Window * modal_window, SDL_Window * parent_window);
@@ -910,7 +934,7 @@ extern DECLSPEC int SDLCALL SDL_SetWindowModalFor(SDL_Window * modal_window, SDL
  *  obscured by other windows.
  *
  *  \param window The window that should get the input focus
- * 
+ *
  *  \return 0 on success, or -1 otherwise.
  *  \sa SDL_RaiseWindow()
  */
@@ -1110,11 +1134,16 @@ extern DECLSPEC void SDLCALL SDL_GL_ResetAttributes(void);
 
 /**
  *  \brief Set an OpenGL window attribute before window creation.
+ *
+ *  \return 0 on success, or -1 if the attribute could not be set.
  */
 extern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value);
 
 /**
  *  \brief Get the actual value for an attribute from the current context.
+ *
+ *  \return 0 on success, or -1 if the attribute could not be retrieved.
+ *          The integer at \c value will be modified in either case.
  */
 extern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int *value);
 
@@ -1213,6 +1242,6 @@ extern DECLSPEC void SDLCALL SDL_GL_DeleteContext(SDL_GLContext context);
 #endif
 #include "close_code.h"
 
-#endif /* _SDL_video_h */
+#endif /* SDL_video_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/include/SDL_vulkan.h b/include/SDL_vulkan.h
new file mode 100644
index 0000000..803b5fe
--- /dev/null
+++ b/include/SDL_vulkan.h
@@ -0,0 +1,257 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 2017, Mark Callow
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+/**
+ *  \file SDL_vulkan.h
+ *
+ *  Header file for functions to creating Vulkan surfaces on SDL windows.
+ */
+
+#ifndef SDL_vulkan_h_
+#define SDL_vulkan_h_
+
+#include "SDL_video.h"
+
+#include "begin_code.h"
+/* Set up for C function definitions, even when using C++ */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Avoid including vulkan.h, don't define VkInstance if it's already included */
+#ifdef VULKAN_H_
+#define NO_SDL_VULKAN_TYPEDEFS
+#endif
+#ifndef NO_SDL_VULKAN_TYPEDEFS
+#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object;
+
+#if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
+#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object;
+#else
+#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object;
+#endif
+
+VK_DEFINE_HANDLE(VkInstance)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR)
+
+#endif /* !NO_SDL_VULKAN_TYPEDEFS */
+
+typedef VkInstance SDL_vulkanInstance;
+typedef VkSurfaceKHR SDL_vulkanSurface; /* for compatibility with Tizen */
+
+/**
+ *  \name Vulkan support functions
+ *
+ *  \note SDL_Vulkan_GetInstanceExtensions & SDL_Vulkan_CreateSurface API
+ *        is compatable with Tizen's implementation of Vulkan in SDL.
+ */
+/* @{ */
+
+/**
+ *  \brief Dynamically load a Vulkan loader library.
+ *
+ *  \param [in] path The platform dependent Vulkan loader library name, or
+ *              \c NULL to open the default Vulkan loader library.
+ *
+ *  \return \c 0 on success, or \c -1 if the library couldn't be loaded.
+ *
+ *  This should be done after initializing the video driver, but before
+ *  creating any Vulkan windows. If no Vulkan loader library is loaded, the
+ *  default library will be loaded upon creation of the first Vulkan window.
+ *
+ *  \note If you specify a non-NULL \a path, you should retrieve all of the
+ *        Vulkan functions used in your program from the dynamic library using
+ *        \c SDL_Vulkan_GetVkGetInstanceProcAddr() unless you can guarantee
+ *        \a path points to the same vulkan loader library that you linked to.
+ *
+ *  \note On Apple devices, if \a path is NULL, SDL will attempt to find
+ *        the vkGetInstanceProcAddr address within all the mach-o images of
+ *        the current process. This is because the currently (v0.17.0)
+ *        recommended MoltenVK (Vulkan on Metal) usage is as a static library.
+ *        If it is not found then SDL will attempt to load \c libMoltenVK.dylib.
+ *        Applications using the dylib alternative therefore do not need to do
+ *        anything special when calling SDL.
+ *
+ *  \note On non-Apple devices, SDL requires you to either not link to the
+ *        Vulkan loader or link to a dynamic library version. This limitation
+ *        may be removed in a future version of SDL.
+ *
+ *  \note This function will fail if there are no working Vulkan drivers
+ *        installed.
+ *
+ *  \sa SDL_Vulkan_GetVkGetInstanceProcAddr()
+ *  \sa SDL_Vulkan_UnloadLibrary()
+ */
+extern DECLSPEC int SDLCALL SDL_Vulkan_LoadLibrary(const char *path);
+
+/**
+ *  \brief Get the address of the \c vkGetInstanceProcAddr function.
+ *
+ *  \note This should be called after either calling SDL_Vulkan_LoadLibrary
+ *        or creating an SDL_Window with the SDL_WINDOW_VULKAN flag.
+ */
+extern DECLSPEC void *SDLCALL SDL_Vulkan_GetVkGetInstanceProcAddr(void);
+
+/**
+ *  \brief Unload the Vulkan loader library previously loaded by
+ *         \c SDL_Vulkan_LoadLibrary().
+ *
+ *  \sa SDL_Vulkan_LoadLibrary()
+ */
+extern DECLSPEC void SDLCALL SDL_Vulkan_UnloadLibrary(void);
+
+/**
+ *  \brief Get the names of the Vulkan instance extensions needed to create
+ *         a surface with \c SDL_Vulkan_CreateSurface().
+ *
+ *  \param [in]     window Window for which the required Vulkan instance
+ *                  extensions should be retrieved
+ *  \param [in,out] count pointer to an \c unsigned related to the number of
+ *                  required Vulkan instance extensions
+ *  \param [out]    names \c NULL or a pointer to an array to be filled with the
+ *                  required Vulkan instance extensions
+ *
+ *  \return \c SDL_TRUE on success, \c SDL_FALSE on error.
+ *
+ *  If \a pNames is \c NULL, then the number of required Vulkan instance
+ *  extensions is returned in pCount. Otherwise, \a pCount must point to a
+ *  variable set to the number of elements in the \a pNames array, and on
+ *  return the variable is overwritten with the number of names actually
+ *  written to \a pNames. If \a pCount is less than the number of required
+ *  extensions, at most \a pCount structures will be written. If \a pCount
+ *  is smaller than the number of required extensions, \c SDL_FALSE will be
+ *  returned instead of \c SDL_TRUE, to indicate that not all the required
+ *  extensions were returned.
+ *
+ *  \note The returned list of extensions will contain \c VK_KHR_surface
+ *        and zero or more platform specific extensions
+ *
+ *  \note The extension names queried here must be enabled when calling
+ *        VkCreateInstance, otherwise surface creation will fail.
+ *
+ *  \note \c window should have been created with the \c SDL_WINDOW_VULKAN flag.
+ *
+ *  \code
+ *  unsigned int count;
+ *  // get count of required extensions
+ *  if(!SDL_Vulkan_GetInstanceExtensions(window, &count, NULL))
+ *      handle_error();
+ *
+ *  static const char *const additionalExtensions[] =
+ *  {
+ *      VK_EXT_DEBUG_REPORT_EXTENSION_NAME, // example additional extension
+ *  };
+ *  size_t additionalExtensionsCount = sizeof(additionalExtensions) / sizeof(additionalExtensions[0]);
+ *  size_t extensionCount = count + additionalExtensionsCount;
+ *  const char **names = malloc(sizeof(const char *) * extensionCount);
+ *  if(!names)
+ *      handle_error();
+ *
+ *  // get names of required extensions
+ *  if(!SDL_Vulkan_GetInstanceExtensions(window, &count, names))
+ *      handle_error();
+ *
+ *  // copy additional extensions after required extensions
+ *  for(size_t i = 0; i < additionalExtensionsCount; i++)
+ *      names[i + count] = additionalExtensions[i];
+ *
+ *  VkInstanceCreateInfo instanceCreateInfo = {};
+ *  instanceCreateInfo.enabledExtensionCount = extensionCount;
+ *  instanceCreateInfo.ppEnabledExtensionNames = names;
+ *  // fill in rest of instanceCreateInfo
+ *
+ *  VkInstance instance;
+ *  // create the Vulkan instance
+ *  VkResult result = vkCreateInstance(&instanceCreateInfo, NULL, &instance);
+ *  free(names);
+ *  \endcode
+ *
+ *  \sa SDL_Vulkan_CreateSurface()
+ */
+extern DECLSPEC SDL_bool SDLCALL SDL_Vulkan_GetInstanceExtensions(
+														SDL_Window *window,
+														unsigned int *pCount,
+														const char **pNames);
+
+/**
+ *  \brief Create a Vulkan rendering surface for a window.
+ *
+ *  \param [in]  window   SDL_Window to which to attach the rendering surface.
+ *  \param [in]  instance handle to the Vulkan instance to use.
+ *  \param [out] surface  pointer to a VkSurfaceKHR handle to receive the
+ *                        handle of the newly created surface.
+ *
+ *  \return \c SDL_TRUE on success, \c SDL_FALSE on error.
+ *
+ *  \code
+ *  VkInstance instance;
+ *  SDL_Window *window;
+ *
+ *  // create instance and window
+ *
+ *  // create the Vulkan surface
+ *  VkSurfaceKHR surface;
+ *  if(!SDL_Vulkan_CreateSurface(window, instance, &surface))
+ *      handle_error();
+ *  \endcode
+ *
+ *  \note \a window should have been created with the \c SDL_WINDOW_VULKAN flag.
+ *
+ *  \note \a instance should have been created with the extensions returned
+ *        by \c SDL_Vulkan_CreateSurface() enabled.
+ *
+ *  \sa SDL_Vulkan_GetInstanceExtensions()
+ */
+extern DECLSPEC SDL_bool SDLCALL SDL_Vulkan_CreateSurface(
+												SDL_Window *window,
+												VkInstance instance,
+												VkSurfaceKHR* surface);
+
+/**
+ *  \brief Get the size of a window's underlying drawable in pixels (for use
+ *         with setting viewport, scissor & etc).
+ *
+ *  \param window   SDL_Window from which the drawable size should be queried
+ *  \param w        Pointer to variable for storing the width in pixels,
+ *                  may be NULL
+ *  \param h        Pointer to variable for storing the height in pixels,
+ *                  may be NULL
+ *
+ * This may differ from SDL_GetWindowSize() if we're rendering to a high-DPI
+ * drawable, i.e. the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a
+ * platform with high-DPI support (Apple calls this "Retina"), and not disabled
+ * by the \c SDL_HINT_VIDEO_HIGHDPI_DISABLED hint.
+ *
+ *  \sa SDL_GetWindowSize()
+ *  \sa SDL_CreateWindow()
+ */
+extern DECLSPEC void SDLCALL SDL_Vulkan_GetDrawableSize(SDL_Window * window,
+                                                        int *w, int *h);
+
+/* @} *//* Vulkan support functions */
+
+/* Ends C function definitions when using C++ */
+#ifdef __cplusplus
+}
+#endif
+#include "close_code.h"
+
+#endif /* SDL_vulkan_h_ */
diff --git a/include/begin_code.h b/include/begin_code.h
index 04e78c6..5372d6f 100644
--- a/include/begin_code.h
+++ b/include/begin_code.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -61,6 +61,12 @@
 #  else
 #   define DECLSPEC __declspec(dllexport)
 #  endif
+# elif defined(__OS2__)
+#   ifdef BUILD_SDL
+#    define DECLSPEC    __declspec(dllexport)
+#   else
+#    define DECLSPEC
+#   endif
 # else
 #  if defined(__GNUC__) && __GNUC__ >= 4
 #   define DECLSPEC __attribute__ ((visibility("default")))
@@ -74,6 +80,11 @@
 #ifndef SDLCALL
 #if (defined(__WIN32__) || defined(__WINRT__)) && !defined(__GNUC__)
 #define SDLCALL __cdecl
+#elif defined(__OS2__) || defined(__EMX__)
+#define SDLCALL _System
+# if defined (__GNUC__) && !defined(_System)
+#  define _System /* for old EMX/GCC compat.  */
+# endif
 #else
 #define SDLCALL
 #endif
@@ -111,7 +122,7 @@
 #elif defined(_MSC_VER) || defined(__BORLANDC__) || \
       defined(__DMC__) || defined(__SC__) || \
       defined(__WATCOMC__) || defined(__LCC__) || \
-      defined(__DECC)
+      defined(__DECC) || defined(__CC_ARM)
 #define SDL_INLINE __inline
 #ifndef __inline__
 #define __inline__ __inline
@@ -134,6 +145,16 @@
 #endif
 #endif /* SDL_FORCE_INLINE not defined */
 
+#ifndef SDL_NORETURN
+#if defined(__GNUC__)
+#define SDL_NORETURN __attribute__((noreturn))
+#elif defined(_MSC_VER)
+#define SDL_NORETURN __declspec(noreturn)
+#else
+#define SDL_NORETURN
+#endif
+#endif /* SDL_NORETURN not defined */
+
 /* Apparently this is needed by several Windows compilers */
 #if !defined(__MACH__)
 #ifndef NULL
diff --git a/include/close_code.h b/include/close_code.h
index d908b00..2a352db 100644
--- a/include/close_code.h
+++ b/include/close_code.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -29,7 +29,7 @@
 #undef _begin_code_h
 
 /* Reset structure packing at previous byte alignment */
-#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__WATCOMC__)  || defined(__BORLANDC__)
+#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__)
 #ifdef __BORLANDC__
 #pragma nopackwarning
 #endif
diff --git a/src/SDL.c b/src/SDL.c
index 9eef00c..0ed49a2 100644
--- a/src/SDL.c
+++ b/src/SDL.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -36,10 +36,7 @@
 
 /* Initialization/Cleanup routines */
 #if !SDL_TIMERS_DISABLED
-extern int SDL_TimerInit(void);
-extern void SDL_TimerQuit(void);
-extern void SDL_TicksInit(void);
-extern void SDL_TicksQuit(void);
+# include "timer/SDL_timer_c.h"
 #endif
 #if SDL_VIDEO_DRIVER_WINDOWS
 extern int SDL_HelperWindowCreate(void);
@@ -81,7 +78,7 @@ SDL_PrivateShouldInitSubsystem(Uint32 subsystem)
 {
     int subsystem_index = SDL_MostSignificantBitIndex32(subsystem);
     SDL_assert(SDL_SubsystemRefCount[subsystem_index] < 255);
-    return (SDL_SubsystemRefCount[subsystem_index] == 0);
+    return (SDL_SubsystemRefCount[subsystem_index] == 0) ? SDL_TRUE : SDL_FALSE;
 }
 
 /* Private helper to check if a system needs to be quit. */
@@ -95,7 +92,7 @@ SDL_PrivateShouldQuitSubsystem(Uint32 subsystem) {
     /* If we're in SDL_Quit, we shut down every subsystem, even if refcount
      * isn't zero.
      */
-    return SDL_SubsystemRefCount[subsystem_index] == 1 || SDL_bInMainQuit;
+    return (SDL_SubsystemRefCount[subsystem_index] == 1 || SDL_bInMainQuit) ? SDL_TRUE : SDL_FALSE;
 }
 
 void
diff --git a/src/SDL_assert.c b/src/SDL_assert.c
index a21f70b..47309eb 100644
--- a/src/SDL_assert.c
+++ b/src/SDL_assert.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -44,7 +44,12 @@
 #endif
 #endif
 
-static SDL_assert_state
+#if defined(__EMSCRIPTEN__)
+#include <emscripten.h>
+#endif
+
+
+static SDL_assert_state SDLCALL
 SDL_PromptAssertion(const SDL_assert_data *data, void *userdata);
 
 /*
@@ -53,7 +58,10 @@ SDL_PromptAssertion(const SDL_assert_data *data, void *userdata);
  */
 static SDL_assert_data *triggered_assertions = NULL;
 
+#ifndef SDL_THREADS_DISABLED
 static SDL_mutex *assertion_mutex = NULL;
+#endif
+
 static SDL_AssertionHandler assertion_handler = SDL_PromptAssertion;
 static void *assertion_userdata = NULL;
 
@@ -111,23 +119,29 @@ static void SDL_GenerateAssertionReport(void)
     }
 }
 
-static void SDL_ExitProcess(int exitcode)
+
+static SDL_NORETURN void SDL_ExitProcess(int exitcode)
 {
 #ifdef __WIN32__
     ExitProcess(exitcode);
+#elif defined(__EMSCRIPTEN__)
+    emscripten_cancel_main_loop();  /* this should "kill" the app. */
+    emscripten_force_exit(exitcode);  /* this should "kill" the app. */
+    exit(exitcode);
 #else
     _exit(exitcode);
 #endif
 }
 
-static void SDL_AbortAssertion(void)
+
+static SDL_NORETURN void SDL_AbortAssertion(void)
 {
     SDL_Quit();
     SDL_ExitProcess(42);
 }
 
 
-static SDL_assert_state
+static SDL_assert_state SDLCALL
 SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
 {
 #ifdef __WIN32__
@@ -216,9 +230,45 @@ SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
             state = (SDL_assert_state)selected;
         }
     }
-#ifdef HAVE_STDIO_H
+
     else
     {
+#if defined(__EMSCRIPTEN__)
+        /* This is nasty, but we can't block on a custom UI. */
+        for ( ; ; ) {
+            SDL_bool okay = SDL_TRUE;
+            char *buf = (char *) EM_ASM_INT({
+                var str =
+                    Pointer_stringify($0) + '\n\n' +
+                    'Abort/Retry/Ignore/AlwaysIgnore? [ariA] :';
+                var reply = window.prompt(str, "i");
+                if (reply === null) {
+                    reply = "i";
+                }
+                return allocate(intArrayFromString(reply), 'i8', ALLOC_NORMAL);
+            }, message);
+
+            if (SDL_strcmp(buf, "a") == 0) {
+                state = SDL_ASSERTION_ABORT;
+            /* (currently) no break functionality on Emscripten
+            } else if (SDL_strcmp(buf, "b") == 0) {
+                state = SDL_ASSERTION_BREAK; */
+            } else if (SDL_strcmp(buf, "r") == 0) {
+                state = SDL_ASSERTION_RETRY;
+            } else if (SDL_strcmp(buf, "i") == 0) {
+                state = SDL_ASSERTION_IGNORE;
+            } else if (SDL_strcmp(buf, "A") == 0) {
+                state = SDL_ASSERTION_ALWAYS_IGNORE;
+            } else {
+                okay = SDL_FALSE;
+            }
+            free(buf);
+
+            if (okay) {
+                break;
+            }
+        }
+#elif defined(HAVE_STDIO_H)
         /* this is a little hacky. */
         for ( ; ; ) {
             char buf[32];
@@ -245,8 +295,8 @@ SDL_PromptAssertion(const SDL_assert_data *data, void *userdata)
                 break;
             }
         }
-    }
 #endif /* HAVE_STDIO_H */
+    }
 
     /* Re-enter fullscreen mode */
     if (window) {
@@ -263,10 +313,11 @@ SDL_assert_state
 SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file,
                     int line)
 {
-    static int assertion_running = 0;
-    static SDL_SpinLock spinlock = 0;
     SDL_assert_state state = SDL_ASSERTION_IGNORE;
+    static int assertion_running = 0;
 
+#ifndef SDL_THREADS_DISABLED
+    static SDL_SpinLock spinlock = 0;
     SDL_AtomicLock(&spinlock);
     if (assertion_mutex == NULL) { /* never called SDL_Init()? */
         assertion_mutex = SDL_CreateMutex();
@@ -280,6 +331,7 @@ SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file,
     if (SDL_LockMutex(assertion_mutex) < 0) {
         return SDL_ASSERTION_IGNORE;   /* oh well, I guess. */
     }
+#endif
 
     /* doing this because Visual C is upset over assigning in the macro. */
     if (data->trigger_count == 0) {
@@ -323,7 +375,10 @@ SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file,
     }
 
     assertion_running--;
+
+#ifndef SDL_THREADS_DISABLED
     SDL_UnlockMutex(assertion_mutex);
+#endif
 
     return state;
 }
@@ -332,10 +387,12 @@ SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file,
 void SDL_AssertionsQuit(void)
 {
     SDL_GenerateAssertionReport();
+#ifndef SDL_THREADS_DISABLED
     if (assertion_mutex != NULL) {
         SDL_DestroyMutex(assertion_mutex);
         assertion_mutex = NULL;
     }
+#endif
 }
 
 void SDL_SetAssertionHandler(SDL_AssertionHandler handler, void *userdata)
diff --git a/src/SDL_assert_c.h b/src/SDL_assert_c.h
index bc3b631..4d87ea6 100644
--- a/src/SDL_assert_c.h
+++ b/src/SDL_assert_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/SDL_dataqueue.c b/src/SDL_dataqueue.c
new file mode 100644
index 0000000..db1adaa
--- /dev/null
+++ b/src/SDL_dataqueue.c
@@ -0,0 +1,314 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "./SDL_internal.h"
+#include "SDL.h"
+#include "./SDL_dataqueue.h"
+#include "SDL_assert.h"
+
+typedef struct SDL_DataQueuePacket
+{
+    size_t datalen;  /* bytes currently in use in this packet. */
+    size_t startpos;  /* bytes currently consumed in this packet. */
+    struct SDL_DataQueuePacket *next;  /* next item in linked list. */
+    Uint8 data[SDL_VARIABLE_LENGTH_ARRAY];  /* packet data */
+} SDL_DataQueuePacket;
+
+struct SDL_DataQueue
+{
+    SDL_DataQueuePacket *head; /* device fed from here. */
+    SDL_DataQueuePacket *tail; /* queue fills to here. */
+    SDL_DataQueuePacket *pool; /* these are unused packets. */
+    size_t packet_size;   /* size of new packets */
+    size_t queued_bytes;  /* number of bytes of data in the queue. */
+};
+
+static void
+SDL_FreeDataQueueList(SDL_DataQueuePacket *packet)
+{
+    while (packet) {
+        SDL_DataQueuePacket *next = packet->next;
+        SDL_free(packet);
+        packet = next;
+    }
+}
+
+
+/* this all expects that you managed thread safety elsewhere. */
+
+SDL_DataQueue *
+SDL_NewDataQueue(const size_t _packetlen, const size_t initialslack)
+{
+    SDL_DataQueue *queue = (SDL_DataQueue *) SDL_malloc(sizeof (SDL_DataQueue));
+
+    if (!queue) {
+        SDL_OutOfMemory();
+        return NULL;
+    } else {
+        const size_t packetlen = _packetlen ? _packetlen : 1024;
+        const size_t wantpackets = (initialslack + (packetlen - 1)) / packetlen;
+        size_t i;
+
+        SDL_zerop(queue);
+        queue->packet_size = packetlen;
+
+        for (i = 0; i < wantpackets; i++) {
+            SDL_DataQueuePacket *packet = (SDL_DataQueuePacket *) SDL_malloc(sizeof (SDL_DataQueuePacket) + packetlen);
+            if (packet) { /* don't care if this fails, we'll deal later. */
+                packet->datalen = 0;
+                packet->startpos = 0;
+                packet->next = queue->pool;
+                queue->pool = packet;
+            }
+        }
+    }
+
+    return queue;
+}
+
+void
+SDL_FreeDataQueue(SDL_DataQueue *queue)
+{
+    if (queue) {
+        SDL_FreeDataQueueList(queue->head);
+        SDL_FreeDataQueueList(queue->pool);
+        SDL_free(queue);
+    }
+}
+
+void
+SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack)
+{
+    const size_t packet_size = queue ? queue->packet_size : 1;
+    const size_t slackpackets = (slack + (packet_size-1)) / packet_size;
+    SDL_DataQueuePacket *packet;
+    SDL_DataQueuePacket *prev = NULL;
+    size_t i;
+
+    if (!queue) {
+        return;
+    }
+
+    packet = queue->head;
+
+    /* merge the available pool and the current queue into one list. */
+    if (packet) {
+        queue->tail->next = queue->pool;
+    } else {
+        packet = queue->pool;
+    }
+
+    /* Remove the queued packets from the device. */
+    queue->tail = NULL;
+    queue->head = NULL;
+    queue->queued_bytes = 0;
+    queue->pool = packet;
+
+    /* Optionally keep some slack in the pool to reduce malloc pressure. */
+    for (i = 0; packet && (i < slackpackets); i++) {
+        prev = packet;
+        packet = packet->next;
+    }
+
+    if (prev) {
+        prev->next = NULL;
+    } else {
+        queue->pool = NULL;
+    }
+
+    SDL_FreeDataQueueList(packet);  /* free extra packets */
+}
+
+static SDL_DataQueuePacket *
+AllocateDataQueuePacket(SDL_DataQueue *queue)
+{
+    SDL_DataQueuePacket *packet;
+
+    SDL_assert(queue != NULL);
+
+    packet = queue->pool;
+    if (packet != NULL) {
+        /* we have one available in the pool. */
+        queue->pool = packet->next;
+    } else {
+        /* Have to allocate a new one! */
+        packet = (SDL_DataQueuePacket *) SDL_malloc(sizeof (SDL_DataQueuePacket) + queue->packet_size);
+        if (packet == NULL) {
+            return NULL;
+        }
+    }
+
+    packet->datalen = 0;
+    packet->startpos = 0;
+    packet->next = NULL;
+                
+    SDL_assert((queue->head != NULL) == (queue->queued_bytes != 0));
+    if (queue->tail == NULL) {
+        queue->head = packet;
+    } else {
+        queue->tail->next = packet;
+    }
+    queue->tail = packet;
+    return packet;
+}
+
+
+int
+SDL_WriteToDataQueue(SDL_DataQueue *queue, const void *_data, const size_t _len)
+{
+    size_t len = _len;
+    const Uint8 *data = (const Uint8 *) _data;
+    const size_t packet_size = queue ? queue->packet_size : 0;
+    SDL_DataQueuePacket *orighead;
+    SDL_DataQueuePacket *origtail;
+    size_t origlen;
+    size_t datalen;
+
+    if (!queue) {
+        return SDL_InvalidParamError("queue");
+    }
+
+    orighead = queue->head;
+    origtail = queue->tail;
+    origlen = origtail ? origtail->datalen : 0;
+
+    while (len > 0) {
+        SDL_DataQueuePacket *packet = queue->tail;
+        SDL_assert(!packet || (packet->datalen <= packet_size));
+        if (!packet || (packet->datalen >= packet_size)) {
+            /* tail packet missing or completely full; we need a new packet. */
+            packet = AllocateDataQueuePacket(queue);
+            if (!packet) {
+                /* uhoh, reset so we've queued nothing new, free what we can. */
+                if (!origtail) {
+                    packet = queue->head;  /* whole queue. */
+                } else {
+                    packet = origtail->next;  /* what we added to existing queue. */
+                    origtail->next = NULL;
+                    origtail->datalen = origlen;
+                }
+                queue->head = orighead;
+                queue->tail = origtail;
+                queue->pool = NULL;
+
+                SDL_FreeDataQueueList(packet);  /* give back what we can. */
+                return SDL_OutOfMemory();
+            }
+        }
+
+        datalen = SDL_min(len, packet_size - packet->datalen);
+        SDL_memcpy(packet->data + packet->datalen, data, datalen);
+        data += datalen;
+        len -= datalen;
+        packet->datalen += datalen;
+        queue->queued_bytes += datalen;
+    }
+
+    return 0;
+}
+
+size_t
+SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len)
+{
+    size_t len = _len;
+    Uint8 *buf = (Uint8 *) _buf;
+    Uint8 *ptr = buf;
+    SDL_DataQueuePacket *packet;
+
+    if (!queue) {
+        return 0;
+    }
+
+    while ((len > 0) && ((packet = queue->head) != NULL)) {
+        const size_t avail = packet->datalen - packet->startpos;
+        const size_t cpy = SDL_min(len, avail);
+        SDL_assert(queue->queued_bytes >= avail);
+
+        SDL_memcpy(ptr, packet->data + packet->startpos, cpy);
+        packet->startpos += cpy;
+        ptr += cpy;
+        queue->queued_bytes -= cpy;
+        len -= cpy;
+
+        if (packet->startpos == packet->datalen) {  /* packet is done, put it in the pool. */
+            queue->head = packet->next;
+            SDL_assert((packet->next != NULL) || (packet == queue->tail));
+            packet->next = queue->pool;
+            queue->pool = packet;
+        }
+    }
+
+    SDL_assert((queue->head != NULL) == (queue->queued_bytes != 0));
+
+    if (queue->head == NULL) {
+        queue->tail = NULL;  /* in case we drained the queue entirely. */
+    }
+
+    return (size_t) (ptr - buf);
+}
+
+size_t
+SDL_CountDataQueue(SDL_DataQueue *queue)
+{
+    return queue ? queue->queued_bytes : 0;
+}
+
+void *
+SDL_ReserveSpaceInDataQueue(SDL_DataQueue *queue, const size_t len)
+{
+    SDL_DataQueuePacket *packet;
+
+    if (!queue) {
+        SDL_InvalidParamError("queue");
+        return NULL;
+    } else if (len == 0) {
+        SDL_InvalidParamError("len");
+        return NULL;
+    } else if (len > queue->packet_size) {
+        SDL_SetError("len is larger than packet size");
+        return NULL;
+    }
+
+    packet = queue->head;
+    if (packet) {
+        const size_t avail = queue->packet_size - packet->datalen;
+        if (len <= avail) {  /* we can use the space at end of this packet. */
+            void *retval = packet->data + packet->datalen;
+            packet->datalen += len;
+            queue->queued_bytes += len;
+            return retval;
+        }
+    }
+
+    /* Need a fresh packet. */
+    packet = AllocateDataQueuePacket(queue);
+    if (!packet) {
+        SDL_OutOfMemory();
+        return NULL;
+    }
+
+    packet->datalen = len;
+    queue->queued_bytes += len;
+    return packet->data;
+}
+
+/* vi: set ts=4 sw=4 expandtab: */
+
diff --git a/src/SDL_dataqueue.h b/src/SDL_dataqueue.h
new file mode 100644
index 0000000..a5e3e1c
--- /dev/null
+++ b/src/SDL_dataqueue.h
@@ -0,0 +1,54 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#ifndef SDL_dataqueue_h_
+#define SDL_dataqueue_h_
+
+/* this is not (currently) a public API. But maybe it should be! */
+
+struct SDL_DataQueue;
+typedef struct SDL_DataQueue SDL_DataQueue;
+
+SDL_DataQueue *SDL_NewDataQueue(const size_t packetlen, const size_t initialslack);
+void SDL_FreeDataQueue(SDL_DataQueue *queue);
+void SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack);
+int SDL_WriteToDataQueue(SDL_DataQueue *queue, const void *data, const size_t len);
+size_t SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *buf, const size_t len);
+size_t SDL_CountDataQueue(SDL_DataQueue *queue);
+
+/* this sets a section of the data queue aside (possibly allocating memory for it)
+   as if it's been written to, but returns a pointer to that space. You may write
+   to this space until a read would consume it. Writes (and other calls to this
+   function) will safely append their data after this reserved space and can
+   be in flight at the same time. There is no thread safety.
+   If there isn't an existing block of memory that can contain the reserved
+   space, one will be allocated for it. You can not (currently) allocate
+   a space larger than the packetlen requested in SDL_NewDataQueue.
+   Returned buffer is uninitialized.
+   This lets you avoid an extra copy in some cases, but it's safer to use
+   SDL_WriteToDataQueue() unless you know what you're doing.
+   Returns pointer to buffer of at least (len) bytes, NULL on error.
+*/
+void *SDL_ReserveSpaceInDataQueue(SDL_DataQueue *queue, const size_t len);
+
+#endif /* SDL_dataqueue_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
+
diff --git a/src/SDL_error.c b/src/SDL_error.c
index 804a1eb..498679a 100644
--- a/src/SDL_error.c
+++ b/src/SDL_error.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -49,6 +49,8 @@ SDL_LookupString(const char *key)
 
 /* Public functions */
 
+static char *SDL_GetErrorMsg(char *errstr, int maxlen);
+
 int
 SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
 {
@@ -110,16 +112,83 @@ SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
     }
     va_end(ap);
 
-    /* If we are in debug mode, print out an error message */
-    SDL_LogDebug(SDL_LOG_CATEGORY_ERROR, "%s", SDL_GetError());
-
+    if (SDL_LogGetPriority(SDL_LOG_CATEGORY_ERROR) <= SDL_LOG_PRIORITY_DEBUG) {
+        /* If we are in debug mode, print out an error message
+         * Avoid stomping on the static buffer in GetError, just
+         * in case this is called while processing a ShowMessageBox to
+         * show an error already in that static buffer.
+         */
+        char errmsg[SDL_ERRBUFIZE];
+        SDL_GetErrorMsg(errmsg, sizeof(errmsg));
+        SDL_LogDebug(SDL_LOG_CATEGORY_ERROR, "%s", errmsg);
+    }
     return -1;
 }
 
-#ifdef __GNUC__
-#pragma GCC diagnostic push
+/* Available for backwards compatibility */
+const char *
+SDL_GetError(void)
+{
+    static char errmsg[SDL_ERRBUFIZE];
+
+    return SDL_GetErrorMsg(errmsg, SDL_ERRBUFIZE);
+}
+
+void
+SDL_ClearError(void)
+{
+    SDL_error *error;
+
+    error = SDL_GetErrBuf();
+    error->error = 0;
+}
+
+/* Very common errors go here */
+int
+SDL_Error(SDL_errorcode code)
+{
+    switch (code) {
+    case SDL_ENOMEM:
+        return SDL_SetError("Out of memory");
+    case SDL_EFREAD:
+        return SDL_SetError("Error reading from datastream");
+    case SDL_EFWRITE:
+        return SDL_SetError("Error writing to datastream");
+    case SDL_EFSEEK:
+        return SDL_SetError("Error seeking in datastream");
+    case SDL_UNSUPPORTED:
+        return SDL_SetError("That operation is not supported");
+    default:
+        return SDL_SetError("Unknown SDL error");
+    }
+}
+
+#ifdef TEST_ERROR
+int
+main(int argc, char *argv[])
+{
+    char buffer[BUFSIZ + 1];
+
+    SDL_SetError("Hi there!");
+    printf("Error 1: %s\n", SDL_GetError());
+    SDL_ClearError();
+    SDL_memset(buffer, '1', BUFSIZ);
+    buffer[BUFSIZ] = 0;
+    SDL_SetError("This is the error: %s (%f)", buffer, 1.0);
+    printf("Error 2: %s\n", SDL_GetError());
+    exit(0);
+}
+#endif
+
+
+/* keep this at the end of the file so it works with GCC builds that don't
+   support "#pragma GCC diagnostic push" ... we'll just leave the warning
+   disabled after this. */
+/* this pragma arrived in GCC 4.2 and causes a warning on older GCCs! Sigh. */
+#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 2))))
 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
 #endif
+
 /* This function has a bit more overhead than most error functions
    so that it supports internationalization and thread-safe errors.
 */
@@ -220,63 +289,5 @@ SDL_GetErrorMsg(char *errstr, int maxlen)
     }
     return (errstr);
 }
-#ifdef __GNUC__
-#pragma GCC diagnostic pop
-#endif
-
-/* Available for backwards compatibility */
-const char *
-SDL_GetError(void)
-{
-    static char errmsg[SDL_ERRBUFIZE];
-
-    return SDL_GetErrorMsg(errmsg, SDL_ERRBUFIZE);
-}
-
-void
-SDL_ClearError(void)
-{
-    SDL_error *error;
-
-    error = SDL_GetErrBuf();
-    error->error = 0;
-}
-
-/* Very common errors go here */
-int
-SDL_Error(SDL_errorcode code)
-{
-    switch (code) {
-    case SDL_ENOMEM:
-        return SDL_SetError("Out of memory");
-    case SDL_EFREAD:
-        return SDL_SetError("Error reading from datastream");
-    case SDL_EFWRITE:
-        return SDL_SetError("Error writing to datastream");
-    case SDL_EFSEEK:
-        return SDL_SetError("Error seeking in datastream");
-    case SDL_UNSUPPORTED:
-        return SDL_SetError("That operation is not supported");
-    default:
-        return SDL_SetError("Unknown SDL error");
-    }
-}
-
-#ifdef TEST_ERROR
-int
-main(int argc, char *argv[])
-{
-    char buffer[BUFSIZ + 1];
-
-    SDL_SetError("Hi there!");
-    printf("Error 1: %s\n", SDL_GetError());
-    SDL_ClearError();
-    SDL_memset(buffer, '1', BUFSIZ);
-    buffer[BUFSIZ] = 0;
-    SDL_SetError("This is the error: %s (%f)", buffer, 1.0);
-    printf("Error 2: %s\n", SDL_GetError());
-    exit(0);
-}
-#endif
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/SDL_error_c.h b/src/SDL_error_c.h
index 76ccf2b..ab65109 100644
--- a/src/SDL_error_c.h
+++ b/src/SDL_error_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,8 +24,8 @@
    error messages
 */
 
-#ifndef _SDL_error_c_h
-#define _SDL_error_c_h
+#ifndef SDL_error_c_h_
+#define SDL_error_c_h_
 
 #define ERR_MAX_STRLEN  128
 #define ERR_MAX_ARGS    5
@@ -59,6 +59,6 @@ typedef struct SDL_error
 /* Defined in SDL_thread.c */
 extern SDL_error *SDL_GetErrBuf(void);
 
-#endif /* _SDL_error_c_h */
+#endif /* SDL_error_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/SDL_hints.c b/src/SDL_hints.c
index 390d94f..6aa2996 100644
--- a/src/SDL_hints.c
+++ b/src/SDL_hints.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -122,7 +122,7 @@ SDL_bool
 SDL_GetHintBoolean(const char *name, SDL_bool default_value)
 {
     const char *hint = SDL_GetHint(name);
-    if (!hint) {
+    if (!hint || !*hint) {
         return default_value;
     }
     if (*hint == '0' || SDL_strcasecmp(hint, "false") == 0) {
diff --git a/src/SDL_internal.h b/src/SDL_internal.h
index 7e92850..654895c 100644
--- a/src/SDL_internal.h
+++ b/src/SDL_internal.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,8 +18,22 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#ifndef _SDL_internal_h
-#define _SDL_internal_h
+#ifndef SDL_internal_h_
+#define SDL_internal_h_
+
+/* Many of SDL's features require _GNU_SOURCE on various platforms */
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+/* This is for a variable-length array at the end of a struct:
+    struct x { int y; char z[SDL_VARIABLE_LENGTH_ARRAY]; };
+   Use this because GCC 2 needs different magic than other compilers. */
+#if (defined(__GNUC__) && (__GNUC__ <= 2)) || defined(__CC_ARM)
+#define SDL_VARIABLE_LENGTH_ARRAY 1
+#else
+#define SDL_VARIABLE_LENGTH_ARRAY
+#endif
 
 #include "dynapi/SDL_dynapi.h"
 
@@ -33,6 +47,6 @@
 
 #include "SDL_config.h"
 
-#endif
+#endif /* SDL_internal_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/SDL_log.c b/src/SDL_log.c
index 760cb13..9897862 100644
--- a/src/SDL_log.c
+++ b/src/SDL_log.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -50,9 +50,7 @@ typedef struct SDL_LogLevel
 } SDL_LogLevel;
 
 /* The default log output function */
-static void SDL_LogOutput(void *userdata,
-                          int category, SDL_LogPriority priority,
-                          const char *message);
+static void SDLCALL SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority, const char *message);
 
 static SDL_LogLevel *SDL_loglevels;
 static SDL_LogPriority SDL_default_priority = DEFAULT_PRIORITY;
@@ -304,7 +302,7 @@ SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list
     SDL_stack_free(message);
 }
 
-#if defined(__WIN32__)
+#if defined(__WIN32__) && !defined(HAVE_STDIO_H) && !defined(__WINRT__)
 /* Flag tracking the attachment of the console: 0=unattached, 1=attached, -1=error */
 static int consoleAttached = 0;
 
@@ -312,7 +310,7 @@ static int consoleAttached = 0;
 static HANDLE stderrHandle = NULL;
 #endif
 
-static void
+static void SDLCALL
 SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
               const char *message)
 {
@@ -335,7 +333,8 @@ SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
             if (!attachResult) {
                     attachError = GetLastError();
                     if (attachError == ERROR_INVALID_HANDLE) {
-                        OutputDebugString(TEXT("Parent process has no console\r\n"));
+                        /* This is expected when running from Visual Studio */
+                        /*OutputDebugString(TEXT("Parent process has no console\r\n"));*/
                         consoleAttached = -1;
                     } else if (attachError == ERROR_GEN_FAILURE) {
                          OutputDebugString(TEXT("Could not attach to console of parent process\r\n"));
diff --git a/src/atomic/SDL_atomic.c b/src/atomic/SDL_atomic.c
index db86d6e..67fcb99 100644
--- a/src/atomic/SDL_atomic.c
+++ b/src/atomic/SDL_atomic.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -35,6 +35,48 @@
 #include <atomic.h>
 #endif
 
+/* The __atomic_load_n() intrinsic showed up in different times for different compilers. */
+#if defined(HAVE_GCC_ATOMICS)
+# if defined(__clang__)
+#   if __has_builtin(__atomic_load_n)
+      /* !!! FIXME: this advertises as available in the NDK but uses an external symbol we don't have.
+         It might be in a later NDK or we might need an extra library? --ryan. */
+#     if !defined(__ANDROID__)
+#       define HAVE_ATOMIC_LOAD_N 1
+#     endif
+#   endif
+# elif defined(__GNUC__)
+#   if (__GNUC__ >= 5)
+#     define HAVE_ATOMIC_LOAD_N 1
+#   endif
+# endif
+#endif
+
+#if defined(__WATCOMC__) && defined(__386__)
+#define HAVE_WATCOM_ATOMICS
+extern _inline int _SDL_xchg_watcom(volatile int *a, int v);
+#pragma aux _SDL_xchg_watcom = \
+  "xchg [ecx], eax" \
+  parm [ecx] [eax] \
+  value [eax] \
+  modify exact [eax];
+
+extern _inline unsigned char _SDL_cmpxchg_watcom(volatile int *a, int newval, int oldval);
+#pragma aux _SDL_cmpxchg_watcom = \
+  "lock cmpxchg [edx], ecx" \
+  "setz al" \
+  parm [edx] [ecx] [eax] \
+  value [al] \
+  modify exact [eax];
+
+extern _inline int _SDL_xadd_watcom(volatile int *a, int v);
+#pragma aux _SDL_xadd_watcom = \
+  "lock xadd [ecx], eax" \
+  parm [ecx] [eax] \
+  value [eax] \
+  modify exact [eax];
+#endif /* __WATCOMC__ && __386__ */
+
 /*
   If any of the operations are not provided then we must emulate some
   of them. That means we need a nice implementation of spin locks
@@ -58,7 +100,7 @@
   Contributed by Bob Pendleton, bob at pendleton.com
 */
 
-#if !defined(HAVE_MSC_ATOMICS) && !defined(HAVE_GCC_ATOMICS) && !defined(__MACOSX__) && !defined(__SOLARIS__)
+#if !defined(HAVE_MSC_ATOMICS) && !defined(HAVE_GCC_ATOMICS) && !defined(__MACOSX__) && !defined(__SOLARIS__) && !defined(HAVE_WATCOM_ATOMICS)
 #define EMULATE_CAS 1
 #endif
 
@@ -88,10 +130,12 @@ SDL_AtomicCAS(SDL_atomic_t *a, int oldval, int newval)
 {
 #ifdef HAVE_MSC_ATOMICS
     return (_InterlockedCompareExchange((long*)&a->value, (long)newval, (long)oldval) == (long)oldval);
-#elif defined(__MACOSX__)  /* !!! FIXME: should we favor gcc atomics? */
-    return (SDL_bool) OSAtomicCompareAndSwap32Barrier(oldval, newval, &a->value);
+#elif defined(HAVE_WATCOM_ATOMICS)
+    return (SDL_bool) _SDL_cmpxchg_watcom(&a->value, newval, oldval);
 #elif defined(HAVE_GCC_ATOMICS)
     return (SDL_bool) __sync_bool_compare_and_swap(&a->value, oldval, newval);
+#elif defined(__MACOSX__)  /* this is deprecated in 10.12 sdk; favor gcc atomics. */
+    return (SDL_bool) OSAtomicCompareAndSwap32Barrier(oldval, newval, &a->value);
 #elif defined(__SOLARIS__) && defined(_LP64)
     return (SDL_bool) ((int) atomic_cas_64((volatile uint64_t*)&a->value, (uint64_t)oldval, (uint64_t)newval) == oldval);
 #elif defined(__SOLARIS__) && !defined(_LP64)
@@ -119,12 +163,14 @@ SDL_AtomicCASPtr(void **a, void *oldval, void *newval)
     return (_InterlockedCompareExchange((long*)a, (long)newval, (long)oldval) == (long)oldval);
 #elif defined(HAVE_MSC_ATOMICS) && (!_M_IX86)
     return (_InterlockedCompareExchangePointer(a, newval, oldval) == oldval);
-#elif defined(__MACOSX__) && defined(__LP64__)   /* !!! FIXME: should we favor gcc atomics? */
-    return (SDL_bool) OSAtomicCompareAndSwap64Barrier((int64_t)oldval, (int64_t)newval, (int64_t*) a);
-#elif defined(__MACOSX__) && !defined(__LP64__)  /* !!! FIXME: should we favor gcc atomics? */
-    return (SDL_bool) OSAtomicCompareAndSwap32Barrier((int32_t)oldval, (int32_t)newval, (int32_t*) a);
+#elif defined(HAVE_WATCOM_ATOMICS)
+    return (SDL_bool) _SDL_cmpxchg_watcom((int *)a, (long)newval, (long)oldval);
 #elif defined(HAVE_GCC_ATOMICS)
     return __sync_bool_compare_and_swap(a, oldval, newval);
+#elif defined(__MACOSX__) && defined(__LP64__)  /* this is deprecated in 10.12 sdk; favor gcc atomics. */
+    return (SDL_bool) OSAtomicCompareAndSwap64Barrier((int64_t)oldval, (int64_t)newval, (int64_t*) a);
+#elif defined(__MACOSX__) && !defined(__LP64__)  /* this is deprecated in 10.12 sdk; favor gcc atomics. */
+    return (SDL_bool) OSAtomicCompareAndSwap32Barrier((int32_t)oldval, (int32_t)newval, (int32_t*) a);
 #elif defined(__SOLARIS__)
     return (SDL_bool) (atomic_cas_ptr(a, oldval, newval) == oldval);
 #elif EMULATE_CAS
@@ -148,6 +194,8 @@ SDL_AtomicSet(SDL_atomic_t *a, int v)
 {
 #ifdef HAVE_MSC_ATOMICS
     return _InterlockedExchange((long*)&a->value, v);
+#elif defined(HAVE_WATCOM_ATOMICS)
+    return _SDL_xchg_watcom(&a->value, v);
 #elif defined(HAVE_GCC_ATOMICS)
     return __sync_lock_test_and_set(&a->value, v);
 #elif defined(__SOLARIS__) && defined(_LP64)
@@ -170,6 +218,8 @@ SDL_AtomicSetPtr(void **a, void *v)
     return (void *) _InterlockedExchange((long *)a, (long) v);
 #elif defined(HAVE_MSC_ATOMICS) && (!_M_IX86)
     return _InterlockedExchangePointer(a, v);
+#elif defined(HAVE_WATCOM_ATOMICS)
+    return (void *) _SDL_xchg_watcom((int *)a, (long)v);
 #elif defined(HAVE_GCC_ATOMICS)
     return __sync_lock_test_and_set(a, v);
 #elif defined(__SOLARIS__)
@@ -188,6 +238,8 @@ SDL_AtomicAdd(SDL_atomic_t *a, int v)
 {
 #ifdef HAVE_MSC_ATOMICS
     return _InterlockedExchangeAdd((long*)&a->value, v);
+#elif defined(HAVE_WATCOM_ATOMICS)
+    return _SDL_xadd_watcom(&a->value, v);
 #elif defined(HAVE_GCC_ATOMICS)
     return __sync_fetch_and_add(&a->value, v);
 #elif defined(__SOLARIS__)
@@ -211,36 +263,41 @@ SDL_AtomicAdd(SDL_atomic_t *a, int v)
 int
 SDL_AtomicGet(SDL_atomic_t *a)
 {
+#ifdef HAVE_ATOMIC_LOAD_N
+    return __atomic_load_n(&a->value, __ATOMIC_SEQ_CST);
+#else
     int value;
     do {
         value = a->value;
     } while (!SDL_AtomicCAS(a, value, value));
     return value;
+#endif
 }
 
 void *
 SDL_AtomicGetPtr(void **a)
 {
+#ifdef HAVE_ATOMIC_LOAD_N
+    return __atomic_load_n(a, __ATOMIC_SEQ_CST);
+#else
     void *value;
     do {
         value = *a;
     } while (!SDL_AtomicCASPtr(a, value, value));
     return value;
+#endif
 }
 
-#ifdef __thumb__
-#if defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__)
-__asm__(
-"   .align 2\n"
-"   .globl _SDL_MemoryBarrierRelease\n"
-"   .globl _SDL_MemoryBarrierAcquire\n"
-"_SDL_MemoryBarrierRelease:\n"
-"_SDL_MemoryBarrierAcquire:\n"
-"   mov r0, #0\n"
-"   mcr p15, 0, r0, c7, c10, 5\n"
-"   bx lr\n"
-);
-#endif
-#endif
+void
+SDL_MemoryBarrierReleaseFunction(void)
+{
+    SDL_MemoryBarrierRelease();
+}
+
+void
+SDL_MemoryBarrierAcquireFunction(void)
+{
+    SDL_MemoryBarrierAcquire();
+}
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/atomic/SDL_spinlock.c b/src/atomic/SDL_spinlock.c
index f582afb..aa68051 100644
--- a/src/atomic/SDL_spinlock.c
+++ b/src/atomic/SDL_spinlock.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -32,6 +32,16 @@
 #include <atomic.h>
 #endif
 
+#if defined(__WATCOMC__) && defined(__386__)
+SDL_COMPILE_TIME_ASSERT(locksize, 4==sizeof(SDL_SpinLock));
+extern _inline int _SDL_xchg_watcom(volatile int *a, int v);
+#pragma aux _SDL_xchg_watcom = \
+  "xchg [ecx], eax" \
+  parm [ecx] [eax] \
+  value [eax] \
+  modify exact [eax];
+#endif /* __WATCOMC__ && __386__ */
+
 /* This function is where all the magic happens... */
 SDL_bool
 SDL_AtomicTryLock(SDL_SpinLock *lock)
@@ -58,6 +68,9 @@ SDL_AtomicTryLock(SDL_SpinLock *lock)
     SDL_COMPILE_TIME_ASSERT(locksize, sizeof(*lock) == sizeof(long));
     return (InterlockedExchange((long*)lock, 1) == 0);
 
+#elif defined(__WATCOMC__) && defined(__386__)
+    return _SDL_xchg_watcom(lock, 1) == 0;
+
 #elif HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET
     return (__sync_lock_test_and_set(lock, 1) == 0);
 
@@ -119,6 +132,10 @@ SDL_AtomicUnlock(SDL_SpinLock *lock)
     _ReadWriteBarrier();
     *lock = 0;
 
+#elif defined(__WATCOMC__) && defined(__386__)
+    SDL_CompilerBarrier ();
+    *lock = 0;
+
 #elif HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET
     __sync_lock_release(lock);
 
diff --git a/src/audio/SDL_audio.c b/src/audio/SDL_audio.c
index 460852d..19cbf72 100644
--- a/src/audio/SDL_audio.c
+++ b/src/audio/SDL_audio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,36 +33,6 @@
 static SDL_AudioDriver current_audio;
 static SDL_AudioDevice *open_devices[16];
 
-/*
- * Not all of these will be compiled and linked in, but it's convenient
- *  to have a complete list here and saves yet-another block of #ifdefs...
- *  Please see bootstrap[], below, for the actual #ifdef mess.
- */
-extern AudioBootStrap PULSEAUDIO_bootstrap;
-extern AudioBootStrap ALSA_bootstrap;
-extern AudioBootStrap SNDIO_bootstrap;
-extern AudioBootStrap BSD_AUDIO_bootstrap;
-extern AudioBootStrap DSP_bootstrap;
-extern AudioBootStrap QSAAUDIO_bootstrap;
-extern AudioBootStrap SUNAUDIO_bootstrap;
-extern AudioBootStrap ARTS_bootstrap;
-extern AudioBootStrap ESD_bootstrap;
-extern AudioBootStrap NACLAUDIO_bootstrap;
-extern AudioBootStrap NAS_bootstrap;
-extern AudioBootStrap XAUDIO2_bootstrap;
-extern AudioBootStrap DSOUND_bootstrap;
-extern AudioBootStrap WINMM_bootstrap;
-extern AudioBootStrap PAUDIO_bootstrap;
-extern AudioBootStrap HAIKUAUDIO_bootstrap;
-extern AudioBootStrap COREAUDIO_bootstrap;
-extern AudioBootStrap DISKAUDIO_bootstrap;
-extern AudioBootStrap DUMMYAUDIO_bootstrap;
-extern AudioBootStrap FUSIONSOUND_bootstrap;
-extern AudioBootStrap ANDROIDAUDIO_bootstrap;
-extern AudioBootStrap PSPAUDIO_bootstrap;
-extern AudioBootStrap SNDIO_bootstrap;
-extern AudioBootStrap EMSCRIPTENAUDIO_bootstrap;
-
 /* Available audio drivers */
 static const AudioBootStrap *const bootstrap[] = {
 #if SDL_AUDIO_DRIVER_PULSEAUDIO
@@ -74,8 +44,8 @@ static const AudioBootStrap *const bootstrap[] = {
 #if SDL_AUDIO_DRIVER_SNDIO
     &SNDIO_bootstrap,
 #endif
-#if SDL_AUDIO_DRIVER_BSD
-    &BSD_AUDIO_bootstrap,
+#if SDL_AUDIO_DRIVER_NETBSD
+    &NETBSDAUDIO_bootstrap,
 #endif
 #if SDL_AUDIO_DRIVER_OSS
     &DSP_bootstrap,
@@ -98,6 +68,9 @@ static const AudioBootStrap *const bootstrap[] = {
 #if SDL_AUDIO_DRIVER_NAS
     &NAS_bootstrap,
 #endif
+#if SDL_AUDIO_DRIVER_WASAPI
+    &WASAPI_bootstrap,
+#endif
 #if SDL_AUDIO_DRIVER_XAUDIO2
     &XAUDIO2_bootstrap,
 #endif
@@ -116,12 +89,6 @@ static const AudioBootStrap *const bootstrap[] = {
 #if SDL_AUDIO_DRIVER_COREAUDIO
     &COREAUDIO_bootstrap,
 #endif
-#if SDL_AUDIO_DRIVER_DISK
-    &DISKAUDIO_bootstrap,
-#endif
-#if SDL_AUDIO_DRIVER_DUMMY
-    &DUMMYAUDIO_bootstrap,
-#endif
 #if SDL_AUDIO_DRIVER_FUSIONSOUND
     &FUSIONSOUND_bootstrap,
 #endif
@@ -134,9 +101,101 @@ static const AudioBootStrap *const bootstrap[] = {
 #if SDL_AUDIO_DRIVER_EMSCRIPTEN
     &EMSCRIPTENAUDIO_bootstrap,
 #endif
+#if SDL_AUDIO_DRIVER_JACK
+    &JACK_bootstrap,
+#endif
+#if SDL_AUDIO_DRIVER_DISK
+    &DISKAUDIO_bootstrap,
+#endif
+#if SDL_AUDIO_DRIVER_DUMMY
+    &DUMMYAUDIO_bootstrap,
+#endif
     NULL
 };
 
+
+#ifdef HAVE_LIBSAMPLERATE_H
+#ifdef SDL_LIBSAMPLERATE_DYNAMIC
+static void *SRC_lib = NULL;
+#endif
+SDL_bool SRC_available = SDL_FALSE;
+int SRC_converter = 0;
+SRC_STATE* (*SRC_src_new)(int converter_type, int channels, int *error) = NULL;
+int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data) = NULL;
+int (*SRC_src_reset)(SRC_STATE *state) = NULL;
+SRC_STATE* (*SRC_src_delete)(SRC_STATE *state) = NULL;
+const char* (*SRC_src_strerror)(int error) = NULL;
+
+static SDL_bool
+LoadLibSampleRate(void)
+{
+    const char *hint = SDL_GetHint(SDL_HINT_AUDIO_RESAMPLING_MODE);
+
+    SRC_available = SDL_FALSE;
+    SRC_converter = 0;
+
+    if (!hint || *hint == '0' || SDL_strcasecmp(hint, "default") == 0) {
+        return SDL_FALSE;  /* don't load anything. */
+    } else if (*hint == '1' || SDL_strcasecmp(hint, "fast") == 0) {
+        SRC_converter = SRC_SINC_FASTEST;
+    } else if (*hint == '2' || SDL_strcasecmp(hint, "medium") == 0) {
+        SRC_converter = SRC_SINC_MEDIUM_QUALITY;
+    } else if (*hint == '3' || SDL_strcasecmp(hint, "best") == 0) {
+        SRC_converter = SRC_SINC_BEST_QUALITY;
+    } else {
+        return SDL_FALSE;  /* treat it like "default", don't load anything. */
+    }
+
+#ifdef SDL_LIBSAMPLERATE_DYNAMIC
+    SDL_assert(SRC_lib == NULL);
+    SRC_lib = SDL_LoadObject(SDL_LIBSAMPLERATE_DYNAMIC);
+    if (!SRC_lib) {
+        SDL_ClearError();
+        return SDL_FALSE;
+    }
+
+    SRC_src_new = (SRC_STATE* (*)(int converter_type, int channels, int *error))SDL_LoadFunction(SRC_lib, "src_new");
+    SRC_src_process = (int (*)(SRC_STATE *state, SRC_DATA *data))SDL_LoadFunction(SRC_lib, "src_process");
+    SRC_src_reset = (int(*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_reset");
+    SRC_src_delete = (SRC_STATE* (*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_delete");
+    SRC_src_strerror = (const char* (*)(int error))SDL_LoadFunction(SRC_lib, "src_strerror");
+
+    if (!SRC_src_new || !SRC_src_process || !SRC_src_reset || !SRC_src_delete || !SRC_src_strerror) {
+        SDL_UnloadObject(SRC_lib);
+        SRC_lib = NULL;
+        return SDL_FALSE;
+    }
+#else
+    SRC_src_new = src_new;
+    SRC_src_process = src_process;
+    SRC_src_reset = src_reset;
+    SRC_src_delete = src_delete;
+    SRC_src_strerror = src_strerror;
+#endif
+
+    SRC_available = SDL_TRUE;
+    return SDL_TRUE;
+}
+
+static void
+UnloadLibSampleRate(void)
+{
+#ifdef SDL_LIBSAMPLERATE_DYNAMIC
+    if (SRC_lib != NULL) {
+        SDL_UnloadObject(SRC_lib);
+    }
+    SRC_lib = NULL;
+#endif
+
+    SRC_available = SDL_FALSE;
+    SRC_src_new = NULL;
+    SRC_src_process = NULL;
+    SRC_src_reset = NULL;
+    SRC_src_delete = NULL;
+    SRC_src_strerror = NULL;
+}
+#endif
+
 static SDL_AudioDevice *
 get_audio_device(SDL_AudioDeviceID id)
 {
@@ -170,6 +229,11 @@ SDL_AudioThreadInit_Default(_THIS)
 }
 
 static void
+SDL_AudioThreadDeinit_Default(_THIS)
+{                               /* no-op. */
+}
+
+static void
 SDL_AudioWaitDevice_Default(_THIS)
 {                               /* no-op. */
 }
@@ -288,6 +352,7 @@ finish_audio_entry_points_init(void)
     FILL_STUB(DetectDevices);
     FILL_STUB(OpenDevice);
     FILL_STUB(ThreadInit);
+    FILL_STUB(ThreadDeinit);
     FILL_STUB(WaitDevice);
     FILL_STUB(PlayDevice);
     FILL_STUB(GetPendingBytes);
@@ -448,136 +513,23 @@ SDL_RemoveAudioDevice(const int iscapture, void *handle)
 
 /* buffer queueing support... */
 
-/* this expects that you managed thread safety elsewhere. */
-static void
-free_audio_queue(SDL_AudioBufferQueue *packet)
-{
-    while (packet) {
-        SDL_AudioBufferQueue *next = packet->next;
-        SDL_free(packet);
-        packet = next;
-    }
-}
-
-/* NOTE: This assumes you'll hold the mixer lock before calling! */
-static int
-queue_audio_to_device(SDL_AudioDevice *device, const Uint8 *data, Uint32 len)
-{
-    SDL_AudioBufferQueue *orighead;
-    SDL_AudioBufferQueue *origtail;
-    Uint32 origlen;
-    Uint32 datalen;
-
-    orighead = device->buffer_queue_head;
-    origtail = device->buffer_queue_tail;
-    origlen = origtail ? origtail->datalen : 0;
-
-    while (len > 0) {
-        SDL_AudioBufferQueue *packet = device->buffer_queue_tail;
-        SDL_assert(!packet || (packet->datalen <= SDL_AUDIOBUFFERQUEUE_PACKETLEN));
-        if (!packet || (packet->datalen >= SDL_AUDIOBUFFERQUEUE_PACKETLEN)) {
-            /* tail packet missing or completely full; we need a new packet. */
-            packet = device->buffer_queue_pool;
-            if (packet != NULL) {
-                /* we have one available in the pool. */
-                device->buffer_queue_pool = packet->next;
-            } else {
-                /* Have to allocate a new one! */
-                packet = (SDL_AudioBufferQueue *) SDL_malloc(sizeof (SDL_AudioBufferQueue));
-                if (packet == NULL) {
-                    /* uhoh, reset so we've queued nothing new, free what we can. */
-                    if (!origtail) {
-                        packet = device->buffer_queue_head;  /* whole queue. */
-                    } else {
-                        packet = origtail->next;  /* what we added to existing queue. */
-                        origtail->next = NULL;
-                        origtail->datalen = origlen;
-                    }
-                    device->buffer_queue_head = orighead;
-                    device->buffer_queue_tail = origtail;
-                    device->buffer_queue_pool = NULL;
-
-                    free_audio_queue(packet);  /* give back what we can. */
-
-                    return SDL_OutOfMemory();
-                }
-            }
-            packet->datalen = 0;
-            packet->startpos = 0;
-            packet->next = NULL;
-
-            SDL_assert((device->buffer_queue_head != NULL) == (device->queued_bytes != 0));
-            if (device->buffer_queue_tail == NULL) {
-                device->buffer_queue_head = packet;
-            } else {
-                device->buffer_queue_tail->next = packet;
-            }
-            device->buffer_queue_tail = packet;
-        }
-
-        datalen = SDL_min(len, SDL_AUDIOBUFFERQUEUE_PACKETLEN - packet->datalen);
-        SDL_memcpy(packet->data + packet->datalen, data, datalen);
-        data += datalen;
-        len -= datalen;
-        packet->datalen += datalen;
-        device->queued_bytes += datalen;
-    }
-
-    return 0;
-}
-
-/* NOTE: This assumes you'll hold the mixer lock before calling! */
-static Uint32
-dequeue_audio_from_device(SDL_AudioDevice *device, Uint8 *stream, Uint32 len)
-{
-    SDL_AudioBufferQueue *packet;
-    Uint8 *ptr = stream;
-
-    while ((len > 0) && ((packet = device->buffer_queue_head) != NULL)) {
-        const Uint32 avail = packet->datalen - packet->startpos;
-        const Uint32 cpy = SDL_min(len, avail);
-        SDL_assert(device->queued_bytes >= avail);
-
-        SDL_memcpy(ptr, packet->data + packet->startpos, cpy);
-        packet->startpos += cpy;
-        ptr += cpy;
-        device->queued_bytes -= cpy;
-        len -= cpy;
-
-        if (packet->startpos == packet->datalen) {  /* packet is done, put it in the pool. */
-            device->buffer_queue_head = packet->next;
-            SDL_assert((packet->next != NULL) || (packet == device->buffer_queue_tail));
-            packet->next = device->buffer_queue_pool;
-            device->buffer_queue_pool = packet;
-        }
-    }
-
-    SDL_assert((device->buffer_queue_head != NULL) == (device->queued_bytes != 0));
-
-    if (device->buffer_queue_head == NULL) {
-        device->buffer_queue_tail = NULL;  /* in case we drained the queue entirely. */
-    }
-
-    return (Uint32) (ptr - stream);
-}
-
 static void SDLCALL
 SDL_BufferQueueDrainCallback(void *userdata, Uint8 *stream, int len)
 {
     /* this function always holds the mixer lock before being called. */
     SDL_AudioDevice *device = (SDL_AudioDevice *) userdata;
-    Uint32 written;
+    size_t dequeued;
 
     SDL_assert(device != NULL);  /* this shouldn't ever happen, right?! */
     SDL_assert(!device->iscapture);  /* this shouldn't ever happen, right?! */
     SDL_assert(len >= 0);  /* this shouldn't ever happen, right?! */
 
-    written = dequeue_audio_from_device(device, stream, (Uint32) len);
-    stream += written;
-    len -= (int) written;
+    dequeued = SDL_ReadFromDataQueue(device->buffer_queue, stream, len);
+    stream += dequeued;
+    len -= (int) dequeued;
 
     if (len > 0) {  /* fill any remaining space in the stream with silence. */
-        SDL_assert(device->buffer_queue_head == NULL);
+        SDL_assert(SDL_CountDataQueue(device->buffer_queue) == 0);
         SDL_memset(stream, device->spec.silence, len);
     }
 }
@@ -595,7 +547,7 @@ SDL_BufferQueueFillCallback(void *userdata, Uint8 *stream, int len)
     /* note that if this needs to allocate more space and run out of memory,
        we have no choice but to quietly drop the data and hope it works out
        later, but you probably have bigger problems in this case anyhow. */
-    queue_audio_to_device(device, stream, (Uint32) len);
+    SDL_WriteToDataQueue(device->buffer_queue, stream, len);
 }
 
 int
@@ -608,13 +560,13 @@ SDL_QueueAudio(SDL_AudioDeviceID devid, const void *data, Uint32 len)
         return -1;  /* get_audio_device() will have set the error state */
     } else if (device->iscapture) {
         return SDL_SetError("This is a capture device, queueing not allowed");
-    } else if (device->spec.callback != SDL_BufferQueueDrainCallback) {
+    } else if (device->callbackspec.callback != SDL_BufferQueueDrainCallback) {
         return SDL_SetError("Audio device has a callback, queueing not allowed");
     }
 
     if (len > 0) {
         current_audio.impl.LockDevice(device);
-        rc = queue_audio_to_device(device, data, len);
+        rc = SDL_WriteToDataQueue(device->buffer_queue, data, len);
         current_audio.impl.UnlockDevice(device);
     }
 
@@ -630,12 +582,12 @@ SDL_DequeueAudio(SDL_AudioDeviceID devid, void *data, Uint32 len)
     if ( (len == 0) ||  /* nothing to do? */
          (!device) ||  /* called with bogus device id */
          (!device->iscapture) ||  /* playback devices can't dequeue */
-         (device->spec.callback != SDL_BufferQueueFillCallback) ) { /* not set for queueing */
+         (device->callbackspec.callback != SDL_BufferQueueFillCallback) ) { /* not set for queueing */
         return 0;  /* just report zero bytes dequeued. */
     }
 
     current_audio.impl.LockDevice(device);
-    rc = dequeue_audio_from_device(device, data, len);
+    rc = (Uint32) SDL_ReadFromDataQueue(device->buffer_queue, data, len);
     current_audio.impl.UnlockDevice(device);
     return rc;
 }
@@ -651,13 +603,13 @@ SDL_GetQueuedAudioSize(SDL_AudioDeviceID devid)
     }
 
     /* Nothing to do unless we're set up for queueing. */
-    if (device->spec.callback == SDL_BufferQueueDrainCallback) {
+    if (device->callbackspec.callback == SDL_BufferQueueDrainCallback) {
         current_audio.impl.LockDevice(device);
-        retval = device->queued_bytes + current_audio.impl.GetPendingBytes(device);
+        retval = ((Uint32) SDL_CountDataQueue(device->buffer_queue)) + current_audio.impl.GetPendingBytes(device);
         current_audio.impl.UnlockDevice(device);
-    } else if (device->spec.callback == SDL_BufferQueueFillCallback) {
+    } else if (device->callbackspec.callback == SDL_BufferQueueFillCallback) {
         current_audio.impl.LockDevice(device);
-        retval = device->queued_bytes;
+        retval = (Uint32) SDL_CountDataQueue(device->buffer_queue);
         current_audio.impl.UnlockDevice(device);
     }
 
@@ -668,7 +620,6 @@ void
 SDL_ClearQueuedAudio(SDL_AudioDeviceID devid)
 {
     SDL_AudioDevice *device = get_audio_device(devid);
-    SDL_AudioBufferQueue *packet;
 
     if (!device) {
         return;  /* nothing to do. */
@@ -677,35 +628,10 @@ SDL_ClearQueuedAudio(SDL_AudioDeviceID devid)
     /* Blank out the device and release the mutex. Free it afterwards. */
     current_audio.impl.LockDevice(device);
 
-    /* merge the available pool and the current queue into one list. */
-    packet = device->buffer_queue_head;
-    if (packet) {
-        device->buffer_queue_tail->next = device->buffer_queue_pool;
-    } else {
-        packet = device->buffer_queue_pool;
-    }
-
-    /* Remove the queued packets from the device. */
-    device->buffer_queue_tail = NULL;
-    device->buffer_queue_head = NULL;
-    device->queued_bytes = 0;
-    device->buffer_queue_pool = packet;
-
     /* Keep up to two packets in the pool to reduce future malloc pressure. */
-    if (packet) {
-        if (!packet->next) {
-            packet = NULL;  /* one packet (the only one) for the pool. */
-        } else {
-            SDL_AudioBufferQueue *next = packet->next->next;
-            packet->next->next = NULL;  /* two packets for the pool. */
-            packet = next;  /* rest will be freed. */
-        }
-    }
+    SDL_ClearDataQueue(device->buffer_queue, SDL_AUDIOBUFFERQUEUE_PACKETLEN * 2);
 
     current_audio.impl.UnlockDevice(device);
-
-    /* free any extra packets we didn't keep in the pool. */
-    free_audio_queue(packet);
 }
 
 
@@ -714,12 +640,9 @@ static int SDLCALL
 SDL_RunAudio(void *devicep)
 {
     SDL_AudioDevice *device = (SDL_AudioDevice *) devicep;
-    const int silence = (int) device->spec.silence;
-    const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq);
-    const int stream_len = (device->convert.needed) ? device->convert.len : device->spec.size;
-    Uint8 *stream;
-    void *udata = device->spec.userdata;
-    void (SDLCALL *callback) (void *, Uint8 *, int) = device->spec.callback;
+    void *udata = device->callbackspec.userdata;
+    SDL_AudioCallback callback = device->callbackspec.callback;
+    Uint8 *data;
 
     SDL_assert(!device->iscapture);
 
@@ -732,51 +655,63 @@ SDL_RunAudio(void *devicep)
 
     /* Loop, filling the audio buffers */
     while (!SDL_AtomicGet(&device->shutdown)) {
+        const int data_len = device->callbackspec.size;
+
         /* Fill the current buffer with sound */
-        if (device->convert.needed) {
-            stream = device->convert.buf;
-        } else if (SDL_AtomicGet(&device->enabled)) {
-            stream = current_audio.impl.GetDeviceBuf(device);
+        if (!device->stream && SDL_AtomicGet(&device->enabled)) {
+            SDL_assert(data_len == device->spec.size);
+            data = current_audio.impl.GetDeviceBuf(device);
         } else {
             /* if the device isn't enabled, we still write to the
-               fake_stream, so the app's callback will fire with
+               work_buffer, so the app's callback will fire with
                a regular frequency, in case they depend on that
                for timing or progress. They can use hotplug
-               now to know if the device failed. */
-            stream = NULL;
+               now to know if the device failed.
+               Streaming playback uses work_buffer, too. */
+            data = NULL;
         }
 
-        if (stream == NULL) {
-            stream = device->fake_stream;
+        if (data == NULL) {
+            data = device->work_buffer;
         }
 
         /* !!! FIXME: this should be LockDevice. */
-        if ( SDL_AtomicGet(&device->enabled) ) {
-            SDL_LockMutex(device->mixer_lock);
-            if (SDL_AtomicGet(&device->paused)) {
-                SDL_memset(stream, silence, stream_len);
-            } else {
-                (*callback) (udata, stream, stream_len);
-            }
-            SDL_UnlockMutex(device->mixer_lock);
+        SDL_LockMutex(device->mixer_lock);
+        if (SDL_AtomicGet(&device->paused)) {
+            SDL_memset(data, device->spec.silence, data_len);
+        } else {
+            callback(udata, data, data_len);
         }
+        SDL_UnlockMutex(device->mixer_lock);
 
-        /* Convert the audio if necessary */
-        if (device->convert.needed && SDL_AtomicGet(&device->enabled)) {
-            SDL_ConvertAudio(&device->convert);
-            stream = current_audio.impl.GetDeviceBuf(device);
-            if (stream == NULL) {
-                stream = device->fake_stream;
-            } else {
-                SDL_memcpy(stream, device->convert.buf,
-                           device->convert.len_cvt);
+        if (device->stream) {
+            /* Stream available audio to device, converting/resampling. */
+            /* if this fails...oh well. We'll play silence here. */
+            SDL_AudioStreamPut(device->stream, data, data_len);
+
+            while (SDL_AudioStreamAvailable(device->stream) >= ((int) device->spec.size)) {
+                int got;
+                data = SDL_AtomicGet(&device->enabled) ? current_audio.impl.GetDeviceBuf(device) : NULL;
+                got = SDL_AudioStreamGet(device->stream, data ? data : device->work_buffer, device->spec.size);
+                SDL_assert((got < 0) || (got == device->spec.size));
+
+                if (data == NULL) {  /* device is having issues... */
+                    const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq);
+                    SDL_Delay(delay);  /* wait for as long as this buffer would have played. Maybe device recovers later? */
+                } else {
+                    if (got != device->spec.size) {
+                        SDL_memset(data, device->spec.silence, device->spec.size);
+                    }
+                    current_audio.impl.PlayDevice(device);
+                    current_audio.impl.WaitDevice(device);
+                }
             }
-        }
-
-        /* Ready current buffer for play and change current buffer */
-        if (stream == device->fake_stream) {
+        } else if (data == device->work_buffer) {
+            /* nothing to do; pause like we queued a buffer to play. */
+            const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq);
             SDL_Delay(delay);
-        } else {
+        } else {  /* writing directly to the device. */
+            /* queue this buffer and wait for it to finish playing. */
             current_audio.impl.PlayDevice(device);
             current_audio.impl.WaitDevice(device);
         }
@@ -787,9 +722,12 @@ SDL_RunAudio(void *devicep)
     /* Wait for the audio to drain. */
     SDL_Delay(((device->spec.samples * 1000) / device->spec.freq) * 2);
 
+    current_audio.impl.ThreadDeinit(device);
+
     return 0;
 }
 
+/* !!! FIXME: this needs to deal with device spec changes. */
 /* The general capture thread function */
 static int SDLCALL
 SDL_CaptureAudio(void *devicep)
@@ -797,10 +735,10 @@ SDL_CaptureAudio(void *devicep)
     SDL_AudioDevice *device = (SDL_AudioDevice *) devicep;
     const int silence = (int) device->spec.silence;
     const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq);
-    const int stream_len = (device->convert.needed) ? device->convert.len : device->spec.size;
-    Uint8 *stream;
-    void *udata = device->spec.userdata;
-    void (SDLCALL *callback) (void *, Uint8 *, int) = device->spec.callback;
+    const int data_len = device->spec.size;
+    Uint8 *data;
+    void *udata = device->callbackspec.userdata;
+    SDL_AudioCallback callback = device->callbackspec.callback;
 
     SDL_assert(device->iscapture);
 
@@ -816,34 +754,41 @@ SDL_CaptureAudio(void *devicep)
         int still_need;
         Uint8 *ptr;
 
-        if (!SDL_AtomicGet(&device->enabled) || SDL_AtomicGet(&device->paused)) {
+        if (SDL_AtomicGet(&device->paused)) {
             SDL_Delay(delay);  /* just so we don't cook the CPU. */
+            if (device->stream) {
+                SDL_AudioStreamClear(device->stream);
+            }
             current_audio.impl.FlushCapture(device);  /* dump anything pending. */
             continue;
         }
 
         /* Fill the current buffer with sound */
-        still_need = stream_len;
-        if (device->convert.needed) {
-            ptr = stream = device->convert.buf;
-        } else {
-            /* just use the "fake" stream to hold data read from the device. */
-            ptr = stream = device->fake_stream;
-        }
+        still_need = data_len;
+
+        /* Use the work_buffer to hold data read from the device. */
+        data = device->work_buffer;
+        SDL_assert(data != NULL);
+
+        ptr = data;
 
         /* We still read from the device when "paused" to keep the state sane,
            and block when there isn't data so this thread isn't eating CPU.
            But we don't process it further or call the app's callback. */
 
-        while (still_need > 0) {
-            const int rc = current_audio.impl.CaptureFromDevice(device, ptr, still_need);
-            SDL_assert(rc <= still_need);  /* device should not overflow buffer. :) */
-            if (rc > 0) {
-                still_need -= rc;
-                ptr += rc;
-            } else {  /* uhoh, device failed for some reason! */
-                SDL_OpenedAudioDeviceDisconnected(device);
-                break;
+        if (!SDL_AtomicGet(&device->enabled)) {
+            SDL_Delay(delay);  /* try to keep callback firing at normal pace. */
+        } else {
+            while (still_need > 0) {
+                const int rc = current_audio.impl.CaptureFromDevice(device, ptr, still_need);
+                SDL_assert(rc <= still_need);  /* device should not overflow buffer. :) */
+                if (rc > 0) {
+                    still_need -= rc;
+                    ptr += rc;
+                } else {  /* uhoh, device failed for some reason! */
+                    SDL_OpenedAudioDeviceDisconnected(device);
+                    break;
+                }
             }
         }
 
@@ -852,22 +797,38 @@ SDL_CaptureAudio(void *devicep)
             SDL_memset(ptr, silence, still_need);
         }
 
-        if (device->convert.needed) {
-            SDL_ConvertAudio(&device->convert);
-        }
+        if (device->stream) {
+            /* if this fails...oh well. */
+            SDL_AudioStreamPut(device->stream, data, data_len);
 
-        /* !!! FIXME: this should be LockDevice. */
-        SDL_LockMutex(device->mixer_lock);
-        if (SDL_AtomicGet(&device->paused)) {
-            current_audio.impl.FlushCapture(device);  /* one snuck in! */
-        } else {
-            (*callback)(udata, stream, stream_len);
+            while (SDL_AudioStreamAvailable(device->stream) >= ((int) device->callbackspec.size)) {
+                const int got = SDL_AudioStreamGet(device->stream, device->work_buffer, device->callbackspec.size);
+                SDL_assert((got < 0) || (got == device->callbackspec.size));
+                if (got != device->callbackspec.size) {
+                    SDL_memset(device->work_buffer, device->spec.silence, device->callbackspec.size);
+                }
+
+                /* !!! FIXME: this should be LockDevice. */
+                SDL_LockMutex(device->mixer_lock);
+                if (!SDL_AtomicGet(&device->paused)) {
+                    callback(udata, device->work_buffer, device->callbackspec.size);
+                }
+                SDL_UnlockMutex(device->mixer_lock);
+            }
+        } else {  /* feeding user callback directly without streaming. */
+            /* !!! FIXME: this should be LockDevice. */
+            SDL_LockMutex(device->mixer_lock);
+            if (!SDL_AtomicGet(&device->paused)) {
+                callback(udata, data, device->callbackspec.size);
+            }
+            SDL_UnlockMutex(device->mixer_lock);
         }
-        SDL_UnlockMutex(device->mixer_lock);
     }
 
     current_audio.impl.FlushCapture(device);
 
+    current_audio.impl.ThreadDeinit(device);
+
     return 0;
 }
 
@@ -968,6 +929,10 @@ SDL_AudioInit(const char *driver_name)
     /* Make sure we have a list of devices available at startup. */
     current_audio.impl.DetectDevices();
 
+#ifdef HAVE_LIBSAMPLERATE_H
+    LoadLibSampleRate();
+#endif
+
     return 0;
 }
 
@@ -1098,16 +1063,15 @@ close_audio_device(SDL_AudioDevice * device)
     if (device->mixer_lock != NULL) {
         SDL_DestroyMutex(device->mixer_lock);
     }
-    SDL_free(device->fake_stream);
-    if (device->convert.needed) {
-        SDL_free(device->convert.buf);
-    }
+
+    SDL_free(device->work_buffer);
+    SDL_FreeAudioStream(device->stream);
+
     if (device->hidden != NULL) {
         current_audio.impl.CloseDevice(device);
     }
 
-    free_audio_queue(device->buffer_queue_head);
-    free_audio_queue(device->buffer_queue_pool);
+    SDL_FreeDataQueue(device->buffer_queue);
 
     SDL_free(device);
 }
@@ -1180,11 +1144,11 @@ open_audio_device(const char *devname, int iscapture,
                   const SDL_AudioSpec * desired, SDL_AudioSpec * obtained,
                   int allowed_changes, int min_id)
 {
-    const SDL_bool is_internal_thread = (desired->callback != NULL);
+    const SDL_bool is_internal_thread = (desired->callback == NULL);
     SDL_AudioDeviceID id = 0;
     SDL_AudioSpec _obtained;
     SDL_AudioDevice *device;
-    SDL_bool build_cvt;
+    SDL_bool build_stream;
     void *handle = NULL;
     int i = 0;
 
@@ -1319,84 +1283,87 @@ open_audio_device(const char *devname, int iscapture,
     SDL_assert(device->hidden != NULL);
 
     /* See if we need to do any conversion */
-    build_cvt = SDL_FALSE;
+    build_stream = SDL_FALSE;
     if (obtained->freq != device->spec.freq) {
         if (allowed_changes & SDL_AUDIO_ALLOW_FREQUENCY_CHANGE) {
             obtained->freq = device->spec.freq;
         } else {
-            build_cvt = SDL_TRUE;
+            build_stream = SDL_TRUE;
         }
     }
     if (obtained->format != device->spec.format) {
         if (allowed_changes & SDL_AUDIO_ALLOW_FORMAT_CHANGE) {
             obtained->format = device->spec.format;
         } else {
-            build_cvt = SDL_TRUE;
+            build_stream = SDL_TRUE;
         }
     }
     if (obtained->channels != device->spec.channels) {
         if (allowed_changes & SDL_AUDIO_ALLOW_CHANNELS_CHANGE) {
             obtained->channels = device->spec.channels;
         } else {
-            build_cvt = SDL_TRUE;
+            build_stream = SDL_TRUE;
         }
     }
 
-    /* If the audio driver changes the buffer size, accept it.
-       This needs to be done after the format is modified above,
-       otherwise it might not have the correct buffer size.
+    /* !!! FIXME in 2.1: add SDL_AUDIO_ALLOW_SAMPLES_CHANGE flag?
+       As of 2.0.6, we will build a stream to buffer the difference between
+       what the app wants to feed and the device wants to eat, so everyone
+       gets their way. In prior releases, SDL would force the callback to
+       feed at the rate the device requested, adjusted for resampling.
      */
     if (device->spec.samples != obtained->samples) {
-        obtained->samples = device->spec.samples;
-        SDL_CalculateAudioSpec(obtained);
+        build_stream = SDL_TRUE;
     }
 
-    if (build_cvt) {
-        /* Build an audio conversion block */
-        if (SDL_BuildAudioCVT(&device->convert,
-                              obtained->format, obtained->channels,
-                              obtained->freq,
-                              device->spec.format, device->spec.channels,
-                              device->spec.freq) < 0) {
+    SDL_CalculateAudioSpec(obtained);  /* recalc after possible changes. */
+
+    device->callbackspec = *obtained;
+
+    if (build_stream) {
+        if (iscapture) {
+            device->stream = SDL_NewAudioStream(device->spec.format,
+                                  device->spec.channels, device->spec.freq,
+                                  obtained->format, obtained->channels, obtained->freq);
+        } else {
+            device->stream = SDL_NewAudioStream(obtained->format, obtained->channels,
+                                  obtained->freq, device->spec.format,
+                                  device->spec.channels, device->spec.freq);
+        }
+
+        if (!device->stream) {
             close_audio_device(device);
             return 0;
         }
-        if (device->convert.needed) {
-            device->convert.len = (int) (((double) device->spec.size) /
-                                         device->convert.len_ratio);
-
-            device->convert.buf =
-                (Uint8 *) SDL_malloc(device->convert.len *
-                                            device->convert.len_mult);
-            if (device->convert.buf == NULL) {
-                close_audio_device(device);
-                SDL_OutOfMemory();
-                return 0;
-            }
-        }
     }
 
     if (device->spec.callback == NULL) {  /* use buffer queueing? */
         /* pool a few packets to start. Enough for two callbacks. */
-        const int packetlen = SDL_AUDIOBUFFERQUEUE_PACKETLEN;
-        const int wantbytes = ((device->convert.needed) ? device->convert.len : device->spec.size) * 2;
-        const int wantpackets = (wantbytes / packetlen) + ((wantbytes % packetlen) ? packetlen : 0);
-        for (i = 0; i < wantpackets; i++) {
-            SDL_AudioBufferQueue *packet = (SDL_AudioBufferQueue *) SDL_malloc(sizeof (SDL_AudioBufferQueue));
-            if (packet) { /* don't care if this fails, we'll deal later. */
-                packet->datalen = 0;
-                packet->startpos = 0;
-                packet->next = device->buffer_queue_pool;
-                device->buffer_queue_pool = packet;
-            }
+        device->buffer_queue = SDL_NewDataQueue(SDL_AUDIOBUFFERQUEUE_PACKETLEN, obtained->size * 2);
+        if (!device->buffer_queue) {
+            close_audio_device(device);
+            SDL_SetError("Couldn't create audio buffer queue");
+            return 0;
         }
+        device->callbackspec.callback = iscapture ? SDL_BufferQueueFillCallback : SDL_BufferQueueDrainCallback;
+        device->callbackspec.userdata = device;
+    }
 
-        device->spec.callback = iscapture ? SDL_BufferQueueFillCallback : SDL_BufferQueueDrainCallback;
-        device->spec.userdata = device;
+    /* Allocate a scratch audio buffer */
+    device->work_buffer_len = build_stream ? device->callbackspec.size : 0;
+    if (device->spec.size > device->work_buffer_len) {
+        device->work_buffer_len = device->spec.size;
+    }
+    SDL_assert(device->work_buffer_len > 0);
+
+    device->work_buffer = (Uint8 *) SDL_malloc(device->work_buffer_len);
+    if (device->work_buffer == NULL) {
+        close_audio_device(device);
+        SDL_OutOfMemory();
+        return 0;
     }
 
-    /* add it to our list of open devices. */
-    open_devices[id] = device;
+    open_devices[id] = device;  /* add it to our list of open devices. */
 
     /* Start the audio thread if necessary */
     if (!current_audio.impl.ProvidesOwnCallbackThread) {
@@ -1406,21 +1373,7 @@ open_audio_device(const char *devname, int iscapture,
         const size_t stacksize = is_internal_thread ? 64 * 1024 : 0;
         char threadname[64];
 
-        /* Allocate a fake audio buffer; only used by our internal threads. */
-        Uint32 stream_len = (device->convert.needed) ? device->convert.len_cvt : 0;
-        if (device->spec.size > stream_len) {
-            stream_len = device->spec.size;
-        }
-        SDL_assert(stream_len > 0);
-
-        device->fake_stream = (Uint8 *) SDL_malloc(stream_len);
-        if (device->fake_stream == NULL) {
-            close_audio_device(device);
-            SDL_OutOfMemory();
-            return 0;
-        }
-
-        SDL_snprintf(threadname, sizeof (threadname), "SDLAudioDev%d", (int) device->id);
+        SDL_snprintf(threadname, sizeof (threadname), "SDLAudio%c%d", (iscapture) ? 'C' : 'P', (int) device->id);
         device->thread = SDL_CreateThreadInternal(iscapture ? SDL_CaptureAudio : SDL_RunAudio, threadname, stacksize, device);
 
         if (device->thread == NULL) {
@@ -1456,7 +1409,14 @@ SDL_OpenAudio(SDL_AudioSpec * desired, SDL_AudioSpec * obtained)
         id = open_audio_device(NULL, 0, desired, obtained,
                                SDL_AUDIO_ALLOW_ANY_CHANGE, 1);
     } else {
-        id = open_audio_device(NULL, 0, desired, NULL, 0, 1);
+        SDL_AudioSpec _obtained;
+        SDL_zero(_obtained);
+        id = open_audio_device(NULL, 0, desired, &_obtained, 0, 1);
+        /* On successful open, copy calculated values into 'desired'. */
+        if (id > 0) {
+            desired->size = _obtained.size;
+            desired->silence = _obtained.silence;
+        }
     }
 
     SDL_assert((id == 0) || (id == 1));
@@ -1579,6 +1539,12 @@ SDL_AudioQuit(void)
 
     SDL_zero(current_audio);
     SDL_zero(open_devices);
+
+#ifdef HAVE_LIBSAMPLERATE_H
+    UnloadLibSampleRate();
+#endif
+
+    SDL_FreeResampleFilter();
 }
 
 #define NUM_FORMATS 10
@@ -1655,13 +1621,7 @@ SDL_MixAudio(Uint8 * dst, const Uint8 * src, Uint32 len, int volume)
     /* Mix the user-level audio format */
     SDL_AudioDevice *device = get_audio_device(1);
     if (device != NULL) {
-        SDL_AudioFormat format;
-        if (device->convert.needed) {
-            format = device->convert.src_format;
-        } else {
-            format = device->spec.format;
-        }
-        SDL_MixAudioFormat(dst, src, format, len, volume);
+        SDL_MixAudioFormat(dst, src, device->callbackspec.format, len, volume);
     }
 }
 
diff --git a/src/audio/SDL_audio_c.h b/src/audio/SDL_audio_c.h
index 7cde3a6..58ecf10 100644
--- a/src/audio/SDL_audio_c.h
+++ b/src/audio/SDL_audio_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,10 +18,35 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
+
+#ifndef SDL_audio_c_h_
+#define SDL_audio_c_h_
+
 #include "../SDL_internal.h"
 
+#ifndef DEBUG_CONVERT
+#define DEBUG_CONVERT 0
+#endif
+
+#if DEBUG_CONVERT
+#define LOG_DEBUG_CONVERT(from, to) fprintf(stderr, "Converting %s to %s.\n", from, to);
+#else
+#define LOG_DEBUG_CONVERT(from, to)
+#endif
+
 /* Functions and variables exported from SDL_audio.c for SDL_sysaudio.c */
 
+#ifdef HAVE_LIBSAMPLERATE_H
+#include "samplerate.h"
+extern SDL_bool SRC_available;
+extern int SRC_converter;
+extern SRC_STATE* (*SRC_src_new)(int converter_type, int channels, int *error);
+extern int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data);
+extern int (*SRC_src_reset)(SRC_STATE *state);
+extern SRC_STATE* (*SRC_src_delete)(SRC_STATE *state);
+extern const char* (*SRC_src_strerror)(int error);
+#endif
+
 /* Functions to get a list of "close" audio formats */
 extern SDL_AudioFormat SDL_FirstAudioFormat(SDL_AudioFormat format);
 extern SDL_AudioFormat SDL_NextAudioFormat(void);
@@ -29,24 +54,66 @@ extern SDL_AudioFormat SDL_NextAudioFormat(void);
 /* Function to calculate the size and silence for a SDL_AudioSpec */
 extern void SDL_CalculateAudioSpec(SDL_AudioSpec * spec);
 
-/* this is used internally to access some autogenerated code. */
-typedef struct
-{
-    SDL_AudioFormat src_fmt;
-    SDL_AudioFormat dst_fmt;
-    SDL_AudioFilter filter;
-} SDL_AudioTypeFilters;
-extern const SDL_AudioTypeFilters sdl_audio_type_filters[];
-
-/* this is used internally to access some autogenerated code. */
-typedef struct
-{
-    SDL_AudioFormat fmt;
-    int channels;
-    int upsample;
-    int multiple;
-    SDL_AudioFilter filter;
-} SDL_AudioRateFilters;
-extern const SDL_AudioRateFilters sdl_audio_rate_filters[];
+/* Choose the audio filter functions below */
+extern void SDL_ChooseAudioConverters(void);
+
+/* These pointers get set during SDL_ChooseAudioConverters() to various SIMD implementations. */
+extern SDL_AudioFilter SDL_Convert_S8_to_F32;
+extern SDL_AudioFilter SDL_Convert_U8_to_F32;
+extern SDL_AudioFilter SDL_Convert_S16_to_F32;
+extern SDL_AudioFilter SDL_Convert_U16_to_F32;
+extern SDL_AudioFilter SDL_Convert_S32_to_F32;
+extern SDL_AudioFilter SDL_Convert_F32_to_S8;
+extern SDL_AudioFilter SDL_Convert_F32_to_U8;
+extern SDL_AudioFilter SDL_Convert_F32_to_S16;
+extern SDL_AudioFilter SDL_Convert_F32_to_U16;
+extern SDL_AudioFilter SDL_Convert_F32_to_S32;
+
+/* You need to call SDL_PrepareResampleFilter() before using the internal resampler.
+   SDL_AudioQuit() calls SDL_FreeResamplerFilter(), you should never call it yourself. */
+extern int SDL_PrepareResampleFilter(void);
+extern void SDL_FreeResampleFilter(void);
+
+
+/* SDL_AudioStream is a new audio conversion interface. It
+    might eventually become a public API.
+   The benefits vs SDL_AudioCVT:
+    - it can handle resampling data in chunks without generating
+      artifacts, when it doesn't have the complete buffer available.
+    - it can handle incoming data in any variable size.
+    - You push data as you have it, and pull it when you need it
+
+    (Note that currently this converts as data is put into the stream, so
+    you need to push more than a handful of bytes if you want decent
+    resampling. This can be changed later.)
+ */
+
+/* this is opaque to the outside world. */
+typedef struct SDL_AudioStream SDL_AudioStream;
+
+/* create a new stream */
+extern SDL_AudioStream *SDL_NewAudioStream(const SDL_AudioFormat src_format,
+                                           const Uint8 src_channels,
+                                           const int src_rate,
+                                           const SDL_AudioFormat dst_format,
+                                           const Uint8 dst_channels,
+                                           const int dst_rate);
+
+/* add data to be converted/resampled to the stream */
+extern int SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, const Uint32 len);
+
+/* get converted/resampled data from the stream */
+extern int SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, const Uint32 len);
+
+/* clear any pending data in the stream without converting it. */
+extern void SDL_AudioStreamClear(SDL_AudioStream *stream);
+
+/* number of converted/resampled bytes available */
+extern int SDL_AudioStreamAvailable(SDL_AudioStream *stream);
+
+/* dispose of a stream */
+extern void SDL_FreeAudioStream(SDL_AudioStream *stream);
+
+#endif /* SDL_audio_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/SDL_audiocvt.c b/src/audio/SDL_audiocvt.c
index 3b47c4c..4b24ccd 100644
--- a/src/audio/SDL_audiocvt.c
+++ b/src/audio/SDL_audiocvt.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,165 +22,68 @@
 
 /* Functions for audio drivers to perform runtime conversion of audio format */
 
+#include "SDL.h"
 #include "SDL_audio.h"
 #include "SDL_audio_c.h"
 
+#include "SDL_loadso.h"
 #include "SDL_assert.h"
+#include "../SDL_dataqueue.h"
+#include "SDL_cpuinfo.h"
 
-/* #define DEBUG_CONVERT */
+#ifdef __SSE3__
+#define HAVE_SSE3_INTRINSICS 1
+#endif
 
-/* Effectively mix right and left channels into a single channel */
+#if HAVE_SSE3_INTRINSICS
+/* Convert from stereo to mono. Average left and right. */
 static void SDLCALL
-SDL_ConvertMono(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_ConvertStereoToMono_SSE3(SDL_AudioCVT * cvt, SDL_AudioFormat format)
 {
-    int i;
-    Sint32 sample;
+    float *dst = (float *) cvt->buf;
+    const float *src = dst;
+    int i = cvt->len_cvt / 8;
+
+    LOG_DEBUG_CONVERT("stereo", "mono (using SSE3)");
+    SDL_assert(format == AUDIO_F32SYS);
+
+    /* We can only do this if dst is aligned to 16 bytes; since src is the
+       same pointer and it moves by 2, it can't be forcibly aligned. */
+    if ((((size_t) dst) & 15) == 0) {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        const __m128 divby2 = _mm_set1_ps(0.5f);
+        while (i >= 4) {   /* 4 * float32 */
+            _mm_store_ps(dst, _mm_mul_ps(_mm_hadd_ps(_mm_load_ps(src), _mm_load_ps(src+4)), divby2));
+            i -= 4; src += 8; dst += 4;
+        }
+    }
 
-#ifdef DEBUG_CONVERT
-    fprintf(stderr, "Converting to mono\n");
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = (src[0] + src[1]) * 0.5f;
+        dst++; i--; src += 2;
+    }
+
+    cvt->len_cvt /= 2;
+    if (cvt->filters[++cvt->filter_index]) {
+        cvt->filters[cvt->filter_index] (cvt, format);
+    }
+}
 #endif
-	switch (format & (SDL_AUDIO_MASK_SIGNED |
-                      SDL_AUDIO_MASK_BITSIZE |
-                      SDL_AUDIO_MASK_DATATYPE)) {
-    case AUDIO_U8:
-        {
-            Uint8 *src, *dst;
-
-            src = cvt->buf;
-            dst = cvt->buf;
-            for (i = cvt->len_cvt / 2; i; --i) {
-                sample = src[0] + src[1];
-                *dst = (Uint8) (sample / 2);
-                src += 2;
-                dst += 1;
-            }
-        }
-        break;
-
-    case AUDIO_S8:
-        {
-            Sint8 *src, *dst;
-
-            src = (Sint8 *) cvt->buf;
-            dst = (Sint8 *) cvt->buf;
-            for (i = cvt->len_cvt / 2; i; --i) {
-                sample = src[0] + src[1];
-                *dst = (Sint8) (sample / 2);
-                src += 2;
-                dst += 1;
-            }
-        }
-        break;
-
-    case AUDIO_U16:
-        {
-            Uint8 *src, *dst;
-
-            src = cvt->buf;
-            dst = cvt->buf;
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    sample = (Uint16) ((src[0] << 8) | src[1]) +
-                        (Uint16) ((src[2] << 8) | src[3]);
-                    sample /= 2;
-                    dst[1] = (sample & 0xFF);
-                    sample >>= 8;
-                    dst[0] = (sample & 0xFF);
-                    src += 4;
-                    dst += 2;
-                }
-            } else {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    sample = (Uint16) ((src[1] << 8) | src[0]) +
-                        (Uint16) ((src[3] << 8) | src[2]);
-                    sample /= 2;
-                    dst[0] = (sample & 0xFF);
-                    sample >>= 8;
-                    dst[1] = (sample & 0xFF);
-                    src += 4;
-                    dst += 2;
-                }
-            }
-        }
-        break;
-
-    case AUDIO_S16:
-        {
-            Uint8 *src, *dst;
-
-            src = cvt->buf;
-            dst = cvt->buf;
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    sample = (Sint16) ((src[0] << 8) | src[1]) +
-                        (Sint16) ((src[2] << 8) | src[3]);
-                    sample /= 2;
-                    dst[1] = (sample & 0xFF);
-                    sample >>= 8;
-                    dst[0] = (sample & 0xFF);
-                    src += 4;
-                    dst += 2;
-                }
-            } else {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    sample = (Sint16) ((src[1] << 8) | src[0]) +
-                        (Sint16) ((src[3] << 8) | src[2]);
-                    sample /= 2;
-                    dst[0] = (sample & 0xFF);
-                    sample >>= 8;
-                    dst[1] = (sample & 0xFF);
-                    src += 4;
-                    dst += 2;
-                }
-            }
-        }
-        break;
-
-    case AUDIO_S32:
-        {
-            const Uint32 *src = (const Uint32 *) cvt->buf;
-            Uint32 *dst = (Uint32 *) cvt->buf;
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 8; i; --i, src += 2) {
-                    const Sint64 added =
-                        (((Sint64) (Sint32) SDL_SwapBE32(src[0])) +
-                         ((Sint64) (Sint32) SDL_SwapBE32(src[1])));
-                    *(dst++) = SDL_SwapBE32((Uint32) ((Sint32) (added / 2)));
-                }
-            } else {
-                for (i = cvt->len_cvt / 8; i; --i, src += 2) {
-                    const Sint64 added =
-                        (((Sint64) (Sint32) SDL_SwapLE32(src[0])) +
-                         ((Sint64) (Sint32) SDL_SwapLE32(src[1])));
-                    *(dst++) = SDL_SwapLE32((Uint32) ((Sint32) (added / 2)));
-                }
-            }
-        }
-        break;
-
-    case AUDIO_F32:
-        {
-            const float *src = (const float *) cvt->buf;
-            float *dst = (float *) cvt->buf;
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 8; i; --i, src += 2) {
-                    const float src1 = SDL_SwapFloatBE(src[0]);
-                    const float src2 = SDL_SwapFloatBE(src[1]);
-                    const double added = ((double) src1) + ((double) src2);
-                    const float halved = (float) (added * 0.5);
-                    *(dst++) = SDL_SwapFloatBE(halved);
-                }
-            } else {
-                for (i = cvt->len_cvt / 8; i; --i, src += 2) {
-                    const float src1 = SDL_SwapFloatLE(src[0]);
-                    const float src2 = SDL_SwapFloatLE(src[1]);
-                    const double added = ((double) src1) + ((double) src2);
-                    const float halved = (float) (added * 0.5);
-                    *(dst++) = SDL_SwapFloatLE(halved);
-                }
-            }
-        }
-        break;
+
+/* Convert from stereo to mono. Average left and right. */
+static void SDLCALL
+SDL_ConvertStereoToMono(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+{
+    float *dst = (float *) cvt->buf;
+    const float *src = dst;
+    int i;
+
+    LOG_DEBUG_CONVERT("stereo", "mono");
+    SDL_assert(format == AUDIO_F32SYS);
+
+    for (i = cvt->len_cvt / 8; i; --i, src += 2) {
+        *(dst++) = (src[0] + src[1]) * 0.5f;
     }
 
     cvt->len_cvt /= 2;
@@ -190,42 +93,46 @@ SDL_ConvertMono(SDL_AudioCVT * cvt, SDL_AudioFormat format)
 }
 
 
-/* Discard top 4 channels */
+/* Convert from 5.1 to stereo. Average left and right, distribute center, discard LFE. */
 static void SDLCALL
-SDL_ConvertStrip(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert51ToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
 {
+    float *dst = (float *) cvt->buf;
+    const float *src = dst;
     int i;
 
-#ifdef DEBUG_CONVERT
-    fprintf(stderr, "Converting down from 6 channels to stereo\n");
-#endif
+    LOG_DEBUG_CONVERT("5.1", "stereo");
+    SDL_assert(format == AUDIO_F32SYS);
 
-#define strip_chans_6_to_2(type) \
-    { \
-        const type *src = (const type *) cvt->buf; \
-        type *dst = (type *) cvt->buf; \
-        for (i = cvt->len_cvt / (sizeof (type) * 6); i; --i) { \
-            dst[0] = src[0]; \
-            dst[1] = src[1]; \
-            src += 6; \
-            dst += 2; \
-        } \
+    /* SDL's 5.1 layout: FL+FR+FC+LFE+BL+BR */
+    for (i = cvt->len_cvt / (sizeof (float) * 6); i; --i, src += 6, dst += 2) {
+        const float front_center_distributed = src[2] * 0.5f;
+        dst[0] = (src[0] + front_center_distributed + src[4]) / 2.5f;  /* left */
+        dst[1] = (src[1] + front_center_distributed + src[5]) / 2.5f;  /* right */
     }
 
-    /* this function only cares about typesize, and data as a block of bits. */
-    switch (SDL_AUDIO_BITSIZE(format)) {
-    case 8:
-        strip_chans_6_to_2(Uint8);
-        break;
-    case 16:
-        strip_chans_6_to_2(Uint16);
-        break;
-    case 32:
-        strip_chans_6_to_2(Uint32);
-        break;
+    cvt->len_cvt /= 3;
+    if (cvt->filters[++cvt->filter_index]) {
+        cvt->filters[cvt->filter_index] (cvt, format);
     }
+}
+
+
+/* Convert from quad to stereo. Average left and right. */
+static void SDLCALL
+SDL_ConvertQuadToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+{
+    float *dst = (float *) cvt->buf;
+    const float *src = dst;
+    int i;
+
+    LOG_DEBUG_CONVERT("quad", "stereo");
+    SDL_assert(format == AUDIO_F32SYS);
 
-#undef strip_chans_6_to_2
+    for (i = cvt->len_cvt / (sizeof (float) * 4); i; --i, src += 4, dst += 2) {
+        dst[0] = (src[0] + src[2]) * 0.5f; /* left */
+        dst[1] = (src[1] + src[3]) * 0.5f; /* right */
+    }
 
     cvt->len_cvt /= 3;
     if (cvt->filters[++cvt->filter_index]) {
@@ -234,44 +141,56 @@ SDL_ConvertStrip(SDL_AudioCVT * cvt, SDL_AudioFormat format)
 }
 
 
-/* Discard top 2 channels of 6 */
+/* Convert from 7.1 to 5.1. Distribute sides across front and back. */
 static void SDLCALL
-SDL_ConvertStrip_2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert71To51(SDL_AudioCVT * cvt, SDL_AudioFormat format)
 {
+    float *dst = (float *) cvt->buf;
+    const float *src = dst;
     int i;
 
-#ifdef DEBUG_CONVERT
-    fprintf(stderr, "Converting 6 down to quad\n");
-#endif
+    LOG_DEBUG_CONVERT("7.1", "5.1");
+    SDL_assert(format == AUDIO_F32SYS);
+
+    for (i = cvt->len_cvt / (sizeof (float) * 8); i; --i, src += 8, dst += 6) {
+        const float surround_left_distributed = src[6] * 0.5f;
+        const float surround_right_distributed = src[7] * 0.5f;
+        dst[0] = (src[0] + surround_left_distributed) / 1.5f;  /* FL */
+        dst[1] = (src[1] + surround_right_distributed) / 1.5f;  /* FR */
+        dst[2] = src[2] / 1.5f; /* CC */
+        dst[3] = src[3] / 1.5f; /* LFE */
+        dst[4] = (src[4] + surround_left_distributed) / 1.5f;  /* BL */
+        dst[5] = (src[5] + surround_right_distributed) / 1.5f;  /* BR */
+    }
 
-#define strip_chans_6_to_4(type) \
-    { \
-        const type *src = (const type *) cvt->buf; \
-        type *dst = (type *) cvt->buf; \
-        for (i = cvt->len_cvt / (sizeof (type) * 6); i; --i) { \
-            dst[0] = src[0]; \
-            dst[1] = src[1]; \
-            dst[2] = src[2]; \
-            dst[3] = src[3]; \
-            src += 6; \
-            dst += 4; \
-        } \
-    }
-
-    /* this function only cares about typesize, and data as a block of bits. */
-    switch (SDL_AUDIO_BITSIZE(format)) {
-    case 8:
-        strip_chans_6_to_4(Uint8);
-        break;
-    case 16:
-        strip_chans_6_to_4(Uint16);
-        break;
-    case 32:
-        strip_chans_6_to_4(Uint32);
-        break;
+    cvt->len_cvt /= 8;
+    cvt->len_cvt *= 6;
+    if (cvt->filters[++cvt->filter_index]) {
+        cvt->filters[cvt->filter_index] (cvt, format);
     }
+}
+
+
+/* Convert from 5.1 to quad. Distribute center across front, discard LFE. */
+static void SDLCALL
+SDL_Convert51ToQuad(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+{
+    float *dst = (float *) cvt->buf;
+    const float *src = dst;
+    int i;
 
-#undef strip_chans_6_to_4
+    LOG_DEBUG_CONVERT("5.1", "quad");
+    SDL_assert(format == AUDIO_F32SYS);
+
+    /* SDL's 4.0 layout: FL+FR+BL+BR */
+    /* SDL's 5.1 layout: FL+FR+FC+LFE+BL+BR */
+    for (i = cvt->len_cvt / (sizeof (float) * 6); i; --i, src += 6, dst += 4) {
+        const float front_center_distributed = src[2] * 0.5f;
+        dst[0] = (src[0] + front_center_distributed) / 1.5f;  /* FL */
+        dst[1] = (src[1] + front_center_distributed) / 1.5f;  /* FR */
+        dst[2] = src[4] / 1.5f;  /* BL */
+        dst[3] = src[5] / 1.5f;  /* BR */
+    }
 
     cvt->len_cvt /= 6;
     cvt->len_cvt *= 4;
@@ -280,535 +199,332 @@ SDL_ConvertStrip_2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
     }
 }
 
-/* Duplicate a mono channel to both stereo channels */
+
+/* Upmix mono to stereo (by duplication) */
 static void SDLCALL
-SDL_ConvertStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_ConvertMonoToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
+    float *dst = (float *) (cvt->buf + cvt->len_cvt * 2);
     int i;
 
-#ifdef DEBUG_CONVERT
-    fprintf(stderr, "Converting to stereo\n");
-#endif
+    LOG_DEBUG_CONVERT("mono", "stereo");
+    SDL_assert(format == AUDIO_F32SYS);
 
-#define dup_chans_1_to_2(type) \
-    { \
-        const type *src = (const type *) (cvt->buf + cvt->len_cvt); \
-        type *dst = (type *) (cvt->buf + cvt->len_cvt * 2); \
-        for (i = cvt->len_cvt / sizeof(type); i; --i) { \
-            src -= 1; \
-            dst -= 2; \
-            dst[0] = dst[1] = *src; \
-        } \
+    for (i = cvt->len_cvt / sizeof (float); i; --i) {
+        src--;
+        dst -= 2;
+        dst[0] = dst[1] = *src;
     }
 
-    /* this function only cares about typesize, and data as a block of bits. */
-    switch (SDL_AUDIO_BITSIZE(format)) {
-    case 8:
-        dup_chans_1_to_2(Uint8);
-        break;
-    case 16:
-        dup_chans_1_to_2(Uint16);
-        break;
-    case 32:
-        dup_chans_1_to_2(Uint32);
-        break;
+    cvt->len_cvt *= 2;
+    if (cvt->filters[++cvt->filter_index]) {
+        cvt->filters[cvt->filter_index] (cvt, format);
     }
+}
 
-#undef dup_chans_1_to_2
 
-    cvt->len_cvt *= 2;
+/* Upmix stereo to a pseudo-5.1 stream */
+static void SDLCALL
+SDL_ConvertStereoTo51(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+{
+    int i;
+    float lf, rf, ce;
+    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
+    float *dst = (float *) (cvt->buf + cvt->len_cvt * 3);
+
+    LOG_DEBUG_CONVERT("stereo", "5.1");
+    SDL_assert(format == AUDIO_F32SYS);
+
+    for (i = cvt->len_cvt / (sizeof(float) * 2); i; --i) {
+        dst -= 6;
+        src -= 2;
+        lf = src[0];
+        rf = src[1];
+        ce = (lf + rf) * 0.5f;
+        /* !!! FIXME: FL and FR may clip */
+        dst[0] = lf + (lf - ce);  /* FL */
+        dst[1] = rf + (rf - ce);  /* FR */
+        dst[2] = ce;  /* FC */
+        dst[3] = 0;   /* LFE (only meant for special LFE effects) */
+        dst[4] = lf;  /* BL */
+        dst[5] = rf;  /* BR */
+    }
+
+    cvt->len_cvt *= 3;
     if (cvt->filters[++cvt->filter_index]) {
         cvt->filters[cvt->filter_index] (cvt, format);
     }
 }
 
 
-/* Duplicate a stereo channel to a pseudo-5.1 stream */
+/* Upmix quad to a pseudo-5.1 stream */
 static void SDLCALL
-SDL_ConvertSurround(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_ConvertQuadTo51(SDL_AudioCVT * cvt, SDL_AudioFormat format)
 {
     int i;
+    float lf, rf, lb, rb, ce;
+    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
+    float *dst = (float *) (cvt->buf + cvt->len_cvt * 3 / 2);
+
+    LOG_DEBUG_CONVERT("quad", "5.1");
+    SDL_assert(format == AUDIO_F32SYS);
+    SDL_assert(cvt->len_cvt % (sizeof(float) * 4) == 0);
+
+    for (i = cvt->len_cvt / (sizeof(float) * 4); i; --i) {
+        dst -= 6;
+        src -= 4;
+        lf = src[0];
+        rf = src[1];
+        lb = src[2];
+        rb = src[3];
+        ce = (lf + rf) * 0.5f;
+        /* !!! FIXME: FL and FR may clip */
+        dst[0] = lf + (lf - ce);  /* FL */
+        dst[1] = rf + (rf - ce);  /* FR */
+        dst[2] = ce;  /* FC */
+        dst[3] = 0;   /* LFE (only meant for special LFE effects) */
+        dst[4] = lb;  /* BL */
+        dst[5] = rb;  /* BR */
+    }
 
-#ifdef DEBUG_CONVERT
-    fprintf(stderr, "Converting stereo to surround\n");
-#endif
+    cvt->len_cvt = cvt->len_cvt * 3 / 2;
+    if (cvt->filters[++cvt->filter_index]) {
+        cvt->filters[cvt->filter_index] (cvt, format);
+    }
+}
 
-    switch (format & (SDL_AUDIO_MASK_SIGNED  |
-                      SDL_AUDIO_MASK_BITSIZE |
-                      SDL_AUDIO_MASK_DATATYPE)) {
-    case AUDIO_U8:
-        {
-            Uint8 *src, *dst, lf, rf, ce;
-
-            src = (Uint8 *) (cvt->buf + cvt->len_cvt);
-            dst = (Uint8 *) (cvt->buf + cvt->len_cvt * 3);
-            for (i = cvt->len_cvt; i; --i) {
-                dst -= 6;
-                src -= 2;
-                lf = src[0];
-                rf = src[1];
-                ce = (lf / 2) + (rf / 2);
-                dst[0] = lf;
-                dst[1] = rf;
-                dst[2] = lf - ce;
-                dst[3] = rf - ce;
-                dst[4] = ce;
-                dst[5] = ce;
-            }
-        }
-        break;
-
-    case AUDIO_S8:
-        {
-            Sint8 *src, *dst, lf, rf, ce;
-
-            src = (Sint8 *) cvt->buf + cvt->len_cvt;
-            dst = (Sint8 *) cvt->buf + cvt->len_cvt * 3;
-            for (i = cvt->len_cvt; i; --i) {
-                dst -= 6;
-                src -= 2;
-                lf = src[0];
-                rf = src[1];
-                ce = (lf / 2) + (rf / 2);
-                dst[0] = lf;
-                dst[1] = rf;
-                dst[2] = lf - ce;
-                dst[3] = rf - ce;
-                dst[4] = ce;
-                dst[5] = ce;
-            }
-        }
-        break;
-
-    case AUDIO_U16:
-        {
-            Uint8 *src, *dst;
-            Uint16 lf, rf, ce, lr, rr;
-
-            src = cvt->buf + cvt->len_cvt;
-            dst = cvt->buf + cvt->len_cvt * 3;
-
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    dst -= 12;
-                    src -= 4;
-                    lf = (Uint16) ((src[0] << 8) | src[1]);
-                    rf = (Uint16) ((src[2] << 8) | src[3]);
-                    ce = (lf / 2) + (rf / 2);
-                    rr = lf - ce;
-                    lr = rf - ce;
-                    dst[1] = (lf & 0xFF);
-                    dst[0] = ((lf >> 8) & 0xFF);
-                    dst[3] = (rf & 0xFF);
-                    dst[2] = ((rf >> 8) & 0xFF);
-
-                    dst[1 + 4] = (lr & 0xFF);
-                    dst[0 + 4] = ((lr >> 8) & 0xFF);
-                    dst[3 + 4] = (rr & 0xFF);
-                    dst[2 + 4] = ((rr >> 8) & 0xFF);
-
-                    dst[1 + 8] = (ce & 0xFF);
-                    dst[0 + 8] = ((ce >> 8) & 0xFF);
-                    dst[3 + 8] = (ce & 0xFF);
-                    dst[2 + 8] = ((ce >> 8) & 0xFF);
-                }
-            } else {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    dst -= 12;
-                    src -= 4;
-                    lf = (Uint16) ((src[1] << 8) | src[0]);
-                    rf = (Uint16) ((src[3] << 8) | src[2]);
-                    ce = (lf / 2) + (rf / 2);
-                    rr = lf - ce;
-                    lr = rf - ce;
-                    dst[0] = (lf & 0xFF);
-                    dst[1] = ((lf >> 8) & 0xFF);
-                    dst[2] = (rf & 0xFF);
-                    dst[3] = ((rf >> 8) & 0xFF);
-
-                    dst[0 + 4] = (lr & 0xFF);
-                    dst[1 + 4] = ((lr >> 8) & 0xFF);
-                    dst[2 + 4] = (rr & 0xFF);
-                    dst[3 + 4] = ((rr >> 8) & 0xFF);
-
-                    dst[0 + 8] = (ce & 0xFF);
-                    dst[1 + 8] = ((ce >> 8) & 0xFF);
-                    dst[2 + 8] = (ce & 0xFF);
-                    dst[3 + 8] = ((ce >> 8) & 0xFF);
-                }
-            }
-        }
-        break;
-
-    case AUDIO_S16:
-        {
-            Uint8 *src, *dst;
-            Sint16 lf, rf, ce, lr, rr;
-
-            src = cvt->buf + cvt->len_cvt;
-            dst = cvt->buf + cvt->len_cvt * 3;
-
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    dst -= 12;
-                    src -= 4;
-                    lf = (Sint16) ((src[0] << 8) | src[1]);
-                    rf = (Sint16) ((src[2] << 8) | src[3]);
-                    ce = (lf / 2) + (rf / 2);
-                    rr = lf - ce;
-                    lr = rf - ce;
-                    dst[1] = (lf & 0xFF);
-                    dst[0] = ((lf >> 8) & 0xFF);
-                    dst[3] = (rf & 0xFF);
-                    dst[2] = ((rf >> 8) & 0xFF);
-
-                    dst[1 + 4] = (lr & 0xFF);
-                    dst[0 + 4] = ((lr >> 8) & 0xFF);
-                    dst[3 + 4] = (rr & 0xFF);
-                    dst[2 + 4] = ((rr >> 8) & 0xFF);
-
-                    dst[1 + 8] = (ce & 0xFF);
-                    dst[0 + 8] = ((ce >> 8) & 0xFF);
-                    dst[3 + 8] = (ce & 0xFF);
-                    dst[2 + 8] = ((ce >> 8) & 0xFF);
-                }
-            } else {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    dst -= 12;
-                    src -= 4;
-                    lf = (Sint16) ((src[1] << 8) | src[0]);
-                    rf = (Sint16) ((src[3] << 8) | src[2]);
-                    ce = (lf / 2) + (rf / 2);
-                    rr = lf - ce;
-                    lr = rf - ce;
-                    dst[0] = (lf & 0xFF);
-                    dst[1] = ((lf >> 8) & 0xFF);
-                    dst[2] = (rf & 0xFF);
-                    dst[3] = ((rf >> 8) & 0xFF);
-
-                    dst[0 + 4] = (lr & 0xFF);
-                    dst[1 + 4] = ((lr >> 8) & 0xFF);
-                    dst[2 + 4] = (rr & 0xFF);
-                    dst[3 + 4] = ((rr >> 8) & 0xFF);
-
-                    dst[0 + 8] = (ce & 0xFF);
-                    dst[1 + 8] = ((ce >> 8) & 0xFF);
-                    dst[2 + 8] = (ce & 0xFF);
-                    dst[3 + 8] = ((ce >> 8) & 0xFF);
-                }
-            }
-        }
-        break;
-
-    case AUDIO_S32:
-        {
-            Sint32 lf, rf, ce;
-            const Uint32 *src = (const Uint32 *) (cvt->buf + cvt->len_cvt);
-            Uint32 *dst = (Uint32 *) (cvt->buf + cvt->len_cvt * 3);
-
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 8; i; --i) {
-                    dst -= 6;
-                    src -= 2;
-                    lf = (Sint32) SDL_SwapBE32(src[0]);
-                    rf = (Sint32) SDL_SwapBE32(src[1]);
-                    ce = (lf / 2) + (rf / 2);
-                    dst[0] = SDL_SwapBE32((Uint32) lf);
-                    dst[1] = SDL_SwapBE32((Uint32) rf);
-                    dst[2] = SDL_SwapBE32((Uint32) (lf - ce));
-                    dst[3] = SDL_SwapBE32((Uint32) (rf - ce));
-                    dst[4] = SDL_SwapBE32((Uint32) ce);
-                    dst[5] = SDL_SwapBE32((Uint32) ce);
-                }
-            } else {
-                for (i = cvt->len_cvt / 8; i; --i) {
-                    dst -= 6;
-                    src -= 2;
-                    lf = (Sint32) SDL_SwapLE32(src[0]);
-                    rf = (Sint32) SDL_SwapLE32(src[1]);
-                    ce = (lf / 2) + (rf / 2);
-                    dst[0] = src[0];
-                    dst[1] = src[1];
-                    dst[2] = SDL_SwapLE32((Uint32) (lf - ce));
-                    dst[3] = SDL_SwapLE32((Uint32) (rf - ce));
-                    dst[4] = SDL_SwapLE32((Uint32) ce);
-                    dst[5] = SDL_SwapLE32((Uint32) ce);
-                }
-            }
-        }
-        break;
-
-    case AUDIO_F32:
-        {
-            float lf, rf, ce;
-            const float *src = (const float *) (cvt->buf + cvt->len_cvt);
-            float *dst = (float *) (cvt->buf + cvt->len_cvt * 3);
-
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 8; i; --i) {
-                    dst -= 6;
-                    src -= 2;
-                    lf = SDL_SwapFloatBE(src[0]);
-                    rf = SDL_SwapFloatBE(src[1]);
-                    ce = (lf * 0.5f) + (rf * 0.5f);
-                    dst[0] = src[0];
-                    dst[1] = src[1];
-                    dst[2] = SDL_SwapFloatBE(lf - ce);
-                    dst[3] = SDL_SwapFloatBE(rf - ce);
-                    dst[4] = dst[5] = SDL_SwapFloatBE(ce);
-                }
-            } else {
-                for (i = cvt->len_cvt / 8; i; --i) {
-                    dst -= 6;
-                    src -= 2;
-                    lf = SDL_SwapFloatLE(src[0]);
-                    rf = SDL_SwapFloatLE(src[1]);
-                    ce = (lf * 0.5f) + (rf * 0.5f);
-                    dst[0] = src[0];
-                    dst[1] = src[1];
-                    dst[2] = SDL_SwapFloatLE(lf - ce);
-                    dst[3] = SDL_SwapFloatLE(rf - ce);
-                    dst[4] = dst[5] = SDL_SwapFloatLE(ce);
-                }
-            }
-        }
-        break;
 
+/* Upmix stereo to a pseudo-4.0 stream (by duplication) */
+static void SDLCALL
+SDL_ConvertStereoToQuad(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+{
+    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
+    float *dst = (float *) (cvt->buf + cvt->len_cvt * 2);
+    float lf, rf;
+    int i;
+
+    LOG_DEBUG_CONVERT("stereo", "quad");
+    SDL_assert(format == AUDIO_F32SYS);
+
+    for (i = cvt->len_cvt / (sizeof(float) * 2); i; --i) {
+        dst -= 4;
+        src -= 2;
+        lf = src[0];
+        rf = src[1];
+        dst[0] = lf;  /* FL */
+        dst[1] = rf;  /* FR */
+        dst[2] = lf;  /* BL */
+        dst[3] = rf;  /* BR */
     }
-    cvt->len_cvt *= 3;
+
+    cvt->len_cvt *= 2;
     if (cvt->filters[++cvt->filter_index]) {
         cvt->filters[cvt->filter_index] (cvt, format);
     }
 }
 
 
-/* Duplicate a stereo channel to a pseudo-4.0 stream */
+/* Upmix 5.1 to 7.1 */
 static void SDLCALL
-SDL_ConvertSurround_4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert51To71(SDL_AudioCVT * cvt, SDL_AudioFormat format)
 {
+    float lf, rf, lb, rb, ls, rs;
     int i;
+    const float *src = (const float *) (cvt->buf + cvt->len_cvt);
+    float *dst = (float *) (cvt->buf + cvt->len_cvt * 4 / 3);
+
+    LOG_DEBUG_CONVERT("5.1", "7.1");
+    SDL_assert(format == AUDIO_F32SYS);
+    SDL_assert(cvt->len_cvt % (sizeof(float) * 6) == 0);
+
+    for (i = cvt->len_cvt / (sizeof(float) * 6); i; --i) {
+        dst -= 8;
+        src -= 6;
+        lf = src[0];
+        rf = src[1];
+        lb = src[4];
+        rb = src[5];
+        ls = (lf + lb) * 0.5f;
+        rs = (rf + rb) * 0.5f;
+        /* !!! FIXME: these four may clip */
+        lf += lf - ls;
+        rf += rf - ls;
+        lb += lb - ls;
+        rb += rb - ls;
+        dst[3] = src[3];  /* LFE */
+        dst[2] = src[2];  /* FC */
+        dst[7] = rs; /* SR */
+        dst[6] = ls; /* SL */
+        dst[5] = rb;  /* BR */
+        dst[4] = lb;  /* BL */
+        dst[1] = rf;  /* FR */
+        dst[0] = lf;  /* FL */
+    }
 
-#ifdef DEBUG_CONVERT
-    fprintf(stderr, "Converting stereo to quad\n");
-#endif
+    cvt->len_cvt = cvt->len_cvt * 4 / 3;
 
-    switch (format & (SDL_AUDIO_MASK_SIGNED |
-                      SDL_AUDIO_MASK_BITSIZE |
-                      SDL_AUDIO_MASK_DATATYPE)) {
-    case AUDIO_U8:
-        {
-            Uint8 *src, *dst, lf, rf, ce;
-
-            src = (Uint8 *) (cvt->buf + cvt->len_cvt);
-            dst = (Uint8 *) (cvt->buf + cvt->len_cvt * 2);
-            for (i = cvt->len_cvt; i; --i) {
-                dst -= 4;
-                src -= 2;
-                lf = src[0];
-                rf = src[1];
-                ce = (lf / 2) + (rf / 2);
-                dst[0] = lf;
-                dst[1] = rf;
-                dst[2] = lf - ce;
-                dst[3] = rf - ce;
-            }
-        }
-        break;
-
-    case AUDIO_S8:
-        {
-            Sint8 *src, *dst, lf, rf, ce;
-
-            src = (Sint8 *) cvt->buf + cvt->len_cvt;
-            dst = (Sint8 *) cvt->buf + cvt->len_cvt * 2;
-            for (i = cvt->len_cvt; i; --i) {
-                dst -= 4;
-                src -= 2;
-                lf = src[0];
-                rf = src[1];
-                ce = (lf / 2) + (rf / 2);
-                dst[0] = lf;
-                dst[1] = rf;
-                dst[2] = lf - ce;
-                dst[3] = rf - ce;
-            }
+    if (cvt->filters[++cvt->filter_index]) {
+        cvt->filters[cvt->filter_index] (cvt, format);
+    }
+}
+
+/* SDL's resampler uses a "bandlimited interpolation" algorithm:
+     https://ccrma.stanford.edu/~jos/resample/ */
+
+#define RESAMPLER_ZERO_CROSSINGS 5
+#define RESAMPLER_BITS_PER_SAMPLE 16
+#define RESAMPLER_SAMPLES_PER_ZERO_CROSSING  (1 << ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1))
+#define RESAMPLER_FILTER_SIZE ((RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS) + 1)
+
+/* This is a "modified" bessel function, so you can't use POSIX j0() */
+static double
+bessel(const double x)
+{
+    const double xdiv2 = x / 2.0;
+    double i0 = 1.0f;
+    double f = 1.0f;
+    int i = 1;
+
+    while (SDL_TRUE) {
+        const double diff = SDL_pow(xdiv2, i * 2) / SDL_pow(f, 2);
+        if (diff < 1.0e-21f) {
+            break;
         }
-        break;
-
-    case AUDIO_U16:
-        {
-            Uint8 *src, *dst;
-            Uint16 lf, rf, ce, lr, rr;
-
-            src = cvt->buf + cvt->len_cvt;
-            dst = cvt->buf + cvt->len_cvt * 2;
-
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    dst -= 8;
-                    src -= 4;
-                    lf = (Uint16) ((src[0] << 8) | src[1]);
-                    rf = (Uint16) ((src[2] << 8) | src[3]);
-                    ce = (lf / 2) + (rf / 2);
-                    rr = lf - ce;
-                    lr = rf - ce;
-                    dst[1] = (lf & 0xFF);
-                    dst[0] = ((lf >> 8) & 0xFF);
-                    dst[3] = (rf & 0xFF);
-                    dst[2] = ((rf >> 8) & 0xFF);
-
-                    dst[1 + 4] = (lr & 0xFF);
-                    dst[0 + 4] = ((lr >> 8) & 0xFF);
-                    dst[3 + 4] = (rr & 0xFF);
-                    dst[2 + 4] = ((rr >> 8) & 0xFF);
-                }
-            } else {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    dst -= 8;
-                    src -= 4;
-                    lf = (Uint16) ((src[1] << 8) | src[0]);
-                    rf = (Uint16) ((src[3] << 8) | src[2]);
-                    ce = (lf / 2) + (rf / 2);
-                    rr = lf - ce;
-                    lr = rf - ce;
-                    dst[0] = (lf & 0xFF);
-                    dst[1] = ((lf >> 8) & 0xFF);
-                    dst[2] = (rf & 0xFF);
-                    dst[3] = ((rf >> 8) & 0xFF);
-
-                    dst[0 + 4] = (lr & 0xFF);
-                    dst[1 + 4] = ((lr >> 8) & 0xFF);
-                    dst[2 + 4] = (rr & 0xFF);
-                    dst[3 + 4] = ((rr >> 8) & 0xFF);
-                }
-            }
+        i0 += diff;
+        i++;
+        f *= (double) i;
+    }
+
+    return i0;
+}
+
+/* build kaiser table with cardinal sine applied to it, and array of differences between elements. */
+static void
+kaiser_and_sinc(float *table, float *diffs, const int tablelen, const double beta)
+{
+    const int lenm1 = tablelen - 1;
+    const int lenm1div2 = lenm1 / 2;
+    int i;
+
+    table[0] = 1.0f;
+    for (i = 1; i < tablelen; i++) {
+        const double kaiser = bessel(beta * SDL_sqrt(1.0 - SDL_pow(((i - lenm1) / 2.0) / lenm1div2, 2.0))) / bessel(beta);
+        table[tablelen - i] = (float) kaiser;
+    }
+
+    for (i = 1; i < tablelen; i++) {
+        const float x = (((float) i) / ((float) RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) * ((float) M_PI);
+        table[i] *= SDL_sinf(x) / x;
+        diffs[i - 1] = table[i] - table[i - 1];
+    }
+    diffs[lenm1] = 0.0f;
+}
+
+
+static SDL_SpinLock ResampleFilterSpinlock = 0;
+static float *ResamplerFilter = NULL;
+static float *ResamplerFilterDifference = NULL;
+
+int
+SDL_PrepareResampleFilter(void)
+{
+    SDL_AtomicLock(&ResampleFilterSpinlock);
+    if (!ResamplerFilter) {
+        /* if dB > 50, beta=(0.1102 * (dB - 8.7)), according to Matlab. */
+        const double dB = 80.0;
+        const double beta = 0.1102 * (dB - 8.7);
+        const size_t alloclen = RESAMPLER_FILTER_SIZE * sizeof (float);
+
+        ResamplerFilter = (float *) SDL_malloc(alloclen);
+        if (!ResamplerFilter) {
+            SDL_AtomicUnlock(&ResampleFilterSpinlock);
+            return SDL_OutOfMemory();
         }
-        break;
-
-    case AUDIO_S16:
-        {
-            Uint8 *src, *dst;
-            Sint16 lf, rf, ce, lr, rr;
-
-            src = cvt->buf + cvt->len_cvt;
-            dst = cvt->buf + cvt->len_cvt * 2;
-
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    dst -= 8;
-                    src -= 4;
-                    lf = (Sint16) ((src[0] << 8) | src[1]);
-                    rf = (Sint16) ((src[2] << 8) | src[3]);
-                    ce = (lf / 2) + (rf / 2);
-                    rr = lf - ce;
-                    lr = rf - ce;
-                    dst[1] = (lf & 0xFF);
-                    dst[0] = ((lf >> 8) & 0xFF);
-                    dst[3] = (rf & 0xFF);
-                    dst[2] = ((rf >> 8) & 0xFF);
-
-                    dst[1 + 4] = (lr & 0xFF);
-                    dst[0 + 4] = ((lr >> 8) & 0xFF);
-                    dst[3 + 4] = (rr & 0xFF);
-                    dst[2 + 4] = ((rr >> 8) & 0xFF);
-                }
-            } else {
-                for (i = cvt->len_cvt / 4; i; --i) {
-                    dst -= 8;
-                    src -= 4;
-                    lf = (Sint16) ((src[1] << 8) | src[0]);
-                    rf = (Sint16) ((src[3] << 8) | src[2]);
-                    ce = (lf / 2) + (rf / 2);
-                    rr = lf - ce;
-                    lr = rf - ce;
-                    dst[0] = (lf & 0xFF);
-                    dst[1] = ((lf >> 8) & 0xFF);
-                    dst[2] = (rf & 0xFF);
-                    dst[3] = ((rf >> 8) & 0xFF);
-
-                    dst[0 + 4] = (lr & 0xFF);
-                    dst[1 + 4] = ((lr >> 8) & 0xFF);
-                    dst[2 + 4] = (rr & 0xFF);
-                    dst[3 + 4] = ((rr >> 8) & 0xFF);
-                }
-            }
+
+        ResamplerFilterDifference = (float *) SDL_malloc(alloclen);
+        if (!ResamplerFilterDifference) {
+            SDL_free(ResamplerFilter);
+            ResamplerFilter = NULL;
+            SDL_AtomicUnlock(&ResampleFilterSpinlock);
+            return SDL_OutOfMemory();
         }
-        break;
-
-    case AUDIO_S32:
-        {
-            const Uint32 *src = (const Uint32 *) (cvt->buf + cvt->len_cvt);
-            Uint32 *dst = (Uint32 *) (cvt->buf + cvt->len_cvt * 2);
-            Sint32 lf, rf, ce;
-
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 8; i; --i) {
-                    dst -= 4;
-                    src -= 2;
-                    lf = (Sint32) SDL_SwapBE32(src[0]);
-                    rf = (Sint32) SDL_SwapBE32(src[1]);
-                    ce = (lf / 2) + (rf / 2);
-                    dst[0] = src[0];
-                    dst[1] = src[1];
-                    dst[2] = SDL_SwapBE32((Uint32) (lf - ce));
-                    dst[3] = SDL_SwapBE32((Uint32) (rf - ce));
-                }
-            } else {
-                for (i = cvt->len_cvt / 8; i; --i) {
-                    dst -= 4;
-                    src -= 2;
-                    lf = (Sint32) SDL_SwapLE32(src[0]);
-                    rf = (Sint32) SDL_SwapLE32(src[1]);
-                    ce = (lf / 2) + (rf / 2);
-                    dst[0] = src[0];
-                    dst[1] = src[1];
-                    dst[2] = SDL_SwapLE32((Uint32) (lf - ce));
-                    dst[3] = SDL_SwapLE32((Uint32) (rf - ce));
-                }
+        kaiser_and_sinc(ResamplerFilter, ResamplerFilterDifference, RESAMPLER_FILTER_SIZE, beta);
+    }
+    SDL_AtomicUnlock(&ResampleFilterSpinlock);
+    return 0;
+}
+
+void
+SDL_FreeResampleFilter(void)
+{
+    SDL_free(ResamplerFilter);
+    SDL_free(ResamplerFilterDifference);
+    ResamplerFilter = NULL;
+    ResamplerFilterDifference = NULL;
+}
+
+static int
+ResamplerPadding(const int inrate, const int outrate)
+{
+    return (inrate > outrate) ? (int) SDL_ceil(((float) (RESAMPLER_SAMPLES_PER_ZERO_CROSSING * inrate) / ((float) outrate))) : RESAMPLER_SAMPLES_PER_ZERO_CROSSING;
+}
+
+/* lpadding and rpadding are expected to be buffers of (ResamplePadding(inrate, outrate) * chans * sizeof (float)) bytes. */
+static int
+SDL_ResampleAudio(const int chans, const int inrate, const int outrate,
+                        float *lpadding, float *rpadding, const float *inbuf,
+                        const int inbuflen, float *outbuf, const int outbuflen)
+{
+    const float outtimeincr = 1.0f / ((float) outrate);
+    const float ratio = ((float) outrate) / ((float) inrate);
+    const int paddinglen = ResamplerPadding(inrate, outrate);
+    const int framelen = chans * (int)sizeof (float);
+    const int inframes = inbuflen / framelen;
+    const int wantedoutframes = (int) ((inbuflen / framelen) * ratio);  /* outbuflen isn't total to write, it's total available. */
+    const int maxoutframes = outbuflen / framelen;
+    const int outframes = (wantedoutframes < maxoutframes) ? wantedoutframes : maxoutframes;
+    float *dst = outbuf;
+    float outtime = 0.0f;
+    int i, j, chan;
+
+    for (i = 0; i < outframes; i++) {
+        const int srcindex = (int) (outtime * inrate);
+        const float finrate = (float) inrate;
+        const float intime = ((float) srcindex) / finrate;
+        const float innexttime = ((float) (srcindex + 1)) / finrate;
+
+        const float interpolation1 = 1.0f - (innexttime - outtime) / (innexttime - intime);
+        const int filterindex1 = (int) (interpolation1 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING);
+        const float interpolation2 = 1.0f - interpolation1;
+        const int filterindex2 = interpolation2 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING;
+
+        for (chan = 0; chan < chans; chan++) {
+            float outsample = 0.0f;
+
+            /* do this twice to calculate the sample, once for the "left wing" and then same for the right. */
+            /* !!! FIXME: do both wings in one loop */
+            for (j = 0; (filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) {
+                const int srcframe = srcindex - j;
+                /* !!! FIXME: we can bubble this conditional out of here by doing a pre loop. */
+                const float insample = (srcframe < 0) ? lpadding[((paddinglen + srcframe) * chans) + chan] : inbuf[(srcframe * chans) + chan];
+                outsample += (insample * (ResamplerFilter[filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)] + (interpolation1 * ResamplerFilterDifference[filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)])));
             }
-        }
-        break;
-
-    case AUDIO_F32:
-        {
-            const float *src = (const float *) (cvt->buf + cvt->len_cvt);
-            float *dst = (float *) (cvt->buf + cvt->len_cvt * 2);
-            float lf, rf, ce;
-
-            if (SDL_AUDIO_ISBIGENDIAN(format)) {
-                for (i = cvt->len_cvt / 8; i; --i) {
-                    dst -= 4;
-                    src -= 2;
-                    lf = SDL_SwapFloatBE(src[0]);
-                    rf = SDL_SwapFloatBE(src[1]);
-                    ce = (lf / 2) + (rf / 2);
-                    dst[0] = src[0];
-                    dst[1] = src[1];
-                    dst[2] = SDL_SwapFloatBE(lf - ce);
-                    dst[3] = SDL_SwapFloatBE(rf - ce);
-                }
-            } else {
-                for (i = cvt->len_cvt / 8; i; --i) {
-                    dst -= 4;
-                    src -= 2;
-                    lf = SDL_SwapFloatLE(src[0]);
-                    rf = SDL_SwapFloatLE(src[1]);
-                    ce = (lf / 2) + (rf / 2);
-                    dst[0] = src[0];
-                    dst[1] = src[1];
-                    dst[2] = SDL_SwapFloatLE(lf - ce);
-                    dst[3] = SDL_SwapFloatLE(rf - ce);
-                }
+
+            for (j = 0; (filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) {
+                const int srcframe = srcindex + 1 + j;
+                /* !!! FIXME: we can bubble this conditional out of here by doing a post loop. */
+                const float insample = (srcframe >= inframes) ? rpadding[((srcframe - inframes) * chans) + chan] : inbuf[(srcframe * chans) + chan];
+                outsample += (insample * (ResamplerFilter[filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)] + (interpolation2 * ResamplerFilterDifference[filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)])));
             }
+            *(dst++) = outsample;
         }
-        break;
-    }
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
+
+        outtime += outtimeincr;
     }
-}
 
+    return outframes * chans * sizeof (float);
+}
 
 int
 SDL_ConvertAudio(SDL_AudioCVT * cvt)
@@ -818,68 +534,145 @@ SDL_ConvertAudio(SDL_AudioCVT * cvt)
 
     /* Make sure there's data to convert */
     if (cvt->buf == NULL) {
-        SDL_SetError("No buffer allocated for conversion");
-        return (-1);
+        return SDL_SetError("No buffer allocated for conversion");
     }
+
     /* Return okay if no conversion is necessary */
     cvt->len_cvt = cvt->len;
     if (cvt->filters[0] == NULL) {
-        return (0);
+        return 0;
     }
 
     /* Set up the conversion and go! */
     cvt->filter_index = 0;
     cvt->filters[0] (cvt, cvt->src_format);
-    return (0);
+    return 0;
 }
 
-
-static SDL_AudioFilter
-SDL_HandTunedTypeCVT(SDL_AudioFormat src_fmt, SDL_AudioFormat dst_fmt)
+static void SDLCALL
+SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
-    /*
-     * Fill in any future conversions that are specialized to a
-     *  processor, platform, compiler, or library here.
-     */
+#if DEBUG_CONVERT
+    printf("Converting byte order\n");
+#endif
+
+    switch (SDL_AUDIO_BITSIZE(format)) {
+        #define CASESWAP(b) \
+            case b: { \
+                Uint##b *ptr = (Uint##b *) cvt->buf; \
+                int i; \
+                for (i = cvt->len_cvt / sizeof (*ptr); i; --i, ++ptr) { \
+                    *ptr = SDL_Swap##b(*ptr); \
+                } \
+                break; \
+            }
+
+        CASESWAP(16);
+        CASESWAP(32);
+        CASESWAP(64);
+
+        #undef CASESWAP
 
-    return NULL;                /* no specialized converter code available. */
+        default: SDL_assert(!"unhandled byteswap datatype!"); break;
+    }
+
+    if (cvt->filters[++cvt->filter_index]) {
+        /* flip endian flag for data. */
+        if (format & SDL_AUDIO_MASK_ENDIAN) {
+            format &= ~SDL_AUDIO_MASK_ENDIAN;
+        } else {
+            format |= SDL_AUDIO_MASK_ENDIAN;
+        }
+        cvt->filters[cvt->filter_index](cvt, format);
+    }
 }
 
+static int
+SDL_AddAudioCVTFilter(SDL_AudioCVT *cvt, const SDL_AudioFilter filter)
+{
+    if (cvt->filter_index >= SDL_AUDIOCVT_MAX_FILTERS) {
+        return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS);
+    }
+    if (filter == NULL) {
+        return SDL_SetError("Audio filter pointer is NULL");
+    }
+    cvt->filters[cvt->filter_index++] = filter;
+    cvt->filters[cvt->filter_index] = NULL; /* Moving terminator */
+    return 0;
+}
 
-/*
- * Find a converter between two data types. We try to select a hand-tuned
- *  asm/vectorized/optimized function first, and then fallback to an
- *  autogenerated function that is customized to convert between two
- *  specific data types.
- */
 static int
-SDL_BuildAudioTypeCVT(SDL_AudioCVT * cvt,
-                      SDL_AudioFormat src_fmt, SDL_AudioFormat dst_fmt)
+SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt)
 {
-    if (src_fmt != dst_fmt) {
+    int retval = 0;  /* 0 == no conversion necessary. */
+
+    if ((SDL_AUDIO_ISBIGENDIAN(src_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) {
+        if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
+            return -1;
+        }
+        retval = 1;  /* added a converter. */
+    }
+
+    if (!SDL_AUDIO_ISFLOAT(src_fmt)) {
         const Uint16 src_bitsize = SDL_AUDIO_BITSIZE(src_fmt);
+        const Uint16 dst_bitsize = 32;
+        SDL_AudioFilter filter = NULL;
+
+        switch (src_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
+            case AUDIO_S8: filter = SDL_Convert_S8_to_F32; break;
+            case AUDIO_U8: filter = SDL_Convert_U8_to_F32; break;
+            case AUDIO_S16: filter = SDL_Convert_S16_to_F32; break;
+            case AUDIO_U16: filter = SDL_Convert_U16_to_F32; break;
+            case AUDIO_S32: filter = SDL_Convert_S32_to_F32; break;
+            default: SDL_assert(!"Unexpected audio format!"); break;
+        }
+
+        if (!filter) {
+            return SDL_SetError("No conversion from source format to float available");
+        }
+
+        if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
+            return -1;
+        }
+        if (src_bitsize < dst_bitsize) {
+            const int mult = (dst_bitsize / src_bitsize);
+            cvt->len_mult *= mult;
+            cvt->len_ratio *= mult;
+        } else if (src_bitsize > dst_bitsize) {
+            cvt->len_ratio /= (src_bitsize / dst_bitsize);
+        }
+
+        retval = 1;  /* added a converter. */
+    }
+
+    return retval;
+}
+
+static int
+SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt)
+{
+    int retval = 0;  /* 0 == no conversion necessary. */
+
+    if (!SDL_AUDIO_ISFLOAT(dst_fmt)) {
         const Uint16 dst_bitsize = SDL_AUDIO_BITSIZE(dst_fmt);
-        SDL_AudioFilter filter = SDL_HandTunedTypeCVT(src_fmt, dst_fmt);
-
-        /* No hand-tuned converter? Try the autogenerated ones. */
-        if (filter == NULL) {
-            int i;
-            for (i = 0; sdl_audio_type_filters[i].filter != NULL; i++) {
-                const SDL_AudioTypeFilters *filt = &sdl_audio_type_filters[i];
-                if ((filt->src_fmt == src_fmt) && (filt->dst_fmt == dst_fmt)) {
-                    filter = filt->filter;
-                    break;
-                }
-            }
+        const Uint16 src_bitsize = 32;
+        SDL_AudioFilter filter = NULL;
+        switch (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
+            case AUDIO_S8: filter = SDL_Convert_F32_to_S8; break;
+            case AUDIO_U8: filter = SDL_Convert_F32_to_U8; break;
+            case AUDIO_S16: filter = SDL_Convert_F32_to_S16; break;
+            case AUDIO_U16: filter = SDL_Convert_F32_to_U16; break;
+            case AUDIO_S32: filter = SDL_Convert_F32_to_S32; break;
+            default: SDL_assert(!"Unexpected audio format!"); break;
+        }
 
-            if (filter == NULL) {
-                SDL_SetError("No conversion available for these formats");
-                return -1;
-            }
+        if (!filter) {
+            return SDL_SetError("No conversion from float to destination format available");
         }
 
-        /* Update (cvt) with filter details... */
-        cvt->filters[cvt->filter_index++] = filter;
+        if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
+            return -1;
+        }
         if (src_bitsize < dst_bitsize) {
             const int mult = (dst_bitsize / src_bitsize);
             cvt->len_mult *= mult;
@@ -887,111 +680,183 @@ SDL_BuildAudioTypeCVT(SDL_AudioCVT * cvt,
         } else if (src_bitsize > dst_bitsize) {
             cvt->len_ratio /= (src_bitsize / dst_bitsize);
         }
+        retval = 1;  /* added a converter. */
+    }
 
-        return 1;               /* added a converter. */
+    if ((SDL_AUDIO_ISBIGENDIAN(dst_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) {
+        if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
+            return -1;
+        }
+        retval = 1;  /* added a converter. */
     }
 
-    return 0;                   /* no conversion necessary. */
+    return retval;
+}
+
+static void
+SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format)
+{
+    /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator).
+       !!! FIXME in 2.1:   We need to store data for this resampler, because the cvt structure doesn't store the original sample rates,
+       !!! FIXME in 2.1:   so we steal the ninth and tenth slot.  :( */
+    const int inrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1];
+    const int outrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS];
+    const float *src = (const float *) cvt->buf;
+    const int srclen = cvt->len_cvt;
+    /*float *dst = (float *) cvt->buf;
+    const int dstlen = (cvt->len * cvt->len_mult);*/
+    /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
+    float *dst = (float *) (cvt->buf + srclen);
+    const int dstlen = (cvt->len * cvt->len_mult) - srclen;
+    const int paddingsamples = (ResamplerPadding(inrate, outrate) * chans);
+    float *padding;
+
+    SDL_assert(format == AUDIO_F32SYS);
+
+    /* we keep no streaming state here, so pad with silence on both ends. */
+    padding = SDL_stack_alloc(float, paddingsamples);
+    if (!padding) {
+        SDL_OutOfMemory();
+        return;
+    }
+    SDL_memset(padding, '\0', paddingsamples * sizeof (float));
+
+    cvt->len_cvt = SDL_ResampleAudio(chans, inrate, outrate, padding, padding, src, srclen, dst, dstlen);
+
+    SDL_stack_free(padding);
+
+    SDL_memcpy(cvt->buf, dst, cvt->len_cvt);  /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
+
+    if (cvt->filters[++cvt->filter_index]) {
+        cvt->filters[cvt->filter_index](cvt, format);
+    }
 }
 
+/* !!! FIXME: We only have this macro salsa because SDL_AudioCVT doesn't
+   !!! FIXME:  store channel info, so we have to have function entry
+   !!! FIXME:  points for each supported channel count and multiple
+   !!! FIXME:  vs arbitrary. When we rev the ABI, clean this up. */
+#define RESAMPLER_FUNCS(chans) \
+    static void SDLCALL \
+    SDL_ResampleCVT_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) { \
+        SDL_ResampleCVT(cvt, chans, format); \
+    }
+RESAMPLER_FUNCS(1)
+RESAMPLER_FUNCS(2)
+RESAMPLER_FUNCS(4)
+RESAMPLER_FUNCS(6)
+RESAMPLER_FUNCS(8)
+#undef RESAMPLER_FUNCS
 
 static SDL_AudioFilter
-SDL_HandTunedResampleCVT(SDL_AudioCVT * cvt, int dst_channels,
-                         int src_rate, int dst_rate)
+ChooseCVTResampler(const int dst_channels)
 {
-    /*
-     * Fill in any future conversions that are specialized to a
-     *  processor, platform, compiler, or library here.
-     */
+    switch (dst_channels) {
+        case 1: return SDL_ResampleCVT_c1;
+        case 2: return SDL_ResampleCVT_c2;
+        case 4: return SDL_ResampleCVT_c4;
+        case 6: return SDL_ResampleCVT_c6;
+        case 8: return SDL_ResampleCVT_c8;
+        default: break;
+    }
 
-    return NULL;                /* no specialized converter code available. */
+    return NULL;
 }
 
 static int
-SDL_FindFrequencyMultiple(const int src_rate, const int dst_rate)
+SDL_BuildAudioResampleCVT(SDL_AudioCVT * cvt, const int dst_channels,
+                          const int src_rate, const int dst_rate)
 {
-    int retval = 0;
+    SDL_AudioFilter filter;
 
-    /* If we only built with the arbitrary resamplers, ignore multiples. */
-#if !LESS_RESAMPLERS
-    int lo, hi;
-    int div;
+    if (src_rate == dst_rate) {
+        return 0;  /* no conversion necessary. */
+    }
 
-    SDL_assert(src_rate != 0);
-    SDL_assert(dst_rate != 0);
-    SDL_assert(src_rate != dst_rate);
+    filter = ChooseCVTResampler(dst_channels);
+    if (filter == NULL) {
+        return SDL_SetError("No conversion available for these rates");
+    }
+
+    if (SDL_PrepareResampleFilter() < 0) {
+        return -1;
+    }
+
+    /* Update (cvt) with filter details... */
+    if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
+        return -1;
+    }
+
+    /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator).
+       !!! FIXME in 2.1:   We need to store data for this resampler, because the cvt structure doesn't store the original sample rates,
+       !!! FIXME in 2.1:   so we steal the ninth and tenth slot.  :( */
+    if (cvt->filter_index >= (SDL_AUDIOCVT_MAX_FILTERS-2)) {
+        return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS-2);
+    }
+    cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1] = (SDL_AudioFilter) (size_t) src_rate;
+    cvt->filters[SDL_AUDIOCVT_MAX_FILTERS] = (SDL_AudioFilter) (size_t) dst_rate;
 
     if (src_rate < dst_rate) {
-        lo = src_rate;
-        hi = dst_rate;
+        const double mult = ((double) dst_rate) / ((double) src_rate);
+        cvt->len_mult *= (int) SDL_ceil(mult);
+        cvt->len_ratio *= mult;
     } else {
-        lo = dst_rate;
-        hi = src_rate;
+        cvt->len_ratio /= ((double) src_rate) / ((double) dst_rate);
     }
 
-    /* zero means "not a supported multiple" ... we only do 2x and 4x. */
-    if ((hi % lo) != 0)
-        return 0;               /* not a multiple. */
+    /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
+    /* the buffer is big enough to hold the destination now, but
+       we need it large enough to hold a separate scratch buffer. */
+    cvt->len_mult *= 2;
 
-    div = hi / lo;
-    retval = ((div == 2) || (div == 4)) ? div : 0;
-#endif
-
-    return retval;
+    return 1;               /* added a converter. */
 }
 
-static int
-SDL_BuildAudioResampleCVT(SDL_AudioCVT * cvt, int dst_channels,
-                          int src_rate, int dst_rate)
+static SDL_bool
+SDL_SupportedAudioFormat(const SDL_AudioFormat fmt)
 {
-    if (src_rate != dst_rate) {
-        SDL_AudioFilter filter = SDL_HandTunedResampleCVT(cvt, dst_channels,
-                                                          src_rate, dst_rate);
-
-        /* No hand-tuned converter? Try the autogenerated ones. */
-        if (filter == NULL) {
-            int i;
-            const int upsample = (src_rate < dst_rate) ? 1 : 0;
-            const int multiple =
-                SDL_FindFrequencyMultiple(src_rate, dst_rate);
-
-            for (i = 0; sdl_audio_rate_filters[i].filter != NULL; i++) {
-                const SDL_AudioRateFilters *filt = &sdl_audio_rate_filters[i];
-                if ((filt->fmt == cvt->dst_format) &&
-                    (filt->channels == dst_channels) &&
-                    (filt->upsample == upsample) &&
-                    (filt->multiple == multiple)) {
-                    filter = filt->filter;
-                    break;
-                }
-            }
-
-            if (filter == NULL) {
-                SDL_SetError("No conversion available for these rates");
-                return -1;
-            }
-        }
+    switch (fmt) {
+        case AUDIO_U8:
+        case AUDIO_S8:
+        case AUDIO_U16LSB:
+        case AUDIO_S16LSB:
+        case AUDIO_U16MSB:
+        case AUDIO_S16MSB:
+        case AUDIO_S32LSB:
+        case AUDIO_S32MSB:
+        case AUDIO_F32LSB:
+        case AUDIO_F32MSB:
+            return SDL_TRUE;  /* supported. */
+
+        default:
+            break;
+    }
 
-        /* Update (cvt) with filter details... */
-        cvt->filters[cvt->filter_index++] = filter;
-        if (src_rate < dst_rate) {
-            const double mult = ((double) dst_rate) / ((double) src_rate);
-            cvt->len_mult *= (int) SDL_ceil(mult);
-            cvt->len_ratio *= mult;
-        } else {
-            cvt->len_ratio /= ((double) src_rate) / ((double) dst_rate);
-        }
+    return SDL_FALSE;  /* unsupported. */
+}
 
-        return 1;               /* added a converter. */
+static SDL_bool
+SDL_SupportedChannelCount(const int channels)
+{
+    switch (channels) {
+        case 1:  /* mono */
+        case 2:  /* stereo */
+        case 4:  /* quad */
+        case 6:  /* 5.1 */
+        case 8:  /* 7.1 */
+          return SDL_TRUE;  /* supported. */
+
+        default:
+            break;
     }
 
-    return 0;                   /* no conversion necessary. */
+    return SDL_FALSE;  /* unsupported. */
 }
 
 
 /* Creates a set of audio filters to convert from one format to another.
-   Returns -1 if the format conversion is not supported, 0 if there's
-   no conversion needed, or 1 if the audio filter is set up.
+   Returns 0 if no conversion is needed, 1 if the audio filter is set up,
+   or -1 if an error like invalid parameter, unsupported format, etc. occurred.
 */
 
 int
@@ -999,123 +864,633 @@ SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
                   SDL_AudioFormat src_fmt, Uint8 src_channels, int src_rate,
                   SDL_AudioFormat dst_fmt, Uint8 dst_channels, int dst_rate)
 {
-    /*
-     * !!! FIXME: reorder filters based on which grow/shrink the buffer.
-     * !!! FIXME: ideally, we should do everything that shrinks the buffer
-     * !!! FIXME: first, so we don't have to process as many bytes in a given
-     * !!! FIXME: filter and abuse the CPU cache less. This might not be as
-     * !!! FIXME: good in practice as it sounds in theory, though.
-     */
-
     /* Sanity check target pointer */
     if (cvt == NULL) {
         return SDL_InvalidParamError("cvt");
     }
 
-    /* there are no unsigned types over 16 bits, so catch this up front. */
-    if ((SDL_AUDIO_BITSIZE(src_fmt) > 16) && (!SDL_AUDIO_ISSIGNED(src_fmt))) {
+    /* Make sure we zero out the audio conversion before error checking */
+    SDL_zerop(cvt);
+
+    if (!SDL_SupportedAudioFormat(src_fmt)) {
         return SDL_SetError("Invalid source format");
-    }
-    if ((SDL_AUDIO_BITSIZE(dst_fmt) > 16) && (!SDL_AUDIO_ISSIGNED(dst_fmt))) {
+    } else if (!SDL_SupportedAudioFormat(dst_fmt)) {
         return SDL_SetError("Invalid destination format");
+    } else if (!SDL_SupportedChannelCount(src_channels)) {
+        return SDL_SetError("Invalid source channels");
+    } else if (!SDL_SupportedChannelCount(dst_channels)) {
+        return SDL_SetError("Invalid destination channels");
+    } else if (src_rate == 0) {
+        return SDL_SetError("Source rate is zero");
+    } else if (dst_rate == 0) {
+        return SDL_SetError("Destination rate is zero");
     }
 
-    /* prevent possible divisions by zero, etc. */
-    if ((src_channels == 0) || (dst_channels == 0)) {
-        return SDL_SetError("Source or destination channels is zero");
-    }
-    if ((src_rate == 0) || (dst_rate == 0)) {
-        return SDL_SetError("Source or destination rate is zero");
-    }
-#ifdef DEBUG_CONVERT
+#if DEBUG_CONVERT
     printf("Build format %04x->%04x, channels %u->%u, rate %d->%d\n",
            src_fmt, dst_fmt, src_channels, dst_channels, src_rate, dst_rate);
 #endif
 
     /* Start off with no conversion necessary */
-    SDL_zerop(cvt);
     cvt->src_format = src_fmt;
     cvt->dst_format = dst_fmt;
     cvt->needed = 0;
     cvt->filter_index = 0;
-    cvt->filters[0] = NULL;
+    SDL_zero(cvt->filters);
     cvt->len_mult = 1;
     cvt->len_ratio = 1.0;
     cvt->rate_incr = ((double) dst_rate) / ((double) src_rate);
 
+    /* Make sure we've chosen audio conversion functions (MMX, scalar, etc.) */
+    SDL_ChooseAudioConverters();
+
+    /* Type conversion goes like this now:
+        - byteswap to CPU native format first if necessary.
+        - convert to native Float32 if necessary.
+        - resample and change channel count if necessary.
+        - convert back to native format.
+        - byteswap back to foreign format if necessary.
+
+       The expectation is we can process data faster in float32
+       (possibly with SIMD), and making several passes over the same
+       buffer is likely to be CPU cache-friendly, avoiding the
+       biggest performance hit in modern times. Previously we had
+       (script-generated) custom converters for every data type and
+       it was a bloat on SDL compile times and final library size. */
+
+    /* see if we can skip float conversion entirely. */
+    if (src_rate == dst_rate && src_channels == dst_channels) {
+        if (src_fmt == dst_fmt) {
+            return 0;
+        }
+
+        /* just a byteswap needed? */
+        if ((src_fmt & ~SDL_AUDIO_MASK_ENDIAN) == (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN)) {
+            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
+                return -1;
+            }
+            cvt->needed = 1;
+            return 1;
+        }
+    }
+
     /* Convert data types, if necessary. Updates (cvt). */
-    if (SDL_BuildAudioTypeCVT(cvt, src_fmt, dst_fmt) == -1) {
+    if (SDL_BuildAudioTypeCVTToFloat(cvt, src_fmt) < 0) {
         return -1;              /* shouldn't happen, but just in case... */
     }
 
     /* Channel conversion */
-    if (src_channels != dst_channels) {
+    if (src_channels < dst_channels) {
+        /* Upmixing */
+        /* Mono -> Stereo [-> ...] */
         if ((src_channels == 1) && (dst_channels > 1)) {
-            cvt->filters[cvt->filter_index++] = SDL_ConvertStereo;
+            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertMonoToStereo) < 0) {
+                return -1;
+            }
             cvt->len_mult *= 2;
             src_channels = 2;
             cvt->len_ratio *= 2;
         }
-        if ((src_channels == 2) && (dst_channels == 6)) {
-            cvt->filters[cvt->filter_index++] = SDL_ConvertSurround;
+        /* [Mono ->] Stereo -> 5.1 [-> 7.1] */
+        if ((src_channels == 2) && (dst_channels >= 6)) {
+            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertStereoTo51) < 0) {
+                return -1;
+            }
             src_channels = 6;
             cvt->len_mult *= 3;
             cvt->len_ratio *= 3;
         }
+        /* Quad -> 5.1 [-> 7.1] */
+        if ((src_channels == 4) && (dst_channels >= 6)) {
+            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertQuadTo51) < 0) {
+                return -1;
+            }
+            src_channels = 6;
+            cvt->len_mult = (cvt->len_mult * 3 + 1) / 2;
+            cvt->len_ratio *= 1.5;
+        }
+        /* [[Mono ->] Stereo ->] 5.1 -> 7.1 */
+        if ((src_channels == 6) && (dst_channels == 8)) {
+            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51To71) < 0) {
+                return -1;
+            }
+            src_channels = 8;
+            cvt->len_mult = (cvt->len_mult * 4 + 2) / 3;
+            /* Should be numerically exact with every valid input to this
+               function */
+            cvt->len_ratio = cvt->len_ratio * 4 / 3;
+        }
+        /* [Mono ->] Stereo -> Quad */
         if ((src_channels == 2) && (dst_channels == 4)) {
-            cvt->filters[cvt->filter_index++] = SDL_ConvertSurround_4;
+            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertStereoToQuad) < 0) {
+                return -1;
+            }
             src_channels = 4;
             cvt->len_mult *= 2;
             cvt->len_ratio *= 2;
         }
-        while ((src_channels * 2) <= dst_channels) {
-            cvt->filters[cvt->filter_index++] = SDL_ConvertStereo;
-            cvt->len_mult *= 2;
-            src_channels *= 2;
-            cvt->len_ratio *= 2;
+    } else if (src_channels > dst_channels) {
+        /* Downmixing */
+        /* 7.1 -> 5.1 [-> Stereo [-> Mono]] */
+        /* 7.1 -> 5.1 [-> Quad] */
+        if ((src_channels == 8) && (dst_channels <= 6)) {
+            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert71To51) < 0) {
+                return -1;
+            }
+            src_channels = 6;
+            cvt->len_ratio *= 0.75;
         }
+        /* [7.1 ->] 5.1 -> Stereo [-> Mono] */
         if ((src_channels == 6) && (dst_channels <= 2)) {
-            cvt->filters[cvt->filter_index++] = SDL_ConvertStrip;
+            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51ToStereo) < 0) {
+                return -1;
+            }
             src_channels = 2;
             cvt->len_ratio /= 3;
         }
+        /* 5.1 -> Quad */
         if ((src_channels == 6) && (dst_channels == 4)) {
-            cvt->filters[cvt->filter_index++] = SDL_ConvertStrip_2;
+            if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51ToQuad) < 0) {
+                return -1;
+            }
             src_channels = 4;
-            cvt->len_ratio /= 2;
+            cvt->len_ratio = cvt->len_ratio * 2 / 3;
         }
-        /* This assumes that 4 channel audio is in the format:
-           Left {front/back} + Right {front/back}
-           so converting to L/R stereo works properly.
-         */
-        while (((src_channels % 2) == 0) &&
-               ((src_channels / 2) >= dst_channels)) {
-            cvt->filters[cvt->filter_index++] = SDL_ConvertMono;
-            src_channels /= 2;
+        /* Quad -> Stereo [-> Mono] */
+        if ((src_channels == 4) && (dst_channels <= 2)) {
+            if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertQuadToStereo) < 0) {
+                return -1;
+            }
+            src_channels = 2;
             cvt->len_ratio /= 2;
         }
-        if (src_channels != dst_channels) {
-            /* Uh oh.. */ ;
+        /* [... ->] Stereo -> Mono */
+        if ((src_channels == 2) && (dst_channels == 1)) {
+            SDL_AudioFilter filter = NULL;
+
+            #if HAVE_SSE3_INTRINSICS
+            if (SDL_HasSSE3()) {
+                filter = SDL_ConvertStereoToMono_SSE3;
+            }
+            #endif
+
+            if (!filter) {
+                filter = SDL_ConvertStereoToMono;
+            }
+
+            if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
+                return -1;
+            }
+
+            src_channels = 1;
+            cvt->len_ratio /= 2;
         }
     }
 
+    if (src_channels != dst_channels) {
+        /* All combinations of supported channel counts should have been
+           handled by now, but let's be defensive */
+      return SDL_SetError("Invalid channel combination");
+    }
+    
     /* Do rate conversion, if necessary. Updates (cvt). */
-    if (SDL_BuildAudioResampleCVT(cvt, dst_channels, src_rate, dst_rate) ==
-        -1) {
+    if (SDL_BuildAudioResampleCVT(cvt, dst_channels, src_rate, dst_rate) < 0) {
         return -1;              /* shouldn't happen, but just in case... */
     }
 
-    /* Set up the filter information */
-    if (cvt->filter_index != 0) {
-        cvt->needed = 1;
-        cvt->src_format = src_fmt;
-        cvt->dst_format = dst_fmt;
-        cvt->len = 0;
-        cvt->buf = NULL;
-        cvt->filters[cvt->filter_index] = NULL;
+    /* Move to final data type. */
+    if (SDL_BuildAudioTypeCVTFromFloat(cvt, dst_fmt) < 0) {
+        return -1;              /* shouldn't happen, but just in case... */
     }
+
+    cvt->needed = (cvt->filter_index != 0);
     return (cvt->needed);
 }
 
+typedef int (*SDL_ResampleAudioStreamFunc)(SDL_AudioStream *stream, const void *inbuf, const int inbuflen, void *outbuf, const int outbuflen);
+typedef void (*SDL_ResetAudioStreamResamplerFunc)(SDL_AudioStream *stream);
+typedef void (*SDL_CleanupAudioStreamResamplerFunc)(SDL_AudioStream *stream);
+
+struct SDL_AudioStream
+{
+    SDL_AudioCVT cvt_before_resampling;
+    SDL_AudioCVT cvt_after_resampling;
+    SDL_DataQueue *queue;
+    Uint8 *work_buffer_base;  /* maybe unaligned pointer from SDL_realloc(). */
+    int work_buffer_len;
+    int src_sample_frame_size;
+    SDL_AudioFormat src_format;
+    Uint8 src_channels;
+    int src_rate;
+    int dst_sample_frame_size;
+    SDL_AudioFormat dst_format;
+    Uint8 dst_channels;
+    int dst_rate;
+    double rate_incr;
+    Uint8 pre_resample_channels;
+    int packetlen;
+    void *resampler_state;
+    SDL_ResampleAudioStreamFunc resampler_func;
+    SDL_ResetAudioStreamResamplerFunc reset_resampler_func;
+    SDL_CleanupAudioStreamResamplerFunc cleanup_resampler_func;
+};
+
+static Uint8 *
+EnsureStreamBufferSize(SDL_AudioStream *stream, const int newlen)
+{
+    Uint8 *ptr;
+    size_t offset;
+
+    if (stream->work_buffer_len >= newlen) {
+        ptr = stream->work_buffer_base;
+    } else {
+        ptr = (Uint8 *) SDL_realloc(stream->work_buffer_base, newlen + 32);
+        if (!ptr) {
+            SDL_OutOfMemory();
+            return NULL;
+        }
+        /* Make sure we're aligned to 16 bytes for SIMD code. */
+        stream->work_buffer_base = ptr;
+        stream->work_buffer_len = newlen;
+    }
+
+    offset = ((size_t) ptr) & 15;
+    return offset ? ptr + (16 - offset) : ptr;
+}
+
+#ifdef HAVE_LIBSAMPLERATE_H
+static int
+SDL_ResampleAudioStream_SRC(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
+{
+    const float *inbuf = (const float *) _inbuf;
+    float *outbuf = (float *) _outbuf;
+    const int framelen = sizeof(float) * stream->pre_resample_channels;
+    SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
+    SRC_DATA data;
+    int result;
+
+    if (inbuf == ((const float *) outbuf)) {  /* libsamplerate can't work in-place. */
+        Uint8 *ptr = EnsureStreamBufferSize(stream, inbuflen + outbuflen);
+        if (ptr == NULL) {
+            SDL_OutOfMemory();
+            return 0;
+        }
+        SDL_memcpy(ptr + outbuflen, ptr, inbuflen);
+        inbuf = (const float *) (ptr + outbuflen);
+        outbuf = (float *) ptr;
+    }
+
+    data.data_in = (float *)inbuf; /* Older versions of libsamplerate had a non-const pointer, but didn't write to it */
+    data.input_frames = inbuflen / framelen;
+    data.input_frames_used = 0;
+
+    data.data_out = outbuf;
+    data.output_frames = outbuflen / framelen;
+
+    data.end_of_input = 0;
+    data.src_ratio = stream->rate_incr;
+
+    result = SRC_src_process(state, &data);
+    if (result != 0) {
+        SDL_SetError("src_process() failed: %s", SRC_src_strerror(result));
+        return 0;
+    }
+
+    /* If this fails, we need to store them off somewhere */
+    SDL_assert(data.input_frames_used == data.input_frames);
+
+    return data.output_frames_gen * (sizeof(float) * stream->pre_resample_channels);
+}
+
+static void
+SDL_ResetAudioStreamResampler_SRC(SDL_AudioStream *stream)
+{
+    SRC_src_reset((SRC_STATE *)stream->resampler_state);
+}
+
+static void
+SDL_CleanupAudioStreamResampler_SRC(SDL_AudioStream *stream)
+{
+    SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
+    if (state) {
+        SRC_src_delete(state);
+    }
+
+    stream->resampler_state = NULL;
+    stream->resampler_func = NULL;
+    stream->reset_resampler_func = NULL;
+    stream->cleanup_resampler_func = NULL;
+}
+
+static SDL_bool
+SetupLibSampleRateResampling(SDL_AudioStream *stream)
+{
+    int result = 0;
+    SRC_STATE *state = NULL;
+
+    if (SRC_available) {
+        state = SRC_src_new(SRC_converter, stream->pre_resample_channels, &result);
+        if (!state) {
+            SDL_SetError("src_new() failed: %s", SRC_src_strerror(result));
+        }
+    }
+
+    if (!state) {
+        SDL_CleanupAudioStreamResampler_SRC(stream);
+        return SDL_FALSE;
+    }
+
+    stream->resampler_state = state;
+    stream->resampler_func = SDL_ResampleAudioStream_SRC;
+    stream->reset_resampler_func = SDL_ResetAudioStreamResampler_SRC;
+    stream->cleanup_resampler_func = SDL_CleanupAudioStreamResampler_SRC;
+
+    return SDL_TRUE;
+}
+#endif /* HAVE_LIBSAMPLERATE_H */
+
+
+static int
+SDL_ResampleAudioStream(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
+{
+    const float *inbuf = (const float *) _inbuf;
+    float *outbuf = (float *) _outbuf;
+    const int chans = (int) stream->pre_resample_channels;
+    const int inrate = stream->src_rate;
+    const int outrate = stream->dst_rate;
+    const int paddingsamples = ResamplerPadding(inrate, outrate) * chans;
+    const int paddingbytes = paddingsamples * sizeof (float);
+    float *lpadding = (float *) stream->resampler_state;
+    float *rpadding;
+    int retval;
+
+    if (inbuf == ((const float *) outbuf)) {  /* !!! FIXME can't work in-place (for now!). */
+        Uint8 *ptr = EnsureStreamBufferSize(stream, inbuflen + outbuflen);
+        if (ptr == NULL) {
+            SDL_OutOfMemory();
+            return 0;
+        }
+        SDL_memcpy(ptr + outbuflen, ptr, inbuflen);
+        inbuf = (const float *) (ptr + outbuflen);
+        outbuf = (float *) ptr;
+    }
+
+    /* !!! FIXME: streaming current resamples on Put, because of probably good reasons I can't remember right now, but if we resample on Get, we'd be able to access legit right padding values. */
+    rpadding = SDL_stack_alloc(float, paddingsamples);
+    if (!rpadding) {
+        SDL_OutOfMemory();
+        return 0;
+    }
+    SDL_memset(rpadding, '\0', paddingbytes);
+
+    retval = SDL_ResampleAudio(chans, inrate, outrate, lpadding, rpadding, inbuf, inbuflen, outbuf, outbuflen);
+
+    SDL_stack_free(rpadding);
+
+    /* update our left padding with end of current input, for next run. */
+    SDL_memcpy(lpadding, ((const Uint8 *) inbuf) + (inbuflen - paddingbytes), paddingbytes);
+
+    return retval;
+}
+
+static void
+SDL_ResetAudioStreamResampler(SDL_AudioStream *stream)
+{
+    /* set all the left padding to silence. */
+    const int inrate = stream->src_rate;
+    const int outrate = stream->dst_rate;
+    const int chans = (int) stream->pre_resample_channels;
+    const int len = ResamplerPadding(inrate, outrate) * chans;
+    SDL_memset(stream->resampler_state, '\0', len * sizeof (float));
+}
+
+static void
+SDL_CleanupAudioStreamResampler(SDL_AudioStream *stream)
+{
+    SDL_free(stream->resampler_state);
+}
+
+SDL_AudioStream *
+SDL_NewAudioStream(const SDL_AudioFormat src_format,
+                   const Uint8 src_channels,
+                   const int src_rate,
+                   const SDL_AudioFormat dst_format,
+                   const Uint8 dst_channels,
+                   const int dst_rate)
+{
+    const int packetlen = 4096;  /* !!! FIXME: good enough for now. */
+    Uint8 pre_resample_channels;
+    SDL_AudioStream *retval;
+
+    retval = (SDL_AudioStream *) SDL_calloc(1, sizeof (SDL_AudioStream));
+    if (!retval) {
+        return NULL;
+    }
+
+    /* If increasing channels, do it after resampling, since we'd just
+       do more work to resample duplicate channels. If we're decreasing, do
+       it first so we resample the interpolated data instead of interpolating
+       the resampled data (!!! FIXME: decide if that works in practice, though!). */
+    pre_resample_channels = SDL_min(src_channels, dst_channels);
+
+    retval->src_sample_frame_size = (SDL_AUDIO_BITSIZE(src_format) / 8) * src_channels;
+    retval->src_format = src_format;
+    retval->src_channels = src_channels;
+    retval->src_rate = src_rate;
+    retval->dst_sample_frame_size = (SDL_AUDIO_BITSIZE(dst_format) / 8) * dst_channels;
+    retval->dst_format = dst_format;
+    retval->dst_channels = dst_channels;
+    retval->dst_rate = dst_rate;
+    retval->pre_resample_channels = pre_resample_channels;
+    retval->packetlen = packetlen;
+    retval->rate_incr = ((double) dst_rate) / ((double) src_rate);
+
+    /* Not resampling? It's an easy conversion (and maybe not even that!). */
+    if (src_rate == dst_rate) {
+        retval->cvt_before_resampling.needed = SDL_FALSE;
+        if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, src_format, src_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) {
+            SDL_FreeAudioStream(retval);
+            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
+        }
+    } else {
+        /* Don't resample at first. Just get us to Float32 format. */
+        /* !!! FIXME: convert to int32 on devices without hardware float. */
+        if (SDL_BuildAudioCVT(&retval->cvt_before_resampling, src_format, src_channels, src_rate, AUDIO_F32SYS, pre_resample_channels, src_rate) < 0) {
+            SDL_FreeAudioStream(retval);
+            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
+        }
+
+#ifdef HAVE_LIBSAMPLERATE_H
+        SetupLibSampleRateResampling(retval);
+#endif
+
+        if (!retval->resampler_func) {
+            const int chans = (int) pre_resample_channels;
+            const int len = ResamplerPadding(src_rate, dst_rate) * chans;
+            retval->resampler_state = SDL_calloc(len, sizeof (float));
+            if (!retval->resampler_state) {
+                SDL_FreeAudioStream(retval);
+                SDL_OutOfMemory();
+                return NULL;
+            }
+
+            if (SDL_PrepareResampleFilter() < 0) {
+                SDL_free(retval->resampler_state);
+                retval->resampler_state = NULL;
+                SDL_FreeAudioStream(retval);
+                return NULL;
+            }
+
+            retval->resampler_func = SDL_ResampleAudioStream;
+            retval->reset_resampler_func = SDL_ResetAudioStreamResampler;
+            retval->cleanup_resampler_func = SDL_CleanupAudioStreamResampler;
+        }
+
+        /* Convert us to the final format after resampling. */
+        if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, AUDIO_F32SYS, pre_resample_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) {
+            SDL_FreeAudioStream(retval);
+            return NULL;  /* SDL_BuildAudioCVT should have called SDL_SetError. */
+        }
+    }
+
+    retval->queue = SDL_NewDataQueue(packetlen, packetlen * 2);
+    if (!retval->queue) {
+        SDL_FreeAudioStream(retval);
+        return NULL;  /* SDL_NewDataQueue should have called SDL_SetError. */
+    }
+
+    return retval;
+}
+
+int
+SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, const Uint32 _buflen)
+{
+    int buflen = (int) _buflen;
+    const void *origbuf = buf;
+
+    /* !!! FIXME: several converters can take advantage of SIMD, but only
+       !!! FIXME:  if the data is aligned to 16 bytes. EnsureStreamBufferSize()
+       !!! FIXME:  guarantees the buffer will align, but the
+       !!! FIXME:  converters will iterate over the data backwards if
+       !!! FIXME:  the output grows, and this means we won't align if buflen
+       !!! FIXME:  isn't a multiple of 16. In these cases, we should chop off
+       !!! FIXME:  a few samples at the end and convert them separately. */
+
+    if (!stream) {
+        return SDL_InvalidParamError("stream");
+    } else if (!buf) {
+        return SDL_InvalidParamError("buf");
+    } else if (buflen == 0) {
+        return 0;  /* nothing to do. */
+    } else if ((buflen % stream->src_sample_frame_size) != 0) {
+        return SDL_SetError("Can't add partial sample frames");
+    }
+
+    if (stream->cvt_before_resampling.needed) {
+        const int workbuflen = buflen * stream->cvt_before_resampling.len_mult;  /* will be "* 1" if not needed */
+        Uint8 *workbuf = EnsureStreamBufferSize(stream, workbuflen);
+        if (workbuf == NULL) {
+            return -1;  /* probably out of memory. */
+        }
+        SDL_assert(buf == origbuf);
+        SDL_memcpy(workbuf, buf, buflen);
+        stream->cvt_before_resampling.buf = workbuf;
+        stream->cvt_before_resampling.len = buflen;
+        if (SDL_ConvertAudio(&stream->cvt_before_resampling) == -1) {
+            return -1;   /* uhoh! */
+        }
+        buf = workbuf;
+        buflen = stream->cvt_before_resampling.len_cvt;
+    }
+
+    if (stream->dst_rate != stream->src_rate) {
+        const int workbuflen = buflen * ((int) SDL_ceil(stream->rate_incr));
+        Uint8 *workbuf = EnsureStreamBufferSize(stream, workbuflen);
+        if (workbuf == NULL) {
+            return -1;  /* probably out of memory. */
+        }
+        /* don't SDL_memcpy(workbuf, buf, buflen) here; our resampler can work inplace or not,
+           libsamplerate needs buffers to be separate; either way, avoid a copy here if possible. */
+        if (buf != origbuf) {
+            buf = workbuf;  /* in case we realloc()'d the pointer. */
+        }
+        buflen = stream->resampler_func(stream, buf, buflen, workbuf, workbuflen);
+        buf = EnsureStreamBufferSize(stream, workbuflen);
+        SDL_assert(buf != NULL);  /* shouldn't be growing, just aligning. */
+    }
+
+    if (stream->cvt_after_resampling.needed) {
+        const int workbuflen = buflen * stream->cvt_after_resampling.len_mult;  /* will be "* 1" if not needed */
+        Uint8 *workbuf = EnsureStreamBufferSize(stream, workbuflen);
+        if (workbuf == NULL) {
+            return -1;  /* probably out of memory. */
+        }
+        if (buf == origbuf) {  /* copy if we haven't before. */
+            SDL_memcpy(workbuf, origbuf, buflen);
+        }
+        stream->cvt_after_resampling.buf = workbuf;
+        stream->cvt_after_resampling.len = buflen;
+        if (SDL_ConvertAudio(&stream->cvt_after_resampling) == -1) {
+            return -1;   /* uhoh! */
+        }
+        buf = workbuf;
+        buflen = stream->cvt_after_resampling.len_cvt;
+    }
+
+    return SDL_WriteToDataQueue(stream->queue, buf, buflen);
+}
+
+void
+SDL_AudioStreamClear(SDL_AudioStream *stream)
+{
+    if (!stream) {
+        SDL_InvalidParamError("stream");
+    } else {
+        SDL_ClearDataQueue(stream->queue, stream->packetlen * 2);
+        if (stream->reset_resampler_func) {
+            stream->reset_resampler_func(stream);
+        }
+    }
+}
+
+
+/* get converted/resampled data from the stream */
+int
+SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, const Uint32 len)
+{
+    if (!stream) {
+        return SDL_InvalidParamError("stream");
+    } else if (!buf) {
+        return SDL_InvalidParamError("buf");
+    } else if (len == 0) {
+        return 0;  /* nothing to do. */
+    } else if ((len % stream->dst_sample_frame_size) != 0) {
+        return SDL_SetError("Can't request partial sample frames");
+    }
+
+    return (int) SDL_ReadFromDataQueue(stream->queue, buf, len);
+}
+
+/* number of converted/resampled bytes available */
+int
+SDL_AudioStreamAvailable(SDL_AudioStream *stream)
+{
+    return stream ? (int) SDL_CountDataQueue(stream->queue) : 0;
+}
+
+/* dispose of a stream */
+void
+SDL_FreeAudioStream(SDL_AudioStream *stream)
+{
+    if (stream) {
+        if (stream->cleanup_resampler_func) {
+            stream->cleanup_resampler_func(stream);
+        }
+        SDL_FreeDataQueue(stream->queue);
+        SDL_free(stream->work_buffer_base);
+        SDL_free(stream);
+    }
+}
 
 /* vi: set ts=4 sw=4 expandtab: */
+
diff --git a/src/audio/SDL_audiodev.c b/src/audio/SDL_audiodev.c
index 5c392cf..d474a4d 100644
--- a/src/audio/SDL_audiodev.c
+++ b/src/audio/SDL_audiodev.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,7 +22,7 @@
 
 /* Get the name of the audio device we use for output */
 
-#if SDL_AUDIO_DRIVER_BSD || SDL_AUDIO_DRIVER_OSS || SDL_AUDIO_DRIVER_SUNAUDIO
+#if SDL_AUDIO_DRIVER_NETBSD || SDL_AUDIO_DRIVER_OSS || SDL_AUDIO_DRIVER_SUNAUDIO
 
 #include <fcntl.h>
 #include <sys/types.h>
@@ -103,9 +103,10 @@ SDL_EnumUnixAudioDevices_Internal(const int iscapture, const int classic, int (*
 
     if (SDL_strlen(audiodev) < (sizeof(audiopath) - 3)) {
         int instance = 0;
-        while (instance++ <= 64) {
+        while (instance <= 64) {
             SDL_snprintf(audiopath, SDL_arraysize(audiopath),
                          "%s%d", audiodev, instance);
+            instance++;
             test_device(iscapture, audiopath, flags, test);
         }
     }
diff --git a/src/audio/SDL_audiodev_c.h b/src/audio/SDL_audiodev_c.h
index fa60bcd..1076ddc 100644
--- a/src/audio/SDL_audiodev_c.h
+++ b/src/audio/SDL_audiodev_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/audio/SDL_audiotypecvt.c b/src/audio/SDL_audiotypecvt.c
index be3b743..86f883c 100644
--- a/src/audio/SDL_audiotypecvt.c
+++ b/src/audio/SDL_audiotypecvt.c
@@ -1,7 +1,6 @@
-/* DO NOT EDIT!  This file is generated by sdlgenaudiocvt.pl */
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,15993 +22,763 @@
 #include "../SDL_internal.h"
 #include "SDL_audio.h"
 #include "SDL_audio_c.h"
+#include "SDL_cpuinfo.h"
+#include "SDL_assert.h"
 
-#ifndef DEBUG_CONVERT
-#define DEBUG_CONVERT 0
-#endif
-
+/* !!! FIXME: write NEON code. */
+#define HAVE_NEON_INTRINSICS 0
 
-/* If you can guarantee your data and need space, you can eliminate code... */
-
-/* Just build the arbitrary resamplers if you're saving code space. */
-#ifndef LESS_RESAMPLERS
-#define LESS_RESAMPLERS 0
+#ifdef __SSE2__
+#define HAVE_SSE2_INTRINSICS 1
 #endif
 
-/* Don't build any resamplers if you're REALLY saving code space. */
-#ifndef NO_RESAMPLERS
-#define NO_RESAMPLERS 0
+#if defined(__x86_64__) && HAVE_SSE2_INTRINSICS
+#define NEED_SCALAR_CONVERTER_FALLBACKS 0  /* x86_64 guarantees SSE2. */
+#elif __MACOSX__ && HAVE_SSE2_INTRINSICS
+#define NEED_SCALAR_CONVERTER_FALLBACKS 0  /* Mac OS X/Intel guarantees SSE2. */
+#elif defined(__ARM_ARCH) && (__ARM_ARCH >= 8) && HAVE_NEON_INTRINSICS
+#define NEED_SCALAR_CONVERTER_FALLBACKS 0  /* ARMv8+ promise NEON. */
+#elif defined(__APPLE__) && defined(__ARM_ARCH) && (__ARM_ARCH >= 7) && HAVE_NEON_INTRINSICS
+#define NEED_SCALAR_CONVERTER_FALLBACKS 0  /* All Apple ARMv7 chips promise NEON support. */
 #endif
 
-/* Don't build any type converters if you're saving code space. */
-#ifndef NO_CONVERTERS
-#define NO_CONVERTERS 0
+/* Set to zero if platform is guaranteed to use a SIMD codepath here. */
+#ifndef NEED_SCALAR_CONVERTER_FALLBACKS
+#define NEED_SCALAR_CONVERTER_FALLBACKS 1
 #endif
 
+/* Function pointers set to a CPU-specific implementation. */
+SDL_AudioFilter SDL_Convert_S8_to_F32 = NULL;
+SDL_AudioFilter SDL_Convert_U8_to_F32 = NULL;
+SDL_AudioFilter SDL_Convert_S16_to_F32 = NULL;
+SDL_AudioFilter SDL_Convert_U16_to_F32 = NULL;
+SDL_AudioFilter SDL_Convert_S32_to_F32 = NULL;
+SDL_AudioFilter SDL_Convert_F32_to_S8 = NULL;
+SDL_AudioFilter SDL_Convert_F32_to_U8 = NULL;
+SDL_AudioFilter SDL_Convert_F32_to_S16 = NULL;
+SDL_AudioFilter SDL_Convert_F32_to_U16 = NULL;
+SDL_AudioFilter SDL_Convert_F32_to_S32 = NULL;
 
-/* *INDENT-OFF* */
 
-#define DIVBY127 0.0078740157480315f
-#define DIVBY32767 3.05185094759972e-05f
-#define DIVBY2147483647 4.6566128752458e-10f
+#define DIVBY128 0.0078125f
+#define DIVBY32768 0.000030517578125f
+#define DIVBY2147483648 0.00000000046566128730773926
 
-#if !NO_CONVERTERS
 
+#if NEED_SCALAR_CONVERTER_FALLBACKS
 static void SDLCALL
-SDL_Convert_U8_to_S8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_S8_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const Sint8 *src = ((const Sint8 *) (cvt->buf + cvt->len_cvt)) - 1;
+    float *dst = ((float *) (cvt->buf + cvt->len_cvt * 4)) - 1;
     int i;
-    const Uint8 *src;
-    Sint8 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U8 to AUDIO_S8.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_S8", "AUDIO_F32");
 
-    src = (const Uint8 *) cvt->buf;
-    dst = (Sint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, ++src, ++dst) {
-        const Sint8 val = ((*src) ^ 0x80);
-        *dst = ((Sint8) val);
+    for (i = cvt->len_cvt; i; --i, --src, --dst) {
+        *dst = ((float) *src) * DIVBY128;
     }
 
+    cvt->len_cvt *= 4;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S8);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U8_to_U16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_U8_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const Uint8 *src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
+    float *dst = ((float *) (cvt->buf + cvt->len_cvt * 4)) - 1;
     int i;
-    const Uint8 *src;
-    Uint16 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U8 to AUDIO_U16LSB.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_U8", "AUDIO_F32");
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Uint16 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Uint16 val = (((Uint16) *src) << 8);
-        *dst = SDL_SwapLE16(val);
+    for (i = cvt->len_cvt; i; --i, --src, --dst) {
+        *dst = (((float) *src) * DIVBY128) - 1.0f;
     }
 
-    cvt->len_cvt *= 2;
+    cvt->len_cvt *= 4;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16LSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U8_to_S16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_S16_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const Sint16 *src = ((const Sint16 *) (cvt->buf + cvt->len_cvt)) - 1;
+    float *dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
     int i;
-    const Uint8 *src;
-    Sint16 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U8 to AUDIO_S16LSB.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_S16", "AUDIO_F32");
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint16 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Sint16 val = (((Sint16) ((*src) ^ 0x80)) << 8);
-        *dst = ((Sint16) SDL_SwapLE16(val));
+    for (i = cvt->len_cvt / sizeof (Sint16); i; --i, --src, --dst) {
+        *dst = ((float) *src) * DIVBY32768;
     }
 
     cvt->len_cvt *= 2;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16LSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U8_to_U16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_U16_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const Uint16 *src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
+    float *dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
     int i;
-    const Uint8 *src;
-    Uint16 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U8 to AUDIO_U16MSB.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_U16", "AUDIO_F32");
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Uint16 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Uint16 val = (((Uint16) *src) << 8);
-        *dst = SDL_SwapBE16(val);
+    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
+        *dst = (((float) *src) * DIVBY32768) - 1.0f;
     }
 
     cvt->len_cvt *= 2;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16MSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U8_to_S16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_S32_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const Sint32 *src = (const Sint32 *) cvt->buf;
+    float *dst = (float *) cvt->buf;
     int i;
-    const Uint8 *src;
-    Sint16 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U8 to AUDIO_S16MSB.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_S32", "AUDIO_F32");
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint16 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Sint16 val = (((Sint16) ((*src) ^ 0x80)) << 8);
-        *dst = ((Sint16) SDL_SwapBE16(val));
+    for (i = cvt->len_cvt / sizeof (Sint32); i; --i, ++src, ++dst) {
+        *dst = (float) (((double) *src) * DIVBY2147483648);
     }
 
-    cvt->len_cvt *= 2;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16MSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U8_to_S32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_F32_to_S8_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) cvt->buf;
+    Sint8 *dst = (Sint8 *) cvt->buf;
     int i;
-    const Uint8 *src;
-    Sint32 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U8 to AUDIO_S32LSB.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S8");
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 4)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((*src) ^ 0x80)) << 24);
-        *dst = ((Sint32) SDL_SwapLE32(val));
+    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
+        *dst = (Sint8) (*src * 127.0f);
     }
 
-    cvt->len_cvt *= 4;
+    cvt->len_cvt /= 4;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32LSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_S8);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U8_to_S32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_F32_to_U8_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) cvt->buf;
+    Uint8 *dst = (Uint8 *) cvt->buf;
     int i;
-    const Uint8 *src;
-    Sint32 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U8 to AUDIO_S32MSB.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U8");
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 4)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((*src) ^ 0x80)) << 24);
-        *dst = ((Sint32) SDL_SwapBE32(val));
+    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
+        *dst = (Uint8) ((*src + 1.0f) * 127.0f);
     }
 
-    cvt->len_cvt *= 4;
+    cvt->len_cvt /= 4;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32MSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_U8);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U8_to_F32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_F32_to_S16_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) cvt->buf;
+    Sint16 *dst = (Sint16 *) cvt->buf;
     int i;
-    const Uint8 *src;
-    float *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U8 to AUDIO_F32LSB.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S16");
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 4)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const float val = ((((float) *src) * DIVBY127) - 1.0f);
-        *dst = SDL_SwapFloatLE(val);
+    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
+        *dst = (Sint16) (*src * 32767.0f);
     }
 
-    cvt->len_cvt *= 4;
+    cvt->len_cvt /= 2;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32LSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_S16SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U8_to_F32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_F32_to_U16_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) cvt->buf;
+    Uint16 *dst = (Uint16 *) cvt->buf;
     int i;
-    const Uint8 *src;
-    float *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U8 to AUDIO_F32MSB.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U16");
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 4)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const float val = ((((float) *src) * DIVBY127) - 1.0f);
-        *dst = SDL_SwapFloatBE(val);
+    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
+        *dst = (Uint16) ((*src + 1.0f) * 32767.0f);
     }
 
-    cvt->len_cvt *= 4;
+    cvt->len_cvt /= 2;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32MSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_U16SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_S8_to_U8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_F32_to_S32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) cvt->buf;
+    Sint32 *dst = (Sint32 *) cvt->buf;
     int i;
-    const Uint8 *src;
-    Uint8 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S8 to AUDIO_U8.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S32");
 
-    src = (const Uint8 *) cvt->buf;
-    dst = (Uint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, ++src, ++dst) {
-        const Uint8 val = ((((Sint8) *src)) ^ 0x80);
-        *dst = val;
+    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
+        *dst = (Sint32) (((double) *src) * 2147483647.0);
     }
 
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U8);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_S32SYS);
     }
 }
-
-static void SDLCALL
-SDL_Convert_S8_to_U16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint8 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S8 to AUDIO_U16LSB.\n");
 #endif
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Uint16 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Uint16 val = (((Uint16) ((((Sint8) *src)) ^ 0x80)) << 8);
-        *dst = SDL_SwapLE16(val);
-    }
-
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16LSB);
-    }
-}
 
+#if HAVE_SSE2_INTRINSICS
 static void SDLCALL
-SDL_Convert_S8_to_S16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_S8_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const Sint8 *src = ((const Sint8 *) (cvt->buf + cvt->len_cvt)) - 1;
+    float *dst = ((float *) (cvt->buf + cvt->len_cvt * 4)) - 1;
     int i;
-    const Uint8 *src;
-    Sint16 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S8 to AUDIO_S16LSB.\n");
-#endif
-
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint16 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Sint16 val = (((Sint16) ((Sint8) *src)) << 8);
-        *dst = ((Sint16) SDL_SwapLE16(val));
-    }
+    LOG_DEBUG_CONVERT("AUDIO_S8", "AUDIO_F32 (using SSE2)");
 
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16LSB);
+    /* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
+    for (i = cvt->len_cvt; i && (((size_t) (dst-15)) & 15); --i, --src, --dst) {
+        *dst = ((float) *src) * DIVBY128;
     }
-}
-
-static void SDLCALL
-SDL_Convert_S8_to_U16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint8 *src;
-    Uint16 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S8 to AUDIO_U16MSB.\n");
-#endif
+    src -= 15; dst -= 15;  /* adjust to read SSE blocks from the start. */
+    SDL_assert(!i || ((((size_t) dst) & 15) == 0));
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Uint16 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Uint16 val = (((Uint16) ((((Sint8) *src)) ^ 0x80)) << 8);
-        *dst = SDL_SwapBE16(val);
-    }
+    /* Make sure src is aligned too. */
+    if ((((size_t) src) & 15) == 0) {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        const __m128i *mmsrc = (const __m128i *) src;
+        const __m128i zero = _mm_setzero_si128();
+        const __m128 divby128 = _mm_set1_ps(DIVBY128);
+        while (i >= 16) {   /* 16 * 8-bit */
+            const __m128i bytes = _mm_load_si128(mmsrc);  /* get 16 sint8 into an XMM register. */
+            /* treat as int16, shift left to clear every other sint16, then back right with sign-extend. Now sint16. */
+            const __m128i shorts1 = _mm_srai_epi16(_mm_slli_epi16(bytes, 8), 8);
+            /* right-shift-sign-extend gets us sint16 with the other set of values. */
+            const __m128i shorts2 = _mm_srai_epi16(bytes, 8);
+            /* unpack against zero to make these int32, shift to make them sign-extend, convert to float, multiply. Whew! */
+            const __m128 floats1 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpacklo_epi16(shorts1, zero), 16), 16)), divby128);
+            const __m128 floats2 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpacklo_epi16(shorts2, zero), 16), 16)), divby128);
+            const __m128 floats3 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpackhi_epi16(shorts1, zero), 16), 16)), divby128);
+            const __m128 floats4 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpackhi_epi16(shorts2, zero), 16), 16)), divby128);
+            /* Interleave back into correct order, store. */
+            _mm_store_ps(dst, _mm_unpacklo_ps(floats1, floats2));
+            _mm_store_ps(dst+4, _mm_unpackhi_ps(floats1, floats2));
+            _mm_store_ps(dst+8, _mm_unpacklo_ps(floats3, floats4));
+            _mm_store_ps(dst+12, _mm_unpackhi_ps(floats3, floats4));
+            i -= 16; mmsrc--; dst -= 16;
+        }
 
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16MSB);
+        src = (const Sint8 *) mmsrc;
     }
-}
 
-static void SDLCALL
-SDL_Convert_S8_to_S16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint8 *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S8 to AUDIO_S16MSB.\n");
-#endif
+    src += 15; dst += 15;  /* adjust for any scalar finishing. */
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint16 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Sint16 val = (((Sint16) ((Sint8) *src)) << 8);
-        *dst = ((Sint16) SDL_SwapBE16(val));
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = ((float) *src) * DIVBY128;
+        i--; src--; dst--;
     }
 
-    cvt->len_cvt *= 2;
+    cvt->len_cvt *= 4;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16MSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_S8_to_S32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_U8_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const Uint8 *src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
+    float *dst = ((float *) (cvt->buf + cvt->len_cvt * 4)) - 1;
     int i;
-    const Uint8 *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S8 to AUDIO_S32LSB.\n");
-#endif
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 4)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((Sint8) *src)) << 24);
-        *dst = ((Sint32) SDL_SwapLE32(val));
-    }
+    LOG_DEBUG_CONVERT("AUDIO_U8", "AUDIO_F32 (using SSE2)");
 
-    cvt->len_cvt *= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32LSB);
+    /* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
+    for (i = cvt->len_cvt; i && (((size_t) (dst-15)) & 15); --i, --src, --dst) {
+        *dst = (((float) *src) * DIVBY128) - 1.0f;
     }
-}
-
-static void SDLCALL
-SDL_Convert_S8_to_S32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint8 *src;
-    Sint32 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S8 to AUDIO_S32MSB.\n");
-#endif
+    src -= 15; dst -= 15;  /* adjust to read SSE blocks from the start. */
+    SDL_assert(!i || ((((size_t) dst) & 15) == 0));
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 4)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((Sint8) *src)) << 24);
-        *dst = ((Sint32) SDL_SwapBE32(val));
-    }
+    /* Make sure src is aligned too. */
+    if ((((size_t) src) & 15) == 0) {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        const __m128i *mmsrc = (const __m128i *) src;
+        const __m128i zero = _mm_setzero_si128();
+        const __m128 divby128 = _mm_set1_ps(DIVBY128);
+        const __m128 minus1 = _mm_set1_ps(-1.0f);
+        while (i >= 16) {   /* 16 * 8-bit */
+            const __m128i bytes = _mm_load_si128(mmsrc);  /* get 16 uint8 into an XMM register. */
+            /* treat as int16, shift left to clear every other sint16, then back right with zero-extend. Now uint16. */
+            const __m128i shorts1 = _mm_srli_epi16(_mm_slli_epi16(bytes, 8), 8);
+            /* right-shift-zero-extend gets us uint16 with the other set of values. */
+            const __m128i shorts2 = _mm_srli_epi16(bytes, 8);
+            /* unpack against zero to make these int32, convert to float, multiply, add. Whew! */
+            /* Note that AVX2 can do floating point multiply+add in one instruction, fwiw. SSE2 cannot. */
+            const __m128 floats1 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi16(shorts1, zero)), divby128), minus1);
+            const __m128 floats2 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi16(shorts2, zero)), divby128), minus1);
+            const __m128 floats3 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi16(shorts1, zero)), divby128), minus1);
+            const __m128 floats4 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi16(shorts2, zero)), divby128), minus1);
+            /* Interleave back into correct order, store. */
+            _mm_store_ps(dst, _mm_unpacklo_ps(floats1, floats2));
+            _mm_store_ps(dst+4, _mm_unpackhi_ps(floats1, floats2));
+            _mm_store_ps(dst+8, _mm_unpacklo_ps(floats3, floats4));
+            _mm_store_ps(dst+12, _mm_unpackhi_ps(floats3, floats4));
+            i -= 16; mmsrc--; dst -= 16;
+        }
 
-    cvt->len_cvt *= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32MSB);
+        src = (const Uint8 *) mmsrc;
     }
-}
-
-static void SDLCALL
-SDL_Convert_S8_to_F32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint8 *src;
-    float *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S8 to AUDIO_F32LSB.\n");
-#endif
+    src += 15; dst += 15;  /* adjust for any scalar finishing. */
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 4)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const float val = (((float) ((Sint8) *src)) * DIVBY127);
-        *dst = SDL_SwapFloatLE(val);
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = (((float) *src) * DIVBY128) - 1.0f;
+        i--; src--; dst--;
     }
 
     cvt->len_cvt *= 4;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32LSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_S8_to_F32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_S16_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const Sint16 *src = ((const Sint16 *) (cvt->buf + cvt->len_cvt)) - 1;
+    float *dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
     int i;
-    const Uint8 *src;
-    float *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S8 to AUDIO_F32MSB.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_S16", "AUDIO_F32 (using SSE2)");
 
-    src = ((const Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 4)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint8); i; --i, --src, --dst) {
-        const float val = (((float) ((Sint8) *src)) * DIVBY127);
-        *dst = SDL_SwapFloatBE(val);
+    /* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
+    for (i = cvt->len_cvt / sizeof (Sint16); i && (((size_t) (dst-7)) & 15); --i, --src, --dst) {
+        *dst = ((float) *src) * DIVBY32768;
     }
 
-    cvt->len_cvt *= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32MSB);
-    }
-}
+    src -= 7; dst -= 7;  /* adjust to read SSE blocks from the start. */
+    SDL_assert(!i || ((((size_t) dst) & 15) == 0));
 
-static void SDLCALL
-SDL_Convert_U16LSB_to_U8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Uint8 *dst;
+    /* Make sure src is aligned too. */
+    if ((((size_t) src) & 15) == 0) {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        const __m128 divby32768 = _mm_set1_ps(DIVBY32768);
+        while (i >= 8) {   /* 8 * 16-bit */
+            const __m128i ints = _mm_load_si128((__m128i const *) src);  /* get 8 sint16 into an XMM register. */
+            /* treat as int32, shift left to clear every other sint16, then back right with sign-extend. Now sint32. */
+            const __m128i a = _mm_srai_epi32(_mm_slli_epi32(ints, 16), 16);
+            /* right-shift-sign-extend gets us sint32 with the other set of values. */
+            const __m128i b = _mm_srai_epi32(ints, 16);
+            /* Interleave these back into the right order, convert to float, multiply, store. */
+            _mm_store_ps(dst, _mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi32(a, b)), divby32768));
+            _mm_store_ps(dst+4, _mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi32(a, b)), divby32768));
+            i -= 8; src -= 8; dst -= 8;
+        }
+    }
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16LSB to AUDIO_U8.\n");
-#endif
+    src += 7; dst += 7;  /* adjust for any scalar finishing. */
 
-    src = (const Uint16 *) cvt->buf;
-    dst = (Uint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Uint8 val = ((Uint8) (SDL_SwapLE16(*src) >> 8));
-        *dst = val;
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = ((float) *src) * DIVBY32768;
+        i--; src--; dst--;
     }
 
-    cvt->len_cvt /= 2;
+    cvt->len_cvt *= 2;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U8);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U16LSB_to_S8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_U16_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const Uint16 *src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
+    float *dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
     int i;
-    const Uint16 *src;
-    Sint8 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16LSB to AUDIO_S8.\n");
-#endif
+    LOG_DEBUG_CONVERT("AUDIO_U16", "AUDIO_F32 (using SSE2)");
 
-    src = (const Uint16 *) cvt->buf;
-    dst = (Sint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Sint8 val = ((Sint8) (((SDL_SwapLE16(*src)) ^ 0x8000) >> 8));
-        *dst = ((Sint8) val);
+    /* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
+    for (i = cvt->len_cvt / sizeof (Sint16); i && (((size_t) (dst-7)) & 15); --i, --src, --dst) {
+        *dst = (((float) *src) * DIVBY32768) - 1.0f;
     }
 
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S8);
-    }
-}
+    src -= 7; dst -= 7;  /* adjust to read SSE blocks from the start. */
+    SDL_assert(!i || ((((size_t) dst) & 15) == 0));
 
-static void SDLCALL
-SDL_Convert_U16LSB_to_S16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint16 *dst;
+    /* Make sure src is aligned too. */
+    if ((((size_t) src) & 15) == 0) {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        const __m128 divby32768 = _mm_set1_ps(DIVBY32768);
+        const __m128 minus1 = _mm_set1_ps(1.0f);
+        while (i >= 8) {   /* 8 * 16-bit */
+            const __m128i ints = _mm_load_si128((__m128i const *) src);  /* get 8 sint16 into an XMM register. */
+            /* treat as int32, shift left to clear every other sint16, then back right with zero-extend. Now sint32. */
+            const __m128i a = _mm_srli_epi32(_mm_slli_epi32(ints, 16), 16);
+            /* right-shift-sign-extend gets us sint32 with the other set of values. */
+            const __m128i b = _mm_srli_epi32(ints, 16);
+            /* Interleave these back into the right order, convert to float, multiply, store. */
+            _mm_store_ps(dst, _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi32(a, b)), divby32768), minus1));
+            _mm_store_ps(dst+4, _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi32(a, b)), divby32768), minus1));
+            i -= 8; src -= 8; dst -= 8;
+        }
+    }
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16LSB to AUDIO_S16LSB.\n");
-#endif
+    src += 7; dst += 7;  /* adjust for any scalar finishing. */
 
-    src = (const Uint16 *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Sint16 val = ((SDL_SwapLE16(*src)) ^ 0x8000);
-        *dst = ((Sint16) SDL_SwapLE16(val));
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = (((float) *src) * DIVBY32768) - 1.0f;
+        i--; src--; dst--;
     }
 
+    cvt->len_cvt *= 2;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16LSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U16LSB_to_U16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_S32_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const Sint32 *src = (const Sint32 *) cvt->buf;
+    float *dst = (float *) cvt->buf;
     int i;
-    const Uint16 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16LSB to AUDIO_U16MSB.\n");
-#endif
 
-    src = (const Uint16 *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Uint16 val = SDL_SwapLE16(*src);
-        *dst = SDL_SwapBE16(val);
-    }
+    LOG_DEBUG_CONVERT("AUDIO_S32", "AUDIO_F32 (using SSE2)");
 
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16MSB);
+    /* Get dst aligned to 16 bytes */
+    for (i = cvt->len_cvt / sizeof (Sint32); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
+        *dst = (float) (((double) *src) * DIVBY2147483648);
     }
-}
 
-static void SDLCALL
-SDL_Convert_U16LSB_to_S16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint16 *dst;
+    SDL_assert(!i || ((((size_t) dst) & 15) == 0));
+    SDL_assert(!i || ((((size_t) src) & 15) == 0));
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16LSB to AUDIO_S16MSB.\n");
-#endif
+    {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        const __m128d divby2147483648 = _mm_set1_pd(DIVBY2147483648);
+        const __m128i *mmsrc = (const __m128i *) src;
+        while (i >= 4) {   /* 4 * sint32 */
+            const __m128i ints = _mm_load_si128(mmsrc);
+            /* bitshift the whole register over, so _mm_cvtepi32_pd can read the top ints in the bottom of the vector. */
+            const __m128d doubles1 = _mm_mul_pd(_mm_cvtepi32_pd(_mm_srli_si128(ints, 8)), divby2147483648);
+            const __m128d doubles2 = _mm_mul_pd(_mm_cvtepi32_pd(ints), divby2147483648);
+            /* convert to float32, bitshift/or to get these into a vector to store. */
+            _mm_store_ps(dst, _mm_castsi128_ps(_mm_or_si128(_mm_slli_si128(_mm_castps_si128(_mm_cvtpd_ps(doubles1)), 8), _mm_castps_si128(_mm_cvtpd_ps(doubles2)))));
+            i -= 4; mmsrc++; dst += 4;
+        }
+        src = (const Sint32 *) mmsrc;
+    }
 
-    src = (const Uint16 *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Sint16 val = ((SDL_SwapLE16(*src)) ^ 0x8000);
-        *dst = ((Sint16) SDL_SwapBE16(val));
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = (float) (((double) *src) * DIVBY2147483648);
+        i--; src++; dst++;
     }
 
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16MSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U16LSB_to_S32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_F32_to_S8_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) cvt->buf;
+    Sint8 *dst = (Sint8 *) cvt->buf;
     int i;
-    const Uint16 *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16LSB to AUDIO_S32LSB.\n");
-#endif
 
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((SDL_SwapLE16(*src)) ^ 0x8000)) << 16);
-        *dst = ((Sint32) SDL_SwapLE32(val));
-    }
+    LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S8 (using SSE2)");
 
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32LSB);
+    /* Get dst aligned to 16 bytes */
+    for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
+        *dst = (Sint8) (*src * 127.0f);
     }
-}
 
-static void SDLCALL
-SDL_Convert_U16LSB_to_S32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint32 *dst;
+    SDL_assert(!i || ((((size_t) dst) & 15) == 0));
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16LSB to AUDIO_S32MSB.\n");
-#endif
+    /* Make sure src is aligned too. */
+    if ((((size_t) src) & 15) == 0) {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        const __m128 mulby127 = _mm_set1_ps(127.0f);
+        __m128i *mmdst = (__m128i *) dst;
+        while (i >= 16) {   /* 16 * float32 */
+            const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src), mulby127));  /* load 4 floats, convert to sint32 */
+            const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src+4), mulby127));  /* load 4 floats, convert to sint32 */
+            const __m128i ints3 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src+8), mulby127));  /* load 4 floats, convert to sint32 */
+            const __m128i ints4 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src+12), mulby127));  /* load 4 floats, convert to sint32 */
+            _mm_store_si128(mmdst, _mm_packs_epi16(_mm_packs_epi32(ints1, ints2), _mm_packs_epi32(ints3, ints4)));  /* pack down, store out. */
+            i -= 16; src += 16; mmdst++;
+        }
+        dst = (Sint8 *) mmdst;
+    }
 
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((SDL_SwapLE16(*src)) ^ 0x8000)) << 16);
-        *dst = ((Sint32) SDL_SwapBE32(val));
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = (Sint8) (*src * 127.0f);
+        i--; src++; dst++;
     }
 
-    cvt->len_cvt *= 2;
+    cvt->len_cvt /= 4;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32MSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_S8);
     }
 }
 
 static void SDLCALL
-SDL_Convert_U16LSB_to_F32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_F32_to_U8_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) cvt->buf;
+    Uint8 *dst = (Uint8 *) cvt->buf;
     int i;
-    const Uint16 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16LSB to AUDIO_F32LSB.\n");
-#endif
 
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const float val = ((((float) SDL_SwapLE16(*src)) * DIVBY32767) - 1.0f);
-        *dst = SDL_SwapFloatLE(val);
-    }
+    LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U8 (using SSE2)");
 
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32LSB);
+    /* Get dst aligned to 16 bytes */
+    for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
+        *dst = (Uint8) ((*src + 1.0f) * 127.0f);
     }
-}
 
-static void SDLCALL
-SDL_Convert_U16LSB_to_F32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    float *dst;
+    SDL_assert(!i || ((((size_t) dst) & 15) == 0));
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16LSB to AUDIO_F32MSB.\n");
-#endif
+    /* Make sure src is aligned too. */
+    if ((((size_t) src) & 15) == 0) {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        const __m128 add1 = _mm_set1_ps(1.0f);
+        const __m128 mulby127 = _mm_set1_ps(127.0f);
+        __m128i *mmdst = (__m128i *) dst;
+        while (i >= 16) {   /* 16 * float32 */
+            const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_load_ps(src), add1), mulby127));  /* load 4 floats, convert to sint32 */
+            const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_load_ps(src+4), add1), mulby127));  /* load 4 floats, convert to sint32 */
+            const __m128i ints3 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_load_ps(src+8), add1), mulby127));  /* load 4 floats, convert to sint32 */
+            const __m128i ints4 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_load_ps(src+12), add1), mulby127));  /* load 4 floats, convert to sint32 */
+            _mm_store_si128(mmdst, _mm_packus_epi16(_mm_packs_epi32(ints1, ints2), _mm_packs_epi32(ints3, ints4)));  /* pack down, store out. */
+            i -= 16; src += 16; mmdst++;
+        }
+        dst = (Uint8 *) mmdst;
+    }
 
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const float val = ((((float) SDL_SwapLE16(*src)) * DIVBY32767) - 1.0f);
-        *dst = SDL_SwapFloatBE(val);
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = (Uint8) ((*src + 1.0f) * 127.0f);
+        i--; src++; dst++;
     }
 
-    cvt->len_cvt *= 2;
+    cvt->len_cvt /= 4;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32MSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_U8);
     }
 }
 
 static void SDLCALL
-SDL_Convert_S16LSB_to_U8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_F32_to_S16_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) cvt->buf;
+    Sint16 *dst = (Sint16 *) cvt->buf;
     int i;
-    const Uint16 *src;
-    Uint8 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16LSB to AUDIO_U8.\n");
-#endif
-
-    src = (const Uint16 *) cvt->buf;
-    dst = (Uint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Uint8 val = ((Uint8) (((((Sint16) SDL_SwapLE16(*src))) ^ 0x8000) >> 8));
-        *dst = val;
-    }
+    LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S16 (using SSE2)");
 
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U8);
+    /* Get dst aligned to 16 bytes */
+    for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
+        *dst = (Sint16) (*src * 32767.0f);
     }
-}
 
-static void SDLCALL
-SDL_Convert_S16LSB_to_S8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint8 *dst;
+    SDL_assert(!i || ((((size_t) dst) & 15) == 0));
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16LSB to AUDIO_S8.\n");
-#endif
+    /* Make sure src is aligned too. */
+    if ((((size_t) src) & 15) == 0) {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        const __m128 mulby32767 = _mm_set1_ps(32767.0f);
+        __m128i *mmdst = (__m128i *) dst;
+        while (i >= 8) {   /* 8 * float32 */
+            const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src), mulby32767));  /* load 4 floats, convert to sint32 */
+            const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src+4), mulby32767));  /* load 4 floats, convert to sint32 */
+            _mm_store_si128(mmdst, _mm_packs_epi32(ints1, ints2));  /* pack to sint16, store out. */
+            i -= 8; src += 8; mmdst++;
+        }
+        dst = (Sint16 *) mmdst;
+    }
 
-    src = (const Uint16 *) cvt->buf;
-    dst = (Sint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Sint8 val = ((Sint8) (((Sint16) SDL_SwapLE16(*src)) >> 8));
-        *dst = ((Sint8) val);
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = (Sint16) (*src * 32767.0f);
+        i--; src++; dst++;
     }
 
     cvt->len_cvt /= 2;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S8);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_S16SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_S16LSB_to_U16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_F32_to_U16_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) cvt->buf;
+    Uint16 *dst = (Uint16 *) cvt->buf;
     int i;
-    const Uint16 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16LSB to AUDIO_U16LSB.\n");
-#endif
 
-    src = (const Uint16 *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Uint16 val = ((((Sint16) SDL_SwapLE16(*src))) ^ 0x8000);
-        *dst = SDL_SwapLE16(val);
-    }
+    LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U16 (using SSE2)");
 
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16LSB);
+    /* Get dst aligned to 16 bytes */
+    for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
+        *dst = (Uint16) ((*src + 1.0f) * 32767.0f);
     }
-}
-
-static void SDLCALL
-SDL_Convert_S16LSB_to_U16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16LSB to AUDIO_U16MSB.\n");
-#endif
 
-    src = (const Uint16 *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Uint16 val = ((((Sint16) SDL_SwapLE16(*src))) ^ 0x8000);
-        *dst = SDL_SwapBE16(val);
-    }
+    SDL_assert(!i || ((((size_t) dst) & 15) == 0));
 
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16MSB);
+    /* Make sure src is aligned too. */
+    if ((((size_t) src) & 15) == 0) {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        /* This calculates differently than the scalar path because SSE2 can't
+           pack int32 data down to unsigned int16. _mm_packs_epi32 does signed
+           saturation, so that would corrupt our data. _mm_packus_epi32 exists,
+           but not before SSE 4.1. So we convert from float to sint16, packing
+           that down with legit signed saturation, and then xor the top bit
+           against 1. This results in the correct unsigned 16-bit value, even
+           though it looks like dark magic. */
+        const __m128 mulby32767 = _mm_set1_ps(32767.0f);
+        const __m128i topbit = _mm_set1_epi16(-32768);
+        __m128i *mmdst = (__m128i *) dst;
+        while (i >= 8) {   /* 8 * float32 */
+            const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src), mulby32767));  /* load 4 floats, convert to sint32 */
+            const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(src+4), mulby32767));  /* load 4 floats, convert to sint32 */
+            _mm_store_si128(mmdst, _mm_xor_si128(_mm_packs_epi32(ints1, ints2), topbit));  /* pack to sint16, xor top bit, store out. */
+            i -= 8; src += 8; mmdst++;
+        }
+        dst = (Uint16 *) mmdst;
     }
-}
 
-static void SDLCALL
-SDL_Convert_S16LSB_to_S16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16LSB to AUDIO_S16MSB.\n");
-#endif
-
-    src = (const Uint16 *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Sint16 val = ((Sint16) SDL_SwapLE16(*src));
-        *dst = ((Sint16) SDL_SwapBE16(val));
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = (Uint16) ((*src + 1.0f) * 32767.0f);
+        i--; src++; dst++;
     }
 
+    cvt->len_cvt /= 2;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16MSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_U16SYS);
     }
 }
 
 static void SDLCALL
-SDL_Convert_S16LSB_to_S32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+SDL_Convert_F32_to_S32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format)
 {
+    const float *src = (const float *) cvt->buf;
+    Sint32 *dst = (Sint32 *) cvt->buf;
     int i;
-    const Uint16 *src;
-    Sint32 *dst;
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16LSB to AUDIO_S32LSB.\n");
-#endif
-
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((Sint16) SDL_SwapLE16(*src))) << 16);
-        *dst = ((Sint32) SDL_SwapLE32(val));
-    }
+    LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S32 (using SSE2)");
 
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32LSB);
+    /* Get dst aligned to 16 bytes */
+    for (i = cvt->len_cvt / sizeof (float); i && (((size_t) dst) & 15); --i, ++src, ++dst) {
+        *dst = (Sint32) (((double) *src) * 2147483647.0);
     }
-}
-
-static void SDLCALL
-SDL_Convert_S16LSB_to_S32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16LSB to AUDIO_S32MSB.\n");
-#endif
 
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((Sint16) SDL_SwapLE16(*src))) << 16);
-        *dst = ((Sint32) SDL_SwapBE32(val));
-    }
+    SDL_assert(!i || ((((size_t) dst) & 15) == 0));
+    SDL_assert(!i || ((((size_t) src) & 15) == 0));
 
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32MSB);
+    {
+        /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
+        const __m128d mulby2147483647 = _mm_set1_pd(2147483647.0);
+        __m128i *mmdst = (__m128i *) dst;
+        while (i >= 4) {   /* 4 * float32 */
+            const __m128 floats = _mm_load_ps(src);
+            /* bitshift the whole register over, so _mm_cvtps_pd can read the top floats in the bottom of the vector. */
+            const __m128d doubles1 = _mm_mul_pd(_mm_cvtps_pd(_mm_castsi128_ps(_mm_srli_si128(_mm_castps_si128(floats), 8))), mulby2147483647);
+            const __m128d doubles2 = _mm_mul_pd(_mm_cvtps_pd(floats), mulby2147483647);
+            _mm_store_si128(mmdst, _mm_or_si128(_mm_slli_si128(_mm_cvtpd_epi32(doubles1), 8), _mm_cvtpd_epi32(doubles2)));
+            i -= 4; src += 4; mmdst++;
+        }
+        dst = (Sint32 *) mmdst;
     }
-}
-
-static void SDLCALL
-SDL_Convert_S16LSB_to_F32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16LSB to AUDIO_F32LSB.\n");
-#endif
 
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const float val = (((float) ((Sint16) SDL_SwapLE16(*src))) * DIVBY32767);
-        *dst = SDL_SwapFloatLE(val);
+    /* Finish off any leftovers with scalar operations. */
+    while (i) {
+        *dst = (Sint32) (((double) *src) * 2147483647.0);
+        i--; src++; dst++;
     }
 
-    cvt->len_cvt *= 2;
     if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32LSB);
+        cvt->filters[cvt->filter_index](cvt, AUDIO_S32SYS);
     }
 }
-
-static void SDLCALL
-SDL_Convert_S16LSB_to_F32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16LSB to AUDIO_F32MSB.\n");
 #endif
 
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const float val = (((float) ((Sint16) SDL_SwapLE16(*src))) * DIVBY32767);
-        *dst = SDL_SwapFloatBE(val);
-    }
-
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32MSB);
-    }
-}
 
-static void SDLCALL
-SDL_Convert_U16MSB_to_U8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
+void SDL_ChooseAudioConverters(void)
 {
-    int i;
-    const Uint16 *src;
-    Uint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16MSB to AUDIO_U8.\n");
-#endif
+    static SDL_bool converters_chosen = SDL_FALSE;
 
-    src = (const Uint16 *) cvt->buf;
-    dst = (Uint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Uint8 val = ((Uint8) (SDL_SwapBE16(*src) >> 8));
-        *dst = val;
+    if (converters_chosen) {
+        return;
     }
 
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U8);
-    }
-}
+#define SET_CONVERTER_FUNCS(fntype) \
+        SDL_Convert_S8_to_F32 = SDL_Convert_S8_to_F32_##fntype; \
+        SDL_Convert_U8_to_F32 = SDL_Convert_U8_to_F32_##fntype; \
+        SDL_Convert_S16_to_F32 = SDL_Convert_S16_to_F32_##fntype; \
+        SDL_Convert_U16_to_F32 = SDL_Convert_U16_to_F32_##fntype; \
+        SDL_Convert_S32_to_F32 = SDL_Convert_S32_to_F32_##fntype; \
+        SDL_Convert_F32_to_S8 = SDL_Convert_F32_to_S8_##fntype; \
+        SDL_Convert_F32_to_U8 = SDL_Convert_F32_to_U8_##fntype; \
+        SDL_Convert_F32_to_S16 = SDL_Convert_F32_to_S16_##fntype; \
+        SDL_Convert_F32_to_U16 = SDL_Convert_F32_to_U16_##fntype; \
+        SDL_Convert_F32_to_S32 = SDL_Convert_F32_to_S32_##fntype; \
+        converters_chosen = SDL_TRUE
 
-static void SDLCALL
-SDL_Convert_U16MSB_to_S8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint8 *dst;
+#if HAVE_SSE2_INTRINSICS
+    if (SDL_HasSSE2()) {
+        SET_CONVERTER_FUNCS(SSE2);
+        return;
+    }
+#endif
 
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16MSB to AUDIO_S8.\n");
+#if NEED_SCALAR_CONVERTER_FALLBACKS
+    SET_CONVERTER_FUNCS(Scalar);
 #endif
 
-    src = (const Uint16 *) cvt->buf;
-    dst = (Sint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Sint8 val = ((Sint8) (((SDL_SwapBE16(*src)) ^ 0x8000) >> 8));
-        *dst = ((Sint8) val);
-    }
+#undef SET_CONVERTER_FUNCS
 
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S8);
-    }
+    SDL_assert(converters_chosen == SDL_TRUE);
 }
 
-static void SDLCALL
-SDL_Convert_U16MSB_to_U16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16MSB to AUDIO_U16LSB.\n");
-#endif
-
-    src = (const Uint16 *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Uint16 val = SDL_SwapBE16(*src);
-        *dst = SDL_SwapLE16(val);
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_U16MSB_to_S16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16MSB to AUDIO_S16LSB.\n");
-#endif
-
-    src = (const Uint16 *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Sint16 val = ((SDL_SwapBE16(*src)) ^ 0x8000);
-        *dst = ((Sint16) SDL_SwapLE16(val));
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_U16MSB_to_S16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16MSB to AUDIO_S16MSB.\n");
-#endif
-
-    src = (const Uint16 *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Sint16 val = ((SDL_SwapBE16(*src)) ^ 0x8000);
-        *dst = ((Sint16) SDL_SwapBE16(val));
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_U16MSB_to_S32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16MSB to AUDIO_S32LSB.\n");
-#endif
-
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((SDL_SwapBE16(*src)) ^ 0x8000)) << 16);
-        *dst = ((Sint32) SDL_SwapLE32(val));
-    }
-
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_U16MSB_to_S32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16MSB to AUDIO_S32MSB.\n");
-#endif
-
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((SDL_SwapBE16(*src)) ^ 0x8000)) << 16);
-        *dst = ((Sint32) SDL_SwapBE32(val));
-    }
-
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_U16MSB_to_F32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16MSB to AUDIO_F32LSB.\n");
-#endif
-
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const float val = ((((float) SDL_SwapBE16(*src)) * DIVBY32767) - 1.0f);
-        *dst = SDL_SwapFloatLE(val);
-    }
-
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_U16MSB_to_F32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_U16MSB to AUDIO_F32MSB.\n");
-#endif
-
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const float val = ((((float) SDL_SwapBE16(*src)) * DIVBY32767) - 1.0f);
-        *dst = SDL_SwapFloatBE(val);
-    }
-
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S16MSB_to_U8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Uint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16MSB to AUDIO_U8.\n");
-#endif
-
-    src = (const Uint16 *) cvt->buf;
-    dst = (Uint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Uint8 val = ((Uint8) (((((Sint16) SDL_SwapBE16(*src))) ^ 0x8000) >> 8));
-        *dst = val;
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U8);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S16MSB_to_S8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16MSB to AUDIO_S8.\n");
-#endif
-
-    src = (const Uint16 *) cvt->buf;
-    dst = (Sint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Sint8 val = ((Sint8) (((Sint16) SDL_SwapBE16(*src)) >> 8));
-        *dst = ((Sint8) val);
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S8);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S16MSB_to_U16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16MSB to AUDIO_U16LSB.\n");
-#endif
-
-    src = (const Uint16 *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Uint16 val = ((((Sint16) SDL_SwapBE16(*src))) ^ 0x8000);
-        *dst = SDL_SwapLE16(val);
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S16MSB_to_S16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16MSB to AUDIO_S16LSB.\n");
-#endif
-
-    src = (const Uint16 *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Sint16 val = ((Sint16) SDL_SwapBE16(*src));
-        *dst = ((Sint16) SDL_SwapLE16(val));
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S16MSB_to_U16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16MSB to AUDIO_U16MSB.\n");
-#endif
-
-    src = (const Uint16 *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, ++src, ++dst) {
-        const Uint16 val = ((((Sint16) SDL_SwapBE16(*src))) ^ 0x8000);
-        *dst = SDL_SwapBE16(val);
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S16MSB_to_S32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16MSB to AUDIO_S32LSB.\n");
-#endif
-
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((Sint16) SDL_SwapBE16(*src))) << 16);
-        *dst = ((Sint32) SDL_SwapLE32(val));
-    }
-
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S16MSB_to_S32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16MSB to AUDIO_S32MSB.\n");
-#endif
-
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((Sint32 *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const Sint32 val = (((Sint32) ((Sint16) SDL_SwapBE16(*src))) << 16);
-        *dst = ((Sint32) SDL_SwapBE32(val));
-    }
-
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S16MSB_to_F32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16MSB to AUDIO_F32LSB.\n");
-#endif
-
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const float val = (((float) ((Sint16) SDL_SwapBE16(*src))) * DIVBY32767);
-        *dst = SDL_SwapFloatLE(val);
-    }
-
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S16MSB_to_F32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint16 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S16MSB to AUDIO_F32MSB.\n");
-#endif
-
-    src = ((const Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = ((float *) (cvt->buf + cvt->len_cvt * 2)) - 1;
-    for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) {
-        const float val = (((float) ((Sint16) SDL_SwapBE16(*src))) * DIVBY32767);
-        *dst = SDL_SwapFloatBE(val);
-    }
-
-    cvt->len_cvt *= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32LSB_to_U8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Uint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32LSB to AUDIO_U8.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Uint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Uint8 val = ((Uint8) (((((Sint32) SDL_SwapLE32(*src))) ^ 0x80000000) >> 24));
-        *dst = val;
-    }
-
-    cvt->len_cvt /= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U8);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32LSB_to_S8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Sint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32LSB to AUDIO_S8.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Sint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Sint8 val = ((Sint8) (((Sint32) SDL_SwapLE32(*src)) >> 24));
-        *dst = ((Sint8) val);
-    }
-
-    cvt->len_cvt /= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S8);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32LSB_to_U16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32LSB to AUDIO_U16LSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Uint16 val = ((Uint16) (((((Sint32) SDL_SwapLE32(*src))) ^ 0x80000000) >> 16));
-        *dst = SDL_SwapLE16(val);
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32LSB_to_S16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32LSB to AUDIO_S16LSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Sint16 val = ((Sint16) (((Sint32) SDL_SwapLE32(*src)) >> 16));
-        *dst = ((Sint16) SDL_SwapLE16(val));
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32LSB_to_U16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32LSB to AUDIO_U16MSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Uint16 val = ((Uint16) (((((Sint32) SDL_SwapLE32(*src))) ^ 0x80000000) >> 16));
-        *dst = SDL_SwapBE16(val);
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32LSB_to_S16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32LSB to AUDIO_S16MSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Sint16 val = ((Sint16) (((Sint32) SDL_SwapLE32(*src)) >> 16));
-        *dst = ((Sint16) SDL_SwapBE16(val));
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32LSB_to_S32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32LSB to AUDIO_S32MSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Sint32 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Sint32 val = ((Sint32) SDL_SwapLE32(*src));
-        *dst = ((Sint32) SDL_SwapBE32(val));
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32LSB_to_F32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32LSB to AUDIO_F32LSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (float *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const float val = (((float) ((Sint32) SDL_SwapLE32(*src))) * DIVBY2147483647);
-        *dst = SDL_SwapFloatLE(val);
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32LSB_to_F32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32LSB to AUDIO_F32MSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (float *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const float val = (((float) ((Sint32) SDL_SwapLE32(*src))) * DIVBY2147483647);
-        *dst = SDL_SwapFloatBE(val);
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32MSB_to_U8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Uint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32MSB to AUDIO_U8.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Uint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Uint8 val = ((Uint8) (((((Sint32) SDL_SwapBE32(*src))) ^ 0x80000000) >> 24));
-        *dst = val;
-    }
-
-    cvt->len_cvt /= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U8);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32MSB_to_S8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Sint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32MSB to AUDIO_S8.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Sint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Sint8 val = ((Sint8) (((Sint32) SDL_SwapBE32(*src)) >> 24));
-        *dst = ((Sint8) val);
-    }
-
-    cvt->len_cvt /= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S8);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32MSB_to_U16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32MSB to AUDIO_U16LSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Uint16 val = ((Uint16) (((((Sint32) SDL_SwapBE32(*src))) ^ 0x80000000) >> 16));
-        *dst = SDL_SwapLE16(val);
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32MSB_to_S16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32MSB to AUDIO_S16LSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Sint16 val = ((Sint16) (((Sint32) SDL_SwapBE32(*src)) >> 16));
-        *dst = ((Sint16) SDL_SwapLE16(val));
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32MSB_to_U16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32MSB to AUDIO_U16MSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Uint16 val = ((Uint16) (((((Sint32) SDL_SwapBE32(*src))) ^ 0x80000000) >> 16));
-        *dst = SDL_SwapBE16(val);
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32MSB_to_S16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32MSB to AUDIO_S16MSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Sint16 val = ((Sint16) (((Sint32) SDL_SwapBE32(*src)) >> 16));
-        *dst = ((Sint16) SDL_SwapBE16(val));
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32MSB_to_S32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32MSB to AUDIO_S32LSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (Sint32 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const Sint32 val = ((Sint32) SDL_SwapBE32(*src));
-        *dst = ((Sint32) SDL_SwapLE32(val));
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32MSB_to_F32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32MSB to AUDIO_F32LSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (float *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const float val = (((float) ((Sint32) SDL_SwapBE32(*src))) * DIVBY2147483647);
-        *dst = SDL_SwapFloatLE(val);
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_S32MSB_to_F32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const Uint32 *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_S32MSB to AUDIO_F32MSB.\n");
-#endif
-
-    src = (const Uint32 *) cvt->buf;
-    dst = (float *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (Uint32); i; --i, ++src, ++dst) {
-        const float val = (((float) ((Sint32) SDL_SwapBE32(*src))) * DIVBY2147483647);
-        *dst = SDL_SwapFloatBE(val);
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32LSB_to_U8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Uint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32LSB to AUDIO_U8.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Uint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Uint8 val = ((Uint8) ((SDL_SwapFloatLE(*src) + 1.0f) * 127.0f));
-        *dst = val;
-    }
-
-    cvt->len_cvt /= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U8);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32LSB_to_S8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Sint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32LSB to AUDIO_S8.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Sint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Sint8 val = ((Sint8) (SDL_SwapFloatLE(*src) * 127.0f));
-        *dst = ((Sint8) val);
-    }
-
-    cvt->len_cvt /= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S8);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32LSB_to_U16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32LSB to AUDIO_U16LSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Uint16 val = ((Uint16) ((SDL_SwapFloatLE(*src) + 1.0f) * 32767.0f));
-        *dst = SDL_SwapLE16(val);
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32LSB_to_S16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32LSB to AUDIO_S16LSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Sint16 val = ((Sint16) (SDL_SwapFloatLE(*src) * 32767.0f));
-        *dst = ((Sint16) SDL_SwapLE16(val));
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32LSB_to_U16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32LSB to AUDIO_U16MSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Uint16 val = ((Uint16) ((SDL_SwapFloatLE(*src) + 1.0f) * 32767.0f));
-        *dst = SDL_SwapBE16(val);
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32LSB_to_S16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32LSB to AUDIO_S16MSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Sint16 val = ((Sint16) (SDL_SwapFloatLE(*src) * 32767.0f));
-        *dst = ((Sint16) SDL_SwapBE16(val));
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32LSB_to_S32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32LSB to AUDIO_S32LSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Sint32 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Sint32 val = ((Sint32) (SDL_SwapFloatLE(*src) * 2147483647.0));
-        *dst = ((Sint32) SDL_SwapLE32(val));
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32LSB_to_S32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32LSB to AUDIO_S32MSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Sint32 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Sint32 val = ((Sint32) (SDL_SwapFloatLE(*src) * 2147483647.0));
-        *dst = ((Sint32) SDL_SwapBE32(val));
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32LSB_to_F32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32LSB to AUDIO_F32MSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (float *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const float val = SDL_SwapFloatLE(*src);
-        *dst = SDL_SwapFloatBE(val);
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32MSB_to_U8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Uint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32MSB to AUDIO_U8.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Uint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Uint8 val = ((Uint8) ((SDL_SwapFloatBE(*src) + 1.0f) * 127.0f));
-        *dst = val;
-    }
-
-    cvt->len_cvt /= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U8);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32MSB_to_S8(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Sint8 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32MSB to AUDIO_S8.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Sint8 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Sint8 val = ((Sint8) (SDL_SwapFloatBE(*src) * 127.0f));
-        *dst = ((Sint8) val);
-    }
-
-    cvt->len_cvt /= 4;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S8);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32MSB_to_U16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32MSB to AUDIO_U16LSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Uint16 val = ((Uint16) ((SDL_SwapFloatBE(*src) + 1.0f) * 32767.0f));
-        *dst = SDL_SwapLE16(val);
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32MSB_to_S16LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32MSB to AUDIO_S16LSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Sint16 val = ((Sint16) (SDL_SwapFloatBE(*src) * 32767.0f));
-        *dst = ((Sint16) SDL_SwapLE16(val));
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32MSB_to_U16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Uint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32MSB to AUDIO_U16MSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Uint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Uint16 val = ((Uint16) ((SDL_SwapFloatBE(*src) + 1.0f) * 32767.0f));
-        *dst = SDL_SwapBE16(val);
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_U16MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32MSB_to_S16MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Sint16 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32MSB to AUDIO_S16MSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Sint16 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Sint16 val = ((Sint16) (SDL_SwapFloatBE(*src) * 32767.0f));
-        *dst = ((Sint16) SDL_SwapBE16(val));
-    }
-
-    cvt->len_cvt /= 2;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S16MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32MSB_to_S32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32MSB to AUDIO_S32LSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Sint32 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Sint32 val = ((Sint32) (SDL_SwapFloatBE(*src) * 2147483647.0));
-        *dst = ((Sint32) SDL_SwapLE32(val));
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32LSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32MSB_to_S32MSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    Sint32 *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32MSB to AUDIO_S32MSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (Sint32 *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const Sint32 val = ((Sint32) (SDL_SwapFloatBE(*src) * 2147483647.0));
-        *dst = ((Sint32) SDL_SwapBE32(val));
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_S32MSB);
-    }
-}
-
-static void SDLCALL
-SDL_Convert_F32MSB_to_F32LSB(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const float *src;
-    float *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_F32MSB to AUDIO_F32LSB.\n");
-#endif
-
-    src = (const float *) cvt->buf;
-    dst = (float *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof (float); i; --i, ++src, ++dst) {
-        const float val = SDL_SwapFloatBE(*src);
-        *dst = SDL_SwapFloatLE(val);
-    }
-
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_F32LSB);
-    }
-}
-
-#endif  /* !NO_CONVERTERS */
-
-
-const SDL_AudioTypeFilters sdl_audio_type_filters[] =
-{
-#if !NO_CONVERTERS
-    { AUDIO_U8, AUDIO_S8, SDL_Convert_U8_to_S8 },
-    { AUDIO_U8, AUDIO_U16LSB, SDL_Convert_U8_to_U16LSB },
-    { AUDIO_U8, AUDIO_S16LSB, SDL_Convert_U8_to_S16LSB },
-    { AUDIO_U8, AUDIO_U16MSB, SDL_Convert_U8_to_U16MSB },
-    { AUDIO_U8, AUDIO_S16MSB, SDL_Convert_U8_to_S16MSB },
-    { AUDIO_U8, AUDIO_S32LSB, SDL_Convert_U8_to_S32LSB },
-    { AUDIO_U8, AUDIO_S32MSB, SDL_Convert_U8_to_S32MSB },
-    { AUDIO_U8, AUDIO_F32LSB, SDL_Convert_U8_to_F32LSB },
-    { AUDIO_U8, AUDIO_F32MSB, SDL_Convert_U8_to_F32MSB },
-    { AUDIO_S8, AUDIO_U8, SDL_Convert_S8_to_U8 },
-    { AUDIO_S8, AUDIO_U16LSB, SDL_Convert_S8_to_U16LSB },
-    { AUDIO_S8, AUDIO_S16LSB, SDL_Convert_S8_to_S16LSB },
-    { AUDIO_S8, AUDIO_U16MSB, SDL_Convert_S8_to_U16MSB },
-    { AUDIO_S8, AUDIO_S16MSB, SDL_Convert_S8_to_S16MSB },
-    { AUDIO_S8, AUDIO_S32LSB, SDL_Convert_S8_to_S32LSB },
-    { AUDIO_S8, AUDIO_S32MSB, SDL_Convert_S8_to_S32MSB },
-    { AUDIO_S8, AUDIO_F32LSB, SDL_Convert_S8_to_F32LSB },
-    { AUDIO_S8, AUDIO_F32MSB, SDL_Convert_S8_to_F32MSB },
-    { AUDIO_U16LSB, AUDIO_U8, SDL_Convert_U16LSB_to_U8 },
-    { AUDIO_U16LSB, AUDIO_S8, SDL_Convert_U16LSB_to_S8 },
-    { AUDIO_U16LSB, AUDIO_S16LSB, SDL_Convert_U16LSB_to_S16LSB },
-    { AUDIO_U16LSB, AUDIO_U16MSB, SDL_Convert_U16LSB_to_U16MSB },
-    { AUDIO_U16LSB, AUDIO_S16MSB, SDL_Convert_U16LSB_to_S16MSB },
-    { AUDIO_U16LSB, AUDIO_S32LSB, SDL_Convert_U16LSB_to_S32LSB },
-    { AUDIO_U16LSB, AUDIO_S32MSB, SDL_Convert_U16LSB_to_S32MSB },
-    { AUDIO_U16LSB, AUDIO_F32LSB, SDL_Convert_U16LSB_to_F32LSB },
-    { AUDIO_U16LSB, AUDIO_F32MSB, SDL_Convert_U16LSB_to_F32MSB },
-    { AUDIO_S16LSB, AUDIO_U8, SDL_Convert_S16LSB_to_U8 },
-    { AUDIO_S16LSB, AUDIO_S8, SDL_Convert_S16LSB_to_S8 },
-    { AUDIO_S16LSB, AUDIO_U16LSB, SDL_Convert_S16LSB_to_U16LSB },
-    { AUDIO_S16LSB, AUDIO_U16MSB, SDL_Convert_S16LSB_to_U16MSB },
-    { AUDIO_S16LSB, AUDIO_S16MSB, SDL_Convert_S16LSB_to_S16MSB },
-    { AUDIO_S16LSB, AUDIO_S32LSB, SDL_Convert_S16LSB_to_S32LSB },
-    { AUDIO_S16LSB, AUDIO_S32MSB, SDL_Convert_S16LSB_to_S32MSB },
-    { AUDIO_S16LSB, AUDIO_F32LSB, SDL_Convert_S16LSB_to_F32LSB },
-    { AUDIO_S16LSB, AUDIO_F32MSB, SDL_Convert_S16LSB_to_F32MSB },
-    { AUDIO_U16MSB, AUDIO_U8, SDL_Convert_U16MSB_to_U8 },
-    { AUDIO_U16MSB, AUDIO_S8, SDL_Convert_U16MSB_to_S8 },
-    { AUDIO_U16MSB, AUDIO_U16LSB, SDL_Convert_U16MSB_to_U16LSB },
-    { AUDIO_U16MSB, AUDIO_S16LSB, SDL_Convert_U16MSB_to_S16LSB },
-    { AUDIO_U16MSB, AUDIO_S16MSB, SDL_Convert_U16MSB_to_S16MSB },
-    { AUDIO_U16MSB, AUDIO_S32LSB, SDL_Convert_U16MSB_to_S32LSB },
-    { AUDIO_U16MSB, AUDIO_S32MSB, SDL_Convert_U16MSB_to_S32MSB },
-    { AUDIO_U16MSB, AUDIO_F32LSB, SDL_Convert_U16MSB_to_F32LSB },
-    { AUDIO_U16MSB, AUDIO_F32MSB, SDL_Convert_U16MSB_to_F32MSB },
-    { AUDIO_S16MSB, AUDIO_U8, SDL_Convert_S16MSB_to_U8 },
-    { AUDIO_S16MSB, AUDIO_S8, SDL_Convert_S16MSB_to_S8 },
-    { AUDIO_S16MSB, AUDIO_U16LSB, SDL_Convert_S16MSB_to_U16LSB },
-    { AUDIO_S16MSB, AUDIO_S16LSB, SDL_Convert_S16MSB_to_S16LSB },
-    { AUDIO_S16MSB, AUDIO_U16MSB, SDL_Convert_S16MSB_to_U16MSB },
-    { AUDIO_S16MSB, AUDIO_S32LSB, SDL_Convert_S16MSB_to_S32LSB },
-    { AUDIO_S16MSB, AUDIO_S32MSB, SDL_Convert_S16MSB_to_S32MSB },
-    { AUDIO_S16MSB, AUDIO_F32LSB, SDL_Convert_S16MSB_to_F32LSB },
-    { AUDIO_S16MSB, AUDIO_F32MSB, SDL_Convert_S16MSB_to_F32MSB },
-    { AUDIO_S32LSB, AUDIO_U8, SDL_Convert_S32LSB_to_U8 },
-    { AUDIO_S32LSB, AUDIO_S8, SDL_Convert_S32LSB_to_S8 },
-    { AUDIO_S32LSB, AUDIO_U16LSB, SDL_Convert_S32LSB_to_U16LSB },
-    { AUDIO_S32LSB, AUDIO_S16LSB, SDL_Convert_S32LSB_to_S16LSB },
-    { AUDIO_S32LSB, AUDIO_U16MSB, SDL_Convert_S32LSB_to_U16MSB },
-    { AUDIO_S32LSB, AUDIO_S16MSB, SDL_Convert_S32LSB_to_S16MSB },
-    { AUDIO_S32LSB, AUDIO_S32MSB, SDL_Convert_S32LSB_to_S32MSB },
-    { AUDIO_S32LSB, AUDIO_F32LSB, SDL_Convert_S32LSB_to_F32LSB },
-    { AUDIO_S32LSB, AUDIO_F32MSB, SDL_Convert_S32LSB_to_F32MSB },
-    { AUDIO_S32MSB, AUDIO_U8, SDL_Convert_S32MSB_to_U8 },
-    { AUDIO_S32MSB, AUDIO_S8, SDL_Convert_S32MSB_to_S8 },
-    { AUDIO_S32MSB, AUDIO_U16LSB, SDL_Convert_S32MSB_to_U16LSB },
-    { AUDIO_S32MSB, AUDIO_S16LSB, SDL_Convert_S32MSB_to_S16LSB },
-    { AUDIO_S32MSB, AUDIO_U16MSB, SDL_Convert_S32MSB_to_U16MSB },
-    { AUDIO_S32MSB, AUDIO_S16MSB, SDL_Convert_S32MSB_to_S16MSB },
-    { AUDIO_S32MSB, AUDIO_S32LSB, SDL_Convert_S32MSB_to_S32LSB },
-    { AUDIO_S32MSB, AUDIO_F32LSB, SDL_Convert_S32MSB_to_F32LSB },
-    { AUDIO_S32MSB, AUDIO_F32MSB, SDL_Convert_S32MSB_to_F32MSB },
-    { AUDIO_F32LSB, AUDIO_U8, SDL_Convert_F32LSB_to_U8 },
-    { AUDIO_F32LSB, AUDIO_S8, SDL_Convert_F32LSB_to_S8 },
-    { AUDIO_F32LSB, AUDIO_U16LSB, SDL_Convert_F32LSB_to_U16LSB },
-    { AUDIO_F32LSB, AUDIO_S16LSB, SDL_Convert_F32LSB_to_S16LSB },
-    { AUDIO_F32LSB, AUDIO_U16MSB, SDL_Convert_F32LSB_to_U16MSB },
-    { AUDIO_F32LSB, AUDIO_S16MSB, SDL_Convert_F32LSB_to_S16MSB },
-    { AUDIO_F32LSB, AUDIO_S32LSB, SDL_Convert_F32LSB_to_S32LSB },
-    { AUDIO_F32LSB, AUDIO_S32MSB, SDL_Convert_F32LSB_to_S32MSB },
-    { AUDIO_F32LSB, AUDIO_F32MSB, SDL_Convert_F32LSB_to_F32MSB },
-    { AUDIO_F32MSB, AUDIO_U8, SDL_Convert_F32MSB_to_U8 },
-    { AUDIO_F32MSB, AUDIO_S8, SDL_Convert_F32MSB_to_S8 },
-    { AUDIO_F32MSB, AUDIO_U16LSB, SDL_Convert_F32MSB_to_U16LSB },
-    { AUDIO_F32MSB, AUDIO_S16LSB, SDL_Convert_F32MSB_to_S16LSB },
-    { AUDIO_F32MSB, AUDIO_U16MSB, SDL_Convert_F32MSB_to_U16MSB },
-    { AUDIO_F32MSB, AUDIO_S16MSB, SDL_Convert_F32MSB_to_S16MSB },
-    { AUDIO_F32MSB, AUDIO_S32LSB, SDL_Convert_F32MSB_to_S32LSB },
-    { AUDIO_F32MSB, AUDIO_S32MSB, SDL_Convert_F32MSB_to_S32MSB },
-    { AUDIO_F32MSB, AUDIO_F32LSB, SDL_Convert_F32MSB_to_F32LSB },
-#endif  /* !NO_CONVERTERS */
-    { 0, 0, NULL }
-};
-
-
-#if !NO_RESAMPLERS
-
-static void SDLCALL
-SDL_Upsample_U8_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U8, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 16;
-    const int dstsize = (int) (((double)(cvt->len_cvt/1)) * cvt->rate_incr) * 1;
-    register int eps = 0;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 1;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Uint8 sample0 = src[0];
-    Uint8 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[0] = sample0;
-        dst--;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src--;
-            sample0 = (Uint8) ((((Sint16) src[0]) + ((Sint16) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U8, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 16;
-    const int dstsize = (int) (((double)(cvt->len_cvt/1)) * cvt->rate_incr) * 1;
-    register int eps = 0;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Uint8 sample0 = src[0];
-    Uint8 last_sample0 = sample0;
-    while (dst < target) {
-        src++;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = sample0;
-            dst++;
-            sample0 = (Uint8) ((((Sint16) src[0]) + ((Sint16) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U8, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 2;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Uint8 sample1 = src[1];
-    Uint8 sample0 = src[0];
-    Uint8 last_sample1 = sample1;
-    Uint8 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[1] = sample1;
-        dst[0] = sample0;
-        dst -= 2;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 2;
-            sample1 = (Uint8) ((((Sint16) src[1]) + ((Sint16) last_sample1)) >> 1);
-            sample0 = (Uint8) ((((Sint16) src[0]) + ((Sint16) last_sample0)) >> 1);
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U8, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Uint8 sample0 = src[0];
-    Uint8 sample1 = src[1];
-    Uint8 last_sample0 = sample0;
-    Uint8 last_sample1 = sample1;
-    while (dst < target) {
-        src += 2;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = sample0;
-            dst[1] = sample1;
-            dst += 2;
-            sample0 = (Uint8) ((((Sint16) src[0]) + ((Sint16) last_sample0)) >> 1);
-            sample1 = (Uint8) ((((Sint16) src[1]) + ((Sint16) last_sample1)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U8, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 4;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Uint8 sample3 = src[3];
-    Uint8 sample2 = src[2];
-    Uint8 sample1 = src[1];
-    Uint8 sample0 = src[0];
-    Uint8 last_sample3 = sample3;
-    Uint8 last_sample2 = sample2;
-    Uint8 last_sample1 = sample1;
-    Uint8 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[3] = sample3;
-        dst[2] = sample2;
-        dst[1] = sample1;
-        dst[0] = sample0;
-        dst -= 4;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 4;
-            sample3 = (Uint8) ((((Sint16) src[3]) + ((Sint16) last_sample3)) >> 1);
-            sample2 = (Uint8) ((((Sint16) src[2]) + ((Sint16) last_sample2)) >> 1);
-            sample1 = (Uint8) ((((Sint16) src[1]) + ((Sint16) last_sample1)) >> 1);
-            sample0 = (Uint8) ((((Sint16) src[0]) + ((Sint16) last_sample0)) >> 1);
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U8, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Uint8 sample0 = src[0];
-    Uint8 sample1 = src[1];
-    Uint8 sample2 = src[2];
-    Uint8 sample3 = src[3];
-    Uint8 last_sample0 = sample0;
-    Uint8 last_sample1 = sample1;
-    Uint8 last_sample2 = sample2;
-    Uint8 last_sample3 = sample3;
-    while (dst < target) {
-        src += 4;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = sample0;
-            dst[1] = sample1;
-            dst[2] = sample2;
-            dst[3] = sample3;
-            dst += 4;
-            sample0 = (Uint8) ((((Sint16) src[0]) + ((Sint16) last_sample0)) >> 1);
-            sample1 = (Uint8) ((((Sint16) src[1]) + ((Sint16) last_sample1)) >> 1);
-            sample2 = (Uint8) ((((Sint16) src[2]) + ((Sint16) last_sample2)) >> 1);
-            sample3 = (Uint8) ((((Sint16) src[3]) + ((Sint16) last_sample3)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U8, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 96;
-    const int dstsize = (int) (((double)(cvt->len_cvt/6)) * cvt->rate_incr) * 6;
-    register int eps = 0;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 6;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Uint8 sample5 = src[5];
-    Uint8 sample4 = src[4];
-    Uint8 sample3 = src[3];
-    Uint8 sample2 = src[2];
-    Uint8 sample1 = src[1];
-    Uint8 sample0 = src[0];
-    Uint8 last_sample5 = sample5;
-    Uint8 last_sample4 = sample4;
-    Uint8 last_sample3 = sample3;
-    Uint8 last_sample2 = sample2;
-    Uint8 last_sample1 = sample1;
-    Uint8 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[5] = sample5;
-        dst[4] = sample4;
-        dst[3] = sample3;
-        dst[2] = sample2;
-        dst[1] = sample1;
-        dst[0] = sample0;
-        dst -= 6;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 6;
-            sample5 = (Uint8) ((((Sint16) src[5]) + ((Sint16) last_sample5)) >> 1);
-            sample4 = (Uint8) ((((Sint16) src[4]) + ((Sint16) last_sample4)) >> 1);
-            sample3 = (Uint8) ((((Sint16) src[3]) + ((Sint16) last_sample3)) >> 1);
-            sample2 = (Uint8) ((((Sint16) src[2]) + ((Sint16) last_sample2)) >> 1);
-            sample1 = (Uint8) ((((Sint16) src[1]) + ((Sint16) last_sample1)) >> 1);
-            sample0 = (Uint8) ((((Sint16) src[0]) + ((Sint16) last_sample0)) >> 1);
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U8, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 96;
-    const int dstsize = (int) (((double)(cvt->len_cvt/6)) * cvt->rate_incr) * 6;
-    register int eps = 0;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Uint8 sample0 = src[0];
-    Uint8 sample1 = src[1];
-    Uint8 sample2 = src[2];
-    Uint8 sample3 = src[3];
-    Uint8 sample4 = src[4];
-    Uint8 sample5 = src[5];
-    Uint8 last_sample0 = sample0;
-    Uint8 last_sample1 = sample1;
-    Uint8 last_sample2 = sample2;
-    Uint8 last_sample3 = sample3;
-    Uint8 last_sample4 = sample4;
-    Uint8 last_sample5 = sample5;
-    while (dst < target) {
-        src += 6;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = sample0;
-            dst[1] = sample1;
-            dst[2] = sample2;
-            dst[3] = sample3;
-            dst[4] = sample4;
-            dst[5] = sample5;
-            dst += 6;
-            sample0 = (Uint8) ((((Sint16) src[0]) + ((Sint16) last_sample0)) >> 1);
-            sample1 = (Uint8) ((((Sint16) src[1]) + ((Sint16) last_sample1)) >> 1);
-            sample2 = (Uint8) ((((Sint16) src[2]) + ((Sint16) last_sample2)) >> 1);
-            sample3 = (Uint8) ((((Sint16) src[3]) + ((Sint16) last_sample3)) >> 1);
-            sample4 = (Uint8) ((((Sint16) src[4]) + ((Sint16) last_sample4)) >> 1);
-            sample5 = (Uint8) ((((Sint16) src[5]) + ((Sint16) last_sample5)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U8, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 8;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Uint8 sample7 = src[7];
-    Uint8 sample6 = src[6];
-    Uint8 sample5 = src[5];
-    Uint8 sample4 = src[4];
-    Uint8 sample3 = src[3];
-    Uint8 sample2 = src[2];
-    Uint8 sample1 = src[1];
-    Uint8 sample0 = src[0];
-    Uint8 last_sample7 = sample7;
-    Uint8 last_sample6 = sample6;
-    Uint8 last_sample5 = sample5;
-    Uint8 last_sample4 = sample4;
-    Uint8 last_sample3 = sample3;
-    Uint8 last_sample2 = sample2;
-    Uint8 last_sample1 = sample1;
-    Uint8 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[7] = sample7;
-        dst[6] = sample6;
-        dst[5] = sample5;
-        dst[4] = sample4;
-        dst[3] = sample3;
-        dst[2] = sample2;
-        dst[1] = sample1;
-        dst[0] = sample0;
-        dst -= 8;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 8;
-            sample7 = (Uint8) ((((Sint16) src[7]) + ((Sint16) last_sample7)) >> 1);
-            sample6 = (Uint8) ((((Sint16) src[6]) + ((Sint16) last_sample6)) >> 1);
-            sample5 = (Uint8) ((((Sint16) src[5]) + ((Sint16) last_sample5)) >> 1);
-            sample4 = (Uint8) ((((Sint16) src[4]) + ((Sint16) last_sample4)) >> 1);
-            sample3 = (Uint8) ((((Sint16) src[3]) + ((Sint16) last_sample3)) >> 1);
-            sample2 = (Uint8) ((((Sint16) src[2]) + ((Sint16) last_sample2)) >> 1);
-            sample1 = (Uint8) ((((Sint16) src[1]) + ((Sint16) last_sample1)) >> 1);
-            sample0 = (Uint8) ((((Sint16) src[0]) + ((Sint16) last_sample0)) >> 1);
-            last_sample7 = sample7;
-            last_sample6 = sample6;
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U8, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Uint8 sample0 = src[0];
-    Uint8 sample1 = src[1];
-    Uint8 sample2 = src[2];
-    Uint8 sample3 = src[3];
-    Uint8 sample4 = src[4];
-    Uint8 sample5 = src[5];
-    Uint8 sample6 = src[6];
-    Uint8 sample7 = src[7];
-    Uint8 last_sample0 = sample0;
-    Uint8 last_sample1 = sample1;
-    Uint8 last_sample2 = sample2;
-    Uint8 last_sample3 = sample3;
-    Uint8 last_sample4 = sample4;
-    Uint8 last_sample5 = sample5;
-    Uint8 last_sample6 = sample6;
-    Uint8 last_sample7 = sample7;
-    while (dst < target) {
-        src += 8;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = sample0;
-            dst[1] = sample1;
-            dst[2] = sample2;
-            dst[3] = sample3;
-            dst[4] = sample4;
-            dst[5] = sample5;
-            dst[6] = sample6;
-            dst[7] = sample7;
-            dst += 8;
-            sample0 = (Uint8) ((((Sint16) src[0]) + ((Sint16) last_sample0)) >> 1);
-            sample1 = (Uint8) ((((Sint16) src[1]) + ((Sint16) last_sample1)) >> 1);
-            sample2 = (Uint8) ((((Sint16) src[2]) + ((Sint16) last_sample2)) >> 1);
-            sample3 = (Uint8) ((((Sint16) src[3]) + ((Sint16) last_sample3)) >> 1);
-            sample4 = (Uint8) ((((Sint16) src[4]) + ((Sint16) last_sample4)) >> 1);
-            sample5 = (Uint8) ((((Sint16) src[5]) + ((Sint16) last_sample5)) >> 1);
-            sample6 = (Uint8) ((((Sint16) src[6]) + ((Sint16) last_sample6)) >> 1);
-            sample7 = (Uint8) ((((Sint16) src[7]) + ((Sint16) last_sample7)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            last_sample6 = sample6;
-            last_sample7 = sample7;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S8, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 16;
-    const int dstsize = (int) (((double)(cvt->len_cvt/1)) * cvt->rate_incr) * 1;
-    register int eps = 0;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 1;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint8 sample0 = ((Sint8) src[0]);
-    Sint8 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[0] = ((Sint8) sample0);
-        dst--;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src--;
-            sample0 = (Sint8) ((((Sint16) ((Sint8) src[0])) + ((Sint16) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S8, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 16;
-    const int dstsize = (int) (((double)(cvt->len_cvt/1)) * cvt->rate_incr) * 1;
-    register int eps = 0;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint8 sample0 = ((Sint8) src[0]);
-    Sint8 last_sample0 = sample0;
-    while (dst < target) {
-        src++;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint8) sample0);
-            dst++;
-            sample0 = (Sint8) ((((Sint16) ((Sint8) src[0])) + ((Sint16) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S8, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 2;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint8 sample1 = ((Sint8) src[1]);
-    Sint8 sample0 = ((Sint8) src[0]);
-    Sint8 last_sample1 = sample1;
-    Sint8 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[1] = ((Sint8) sample1);
-        dst[0] = ((Sint8) sample0);
-        dst -= 2;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 2;
-            sample1 = (Sint8) ((((Sint16) ((Sint8) src[1])) + ((Sint16) last_sample1)) >> 1);
-            sample0 = (Sint8) ((((Sint16) ((Sint8) src[0])) + ((Sint16) last_sample0)) >> 1);
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S8, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint8 sample0 = ((Sint8) src[0]);
-    Sint8 sample1 = ((Sint8) src[1]);
-    Sint8 last_sample0 = sample0;
-    Sint8 last_sample1 = sample1;
-    while (dst < target) {
-        src += 2;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint8) sample0);
-            dst[1] = ((Sint8) sample1);
-            dst += 2;
-            sample0 = (Sint8) ((((Sint16) ((Sint8) src[0])) + ((Sint16) last_sample0)) >> 1);
-            sample1 = (Sint8) ((((Sint16) ((Sint8) src[1])) + ((Sint16) last_sample1)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S8, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 4;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint8 sample3 = ((Sint8) src[3]);
-    Sint8 sample2 = ((Sint8) src[2]);
-    Sint8 sample1 = ((Sint8) src[1]);
-    Sint8 sample0 = ((Sint8) src[0]);
-    Sint8 last_sample3 = sample3;
-    Sint8 last_sample2 = sample2;
-    Sint8 last_sample1 = sample1;
-    Sint8 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[3] = ((Sint8) sample3);
-        dst[2] = ((Sint8) sample2);
-        dst[1] = ((Sint8) sample1);
-        dst[0] = ((Sint8) sample0);
-        dst -= 4;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 4;
-            sample3 = (Sint8) ((((Sint16) ((Sint8) src[3])) + ((Sint16) last_sample3)) >> 1);
-            sample2 = (Sint8) ((((Sint16) ((Sint8) src[2])) + ((Sint16) last_sample2)) >> 1);
-            sample1 = (Sint8) ((((Sint16) ((Sint8) src[1])) + ((Sint16) last_sample1)) >> 1);
-            sample0 = (Sint8) ((((Sint16) ((Sint8) src[0])) + ((Sint16) last_sample0)) >> 1);
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S8, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint8 sample0 = ((Sint8) src[0]);
-    Sint8 sample1 = ((Sint8) src[1]);
-    Sint8 sample2 = ((Sint8) src[2]);
-    Sint8 sample3 = ((Sint8) src[3]);
-    Sint8 last_sample0 = sample0;
-    Sint8 last_sample1 = sample1;
-    Sint8 last_sample2 = sample2;
-    Sint8 last_sample3 = sample3;
-    while (dst < target) {
-        src += 4;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint8) sample0);
-            dst[1] = ((Sint8) sample1);
-            dst[2] = ((Sint8) sample2);
-            dst[3] = ((Sint8) sample3);
-            dst += 4;
-            sample0 = (Sint8) ((((Sint16) ((Sint8) src[0])) + ((Sint16) last_sample0)) >> 1);
-            sample1 = (Sint8) ((((Sint16) ((Sint8) src[1])) + ((Sint16) last_sample1)) >> 1);
-            sample2 = (Sint8) ((((Sint16) ((Sint8) src[2])) + ((Sint16) last_sample2)) >> 1);
-            sample3 = (Sint8) ((((Sint16) ((Sint8) src[3])) + ((Sint16) last_sample3)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S8, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 96;
-    const int dstsize = (int) (((double)(cvt->len_cvt/6)) * cvt->rate_incr) * 6;
-    register int eps = 0;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 6;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint8 sample5 = ((Sint8) src[5]);
-    Sint8 sample4 = ((Sint8) src[4]);
-    Sint8 sample3 = ((Sint8) src[3]);
-    Sint8 sample2 = ((Sint8) src[2]);
-    Sint8 sample1 = ((Sint8) src[1]);
-    Sint8 sample0 = ((Sint8) src[0]);
-    Sint8 last_sample5 = sample5;
-    Sint8 last_sample4 = sample4;
-    Sint8 last_sample3 = sample3;
-    Sint8 last_sample2 = sample2;
-    Sint8 last_sample1 = sample1;
-    Sint8 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[5] = ((Sint8) sample5);
-        dst[4] = ((Sint8) sample4);
-        dst[3] = ((Sint8) sample3);
-        dst[2] = ((Sint8) sample2);
-        dst[1] = ((Sint8) sample1);
-        dst[0] = ((Sint8) sample0);
-        dst -= 6;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 6;
-            sample5 = (Sint8) ((((Sint16) ((Sint8) src[5])) + ((Sint16) last_sample5)) >> 1);
-            sample4 = (Sint8) ((((Sint16) ((Sint8) src[4])) + ((Sint16) last_sample4)) >> 1);
-            sample3 = (Sint8) ((((Sint16) ((Sint8) src[3])) + ((Sint16) last_sample3)) >> 1);
-            sample2 = (Sint8) ((((Sint16) ((Sint8) src[2])) + ((Sint16) last_sample2)) >> 1);
-            sample1 = (Sint8) ((((Sint16) ((Sint8) src[1])) + ((Sint16) last_sample1)) >> 1);
-            sample0 = (Sint8) ((((Sint16) ((Sint8) src[0])) + ((Sint16) last_sample0)) >> 1);
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S8, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 96;
-    const int dstsize = (int) (((double)(cvt->len_cvt/6)) * cvt->rate_incr) * 6;
-    register int eps = 0;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint8 sample0 = ((Sint8) src[0]);
-    Sint8 sample1 = ((Sint8) src[1]);
-    Sint8 sample2 = ((Sint8) src[2]);
-    Sint8 sample3 = ((Sint8) src[3]);
-    Sint8 sample4 = ((Sint8) src[4]);
-    Sint8 sample5 = ((Sint8) src[5]);
-    Sint8 last_sample0 = sample0;
-    Sint8 last_sample1 = sample1;
-    Sint8 last_sample2 = sample2;
-    Sint8 last_sample3 = sample3;
-    Sint8 last_sample4 = sample4;
-    Sint8 last_sample5 = sample5;
-    while (dst < target) {
-        src += 6;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint8) sample0);
-            dst[1] = ((Sint8) sample1);
-            dst[2] = ((Sint8) sample2);
-            dst[3] = ((Sint8) sample3);
-            dst[4] = ((Sint8) sample4);
-            dst[5] = ((Sint8) sample5);
-            dst += 6;
-            sample0 = (Sint8) ((((Sint16) ((Sint8) src[0])) + ((Sint16) last_sample0)) >> 1);
-            sample1 = (Sint8) ((((Sint16) ((Sint8) src[1])) + ((Sint16) last_sample1)) >> 1);
-            sample2 = (Sint8) ((((Sint16) ((Sint8) src[2])) + ((Sint16) last_sample2)) >> 1);
-            sample3 = (Sint8) ((((Sint16) ((Sint8) src[3])) + ((Sint16) last_sample3)) >> 1);
-            sample4 = (Sint8) ((((Sint16) ((Sint8) src[4])) + ((Sint16) last_sample4)) >> 1);
-            sample5 = (Sint8) ((((Sint16) ((Sint8) src[5])) + ((Sint16) last_sample5)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S8, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 8;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint8 sample7 = ((Sint8) src[7]);
-    Sint8 sample6 = ((Sint8) src[6]);
-    Sint8 sample5 = ((Sint8) src[5]);
-    Sint8 sample4 = ((Sint8) src[4]);
-    Sint8 sample3 = ((Sint8) src[3]);
-    Sint8 sample2 = ((Sint8) src[2]);
-    Sint8 sample1 = ((Sint8) src[1]);
-    Sint8 sample0 = ((Sint8) src[0]);
-    Sint8 last_sample7 = sample7;
-    Sint8 last_sample6 = sample6;
-    Sint8 last_sample5 = sample5;
-    Sint8 last_sample4 = sample4;
-    Sint8 last_sample3 = sample3;
-    Sint8 last_sample2 = sample2;
-    Sint8 last_sample1 = sample1;
-    Sint8 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[7] = ((Sint8) sample7);
-        dst[6] = ((Sint8) sample6);
-        dst[5] = ((Sint8) sample5);
-        dst[4] = ((Sint8) sample4);
-        dst[3] = ((Sint8) sample3);
-        dst[2] = ((Sint8) sample2);
-        dst[1] = ((Sint8) sample1);
-        dst[0] = ((Sint8) sample0);
-        dst -= 8;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 8;
-            sample7 = (Sint8) ((((Sint16) ((Sint8) src[7])) + ((Sint16) last_sample7)) >> 1);
-            sample6 = (Sint8) ((((Sint16) ((Sint8) src[6])) + ((Sint16) last_sample6)) >> 1);
-            sample5 = (Sint8) ((((Sint16) ((Sint8) src[5])) + ((Sint16) last_sample5)) >> 1);
-            sample4 = (Sint8) ((((Sint16) ((Sint8) src[4])) + ((Sint16) last_sample4)) >> 1);
-            sample3 = (Sint8) ((((Sint16) ((Sint8) src[3])) + ((Sint16) last_sample3)) >> 1);
-            sample2 = (Sint8) ((((Sint16) ((Sint8) src[2])) + ((Sint16) last_sample2)) >> 1);
-            sample1 = (Sint8) ((((Sint16) ((Sint8) src[1])) + ((Sint16) last_sample1)) >> 1);
-            sample0 = (Sint8) ((((Sint16) ((Sint8) src[0])) + ((Sint16) last_sample0)) >> 1);
-            last_sample7 = sample7;
-            last_sample6 = sample6;
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S8, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint8 sample0 = ((Sint8) src[0]);
-    Sint8 sample1 = ((Sint8) src[1]);
-    Sint8 sample2 = ((Sint8) src[2]);
-    Sint8 sample3 = ((Sint8) src[3]);
-    Sint8 sample4 = ((Sint8) src[4]);
-    Sint8 sample5 = ((Sint8) src[5]);
-    Sint8 sample6 = ((Sint8) src[6]);
-    Sint8 sample7 = ((Sint8) src[7]);
-    Sint8 last_sample0 = sample0;
-    Sint8 last_sample1 = sample1;
-    Sint8 last_sample2 = sample2;
-    Sint8 last_sample3 = sample3;
-    Sint8 last_sample4 = sample4;
-    Sint8 last_sample5 = sample5;
-    Sint8 last_sample6 = sample6;
-    Sint8 last_sample7 = sample7;
-    while (dst < target) {
-        src += 8;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint8) sample0);
-            dst[1] = ((Sint8) sample1);
-            dst[2] = ((Sint8) sample2);
-            dst[3] = ((Sint8) sample3);
-            dst[4] = ((Sint8) sample4);
-            dst[5] = ((Sint8) sample5);
-            dst[6] = ((Sint8) sample6);
-            dst[7] = ((Sint8) sample7);
-            dst += 8;
-            sample0 = (Sint8) ((((Sint16) ((Sint8) src[0])) + ((Sint16) last_sample0)) >> 1);
-            sample1 = (Sint8) ((((Sint16) ((Sint8) src[1])) + ((Sint16) last_sample1)) >> 1);
-            sample2 = (Sint8) ((((Sint16) ((Sint8) src[2])) + ((Sint16) last_sample2)) >> 1);
-            sample3 = (Sint8) ((((Sint16) ((Sint8) src[3])) + ((Sint16) last_sample3)) >> 1);
-            sample4 = (Sint8) ((((Sint16) ((Sint8) src[4])) + ((Sint16) last_sample4)) >> 1);
-            sample5 = (Sint8) ((((Sint16) ((Sint8) src[5])) + ((Sint16) last_sample5)) >> 1);
-            sample6 = (Sint8) ((((Sint16) ((Sint8) src[6])) + ((Sint16) last_sample6)) >> 1);
-            sample7 = (Sint8) ((((Sint16) ((Sint8) src[7])) + ((Sint16) last_sample7)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            last_sample6 = sample6;
-            last_sample7 = sample7;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U16LSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 1;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Uint16 sample0 = SDL_SwapLE16(src[0]);
-    Uint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[0] = SDL_SwapLE16(sample0);
-        dst--;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src--;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapLE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U16LSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Uint16 sample0 = SDL_SwapLE16(src[0]);
-    Uint16 last_sample0 = sample0;
-    while (dst < target) {
-        src++;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapLE16(sample0);
-            dst++;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapLE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U16LSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Uint16 sample1 = SDL_SwapLE16(src[1]);
-    Uint16 sample0 = SDL_SwapLE16(src[0]);
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[1] = SDL_SwapLE16(sample1);
-        dst[0] = SDL_SwapLE16(sample0);
-        dst -= 2;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 2;
-            sample1 = (Uint16) ((((Sint32) SDL_SwapLE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Uint16) ((((Sint32) SDL_SwapLE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U16LSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Uint16 sample0 = SDL_SwapLE16(src[0]);
-    Uint16 sample1 = SDL_SwapLE16(src[1]);
-    Uint16 last_sample0 = sample0;
-    Uint16 last_sample1 = sample1;
-    while (dst < target) {
-        src += 2;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapLE16(sample0);
-            dst[1] = SDL_SwapLE16(sample1);
-            dst += 2;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapLE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapLE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U16LSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Uint16 sample3 = SDL_SwapLE16(src[3]);
-    Uint16 sample2 = SDL_SwapLE16(src[2]);
-    Uint16 sample1 = SDL_SwapLE16(src[1]);
-    Uint16 sample0 = SDL_SwapLE16(src[0]);
-    Uint16 last_sample3 = sample3;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[3] = SDL_SwapLE16(sample3);
-        dst[2] = SDL_SwapLE16(sample2);
-        dst[1] = SDL_SwapLE16(sample1);
-        dst[0] = SDL_SwapLE16(sample0);
-        dst -= 4;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 4;
-            sample3 = (Uint16) ((((Sint32) SDL_SwapLE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapLE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapLE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Uint16) ((((Sint32) SDL_SwapLE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U16LSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Uint16 sample0 = SDL_SwapLE16(src[0]);
-    Uint16 sample1 = SDL_SwapLE16(src[1]);
-    Uint16 sample2 = SDL_SwapLE16(src[2]);
-    Uint16 sample3 = SDL_SwapLE16(src[3]);
-    Uint16 last_sample0 = sample0;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample3 = sample3;
-    while (dst < target) {
-        src += 4;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapLE16(sample0);
-            dst[1] = SDL_SwapLE16(sample1);
-            dst[2] = SDL_SwapLE16(sample2);
-            dst[3] = SDL_SwapLE16(sample3);
-            dst += 4;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapLE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapLE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapLE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Uint16) ((((Sint32) SDL_SwapLE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U16LSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 192;
-    const int dstsize = (int) (((double)(cvt->len_cvt/12)) * cvt->rate_incr) * 12;
-    register int eps = 0;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 6;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Uint16 sample5 = SDL_SwapLE16(src[5]);
-    Uint16 sample4 = SDL_SwapLE16(src[4]);
-    Uint16 sample3 = SDL_SwapLE16(src[3]);
-    Uint16 sample2 = SDL_SwapLE16(src[2]);
-    Uint16 sample1 = SDL_SwapLE16(src[1]);
-    Uint16 sample0 = SDL_SwapLE16(src[0]);
-    Uint16 last_sample5 = sample5;
-    Uint16 last_sample4 = sample4;
-    Uint16 last_sample3 = sample3;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[5] = SDL_SwapLE16(sample5);
-        dst[4] = SDL_SwapLE16(sample4);
-        dst[3] = SDL_SwapLE16(sample3);
-        dst[2] = SDL_SwapLE16(sample2);
-        dst[1] = SDL_SwapLE16(sample1);
-        dst[0] = SDL_SwapLE16(sample0);
-        dst -= 6;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 6;
-            sample5 = (Uint16) ((((Sint32) SDL_SwapLE16(src[5])) + ((Sint32) last_sample5)) >> 1);
-            sample4 = (Uint16) ((((Sint32) SDL_SwapLE16(src[4])) + ((Sint32) last_sample4)) >> 1);
-            sample3 = (Uint16) ((((Sint32) SDL_SwapLE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapLE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapLE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Uint16) ((((Sint32) SDL_SwapLE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U16LSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 192;
-    const int dstsize = (int) (((double)(cvt->len_cvt/12)) * cvt->rate_incr) * 12;
-    register int eps = 0;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Uint16 sample0 = SDL_SwapLE16(src[0]);
-    Uint16 sample1 = SDL_SwapLE16(src[1]);
-    Uint16 sample2 = SDL_SwapLE16(src[2]);
-    Uint16 sample3 = SDL_SwapLE16(src[3]);
-    Uint16 sample4 = SDL_SwapLE16(src[4]);
-    Uint16 sample5 = SDL_SwapLE16(src[5]);
-    Uint16 last_sample0 = sample0;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample3 = sample3;
-    Uint16 last_sample4 = sample4;
-    Uint16 last_sample5 = sample5;
-    while (dst < target) {
-        src += 6;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapLE16(sample0);
-            dst[1] = SDL_SwapLE16(sample1);
-            dst[2] = SDL_SwapLE16(sample2);
-            dst[3] = SDL_SwapLE16(sample3);
-            dst[4] = SDL_SwapLE16(sample4);
-            dst[5] = SDL_SwapLE16(sample5);
-            dst += 6;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapLE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapLE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapLE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Uint16) ((((Sint32) SDL_SwapLE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            sample4 = (Uint16) ((((Sint32) SDL_SwapLE16(src[4])) + ((Sint32) last_sample4)) >> 1);
-            sample5 = (Uint16) ((((Sint32) SDL_SwapLE16(src[5])) + ((Sint32) last_sample5)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U16LSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 8;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Uint16 sample7 = SDL_SwapLE16(src[7]);
-    Uint16 sample6 = SDL_SwapLE16(src[6]);
-    Uint16 sample5 = SDL_SwapLE16(src[5]);
-    Uint16 sample4 = SDL_SwapLE16(src[4]);
-    Uint16 sample3 = SDL_SwapLE16(src[3]);
-    Uint16 sample2 = SDL_SwapLE16(src[2]);
-    Uint16 sample1 = SDL_SwapLE16(src[1]);
-    Uint16 sample0 = SDL_SwapLE16(src[0]);
-    Uint16 last_sample7 = sample7;
-    Uint16 last_sample6 = sample6;
-    Uint16 last_sample5 = sample5;
-    Uint16 last_sample4 = sample4;
-    Uint16 last_sample3 = sample3;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[7] = SDL_SwapLE16(sample7);
-        dst[6] = SDL_SwapLE16(sample6);
-        dst[5] = SDL_SwapLE16(sample5);
-        dst[4] = SDL_SwapLE16(sample4);
-        dst[3] = SDL_SwapLE16(sample3);
-        dst[2] = SDL_SwapLE16(sample2);
-        dst[1] = SDL_SwapLE16(sample1);
-        dst[0] = SDL_SwapLE16(sample0);
-        dst -= 8;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 8;
-            sample7 = (Uint16) ((((Sint32) SDL_SwapLE16(src[7])) + ((Sint32) last_sample7)) >> 1);
-            sample6 = (Uint16) ((((Sint32) SDL_SwapLE16(src[6])) + ((Sint32) last_sample6)) >> 1);
-            sample5 = (Uint16) ((((Sint32) SDL_SwapLE16(src[5])) + ((Sint32) last_sample5)) >> 1);
-            sample4 = (Uint16) ((((Sint32) SDL_SwapLE16(src[4])) + ((Sint32) last_sample4)) >> 1);
-            sample3 = (Uint16) ((((Sint32) SDL_SwapLE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapLE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapLE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Uint16) ((((Sint32) SDL_SwapLE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample7 = sample7;
-            last_sample6 = sample6;
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U16LSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Uint16 sample0 = SDL_SwapLE16(src[0]);
-    Uint16 sample1 = SDL_SwapLE16(src[1]);
-    Uint16 sample2 = SDL_SwapLE16(src[2]);
-    Uint16 sample3 = SDL_SwapLE16(src[3]);
-    Uint16 sample4 = SDL_SwapLE16(src[4]);
-    Uint16 sample5 = SDL_SwapLE16(src[5]);
-    Uint16 sample6 = SDL_SwapLE16(src[6]);
-    Uint16 sample7 = SDL_SwapLE16(src[7]);
-    Uint16 last_sample0 = sample0;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample3 = sample3;
-    Uint16 last_sample4 = sample4;
-    Uint16 last_sample5 = sample5;
-    Uint16 last_sample6 = sample6;
-    Uint16 last_sample7 = sample7;
-    while (dst < target) {
-        src += 8;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapLE16(sample0);
-            dst[1] = SDL_SwapLE16(sample1);
-            dst[2] = SDL_SwapLE16(sample2);
-            dst[3] = SDL_SwapLE16(sample3);
-            dst[4] = SDL_SwapLE16(sample4);
-            dst[5] = SDL_SwapLE16(sample5);
-            dst[6] = SDL_SwapLE16(sample6);
-            dst[7] = SDL_SwapLE16(sample7);
-            dst += 8;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapLE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapLE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapLE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Uint16) ((((Sint32) SDL_SwapLE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            sample4 = (Uint16) ((((Sint32) SDL_SwapLE16(src[4])) + ((Sint32) last_sample4)) >> 1);
-            sample5 = (Uint16) ((((Sint32) SDL_SwapLE16(src[5])) + ((Sint32) last_sample5)) >> 1);
-            sample6 = (Uint16) ((((Sint32) SDL_SwapLE16(src[6])) + ((Sint32) last_sample6)) >> 1);
-            sample7 = (Uint16) ((((Sint32) SDL_SwapLE16(src[7])) + ((Sint32) last_sample7)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            last_sample6 = sample6;
-            last_sample7 = sample7;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S16LSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 1;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint16 sample0 = ((Sint16) SDL_SwapLE16(src[0]));
-    Sint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[0] = ((Sint16) SDL_SwapLE16(sample0));
-        dst--;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src--;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S16LSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint16 sample0 = ((Sint16) SDL_SwapLE16(src[0]));
-    Sint16 last_sample0 = sample0;
-    while (dst < target) {
-        src++;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint16) SDL_SwapLE16(sample0));
-            dst++;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S16LSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint16 sample1 = ((Sint16) SDL_SwapLE16(src[1]));
-    Sint16 sample0 = ((Sint16) SDL_SwapLE16(src[0]));
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[1] = ((Sint16) SDL_SwapLE16(sample1));
-        dst[0] = ((Sint16) SDL_SwapLE16(sample0));
-        dst -= 2;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 2;
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S16LSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint16 sample0 = ((Sint16) SDL_SwapLE16(src[0]));
-    Sint16 sample1 = ((Sint16) SDL_SwapLE16(src[1]));
-    Sint16 last_sample0 = sample0;
-    Sint16 last_sample1 = sample1;
-    while (dst < target) {
-        src += 2;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint16) SDL_SwapLE16(sample0));
-            dst[1] = ((Sint16) SDL_SwapLE16(sample1));
-            dst += 2;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S16LSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint16 sample3 = ((Sint16) SDL_SwapLE16(src[3]));
-    Sint16 sample2 = ((Sint16) SDL_SwapLE16(src[2]));
-    Sint16 sample1 = ((Sint16) SDL_SwapLE16(src[1]));
-    Sint16 sample0 = ((Sint16) SDL_SwapLE16(src[0]));
-    Sint16 last_sample3 = sample3;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[3] = ((Sint16) SDL_SwapLE16(sample3));
-        dst[2] = ((Sint16) SDL_SwapLE16(sample2));
-        dst[1] = ((Sint16) SDL_SwapLE16(sample1));
-        dst[0] = ((Sint16) SDL_SwapLE16(sample0));
-        dst -= 4;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 4;
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S16LSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint16 sample0 = ((Sint16) SDL_SwapLE16(src[0]));
-    Sint16 sample1 = ((Sint16) SDL_SwapLE16(src[1]));
-    Sint16 sample2 = ((Sint16) SDL_SwapLE16(src[2]));
-    Sint16 sample3 = ((Sint16) SDL_SwapLE16(src[3]));
-    Sint16 last_sample0 = sample0;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample3 = sample3;
-    while (dst < target) {
-        src += 4;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint16) SDL_SwapLE16(sample0));
-            dst[1] = ((Sint16) SDL_SwapLE16(sample1));
-            dst[2] = ((Sint16) SDL_SwapLE16(sample2));
-            dst[3] = ((Sint16) SDL_SwapLE16(sample3));
-            dst += 4;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S16LSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 192;
-    const int dstsize = (int) (((double)(cvt->len_cvt/12)) * cvt->rate_incr) * 12;
-    register int eps = 0;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 6;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint16 sample5 = ((Sint16) SDL_SwapLE16(src[5]));
-    Sint16 sample4 = ((Sint16) SDL_SwapLE16(src[4]));
-    Sint16 sample3 = ((Sint16) SDL_SwapLE16(src[3]));
-    Sint16 sample2 = ((Sint16) SDL_SwapLE16(src[2]));
-    Sint16 sample1 = ((Sint16) SDL_SwapLE16(src[1]));
-    Sint16 sample0 = ((Sint16) SDL_SwapLE16(src[0]));
-    Sint16 last_sample5 = sample5;
-    Sint16 last_sample4 = sample4;
-    Sint16 last_sample3 = sample3;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[5] = ((Sint16) SDL_SwapLE16(sample5));
-        dst[4] = ((Sint16) SDL_SwapLE16(sample4));
-        dst[3] = ((Sint16) SDL_SwapLE16(sample3));
-        dst[2] = ((Sint16) SDL_SwapLE16(sample2));
-        dst[1] = ((Sint16) SDL_SwapLE16(sample1));
-        dst[0] = ((Sint16) SDL_SwapLE16(sample0));
-        dst -= 6;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 6;
-            sample5 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[5]))) + ((Sint32) last_sample5)) >> 1);
-            sample4 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[4]))) + ((Sint32) last_sample4)) >> 1);
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S16LSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 192;
-    const int dstsize = (int) (((double)(cvt->len_cvt/12)) * cvt->rate_incr) * 12;
-    register int eps = 0;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint16 sample0 = ((Sint16) SDL_SwapLE16(src[0]));
-    Sint16 sample1 = ((Sint16) SDL_SwapLE16(src[1]));
-    Sint16 sample2 = ((Sint16) SDL_SwapLE16(src[2]));
-    Sint16 sample3 = ((Sint16) SDL_SwapLE16(src[3]));
-    Sint16 sample4 = ((Sint16) SDL_SwapLE16(src[4]));
-    Sint16 sample5 = ((Sint16) SDL_SwapLE16(src[5]));
-    Sint16 last_sample0 = sample0;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample3 = sample3;
-    Sint16 last_sample4 = sample4;
-    Sint16 last_sample5 = sample5;
-    while (dst < target) {
-        src += 6;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint16) SDL_SwapLE16(sample0));
-            dst[1] = ((Sint16) SDL_SwapLE16(sample1));
-            dst[2] = ((Sint16) SDL_SwapLE16(sample2));
-            dst[3] = ((Sint16) SDL_SwapLE16(sample3));
-            dst[4] = ((Sint16) SDL_SwapLE16(sample4));
-            dst[5] = ((Sint16) SDL_SwapLE16(sample5));
-            dst += 6;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            sample4 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[4]))) + ((Sint32) last_sample4)) >> 1);
-            sample5 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[5]))) + ((Sint32) last_sample5)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S16LSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 8;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint16 sample7 = ((Sint16) SDL_SwapLE16(src[7]));
-    Sint16 sample6 = ((Sint16) SDL_SwapLE16(src[6]));
-    Sint16 sample5 = ((Sint16) SDL_SwapLE16(src[5]));
-    Sint16 sample4 = ((Sint16) SDL_SwapLE16(src[4]));
-    Sint16 sample3 = ((Sint16) SDL_SwapLE16(src[3]));
-    Sint16 sample2 = ((Sint16) SDL_SwapLE16(src[2]));
-    Sint16 sample1 = ((Sint16) SDL_SwapLE16(src[1]));
-    Sint16 sample0 = ((Sint16) SDL_SwapLE16(src[0]));
-    Sint16 last_sample7 = sample7;
-    Sint16 last_sample6 = sample6;
-    Sint16 last_sample5 = sample5;
-    Sint16 last_sample4 = sample4;
-    Sint16 last_sample3 = sample3;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[7] = ((Sint16) SDL_SwapLE16(sample7));
-        dst[6] = ((Sint16) SDL_SwapLE16(sample6));
-        dst[5] = ((Sint16) SDL_SwapLE16(sample5));
-        dst[4] = ((Sint16) SDL_SwapLE16(sample4));
-        dst[3] = ((Sint16) SDL_SwapLE16(sample3));
-        dst[2] = ((Sint16) SDL_SwapLE16(sample2));
-        dst[1] = ((Sint16) SDL_SwapLE16(sample1));
-        dst[0] = ((Sint16) SDL_SwapLE16(sample0));
-        dst -= 8;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 8;
-            sample7 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[7]))) + ((Sint32) last_sample7)) >> 1);
-            sample6 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[6]))) + ((Sint32) last_sample6)) >> 1);
-            sample5 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[5]))) + ((Sint32) last_sample5)) >> 1);
-            sample4 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[4]))) + ((Sint32) last_sample4)) >> 1);
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample7 = sample7;
-            last_sample6 = sample6;
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S16LSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint16 sample0 = ((Sint16) SDL_SwapLE16(src[0]));
-    Sint16 sample1 = ((Sint16) SDL_SwapLE16(src[1]));
-    Sint16 sample2 = ((Sint16) SDL_SwapLE16(src[2]));
-    Sint16 sample3 = ((Sint16) SDL_SwapLE16(src[3]));
-    Sint16 sample4 = ((Sint16) SDL_SwapLE16(src[4]));
-    Sint16 sample5 = ((Sint16) SDL_SwapLE16(src[5]));
-    Sint16 sample6 = ((Sint16) SDL_SwapLE16(src[6]));
-    Sint16 sample7 = ((Sint16) SDL_SwapLE16(src[7]));
-    Sint16 last_sample0 = sample0;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample3 = sample3;
-    Sint16 last_sample4 = sample4;
-    Sint16 last_sample5 = sample5;
-    Sint16 last_sample6 = sample6;
-    Sint16 last_sample7 = sample7;
-    while (dst < target) {
-        src += 8;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint16) SDL_SwapLE16(sample0));
-            dst[1] = ((Sint16) SDL_SwapLE16(sample1));
-            dst[2] = ((Sint16) SDL_SwapLE16(sample2));
-            dst[3] = ((Sint16) SDL_SwapLE16(sample3));
-            dst[4] = ((Sint16) SDL_SwapLE16(sample4));
-            dst[5] = ((Sint16) SDL_SwapLE16(sample5));
-            dst[6] = ((Sint16) SDL_SwapLE16(sample6));
-            dst[7] = ((Sint16) SDL_SwapLE16(sample7));
-            dst += 8;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            sample4 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[4]))) + ((Sint32) last_sample4)) >> 1);
-            sample5 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[5]))) + ((Sint32) last_sample5)) >> 1);
-            sample6 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[6]))) + ((Sint32) last_sample6)) >> 1);
-            sample7 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapLE16(src[7]))) + ((Sint32) last_sample7)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            last_sample6 = sample6;
-            last_sample7 = sample7;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U16MSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 1;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Uint16 sample0 = SDL_SwapBE16(src[0]);
-    Uint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[0] = SDL_SwapBE16(sample0);
-        dst--;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src--;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapBE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U16MSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Uint16 sample0 = SDL_SwapBE16(src[0]);
-    Uint16 last_sample0 = sample0;
-    while (dst < target) {
-        src++;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapBE16(sample0);
-            dst++;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapBE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U16MSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Uint16 sample1 = SDL_SwapBE16(src[1]);
-    Uint16 sample0 = SDL_SwapBE16(src[0]);
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[1] = SDL_SwapBE16(sample1);
-        dst[0] = SDL_SwapBE16(sample0);
-        dst -= 2;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 2;
-            sample1 = (Uint16) ((((Sint32) SDL_SwapBE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Uint16) ((((Sint32) SDL_SwapBE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U16MSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Uint16 sample0 = SDL_SwapBE16(src[0]);
-    Uint16 sample1 = SDL_SwapBE16(src[1]);
-    Uint16 last_sample0 = sample0;
-    Uint16 last_sample1 = sample1;
-    while (dst < target) {
-        src += 2;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapBE16(sample0);
-            dst[1] = SDL_SwapBE16(sample1);
-            dst += 2;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapBE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapBE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U16MSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Uint16 sample3 = SDL_SwapBE16(src[3]);
-    Uint16 sample2 = SDL_SwapBE16(src[2]);
-    Uint16 sample1 = SDL_SwapBE16(src[1]);
-    Uint16 sample0 = SDL_SwapBE16(src[0]);
-    Uint16 last_sample3 = sample3;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[3] = SDL_SwapBE16(sample3);
-        dst[2] = SDL_SwapBE16(sample2);
-        dst[1] = SDL_SwapBE16(sample1);
-        dst[0] = SDL_SwapBE16(sample0);
-        dst -= 4;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 4;
-            sample3 = (Uint16) ((((Sint32) SDL_SwapBE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapBE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapBE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Uint16) ((((Sint32) SDL_SwapBE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U16MSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Uint16 sample0 = SDL_SwapBE16(src[0]);
-    Uint16 sample1 = SDL_SwapBE16(src[1]);
-    Uint16 sample2 = SDL_SwapBE16(src[2]);
-    Uint16 sample3 = SDL_SwapBE16(src[3]);
-    Uint16 last_sample0 = sample0;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample3 = sample3;
-    while (dst < target) {
-        src += 4;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapBE16(sample0);
-            dst[1] = SDL_SwapBE16(sample1);
-            dst[2] = SDL_SwapBE16(sample2);
-            dst[3] = SDL_SwapBE16(sample3);
-            dst += 4;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapBE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapBE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapBE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Uint16) ((((Sint32) SDL_SwapBE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U16MSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 192;
-    const int dstsize = (int) (((double)(cvt->len_cvt/12)) * cvt->rate_incr) * 12;
-    register int eps = 0;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 6;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Uint16 sample5 = SDL_SwapBE16(src[5]);
-    Uint16 sample4 = SDL_SwapBE16(src[4]);
-    Uint16 sample3 = SDL_SwapBE16(src[3]);
-    Uint16 sample2 = SDL_SwapBE16(src[2]);
-    Uint16 sample1 = SDL_SwapBE16(src[1]);
-    Uint16 sample0 = SDL_SwapBE16(src[0]);
-    Uint16 last_sample5 = sample5;
-    Uint16 last_sample4 = sample4;
-    Uint16 last_sample3 = sample3;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[5] = SDL_SwapBE16(sample5);
-        dst[4] = SDL_SwapBE16(sample4);
-        dst[3] = SDL_SwapBE16(sample3);
-        dst[2] = SDL_SwapBE16(sample2);
-        dst[1] = SDL_SwapBE16(sample1);
-        dst[0] = SDL_SwapBE16(sample0);
-        dst -= 6;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 6;
-            sample5 = (Uint16) ((((Sint32) SDL_SwapBE16(src[5])) + ((Sint32) last_sample5)) >> 1);
-            sample4 = (Uint16) ((((Sint32) SDL_SwapBE16(src[4])) + ((Sint32) last_sample4)) >> 1);
-            sample3 = (Uint16) ((((Sint32) SDL_SwapBE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapBE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapBE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Uint16) ((((Sint32) SDL_SwapBE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U16MSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 192;
-    const int dstsize = (int) (((double)(cvt->len_cvt/12)) * cvt->rate_incr) * 12;
-    register int eps = 0;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Uint16 sample0 = SDL_SwapBE16(src[0]);
-    Uint16 sample1 = SDL_SwapBE16(src[1]);
-    Uint16 sample2 = SDL_SwapBE16(src[2]);
-    Uint16 sample3 = SDL_SwapBE16(src[3]);
-    Uint16 sample4 = SDL_SwapBE16(src[4]);
-    Uint16 sample5 = SDL_SwapBE16(src[5]);
-    Uint16 last_sample0 = sample0;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample3 = sample3;
-    Uint16 last_sample4 = sample4;
-    Uint16 last_sample5 = sample5;
-    while (dst < target) {
-        src += 6;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapBE16(sample0);
-            dst[1] = SDL_SwapBE16(sample1);
-            dst[2] = SDL_SwapBE16(sample2);
-            dst[3] = SDL_SwapBE16(sample3);
-            dst[4] = SDL_SwapBE16(sample4);
-            dst[5] = SDL_SwapBE16(sample5);
-            dst += 6;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapBE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapBE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapBE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Uint16) ((((Sint32) SDL_SwapBE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            sample4 = (Uint16) ((((Sint32) SDL_SwapBE16(src[4])) + ((Sint32) last_sample4)) >> 1);
-            sample5 = (Uint16) ((((Sint32) SDL_SwapBE16(src[5])) + ((Sint32) last_sample5)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_U16MSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 8;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Uint16 sample7 = SDL_SwapBE16(src[7]);
-    Uint16 sample6 = SDL_SwapBE16(src[6]);
-    Uint16 sample5 = SDL_SwapBE16(src[5]);
-    Uint16 sample4 = SDL_SwapBE16(src[4]);
-    Uint16 sample3 = SDL_SwapBE16(src[3]);
-    Uint16 sample2 = SDL_SwapBE16(src[2]);
-    Uint16 sample1 = SDL_SwapBE16(src[1]);
-    Uint16 sample0 = SDL_SwapBE16(src[0]);
-    Uint16 last_sample7 = sample7;
-    Uint16 last_sample6 = sample6;
-    Uint16 last_sample5 = sample5;
-    Uint16 last_sample4 = sample4;
-    Uint16 last_sample3 = sample3;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[7] = SDL_SwapBE16(sample7);
-        dst[6] = SDL_SwapBE16(sample6);
-        dst[5] = SDL_SwapBE16(sample5);
-        dst[4] = SDL_SwapBE16(sample4);
-        dst[3] = SDL_SwapBE16(sample3);
-        dst[2] = SDL_SwapBE16(sample2);
-        dst[1] = SDL_SwapBE16(sample1);
-        dst[0] = SDL_SwapBE16(sample0);
-        dst -= 8;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 8;
-            sample7 = (Uint16) ((((Sint32) SDL_SwapBE16(src[7])) + ((Sint32) last_sample7)) >> 1);
-            sample6 = (Uint16) ((((Sint32) SDL_SwapBE16(src[6])) + ((Sint32) last_sample6)) >> 1);
-            sample5 = (Uint16) ((((Sint32) SDL_SwapBE16(src[5])) + ((Sint32) last_sample5)) >> 1);
-            sample4 = (Uint16) ((((Sint32) SDL_SwapBE16(src[4])) + ((Sint32) last_sample4)) >> 1);
-            sample3 = (Uint16) ((((Sint32) SDL_SwapBE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapBE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapBE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Uint16) ((((Sint32) SDL_SwapBE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            last_sample7 = sample7;
-            last_sample6 = sample6;
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_U16MSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Uint16 sample0 = SDL_SwapBE16(src[0]);
-    Uint16 sample1 = SDL_SwapBE16(src[1]);
-    Uint16 sample2 = SDL_SwapBE16(src[2]);
-    Uint16 sample3 = SDL_SwapBE16(src[3]);
-    Uint16 sample4 = SDL_SwapBE16(src[4]);
-    Uint16 sample5 = SDL_SwapBE16(src[5]);
-    Uint16 sample6 = SDL_SwapBE16(src[6]);
-    Uint16 sample7 = SDL_SwapBE16(src[7]);
-    Uint16 last_sample0 = sample0;
-    Uint16 last_sample1 = sample1;
-    Uint16 last_sample2 = sample2;
-    Uint16 last_sample3 = sample3;
-    Uint16 last_sample4 = sample4;
-    Uint16 last_sample5 = sample5;
-    Uint16 last_sample6 = sample6;
-    Uint16 last_sample7 = sample7;
-    while (dst < target) {
-        src += 8;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapBE16(sample0);
-            dst[1] = SDL_SwapBE16(sample1);
-            dst[2] = SDL_SwapBE16(sample2);
-            dst[3] = SDL_SwapBE16(sample3);
-            dst[4] = SDL_SwapBE16(sample4);
-            dst[5] = SDL_SwapBE16(sample5);
-            dst[6] = SDL_SwapBE16(sample6);
-            dst[7] = SDL_SwapBE16(sample7);
-            dst += 8;
-            sample0 = (Uint16) ((((Sint32) SDL_SwapBE16(src[0])) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Uint16) ((((Sint32) SDL_SwapBE16(src[1])) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Uint16) ((((Sint32) SDL_SwapBE16(src[2])) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Uint16) ((((Sint32) SDL_SwapBE16(src[3])) + ((Sint32) last_sample3)) >> 1);
-            sample4 = (Uint16) ((((Sint32) SDL_SwapBE16(src[4])) + ((Sint32) last_sample4)) >> 1);
-            sample5 = (Uint16) ((((Sint32) SDL_SwapBE16(src[5])) + ((Sint32) last_sample5)) >> 1);
-            sample6 = (Uint16) ((((Sint32) SDL_SwapBE16(src[6])) + ((Sint32) last_sample6)) >> 1);
-            sample7 = (Uint16) ((((Sint32) SDL_SwapBE16(src[7])) + ((Sint32) last_sample7)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            last_sample6 = sample6;
-            last_sample7 = sample7;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S16MSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 1;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint16 sample0 = ((Sint16) SDL_SwapBE16(src[0]));
-    Sint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[0] = ((Sint16) SDL_SwapBE16(sample0));
-        dst--;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src--;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S16MSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 32;
-    const int dstsize = (int) (((double)(cvt->len_cvt/2)) * cvt->rate_incr) * 2;
-    register int eps = 0;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint16 sample0 = ((Sint16) SDL_SwapBE16(src[0]));
-    Sint16 last_sample0 = sample0;
-    while (dst < target) {
-        src++;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint16) SDL_SwapBE16(sample0));
-            dst++;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S16MSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint16 sample1 = ((Sint16) SDL_SwapBE16(src[1]));
-    Sint16 sample0 = ((Sint16) SDL_SwapBE16(src[0]));
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[1] = ((Sint16) SDL_SwapBE16(sample1));
-        dst[0] = ((Sint16) SDL_SwapBE16(sample0));
-        dst -= 2;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 2;
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S16MSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint16 sample0 = ((Sint16) SDL_SwapBE16(src[0]));
-    Sint16 sample1 = ((Sint16) SDL_SwapBE16(src[1]));
-    Sint16 last_sample0 = sample0;
-    Sint16 last_sample1 = sample1;
-    while (dst < target) {
-        src += 2;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint16) SDL_SwapBE16(sample0));
-            dst[1] = ((Sint16) SDL_SwapBE16(sample1));
-            dst += 2;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S16MSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint16 sample3 = ((Sint16) SDL_SwapBE16(src[3]));
-    Sint16 sample2 = ((Sint16) SDL_SwapBE16(src[2]));
-    Sint16 sample1 = ((Sint16) SDL_SwapBE16(src[1]));
-    Sint16 sample0 = ((Sint16) SDL_SwapBE16(src[0]));
-    Sint16 last_sample3 = sample3;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[3] = ((Sint16) SDL_SwapBE16(sample3));
-        dst[2] = ((Sint16) SDL_SwapBE16(sample2));
-        dst[1] = ((Sint16) SDL_SwapBE16(sample1));
-        dst[0] = ((Sint16) SDL_SwapBE16(sample0));
-        dst -= 4;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 4;
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S16MSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint16 sample0 = ((Sint16) SDL_SwapBE16(src[0]));
-    Sint16 sample1 = ((Sint16) SDL_SwapBE16(src[1]));
-    Sint16 sample2 = ((Sint16) SDL_SwapBE16(src[2]));
-    Sint16 sample3 = ((Sint16) SDL_SwapBE16(src[3]));
-    Sint16 last_sample0 = sample0;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample3 = sample3;
-    while (dst < target) {
-        src += 4;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint16) SDL_SwapBE16(sample0));
-            dst[1] = ((Sint16) SDL_SwapBE16(sample1));
-            dst[2] = ((Sint16) SDL_SwapBE16(sample2));
-            dst[3] = ((Sint16) SDL_SwapBE16(sample3));
-            dst += 4;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S16MSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 192;
-    const int dstsize = (int) (((double)(cvt->len_cvt/12)) * cvt->rate_incr) * 12;
-    register int eps = 0;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 6;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint16 sample5 = ((Sint16) SDL_SwapBE16(src[5]));
-    Sint16 sample4 = ((Sint16) SDL_SwapBE16(src[4]));
-    Sint16 sample3 = ((Sint16) SDL_SwapBE16(src[3]));
-    Sint16 sample2 = ((Sint16) SDL_SwapBE16(src[2]));
-    Sint16 sample1 = ((Sint16) SDL_SwapBE16(src[1]));
-    Sint16 sample0 = ((Sint16) SDL_SwapBE16(src[0]));
-    Sint16 last_sample5 = sample5;
-    Sint16 last_sample4 = sample4;
-    Sint16 last_sample3 = sample3;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[5] = ((Sint16) SDL_SwapBE16(sample5));
-        dst[4] = ((Sint16) SDL_SwapBE16(sample4));
-        dst[3] = ((Sint16) SDL_SwapBE16(sample3));
-        dst[2] = ((Sint16) SDL_SwapBE16(sample2));
-        dst[1] = ((Sint16) SDL_SwapBE16(sample1));
-        dst[0] = ((Sint16) SDL_SwapBE16(sample0));
-        dst -= 6;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 6;
-            sample5 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[5]))) + ((Sint32) last_sample5)) >> 1);
-            sample4 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[4]))) + ((Sint32) last_sample4)) >> 1);
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S16MSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 192;
-    const int dstsize = (int) (((double)(cvt->len_cvt/12)) * cvt->rate_incr) * 12;
-    register int eps = 0;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint16 sample0 = ((Sint16) SDL_SwapBE16(src[0]));
-    Sint16 sample1 = ((Sint16) SDL_SwapBE16(src[1]));
-    Sint16 sample2 = ((Sint16) SDL_SwapBE16(src[2]));
-    Sint16 sample3 = ((Sint16) SDL_SwapBE16(src[3]));
-    Sint16 sample4 = ((Sint16) SDL_SwapBE16(src[4]));
-    Sint16 sample5 = ((Sint16) SDL_SwapBE16(src[5]));
-    Sint16 last_sample0 = sample0;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample3 = sample3;
-    Sint16 last_sample4 = sample4;
-    Sint16 last_sample5 = sample5;
-    while (dst < target) {
-        src += 6;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint16) SDL_SwapBE16(sample0));
-            dst[1] = ((Sint16) SDL_SwapBE16(sample1));
-            dst[2] = ((Sint16) SDL_SwapBE16(sample2));
-            dst[3] = ((Sint16) SDL_SwapBE16(sample3));
-            dst[4] = ((Sint16) SDL_SwapBE16(sample4));
-            dst[5] = ((Sint16) SDL_SwapBE16(sample5));
-            dst += 6;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            sample4 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[4]))) + ((Sint32) last_sample4)) >> 1);
-            sample5 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[5]))) + ((Sint32) last_sample5)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S16MSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 8;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint16 sample7 = ((Sint16) SDL_SwapBE16(src[7]));
-    Sint16 sample6 = ((Sint16) SDL_SwapBE16(src[6]));
-    Sint16 sample5 = ((Sint16) SDL_SwapBE16(src[5]));
-    Sint16 sample4 = ((Sint16) SDL_SwapBE16(src[4]));
-    Sint16 sample3 = ((Sint16) SDL_SwapBE16(src[3]));
-    Sint16 sample2 = ((Sint16) SDL_SwapBE16(src[2]));
-    Sint16 sample1 = ((Sint16) SDL_SwapBE16(src[1]));
-    Sint16 sample0 = ((Sint16) SDL_SwapBE16(src[0]));
-    Sint16 last_sample7 = sample7;
-    Sint16 last_sample6 = sample6;
-    Sint16 last_sample5 = sample5;
-    Sint16 last_sample4 = sample4;
-    Sint16 last_sample3 = sample3;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[7] = ((Sint16) SDL_SwapBE16(sample7));
-        dst[6] = ((Sint16) SDL_SwapBE16(sample6));
-        dst[5] = ((Sint16) SDL_SwapBE16(sample5));
-        dst[4] = ((Sint16) SDL_SwapBE16(sample4));
-        dst[3] = ((Sint16) SDL_SwapBE16(sample3));
-        dst[2] = ((Sint16) SDL_SwapBE16(sample2));
-        dst[1] = ((Sint16) SDL_SwapBE16(sample1));
-        dst[0] = ((Sint16) SDL_SwapBE16(sample0));
-        dst -= 8;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 8;
-            sample7 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[7]))) + ((Sint32) last_sample7)) >> 1);
-            sample6 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[6]))) + ((Sint32) last_sample6)) >> 1);
-            sample5 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[5]))) + ((Sint32) last_sample5)) >> 1);
-            sample4 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[4]))) + ((Sint32) last_sample4)) >> 1);
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            last_sample7 = sample7;
-            last_sample6 = sample6;
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S16MSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint16 sample0 = ((Sint16) SDL_SwapBE16(src[0]));
-    Sint16 sample1 = ((Sint16) SDL_SwapBE16(src[1]));
-    Sint16 sample2 = ((Sint16) SDL_SwapBE16(src[2]));
-    Sint16 sample3 = ((Sint16) SDL_SwapBE16(src[3]));
-    Sint16 sample4 = ((Sint16) SDL_SwapBE16(src[4]));
-    Sint16 sample5 = ((Sint16) SDL_SwapBE16(src[5]));
-    Sint16 sample6 = ((Sint16) SDL_SwapBE16(src[6]));
-    Sint16 sample7 = ((Sint16) SDL_SwapBE16(src[7]));
-    Sint16 last_sample0 = sample0;
-    Sint16 last_sample1 = sample1;
-    Sint16 last_sample2 = sample2;
-    Sint16 last_sample3 = sample3;
-    Sint16 last_sample4 = sample4;
-    Sint16 last_sample5 = sample5;
-    Sint16 last_sample6 = sample6;
-    Sint16 last_sample7 = sample7;
-    while (dst < target) {
-        src += 8;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint16) SDL_SwapBE16(sample0));
-            dst[1] = ((Sint16) SDL_SwapBE16(sample1));
-            dst[2] = ((Sint16) SDL_SwapBE16(sample2));
-            dst[3] = ((Sint16) SDL_SwapBE16(sample3));
-            dst[4] = ((Sint16) SDL_SwapBE16(sample4));
-            dst[5] = ((Sint16) SDL_SwapBE16(sample5));
-            dst[6] = ((Sint16) SDL_SwapBE16(sample6));
-            dst[7] = ((Sint16) SDL_SwapBE16(sample7));
-            dst += 8;
-            sample0 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[0]))) + ((Sint32) last_sample0)) >> 1);
-            sample1 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[1]))) + ((Sint32) last_sample1)) >> 1);
-            sample2 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[2]))) + ((Sint32) last_sample2)) >> 1);
-            sample3 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[3]))) + ((Sint32) last_sample3)) >> 1);
-            sample4 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[4]))) + ((Sint32) last_sample4)) >> 1);
-            sample5 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[5]))) + ((Sint32) last_sample5)) >> 1);
-            sample6 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[6]))) + ((Sint32) last_sample6)) >> 1);
-            sample7 = (Sint16) ((((Sint32) ((Sint16) SDL_SwapBE16(src[7]))) + ((Sint32) last_sample7)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            last_sample6 = sample6;
-            last_sample7 = sample7;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S32LSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 1;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint32 sample0 = ((Sint32) SDL_SwapLE32(src[0]));
-    Sint32 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[0] = ((Sint32) SDL_SwapLE32(sample0));
-        dst--;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src--;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S32LSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint32 sample0 = ((Sint32) SDL_SwapLE32(src[0]));
-    Sint32 last_sample0 = sample0;
-    while (dst < target) {
-        src++;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint32) SDL_SwapLE32(sample0));
-            dst++;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S32LSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint32 sample1 = ((Sint32) SDL_SwapLE32(src[1]));
-    Sint32 sample0 = ((Sint32) SDL_SwapLE32(src[0]));
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[1] = ((Sint32) SDL_SwapLE32(sample1));
-        dst[0] = ((Sint32) SDL_SwapLE32(sample0));
-        dst -= 2;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 2;
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S32LSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint32 sample0 = ((Sint32) SDL_SwapLE32(src[0]));
-    Sint32 sample1 = ((Sint32) SDL_SwapLE32(src[1]));
-    Sint32 last_sample0 = sample0;
-    Sint32 last_sample1 = sample1;
-    while (dst < target) {
-        src += 2;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint32) SDL_SwapLE32(sample0));
-            dst[1] = ((Sint32) SDL_SwapLE32(sample1));
-            dst += 2;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S32LSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint32 sample3 = ((Sint32) SDL_SwapLE32(src[3]));
-    Sint32 sample2 = ((Sint32) SDL_SwapLE32(src[2]));
-    Sint32 sample1 = ((Sint32) SDL_SwapLE32(src[1]));
-    Sint32 sample0 = ((Sint32) SDL_SwapLE32(src[0]));
-    Sint32 last_sample3 = sample3;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[3] = ((Sint32) SDL_SwapLE32(sample3));
-        dst[2] = ((Sint32) SDL_SwapLE32(sample2));
-        dst[1] = ((Sint32) SDL_SwapLE32(sample1));
-        dst[0] = ((Sint32) SDL_SwapLE32(sample0));
-        dst -= 4;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 4;
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S32LSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint32 sample0 = ((Sint32) SDL_SwapLE32(src[0]));
-    Sint32 sample1 = ((Sint32) SDL_SwapLE32(src[1]));
-    Sint32 sample2 = ((Sint32) SDL_SwapLE32(src[2]));
-    Sint32 sample3 = ((Sint32) SDL_SwapLE32(src[3]));
-    Sint32 last_sample0 = sample0;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample3 = sample3;
-    while (dst < target) {
-        src += 4;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint32) SDL_SwapLE32(sample0));
-            dst[1] = ((Sint32) SDL_SwapLE32(sample1));
-            dst[2] = ((Sint32) SDL_SwapLE32(sample2));
-            dst[3] = ((Sint32) SDL_SwapLE32(sample3));
-            dst += 4;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S32LSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 384;
-    const int dstsize = (int) (((double)(cvt->len_cvt/24)) * cvt->rate_incr) * 24;
-    register int eps = 0;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 6;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint32 sample5 = ((Sint32) SDL_SwapLE32(src[5]));
-    Sint32 sample4 = ((Sint32) SDL_SwapLE32(src[4]));
-    Sint32 sample3 = ((Sint32) SDL_SwapLE32(src[3]));
-    Sint32 sample2 = ((Sint32) SDL_SwapLE32(src[2]));
-    Sint32 sample1 = ((Sint32) SDL_SwapLE32(src[1]));
-    Sint32 sample0 = ((Sint32) SDL_SwapLE32(src[0]));
-    Sint32 last_sample5 = sample5;
-    Sint32 last_sample4 = sample4;
-    Sint32 last_sample3 = sample3;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[5] = ((Sint32) SDL_SwapLE32(sample5));
-        dst[4] = ((Sint32) SDL_SwapLE32(sample4));
-        dst[3] = ((Sint32) SDL_SwapLE32(sample3));
-        dst[2] = ((Sint32) SDL_SwapLE32(sample2));
-        dst[1] = ((Sint32) SDL_SwapLE32(sample1));
-        dst[0] = ((Sint32) SDL_SwapLE32(sample0));
-        dst -= 6;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 6;
-            sample5 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[5]))) + ((Sint64) last_sample5)) >> 1);
-            sample4 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[4]))) + ((Sint64) last_sample4)) >> 1);
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S32LSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 384;
-    const int dstsize = (int) (((double)(cvt->len_cvt/24)) * cvt->rate_incr) * 24;
-    register int eps = 0;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint32 sample0 = ((Sint32) SDL_SwapLE32(src[0]));
-    Sint32 sample1 = ((Sint32) SDL_SwapLE32(src[1]));
-    Sint32 sample2 = ((Sint32) SDL_SwapLE32(src[2]));
-    Sint32 sample3 = ((Sint32) SDL_SwapLE32(src[3]));
-    Sint32 sample4 = ((Sint32) SDL_SwapLE32(src[4]));
-    Sint32 sample5 = ((Sint32) SDL_SwapLE32(src[5]));
-    Sint32 last_sample0 = sample0;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample3 = sample3;
-    Sint32 last_sample4 = sample4;
-    Sint32 last_sample5 = sample5;
-    while (dst < target) {
-        src += 6;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint32) SDL_SwapLE32(sample0));
-            dst[1] = ((Sint32) SDL_SwapLE32(sample1));
-            dst[2] = ((Sint32) SDL_SwapLE32(sample2));
-            dst[3] = ((Sint32) SDL_SwapLE32(sample3));
-            dst[4] = ((Sint32) SDL_SwapLE32(sample4));
-            dst[5] = ((Sint32) SDL_SwapLE32(sample5));
-            dst += 6;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            sample4 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[4]))) + ((Sint64) last_sample4)) >> 1);
-            sample5 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[5]))) + ((Sint64) last_sample5)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S32LSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 512;
-    const int dstsize = (int) (((double)(cvt->len_cvt/32)) * cvt->rate_incr) * 32;
-    register int eps = 0;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 8;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint32 sample7 = ((Sint32) SDL_SwapLE32(src[7]));
-    Sint32 sample6 = ((Sint32) SDL_SwapLE32(src[6]));
-    Sint32 sample5 = ((Sint32) SDL_SwapLE32(src[5]));
-    Sint32 sample4 = ((Sint32) SDL_SwapLE32(src[4]));
-    Sint32 sample3 = ((Sint32) SDL_SwapLE32(src[3]));
-    Sint32 sample2 = ((Sint32) SDL_SwapLE32(src[2]));
-    Sint32 sample1 = ((Sint32) SDL_SwapLE32(src[1]));
-    Sint32 sample0 = ((Sint32) SDL_SwapLE32(src[0]));
-    Sint32 last_sample7 = sample7;
-    Sint32 last_sample6 = sample6;
-    Sint32 last_sample5 = sample5;
-    Sint32 last_sample4 = sample4;
-    Sint32 last_sample3 = sample3;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[7] = ((Sint32) SDL_SwapLE32(sample7));
-        dst[6] = ((Sint32) SDL_SwapLE32(sample6));
-        dst[5] = ((Sint32) SDL_SwapLE32(sample5));
-        dst[4] = ((Sint32) SDL_SwapLE32(sample4));
-        dst[3] = ((Sint32) SDL_SwapLE32(sample3));
-        dst[2] = ((Sint32) SDL_SwapLE32(sample2));
-        dst[1] = ((Sint32) SDL_SwapLE32(sample1));
-        dst[0] = ((Sint32) SDL_SwapLE32(sample0));
-        dst -= 8;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 8;
-            sample7 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[7]))) + ((Sint64) last_sample7)) >> 1);
-            sample6 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[6]))) + ((Sint64) last_sample6)) >> 1);
-            sample5 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[5]))) + ((Sint64) last_sample5)) >> 1);
-            sample4 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[4]))) + ((Sint64) last_sample4)) >> 1);
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample7 = sample7;
-            last_sample6 = sample6;
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S32LSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 512;
-    const int dstsize = (int) (((double)(cvt->len_cvt/32)) * cvt->rate_incr) * 32;
-    register int eps = 0;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint32 sample0 = ((Sint32) SDL_SwapLE32(src[0]));
-    Sint32 sample1 = ((Sint32) SDL_SwapLE32(src[1]));
-    Sint32 sample2 = ((Sint32) SDL_SwapLE32(src[2]));
-    Sint32 sample3 = ((Sint32) SDL_SwapLE32(src[3]));
-    Sint32 sample4 = ((Sint32) SDL_SwapLE32(src[4]));
-    Sint32 sample5 = ((Sint32) SDL_SwapLE32(src[5]));
-    Sint32 sample6 = ((Sint32) SDL_SwapLE32(src[6]));
-    Sint32 sample7 = ((Sint32) SDL_SwapLE32(src[7]));
-    Sint32 last_sample0 = sample0;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample3 = sample3;
-    Sint32 last_sample4 = sample4;
-    Sint32 last_sample5 = sample5;
-    Sint32 last_sample6 = sample6;
-    Sint32 last_sample7 = sample7;
-    while (dst < target) {
-        src += 8;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint32) SDL_SwapLE32(sample0));
-            dst[1] = ((Sint32) SDL_SwapLE32(sample1));
-            dst[2] = ((Sint32) SDL_SwapLE32(sample2));
-            dst[3] = ((Sint32) SDL_SwapLE32(sample3));
-            dst[4] = ((Sint32) SDL_SwapLE32(sample4));
-            dst[5] = ((Sint32) SDL_SwapLE32(sample5));
-            dst[6] = ((Sint32) SDL_SwapLE32(sample6));
-            dst[7] = ((Sint32) SDL_SwapLE32(sample7));
-            dst += 8;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            sample4 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[4]))) + ((Sint64) last_sample4)) >> 1);
-            sample5 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[5]))) + ((Sint64) last_sample5)) >> 1);
-            sample6 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[6]))) + ((Sint64) last_sample6)) >> 1);
-            sample7 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapLE32(src[7]))) + ((Sint64) last_sample7)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            last_sample6 = sample6;
-            last_sample7 = sample7;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S32MSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 1;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint32 sample0 = ((Sint32) SDL_SwapBE32(src[0]));
-    Sint32 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[0] = ((Sint32) SDL_SwapBE32(sample0));
-        dst--;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src--;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S32MSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint32 sample0 = ((Sint32) SDL_SwapBE32(src[0]));
-    Sint32 last_sample0 = sample0;
-    while (dst < target) {
-        src++;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint32) SDL_SwapBE32(sample0));
-            dst++;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample0 = sample0;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S32MSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint32 sample1 = ((Sint32) SDL_SwapBE32(src[1]));
-    Sint32 sample0 = ((Sint32) SDL_SwapBE32(src[0]));
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[1] = ((Sint32) SDL_SwapBE32(sample1));
-        dst[0] = ((Sint32) SDL_SwapBE32(sample0));
-        dst -= 2;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 2;
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S32MSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint32 sample0 = ((Sint32) SDL_SwapBE32(src[0]));
-    Sint32 sample1 = ((Sint32) SDL_SwapBE32(src[1]));
-    Sint32 last_sample0 = sample0;
-    Sint32 last_sample1 = sample1;
-    while (dst < target) {
-        src += 2;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint32) SDL_SwapBE32(sample0));
-            dst[1] = ((Sint32) SDL_SwapBE32(sample1));
-            dst += 2;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S32MSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint32 sample3 = ((Sint32) SDL_SwapBE32(src[3]));
-    Sint32 sample2 = ((Sint32) SDL_SwapBE32(src[2]));
-    Sint32 sample1 = ((Sint32) SDL_SwapBE32(src[1]));
-    Sint32 sample0 = ((Sint32) SDL_SwapBE32(src[0]));
-    Sint32 last_sample3 = sample3;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[3] = ((Sint32) SDL_SwapBE32(sample3));
-        dst[2] = ((Sint32) SDL_SwapBE32(sample2));
-        dst[1] = ((Sint32) SDL_SwapBE32(sample1));
-        dst[0] = ((Sint32) SDL_SwapBE32(sample0));
-        dst -= 4;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 4;
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S32MSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint32 sample0 = ((Sint32) SDL_SwapBE32(src[0]));
-    Sint32 sample1 = ((Sint32) SDL_SwapBE32(src[1]));
-    Sint32 sample2 = ((Sint32) SDL_SwapBE32(src[2]));
-    Sint32 sample3 = ((Sint32) SDL_SwapBE32(src[3]));
-    Sint32 last_sample0 = sample0;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample3 = sample3;
-    while (dst < target) {
-        src += 4;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint32) SDL_SwapBE32(sample0));
-            dst[1] = ((Sint32) SDL_SwapBE32(sample1));
-            dst[2] = ((Sint32) SDL_SwapBE32(sample2));
-            dst[3] = ((Sint32) SDL_SwapBE32(sample3));
-            dst += 4;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S32MSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 384;
-    const int dstsize = (int) (((double)(cvt->len_cvt/24)) * cvt->rate_incr) * 24;
-    register int eps = 0;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 6;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint32 sample5 = ((Sint32) SDL_SwapBE32(src[5]));
-    Sint32 sample4 = ((Sint32) SDL_SwapBE32(src[4]));
-    Sint32 sample3 = ((Sint32) SDL_SwapBE32(src[3]));
-    Sint32 sample2 = ((Sint32) SDL_SwapBE32(src[2]));
-    Sint32 sample1 = ((Sint32) SDL_SwapBE32(src[1]));
-    Sint32 sample0 = ((Sint32) SDL_SwapBE32(src[0]));
-    Sint32 last_sample5 = sample5;
-    Sint32 last_sample4 = sample4;
-    Sint32 last_sample3 = sample3;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[5] = ((Sint32) SDL_SwapBE32(sample5));
-        dst[4] = ((Sint32) SDL_SwapBE32(sample4));
-        dst[3] = ((Sint32) SDL_SwapBE32(sample3));
-        dst[2] = ((Sint32) SDL_SwapBE32(sample2));
-        dst[1] = ((Sint32) SDL_SwapBE32(sample1));
-        dst[0] = ((Sint32) SDL_SwapBE32(sample0));
-        dst -= 6;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 6;
-            sample5 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[5]))) + ((Sint64) last_sample5)) >> 1);
-            sample4 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[4]))) + ((Sint64) last_sample4)) >> 1);
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S32MSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 384;
-    const int dstsize = (int) (((double)(cvt->len_cvt/24)) * cvt->rate_incr) * 24;
-    register int eps = 0;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint32 sample0 = ((Sint32) SDL_SwapBE32(src[0]));
-    Sint32 sample1 = ((Sint32) SDL_SwapBE32(src[1]));
-    Sint32 sample2 = ((Sint32) SDL_SwapBE32(src[2]));
-    Sint32 sample3 = ((Sint32) SDL_SwapBE32(src[3]));
-    Sint32 sample4 = ((Sint32) SDL_SwapBE32(src[4]));
-    Sint32 sample5 = ((Sint32) SDL_SwapBE32(src[5]));
-    Sint32 last_sample0 = sample0;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample3 = sample3;
-    Sint32 last_sample4 = sample4;
-    Sint32 last_sample5 = sample5;
-    while (dst < target) {
-        src += 6;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint32) SDL_SwapBE32(sample0));
-            dst[1] = ((Sint32) SDL_SwapBE32(sample1));
-            dst[2] = ((Sint32) SDL_SwapBE32(sample2));
-            dst[3] = ((Sint32) SDL_SwapBE32(sample3));
-            dst[4] = ((Sint32) SDL_SwapBE32(sample4));
-            dst[5] = ((Sint32) SDL_SwapBE32(sample5));
-            dst += 6;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            sample4 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[4]))) + ((Sint64) last_sample4)) >> 1);
-            sample5 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[5]))) + ((Sint64) last_sample5)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_S32MSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 512;
-    const int dstsize = (int) (((double)(cvt->len_cvt/32)) * cvt->rate_incr) * 32;
-    register int eps = 0;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 8;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint32 sample7 = ((Sint32) SDL_SwapBE32(src[7]));
-    Sint32 sample6 = ((Sint32) SDL_SwapBE32(src[6]));
-    Sint32 sample5 = ((Sint32) SDL_SwapBE32(src[5]));
-    Sint32 sample4 = ((Sint32) SDL_SwapBE32(src[4]));
-    Sint32 sample3 = ((Sint32) SDL_SwapBE32(src[3]));
-    Sint32 sample2 = ((Sint32) SDL_SwapBE32(src[2]));
-    Sint32 sample1 = ((Sint32) SDL_SwapBE32(src[1]));
-    Sint32 sample0 = ((Sint32) SDL_SwapBE32(src[0]));
-    Sint32 last_sample7 = sample7;
-    Sint32 last_sample6 = sample6;
-    Sint32 last_sample5 = sample5;
-    Sint32 last_sample4 = sample4;
-    Sint32 last_sample3 = sample3;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample0 = sample0;
-    while (dst >= target) {
-        dst[7] = ((Sint32) SDL_SwapBE32(sample7));
-        dst[6] = ((Sint32) SDL_SwapBE32(sample6));
-        dst[5] = ((Sint32) SDL_SwapBE32(sample5));
-        dst[4] = ((Sint32) SDL_SwapBE32(sample4));
-        dst[3] = ((Sint32) SDL_SwapBE32(sample3));
-        dst[2] = ((Sint32) SDL_SwapBE32(sample2));
-        dst[1] = ((Sint32) SDL_SwapBE32(sample1));
-        dst[0] = ((Sint32) SDL_SwapBE32(sample0));
-        dst -= 8;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 8;
-            sample7 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[7]))) + ((Sint64) last_sample7)) >> 1);
-            sample6 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[6]))) + ((Sint64) last_sample6)) >> 1);
-            sample5 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[5]))) + ((Sint64) last_sample5)) >> 1);
-            sample4 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[4]))) + ((Sint64) last_sample4)) >> 1);
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            last_sample7 = sample7;
-            last_sample6 = sample6;
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_S32MSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 512;
-    const int dstsize = (int) (((double)(cvt->len_cvt/32)) * cvt->rate_incr) * 32;
-    register int eps = 0;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint32 sample0 = ((Sint32) SDL_SwapBE32(src[0]));
-    Sint32 sample1 = ((Sint32) SDL_SwapBE32(src[1]));
-    Sint32 sample2 = ((Sint32) SDL_SwapBE32(src[2]));
-    Sint32 sample3 = ((Sint32) SDL_SwapBE32(src[3]));
-    Sint32 sample4 = ((Sint32) SDL_SwapBE32(src[4]));
-    Sint32 sample5 = ((Sint32) SDL_SwapBE32(src[5]));
-    Sint32 sample6 = ((Sint32) SDL_SwapBE32(src[6]));
-    Sint32 sample7 = ((Sint32) SDL_SwapBE32(src[7]));
-    Sint32 last_sample0 = sample0;
-    Sint32 last_sample1 = sample1;
-    Sint32 last_sample2 = sample2;
-    Sint32 last_sample3 = sample3;
-    Sint32 last_sample4 = sample4;
-    Sint32 last_sample5 = sample5;
-    Sint32 last_sample6 = sample6;
-    Sint32 last_sample7 = sample7;
-    while (dst < target) {
-        src += 8;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = ((Sint32) SDL_SwapBE32(sample0));
-            dst[1] = ((Sint32) SDL_SwapBE32(sample1));
-            dst[2] = ((Sint32) SDL_SwapBE32(sample2));
-            dst[3] = ((Sint32) SDL_SwapBE32(sample3));
-            dst[4] = ((Sint32) SDL_SwapBE32(sample4));
-            dst[5] = ((Sint32) SDL_SwapBE32(sample5));
-            dst[6] = ((Sint32) SDL_SwapBE32(sample6));
-            dst[7] = ((Sint32) SDL_SwapBE32(sample7));
-            dst += 8;
-            sample0 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[0]))) + ((Sint64) last_sample0)) >> 1);
-            sample1 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[1]))) + ((Sint64) last_sample1)) >> 1);
-            sample2 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[2]))) + ((Sint64) last_sample2)) >> 1);
-            sample3 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[3]))) + ((Sint64) last_sample3)) >> 1);
-            sample4 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[4]))) + ((Sint64) last_sample4)) >> 1);
-            sample5 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[5]))) + ((Sint64) last_sample5)) >> 1);
-            sample6 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[6]))) + ((Sint64) last_sample6)) >> 1);
-            sample7 = (Sint32) ((((Sint64) ((Sint32) SDL_SwapBE32(src[7]))) + ((Sint64) last_sample7)) >> 1);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            last_sample6 = sample6;
-            last_sample7 = sample7;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_F32LSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 1;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 1;
-    const float *target = ((const float *) cvt->buf);
-    float sample0 = SDL_SwapFloatLE(src[0]);
-    float last_sample0 = sample0;
-    while (dst >= target) {
-        dst[0] = SDL_SwapFloatLE(sample0);
-        dst--;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src--;
-            sample0 = (float) ((((double) SDL_SwapFloatLE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_F32LSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    float sample0 = SDL_SwapFloatLE(src[0]);
-    float last_sample0 = sample0;
-    while (dst < target) {
-        src++;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapFloatLE(sample0);
-            dst++;
-            sample0 = (float) ((((double) SDL_SwapFloatLE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample0 = sample0;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_F32LSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 2;
-    const float *target = ((const float *) cvt->buf);
-    float sample1 = SDL_SwapFloatLE(src[1]);
-    float sample0 = SDL_SwapFloatLE(src[0]);
-    float last_sample1 = sample1;
-    float last_sample0 = sample0;
-    while (dst >= target) {
-        dst[1] = SDL_SwapFloatLE(sample1);
-        dst[0] = SDL_SwapFloatLE(sample0);
-        dst -= 2;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 2;
-            sample1 = (float) ((((double) SDL_SwapFloatLE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample0 = (float) ((((double) SDL_SwapFloatLE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_F32LSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    float sample0 = SDL_SwapFloatLE(src[0]);
-    float sample1 = SDL_SwapFloatLE(src[1]);
-    float last_sample0 = sample0;
-    float last_sample1 = sample1;
-    while (dst < target) {
-        src += 2;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapFloatLE(sample0);
-            dst[1] = SDL_SwapFloatLE(sample1);
-            dst += 2;
-            sample0 = (float) ((((double) SDL_SwapFloatLE(src[0])) + ((double) last_sample0)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatLE(src[1])) + ((double) last_sample1)) * 0.5);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_F32LSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 4;
-    const float *target = ((const float *) cvt->buf);
-    float sample3 = SDL_SwapFloatLE(src[3]);
-    float sample2 = SDL_SwapFloatLE(src[2]);
-    float sample1 = SDL_SwapFloatLE(src[1]);
-    float sample0 = SDL_SwapFloatLE(src[0]);
-    float last_sample3 = sample3;
-    float last_sample2 = sample2;
-    float last_sample1 = sample1;
-    float last_sample0 = sample0;
-    while (dst >= target) {
-        dst[3] = SDL_SwapFloatLE(sample3);
-        dst[2] = SDL_SwapFloatLE(sample2);
-        dst[1] = SDL_SwapFloatLE(sample1);
-        dst[0] = SDL_SwapFloatLE(sample0);
-        dst -= 4;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 4;
-            sample3 = (float) ((((double) SDL_SwapFloatLE(src[3])) + ((double) last_sample3)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatLE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatLE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample0 = (float) ((((double) SDL_SwapFloatLE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_F32LSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    float sample0 = SDL_SwapFloatLE(src[0]);
-    float sample1 = SDL_SwapFloatLE(src[1]);
-    float sample2 = SDL_SwapFloatLE(src[2]);
-    float sample3 = SDL_SwapFloatLE(src[3]);
-    float last_sample0 = sample0;
-    float last_sample1 = sample1;
-    float last_sample2 = sample2;
-    float last_sample3 = sample3;
-    while (dst < target) {
-        src += 4;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapFloatLE(sample0);
-            dst[1] = SDL_SwapFloatLE(sample1);
-            dst[2] = SDL_SwapFloatLE(sample2);
-            dst[3] = SDL_SwapFloatLE(sample3);
-            dst += 4;
-            sample0 = (float) ((((double) SDL_SwapFloatLE(src[0])) + ((double) last_sample0)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatLE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatLE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample3 = (float) ((((double) SDL_SwapFloatLE(src[3])) + ((double) last_sample3)) * 0.5);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_F32LSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 384;
-    const int dstsize = (int) (((double)(cvt->len_cvt/24)) * cvt->rate_incr) * 24;
-    register int eps = 0;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 6;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 6;
-    const float *target = ((const float *) cvt->buf);
-    float sample5 = SDL_SwapFloatLE(src[5]);
-    float sample4 = SDL_SwapFloatLE(src[4]);
-    float sample3 = SDL_SwapFloatLE(src[3]);
-    float sample2 = SDL_SwapFloatLE(src[2]);
-    float sample1 = SDL_SwapFloatLE(src[1]);
-    float sample0 = SDL_SwapFloatLE(src[0]);
-    float last_sample5 = sample5;
-    float last_sample4 = sample4;
-    float last_sample3 = sample3;
-    float last_sample2 = sample2;
-    float last_sample1 = sample1;
-    float last_sample0 = sample0;
-    while (dst >= target) {
-        dst[5] = SDL_SwapFloatLE(sample5);
-        dst[4] = SDL_SwapFloatLE(sample4);
-        dst[3] = SDL_SwapFloatLE(sample3);
-        dst[2] = SDL_SwapFloatLE(sample2);
-        dst[1] = SDL_SwapFloatLE(sample1);
-        dst[0] = SDL_SwapFloatLE(sample0);
-        dst -= 6;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 6;
-            sample5 = (float) ((((double) SDL_SwapFloatLE(src[5])) + ((double) last_sample5)) * 0.5);
-            sample4 = (float) ((((double) SDL_SwapFloatLE(src[4])) + ((double) last_sample4)) * 0.5);
-            sample3 = (float) ((((double) SDL_SwapFloatLE(src[3])) + ((double) last_sample3)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatLE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatLE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample0 = (float) ((((double) SDL_SwapFloatLE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_F32LSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 384;
-    const int dstsize = (int) (((double)(cvt->len_cvt/24)) * cvt->rate_incr) * 24;
-    register int eps = 0;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    float sample0 = SDL_SwapFloatLE(src[0]);
-    float sample1 = SDL_SwapFloatLE(src[1]);
-    float sample2 = SDL_SwapFloatLE(src[2]);
-    float sample3 = SDL_SwapFloatLE(src[3]);
-    float sample4 = SDL_SwapFloatLE(src[4]);
-    float sample5 = SDL_SwapFloatLE(src[5]);
-    float last_sample0 = sample0;
-    float last_sample1 = sample1;
-    float last_sample2 = sample2;
-    float last_sample3 = sample3;
-    float last_sample4 = sample4;
-    float last_sample5 = sample5;
-    while (dst < target) {
-        src += 6;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapFloatLE(sample0);
-            dst[1] = SDL_SwapFloatLE(sample1);
-            dst[2] = SDL_SwapFloatLE(sample2);
-            dst[3] = SDL_SwapFloatLE(sample3);
-            dst[4] = SDL_SwapFloatLE(sample4);
-            dst[5] = SDL_SwapFloatLE(sample5);
-            dst += 6;
-            sample0 = (float) ((((double) SDL_SwapFloatLE(src[0])) + ((double) last_sample0)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatLE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatLE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample3 = (float) ((((double) SDL_SwapFloatLE(src[3])) + ((double) last_sample3)) * 0.5);
-            sample4 = (float) ((((double) SDL_SwapFloatLE(src[4])) + ((double) last_sample4)) * 0.5);
-            sample5 = (float) ((((double) SDL_SwapFloatLE(src[5])) + ((double) last_sample5)) * 0.5);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_F32LSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 512;
-    const int dstsize = (int) (((double)(cvt->len_cvt/32)) * cvt->rate_incr) * 32;
-    register int eps = 0;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 8;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 8;
-    const float *target = ((const float *) cvt->buf);
-    float sample7 = SDL_SwapFloatLE(src[7]);
-    float sample6 = SDL_SwapFloatLE(src[6]);
-    float sample5 = SDL_SwapFloatLE(src[5]);
-    float sample4 = SDL_SwapFloatLE(src[4]);
-    float sample3 = SDL_SwapFloatLE(src[3]);
-    float sample2 = SDL_SwapFloatLE(src[2]);
-    float sample1 = SDL_SwapFloatLE(src[1]);
-    float sample0 = SDL_SwapFloatLE(src[0]);
-    float last_sample7 = sample7;
-    float last_sample6 = sample6;
-    float last_sample5 = sample5;
-    float last_sample4 = sample4;
-    float last_sample3 = sample3;
-    float last_sample2 = sample2;
-    float last_sample1 = sample1;
-    float last_sample0 = sample0;
-    while (dst >= target) {
-        dst[7] = SDL_SwapFloatLE(sample7);
-        dst[6] = SDL_SwapFloatLE(sample6);
-        dst[5] = SDL_SwapFloatLE(sample5);
-        dst[4] = SDL_SwapFloatLE(sample4);
-        dst[3] = SDL_SwapFloatLE(sample3);
-        dst[2] = SDL_SwapFloatLE(sample2);
-        dst[1] = SDL_SwapFloatLE(sample1);
-        dst[0] = SDL_SwapFloatLE(sample0);
-        dst -= 8;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 8;
-            sample7 = (float) ((((double) SDL_SwapFloatLE(src[7])) + ((double) last_sample7)) * 0.5);
-            sample6 = (float) ((((double) SDL_SwapFloatLE(src[6])) + ((double) last_sample6)) * 0.5);
-            sample5 = (float) ((((double) SDL_SwapFloatLE(src[5])) + ((double) last_sample5)) * 0.5);
-            sample4 = (float) ((((double) SDL_SwapFloatLE(src[4])) + ((double) last_sample4)) * 0.5);
-            sample3 = (float) ((((double) SDL_SwapFloatLE(src[3])) + ((double) last_sample3)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatLE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatLE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample0 = (float) ((((double) SDL_SwapFloatLE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample7 = sample7;
-            last_sample6 = sample6;
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_F32LSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 512;
-    const int dstsize = (int) (((double)(cvt->len_cvt/32)) * cvt->rate_incr) * 32;
-    register int eps = 0;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    float sample0 = SDL_SwapFloatLE(src[0]);
-    float sample1 = SDL_SwapFloatLE(src[1]);
-    float sample2 = SDL_SwapFloatLE(src[2]);
-    float sample3 = SDL_SwapFloatLE(src[3]);
-    float sample4 = SDL_SwapFloatLE(src[4]);
-    float sample5 = SDL_SwapFloatLE(src[5]);
-    float sample6 = SDL_SwapFloatLE(src[6]);
-    float sample7 = SDL_SwapFloatLE(src[7]);
-    float last_sample0 = sample0;
-    float last_sample1 = sample1;
-    float last_sample2 = sample2;
-    float last_sample3 = sample3;
-    float last_sample4 = sample4;
-    float last_sample5 = sample5;
-    float last_sample6 = sample6;
-    float last_sample7 = sample7;
-    while (dst < target) {
-        src += 8;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapFloatLE(sample0);
-            dst[1] = SDL_SwapFloatLE(sample1);
-            dst[2] = SDL_SwapFloatLE(sample2);
-            dst[3] = SDL_SwapFloatLE(sample3);
-            dst[4] = SDL_SwapFloatLE(sample4);
-            dst[5] = SDL_SwapFloatLE(sample5);
-            dst[6] = SDL_SwapFloatLE(sample6);
-            dst[7] = SDL_SwapFloatLE(sample7);
-            dst += 8;
-            sample0 = (float) ((((double) SDL_SwapFloatLE(src[0])) + ((double) last_sample0)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatLE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatLE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample3 = (float) ((((double) SDL_SwapFloatLE(src[3])) + ((double) last_sample3)) * 0.5);
-            sample4 = (float) ((((double) SDL_SwapFloatLE(src[4])) + ((double) last_sample4)) * 0.5);
-            sample5 = (float) ((((double) SDL_SwapFloatLE(src[5])) + ((double) last_sample5)) * 0.5);
-            sample6 = (float) ((((double) SDL_SwapFloatLE(src[6])) + ((double) last_sample6)) * 0.5);
-            sample7 = (float) ((((double) SDL_SwapFloatLE(src[7])) + ((double) last_sample7)) * 0.5);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            last_sample6 = sample6;
-            last_sample7 = sample7;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_F32MSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 1;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 1;
-    const float *target = ((const float *) cvt->buf);
-    float sample0 = SDL_SwapFloatBE(src[0]);
-    float last_sample0 = sample0;
-    while (dst >= target) {
-        dst[0] = SDL_SwapFloatBE(sample0);
-        dst--;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src--;
-            sample0 = (float) ((((double) SDL_SwapFloatBE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_1c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_F32MSB, 1 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 64;
-    const int dstsize = (int) (((double)(cvt->len_cvt/4)) * cvt->rate_incr) * 4;
-    register int eps = 0;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    float sample0 = SDL_SwapFloatBE(src[0]);
-    float last_sample0 = sample0;
-    while (dst < target) {
-        src++;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapFloatBE(sample0);
-            dst++;
-            sample0 = (float) ((((double) SDL_SwapFloatBE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample0 = sample0;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_F32MSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 2;
-    const float *target = ((const float *) cvt->buf);
-    float sample1 = SDL_SwapFloatBE(src[1]);
-    float sample0 = SDL_SwapFloatBE(src[0]);
-    float last_sample1 = sample1;
-    float last_sample0 = sample0;
-    while (dst >= target) {
-        dst[1] = SDL_SwapFloatBE(sample1);
-        dst[0] = SDL_SwapFloatBE(sample0);
-        dst -= 2;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 2;
-            sample1 = (float) ((((double) SDL_SwapFloatBE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample0 = (float) ((((double) SDL_SwapFloatBE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_2c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_F32MSB, 2 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 128;
-    const int dstsize = (int) (((double)(cvt->len_cvt/8)) * cvt->rate_incr) * 8;
-    register int eps = 0;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    float sample0 = SDL_SwapFloatBE(src[0]);
-    float sample1 = SDL_SwapFloatBE(src[1]);
-    float last_sample0 = sample0;
-    float last_sample1 = sample1;
-    while (dst < target) {
-        src += 2;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapFloatBE(sample0);
-            dst[1] = SDL_SwapFloatBE(sample1);
-            dst += 2;
-            sample0 = (float) ((((double) SDL_SwapFloatBE(src[0])) + ((double) last_sample0)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatBE(src[1])) + ((double) last_sample1)) * 0.5);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_F32MSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 4;
-    const float *target = ((const float *) cvt->buf);
-    float sample3 = SDL_SwapFloatBE(src[3]);
-    float sample2 = SDL_SwapFloatBE(src[2]);
-    float sample1 = SDL_SwapFloatBE(src[1]);
-    float sample0 = SDL_SwapFloatBE(src[0]);
-    float last_sample3 = sample3;
-    float last_sample2 = sample2;
-    float last_sample1 = sample1;
-    float last_sample0 = sample0;
-    while (dst >= target) {
-        dst[3] = SDL_SwapFloatBE(sample3);
-        dst[2] = SDL_SwapFloatBE(sample2);
-        dst[1] = SDL_SwapFloatBE(sample1);
-        dst[0] = SDL_SwapFloatBE(sample0);
-        dst -= 4;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 4;
-            sample3 = (float) ((((double) SDL_SwapFloatBE(src[3])) + ((double) last_sample3)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatBE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatBE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample0 = (float) ((((double) SDL_SwapFloatBE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_4c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_F32MSB, 4 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 256;
-    const int dstsize = (int) (((double)(cvt->len_cvt/16)) * cvt->rate_incr) * 16;
-    register int eps = 0;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    float sample0 = SDL_SwapFloatBE(src[0]);
-    float sample1 = SDL_SwapFloatBE(src[1]);
-    float sample2 = SDL_SwapFloatBE(src[2]);
-    float sample3 = SDL_SwapFloatBE(src[3]);
-    float last_sample0 = sample0;
-    float last_sample1 = sample1;
-    float last_sample2 = sample2;
-    float last_sample3 = sample3;
-    while (dst < target) {
-        src += 4;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapFloatBE(sample0);
-            dst[1] = SDL_SwapFloatBE(sample1);
-            dst[2] = SDL_SwapFloatBE(sample2);
-            dst[3] = SDL_SwapFloatBE(sample3);
-            dst += 4;
-            sample0 = (float) ((((double) SDL_SwapFloatBE(src[0])) + ((double) last_sample0)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatBE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatBE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample3 = (float) ((((double) SDL_SwapFloatBE(src[3])) + ((double) last_sample3)) * 0.5);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_F32MSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 384;
-    const int dstsize = (int) (((double)(cvt->len_cvt/24)) * cvt->rate_incr) * 24;
-    register int eps = 0;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 6;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 6;
-    const float *target = ((const float *) cvt->buf);
-    float sample5 = SDL_SwapFloatBE(src[5]);
-    float sample4 = SDL_SwapFloatBE(src[4]);
-    float sample3 = SDL_SwapFloatBE(src[3]);
-    float sample2 = SDL_SwapFloatBE(src[2]);
-    float sample1 = SDL_SwapFloatBE(src[1]);
-    float sample0 = SDL_SwapFloatBE(src[0]);
-    float last_sample5 = sample5;
-    float last_sample4 = sample4;
-    float last_sample3 = sample3;
-    float last_sample2 = sample2;
-    float last_sample1 = sample1;
-    float last_sample0 = sample0;
-    while (dst >= target) {
-        dst[5] = SDL_SwapFloatBE(sample5);
-        dst[4] = SDL_SwapFloatBE(sample4);
-        dst[3] = SDL_SwapFloatBE(sample3);
-        dst[2] = SDL_SwapFloatBE(sample2);
-        dst[1] = SDL_SwapFloatBE(sample1);
-        dst[0] = SDL_SwapFloatBE(sample0);
-        dst -= 6;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 6;
-            sample5 = (float) ((((double) SDL_SwapFloatBE(src[5])) + ((double) last_sample5)) * 0.5);
-            sample4 = (float) ((((double) SDL_SwapFloatBE(src[4])) + ((double) last_sample4)) * 0.5);
-            sample3 = (float) ((((double) SDL_SwapFloatBE(src[3])) + ((double) last_sample3)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatBE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatBE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample0 = (float) ((((double) SDL_SwapFloatBE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_6c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_F32MSB, 6 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 384;
-    const int dstsize = (int) (((double)(cvt->len_cvt/24)) * cvt->rate_incr) * 24;
-    register int eps = 0;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    float sample0 = SDL_SwapFloatBE(src[0]);
-    float sample1 = SDL_SwapFloatBE(src[1]);
-    float sample2 = SDL_SwapFloatBE(src[2]);
-    float sample3 = SDL_SwapFloatBE(src[3]);
-    float sample4 = SDL_SwapFloatBE(src[4]);
-    float sample5 = SDL_SwapFloatBE(src[5]);
-    float last_sample0 = sample0;
-    float last_sample1 = sample1;
-    float last_sample2 = sample2;
-    float last_sample3 = sample3;
-    float last_sample4 = sample4;
-    float last_sample5 = sample5;
-    while (dst < target) {
-        src += 6;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapFloatBE(sample0);
-            dst[1] = SDL_SwapFloatBE(sample1);
-            dst[2] = SDL_SwapFloatBE(sample2);
-            dst[3] = SDL_SwapFloatBE(sample3);
-            dst[4] = SDL_SwapFloatBE(sample4);
-            dst[5] = SDL_SwapFloatBE(sample5);
-            dst += 6;
-            sample0 = (float) ((((double) SDL_SwapFloatBE(src[0])) + ((double) last_sample0)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatBE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatBE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample3 = (float) ((((double) SDL_SwapFloatBE(src[3])) + ((double) last_sample3)) * 0.5);
-            sample4 = (float) ((((double) SDL_SwapFloatBE(src[4])) + ((double) last_sample4)) * 0.5);
-            sample5 = (float) ((((double) SDL_SwapFloatBE(src[5])) + ((double) last_sample5)) * 0.5);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample arbitrary (x%f) AUDIO_F32MSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 512;
-    const int dstsize = (int) (((double)(cvt->len_cvt/32)) * cvt->rate_incr) * 32;
-    register int eps = 0;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 8;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 8;
-    const float *target = ((const float *) cvt->buf);
-    float sample7 = SDL_SwapFloatBE(src[7]);
-    float sample6 = SDL_SwapFloatBE(src[6]);
-    float sample5 = SDL_SwapFloatBE(src[5]);
-    float sample4 = SDL_SwapFloatBE(src[4]);
-    float sample3 = SDL_SwapFloatBE(src[3]);
-    float sample2 = SDL_SwapFloatBE(src[2]);
-    float sample1 = SDL_SwapFloatBE(src[1]);
-    float sample0 = SDL_SwapFloatBE(src[0]);
-    float last_sample7 = sample7;
-    float last_sample6 = sample6;
-    float last_sample5 = sample5;
-    float last_sample4 = sample4;
-    float last_sample3 = sample3;
-    float last_sample2 = sample2;
-    float last_sample1 = sample1;
-    float last_sample0 = sample0;
-    while (dst >= target) {
-        dst[7] = SDL_SwapFloatBE(sample7);
-        dst[6] = SDL_SwapFloatBE(sample6);
-        dst[5] = SDL_SwapFloatBE(sample5);
-        dst[4] = SDL_SwapFloatBE(sample4);
-        dst[3] = SDL_SwapFloatBE(sample3);
-        dst[2] = SDL_SwapFloatBE(sample2);
-        dst[1] = SDL_SwapFloatBE(sample1);
-        dst[0] = SDL_SwapFloatBE(sample0);
-        dst -= 8;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            src -= 8;
-            sample7 = (float) ((((double) SDL_SwapFloatBE(src[7])) + ((double) last_sample7)) * 0.5);
-            sample6 = (float) ((((double) SDL_SwapFloatBE(src[6])) + ((double) last_sample6)) * 0.5);
-            sample5 = (float) ((((double) SDL_SwapFloatBE(src[5])) + ((double) last_sample5)) * 0.5);
-            sample4 = (float) ((((double) SDL_SwapFloatBE(src[4])) + ((double) last_sample4)) * 0.5);
-            sample3 = (float) ((((double) SDL_SwapFloatBE(src[3])) + ((double) last_sample3)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatBE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatBE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample0 = (float) ((((double) SDL_SwapFloatBE(src[0])) + ((double) last_sample0)) * 0.5);
-            last_sample7 = sample7;
-            last_sample6 = sample6;
-            last_sample5 = sample5;
-            last_sample4 = sample4;
-            last_sample3 = sample3;
-            last_sample2 = sample2;
-            last_sample1 = sample1;
-            last_sample0 = sample0;
-            eps -= dstsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_8c(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample arbitrary (x%f) AUDIO_F32MSB, 8 channels.\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - 512;
-    const int dstsize = (int) (((double)(cvt->len_cvt/32)) * cvt->rate_incr) * 32;
-    register int eps = 0;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    float sample0 = SDL_SwapFloatBE(src[0]);
-    float sample1 = SDL_SwapFloatBE(src[1]);
-    float sample2 = SDL_SwapFloatBE(src[2]);
-    float sample3 = SDL_SwapFloatBE(src[3]);
-    float sample4 = SDL_SwapFloatBE(src[4]);
-    float sample5 = SDL_SwapFloatBE(src[5]);
-    float sample6 = SDL_SwapFloatBE(src[6]);
-    float sample7 = SDL_SwapFloatBE(src[7]);
-    float last_sample0 = sample0;
-    float last_sample1 = sample1;
-    float last_sample2 = sample2;
-    float last_sample3 = sample3;
-    float last_sample4 = sample4;
-    float last_sample5 = sample5;
-    float last_sample6 = sample6;
-    float last_sample7 = sample7;
-    while (dst < target) {
-        src += 8;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-            dst[0] = SDL_SwapFloatBE(sample0);
-            dst[1] = SDL_SwapFloatBE(sample1);
-            dst[2] = SDL_SwapFloatBE(sample2);
-            dst[3] = SDL_SwapFloatBE(sample3);
-            dst[4] = SDL_SwapFloatBE(sample4);
-            dst[5] = SDL_SwapFloatBE(sample5);
-            dst[6] = SDL_SwapFloatBE(sample6);
-            dst[7] = SDL_SwapFloatBE(sample7);
-            dst += 8;
-            sample0 = (float) ((((double) SDL_SwapFloatBE(src[0])) + ((double) last_sample0)) * 0.5);
-            sample1 = (float) ((((double) SDL_SwapFloatBE(src[1])) + ((double) last_sample1)) * 0.5);
-            sample2 = (float) ((((double) SDL_SwapFloatBE(src[2])) + ((double) last_sample2)) * 0.5);
-            sample3 = (float) ((((double) SDL_SwapFloatBE(src[3])) + ((double) last_sample3)) * 0.5);
-            sample4 = (float) ((((double) SDL_SwapFloatBE(src[4])) + ((double) last_sample4)) * 0.5);
-            sample5 = (float) ((((double) SDL_SwapFloatBE(src[5])) + ((double) last_sample5)) * 0.5);
-            sample6 = (float) ((((double) SDL_SwapFloatBE(src[6])) + ((double) last_sample6)) * 0.5);
-            sample7 = (float) ((((double) SDL_SwapFloatBE(src[7])) + ((double) last_sample7)) * 0.5);
-            last_sample0 = sample0;
-            last_sample1 = sample1;
-            last_sample2 = sample2;
-            last_sample3 = sample3;
-            last_sample4 = sample4;
-            last_sample5 = sample5;
-            last_sample6 = sample6;
-            last_sample7 = sample7;
-            eps -= srcsize;
-        }
-    }
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-
-#if !LESS_RESAMPLERS
-
-static void SDLCALL
-SDL_Upsample_U8_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U8, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 1 * 2;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst >= target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        src--;
-        dst[1] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[0] = (Uint8) sample0;
-        last_sample0 = sample0;
-        dst -= 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U8, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        src += 2;
-        dst[0] = (Uint8) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U8, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 1 * 4;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst >= target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        src--;
-        dst[3] = (Uint8) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[2] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint8) (((3 * sample0) + last_sample0) >> 2);
-        dst[0] = (Uint8) sample0;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U8, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        src += 4;
-        dst[0] = (Uint8) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U8, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 2 * 2;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst >= target) {
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample0 = (Sint16) src[0];
-        src -= 2;
-        dst[3] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint8) sample1;
-        dst[0] = (Uint8) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U8, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) src[0];
-    Sint16 last_sample1 = (Sint16) src[1];
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        const Sint16 sample1 = (Sint16) src[1];
-        src += 4;
-        dst[0] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint8) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U8, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 2 * 4;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst >= target) {
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample0 = (Sint16) src[0];
-        src -= 2;
-        dst[7] = (Uint8) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[6] = (Uint8) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[5] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Uint8) (((3 * sample1) + last_sample1) >> 2);
-        dst[2] = (Uint8) (((3 * sample0) + last_sample0) >> 2);
-        dst[1] = (Uint8) sample1;
-        dst[0] = (Uint8) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U8, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) src[0];
-    Sint16 last_sample1 = (Sint16) src[1];
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        const Sint16 sample1 = (Sint16) src[1];
-        src += 8;
-        dst[0] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint8) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U8, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 4 * 2;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Sint16 last_sample3 = (Sint16) src[3];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst >= target) {
-        const Sint16 sample3 = (Sint16) src[3];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample0 = (Sint16) src[0];
-        src -= 4;
-        dst[7] = (Uint8) ((sample3 + last_sample3) >> 1);
-        dst[6] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[5] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Uint8) sample3;
-        dst[2] = (Uint8) sample2;
-        dst[1] = (Uint8) sample1;
-        dst[0] = (Uint8) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U8, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) src[0];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample3 = (Sint16) src[3];
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample3 = (Sint16) src[3];
-        src += 8;
-        dst[0] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint8) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U8, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 4 * 4;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Sint16 last_sample3 = (Sint16) src[3];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst >= target) {
-        const Sint16 sample3 = (Sint16) src[3];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample0 = (Sint16) src[0];
-        src -= 4;
-        dst[15] = (Uint8) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[14] = (Uint8) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[13] = (Uint8) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[12] = (Uint8) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[11] = (Uint8) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Uint8) (((3 * sample3) + last_sample3) >> 2);
-        dst[6] = (Uint8) (((3 * sample2) + last_sample2) >> 2);
-        dst[5] = (Uint8) (((3 * sample1) + last_sample1) >> 2);
-        dst[4] = (Uint8) (((3 * sample0) + last_sample0) >> 2);
-        dst[3] = (Uint8) sample3;
-        dst[2] = (Uint8) sample2;
-        dst[1] = (Uint8) sample1;
-        dst[0] = (Uint8) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U8, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) src[0];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample3 = (Sint16) src[3];
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample3 = (Sint16) src[3];
-        src += 16;
-        dst[0] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint8) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U8, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 6 * 2;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Sint16 last_sample5 = (Sint16) src[5];
-    Sint16 last_sample4 = (Sint16) src[4];
-    Sint16 last_sample3 = (Sint16) src[3];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst >= target) {
-        const Sint16 sample5 = (Sint16) src[5];
-        const Sint16 sample4 = (Sint16) src[4];
-        const Sint16 sample3 = (Sint16) src[3];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample0 = (Sint16) src[0];
-        src -= 6;
-        dst[11] = (Uint8) ((sample5 + last_sample5) >> 1);
-        dst[10] = (Uint8) ((sample4 + last_sample4) >> 1);
-        dst[9] = (Uint8) ((sample3 + last_sample3) >> 1);
-        dst[8] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[7] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[6] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[5] = (Uint8) sample5;
-        dst[4] = (Uint8) sample4;
-        dst[3] = (Uint8) sample3;
-        dst[2] = (Uint8) sample2;
-        dst[1] = (Uint8) sample1;
-        dst[0] = (Uint8) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 12;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U8, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) src[0];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample3 = (Sint16) src[3];
-    Sint16 last_sample4 = (Sint16) src[4];
-    Sint16 last_sample5 = (Sint16) src[5];
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample3 = (Sint16) src[3];
-        const Sint16 sample4 = (Sint16) src[4];
-        const Sint16 sample5 = (Sint16) src[5];
-        src += 12;
-        dst[0] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint8) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint8) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint8) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U8, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 6 * 4;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Sint16 last_sample5 = (Sint16) src[5];
-    Sint16 last_sample4 = (Sint16) src[4];
-    Sint16 last_sample3 = (Sint16) src[3];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst >= target) {
-        const Sint16 sample5 = (Sint16) src[5];
-        const Sint16 sample4 = (Sint16) src[4];
-        const Sint16 sample3 = (Sint16) src[3];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample0 = (Sint16) src[0];
-        src -= 6;
-        dst[23] = (Uint8) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[22] = (Uint8) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[21] = (Uint8) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[20] = (Uint8) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[19] = (Uint8) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[18] = (Uint8) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[17] = (Uint8) ((sample5 + last_sample5) >> 1);
-        dst[16] = (Uint8) ((sample4 + last_sample4) >> 1);
-        dst[15] = (Uint8) ((sample3 + last_sample3) >> 1);
-        dst[14] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[13] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[12] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[11] = (Uint8) (((3 * sample5) + last_sample5) >> 2);
-        dst[10] = (Uint8) (((3 * sample4) + last_sample4) >> 2);
-        dst[9] = (Uint8) (((3 * sample3) + last_sample3) >> 2);
-        dst[8] = (Uint8) (((3 * sample2) + last_sample2) >> 2);
-        dst[7] = (Uint8) (((3 * sample1) + last_sample1) >> 2);
-        dst[6] = (Uint8) (((3 * sample0) + last_sample0) >> 2);
-        dst[5] = (Uint8) sample5;
-        dst[4] = (Uint8) sample4;
-        dst[3] = (Uint8) sample3;
-        dst[2] = (Uint8) sample2;
-        dst[1] = (Uint8) sample1;
-        dst[0] = (Uint8) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 24;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U8, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) src[0];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample3 = (Sint16) src[3];
-    Sint16 last_sample4 = (Sint16) src[4];
-    Sint16 last_sample5 = (Sint16) src[5];
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample3 = (Sint16) src[3];
-        const Sint16 sample4 = (Sint16) src[4];
-        const Sint16 sample5 = (Sint16) src[5];
-        src += 24;
-        dst[0] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint8) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint8) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint8) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U8, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 8 * 2;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Sint16 last_sample7 = (Sint16) src[7];
-    Sint16 last_sample6 = (Sint16) src[6];
-    Sint16 last_sample5 = (Sint16) src[5];
-    Sint16 last_sample4 = (Sint16) src[4];
-    Sint16 last_sample3 = (Sint16) src[3];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst >= target) {
-        const Sint16 sample7 = (Sint16) src[7];
-        const Sint16 sample6 = (Sint16) src[6];
-        const Sint16 sample5 = (Sint16) src[5];
-        const Sint16 sample4 = (Sint16) src[4];
-        const Sint16 sample3 = (Sint16) src[3];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample0 = (Sint16) src[0];
-        src -= 8;
-        dst[15] = (Uint8) ((sample7 + last_sample7) >> 1);
-        dst[14] = (Uint8) ((sample6 + last_sample6) >> 1);
-        dst[13] = (Uint8) ((sample5 + last_sample5) >> 1);
-        dst[12] = (Uint8) ((sample4 + last_sample4) >> 1);
-        dst[11] = (Uint8) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Uint8) sample7;
-        dst[6] = (Uint8) sample6;
-        dst[5] = (Uint8) sample5;
-        dst[4] = (Uint8) sample4;
-        dst[3] = (Uint8) sample3;
-        dst[2] = (Uint8) sample2;
-        dst[1] = (Uint8) sample1;
-        dst[0] = (Uint8) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U8, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) src[0];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample3 = (Sint16) src[3];
-    Sint16 last_sample4 = (Sint16) src[4];
-    Sint16 last_sample5 = (Sint16) src[5];
-    Sint16 last_sample6 = (Sint16) src[6];
-    Sint16 last_sample7 = (Sint16) src[7];
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample3 = (Sint16) src[3];
-        const Sint16 sample4 = (Sint16) src[4];
-        const Sint16 sample5 = (Sint16) src[5];
-        const Sint16 sample6 = (Sint16) src[6];
-        const Sint16 sample7 = (Sint16) src[7];
-        src += 16;
-        dst[0] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint8) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint8) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint8) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Uint8) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Uint8) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U8_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U8, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint8 *dst = ((Uint8 *) (cvt->buf + dstsize)) - 8 * 4;
-    const Uint8 *src = ((Uint8 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Uint8 *target = ((const Uint8 *) cvt->buf);
-    Sint16 last_sample7 = (Sint16) src[7];
-    Sint16 last_sample6 = (Sint16) src[6];
-    Sint16 last_sample5 = (Sint16) src[5];
-    Sint16 last_sample4 = (Sint16) src[4];
-    Sint16 last_sample3 = (Sint16) src[3];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample0 = (Sint16) src[0];
-    while (dst >= target) {
-        const Sint16 sample7 = (Sint16) src[7];
-        const Sint16 sample6 = (Sint16) src[6];
-        const Sint16 sample5 = (Sint16) src[5];
-        const Sint16 sample4 = (Sint16) src[4];
-        const Sint16 sample3 = (Sint16) src[3];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample0 = (Sint16) src[0];
-        src -= 8;
-        dst[31] = (Uint8) ((sample7 + (3 * last_sample7)) >> 2);
-        dst[30] = (Uint8) ((sample6 + (3 * last_sample6)) >> 2);
-        dst[29] = (Uint8) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[28] = (Uint8) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[27] = (Uint8) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[26] = (Uint8) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[25] = (Uint8) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[24] = (Uint8) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[23] = (Uint8) ((sample7 + last_sample7) >> 1);
-        dst[22] = (Uint8) ((sample6 + last_sample6) >> 1);
-        dst[21] = (Uint8) ((sample5 + last_sample5) >> 1);
-        dst[20] = (Uint8) ((sample4 + last_sample4) >> 1);
-        dst[19] = (Uint8) ((sample3 + last_sample3) >> 1);
-        dst[18] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[17] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[16] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[15] = (Uint8) (((3 * sample7) + last_sample7) >> 2);
-        dst[14] = (Uint8) (((3 * sample6) + last_sample6) >> 2);
-        dst[13] = (Uint8) (((3 * sample5) + last_sample5) >> 2);
-        dst[12] = (Uint8) (((3 * sample4) + last_sample4) >> 2);
-        dst[11] = (Uint8) (((3 * sample3) + last_sample3) >> 2);
-        dst[10] = (Uint8) (((3 * sample2) + last_sample2) >> 2);
-        dst[9] = (Uint8) (((3 * sample1) + last_sample1) >> 2);
-        dst[8] = (Uint8) (((3 * sample0) + last_sample0) >> 2);
-        dst[7] = (Uint8) sample7;
-        dst[6] = (Uint8) sample6;
-        dst[5] = (Uint8) sample5;
-        dst[4] = (Uint8) sample4;
-        dst[3] = (Uint8) sample3;
-        dst[2] = (Uint8) sample2;
-        dst[1] = (Uint8) sample1;
-        dst[0] = (Uint8) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 32;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U8_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U8, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint8 *dst = (Uint8 *) cvt->buf;
-    const Uint8 *src = (Uint8 *) cvt->buf;
-    const Uint8 *target = (const Uint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) src[0];
-    Sint16 last_sample1 = (Sint16) src[1];
-    Sint16 last_sample2 = (Sint16) src[2];
-    Sint16 last_sample3 = (Sint16) src[3];
-    Sint16 last_sample4 = (Sint16) src[4];
-    Sint16 last_sample5 = (Sint16) src[5];
-    Sint16 last_sample6 = (Sint16) src[6];
-    Sint16 last_sample7 = (Sint16) src[7];
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) src[0];
-        const Sint16 sample1 = (Sint16) src[1];
-        const Sint16 sample2 = (Sint16) src[2];
-        const Sint16 sample3 = (Sint16) src[3];
-        const Sint16 sample4 = (Sint16) src[4];
-        const Sint16 sample5 = (Sint16) src[5];
-        const Sint16 sample6 = (Sint16) src[6];
-        const Sint16 sample7 = (Sint16) src[7];
-        src += 32;
-        dst[0] = (Uint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint8) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint8) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint8) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Uint8) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Uint8) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S8, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 1 * 2;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst >= target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src--;
-        dst[1] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[0] = (Sint8) sample0;
-        last_sample0 = sample0;
-        dst -= 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S8, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src += 2;
-        dst[0] = (Sint8) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S8, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 1 * 4;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst >= target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src--;
-        dst[3] = (Sint8) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[2] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint8) (((3 * sample0) + last_sample0) >> 2);
-        dst[0] = (Sint8) sample0;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S8, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src += 4;
-        dst[0] = (Sint8) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S8, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 2 * 2;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst >= target) {
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src -= 2;
-        dst[3] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint8) sample1;
-        dst[0] = (Sint8) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S8, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        src += 4;
-        dst[0] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint8) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S8, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 2 * 4;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst >= target) {
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src -= 2;
-        dst[7] = (Sint8) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[6] = (Sint8) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[5] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Sint8) (((3 * sample1) + last_sample1) >> 2);
-        dst[2] = (Sint8) (((3 * sample0) + last_sample0) >> 2);
-        dst[1] = (Sint8) sample1;
-        dst[0] = (Sint8) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S8, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        src += 8;
-        dst[0] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint8) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S8, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 4 * 2;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst >= target) {
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src -= 4;
-        dst[7] = (Sint8) ((sample3 + last_sample3) >> 1);
-        dst[6] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[5] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Sint8) sample3;
-        dst[2] = (Sint8) sample2;
-        dst[1] = (Sint8) sample1;
-        dst[0] = (Sint8) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S8, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        src += 8;
-        dst[0] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint8) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S8, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 4 * 4;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst >= target) {
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src -= 4;
-        dst[15] = (Sint8) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[14] = (Sint8) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[13] = (Sint8) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[12] = (Sint8) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[11] = (Sint8) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Sint8) (((3 * sample3) + last_sample3) >> 2);
-        dst[6] = (Sint8) (((3 * sample2) + last_sample2) >> 2);
-        dst[5] = (Sint8) (((3 * sample1) + last_sample1) >> 2);
-        dst[4] = (Sint8) (((3 * sample0) + last_sample0) >> 2);
-        dst[3] = (Sint8) sample3;
-        dst[2] = (Sint8) sample2;
-        dst[1] = (Sint8) sample1;
-        dst[0] = (Sint8) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S8, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        src += 16;
-        dst[0] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint8) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S8, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 6 * 2;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint16 last_sample5 = (Sint16) ((Sint8) src[5]);
-    Sint16 last_sample4 = (Sint16) ((Sint8) src[4]);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst >= target) {
-        const Sint16 sample5 = (Sint16) ((Sint8) src[5]);
-        const Sint16 sample4 = (Sint16) ((Sint8) src[4]);
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src -= 6;
-        dst[11] = (Sint8) ((sample5 + last_sample5) >> 1);
-        dst[10] = (Sint8) ((sample4 + last_sample4) >> 1);
-        dst[9] = (Sint8) ((sample3 + last_sample3) >> 1);
-        dst[8] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[7] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[6] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[5] = (Sint8) sample5;
-        dst[4] = (Sint8) sample4;
-        dst[3] = (Sint8) sample3;
-        dst[2] = (Sint8) sample2;
-        dst[1] = (Sint8) sample1;
-        dst[0] = (Sint8) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 12;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S8, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    Sint16 last_sample4 = (Sint16) ((Sint8) src[4]);
-    Sint16 last_sample5 = (Sint16) ((Sint8) src[5]);
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        const Sint16 sample4 = (Sint16) ((Sint8) src[4]);
-        const Sint16 sample5 = (Sint16) ((Sint8) src[5]);
-        src += 12;
-        dst[0] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint8) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint8) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint8) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S8, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 6 * 4;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint16 last_sample5 = (Sint16) ((Sint8) src[5]);
-    Sint16 last_sample4 = (Sint16) ((Sint8) src[4]);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst >= target) {
-        const Sint16 sample5 = (Sint16) ((Sint8) src[5]);
-        const Sint16 sample4 = (Sint16) ((Sint8) src[4]);
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src -= 6;
-        dst[23] = (Sint8) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[22] = (Sint8) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[21] = (Sint8) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[20] = (Sint8) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[19] = (Sint8) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[18] = (Sint8) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[17] = (Sint8) ((sample5 + last_sample5) >> 1);
-        dst[16] = (Sint8) ((sample4 + last_sample4) >> 1);
-        dst[15] = (Sint8) ((sample3 + last_sample3) >> 1);
-        dst[14] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[13] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[12] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[11] = (Sint8) (((3 * sample5) + last_sample5) >> 2);
-        dst[10] = (Sint8) (((3 * sample4) + last_sample4) >> 2);
-        dst[9] = (Sint8) (((3 * sample3) + last_sample3) >> 2);
-        dst[8] = (Sint8) (((3 * sample2) + last_sample2) >> 2);
-        dst[7] = (Sint8) (((3 * sample1) + last_sample1) >> 2);
-        dst[6] = (Sint8) (((3 * sample0) + last_sample0) >> 2);
-        dst[5] = (Sint8) sample5;
-        dst[4] = (Sint8) sample4;
-        dst[3] = (Sint8) sample3;
-        dst[2] = (Sint8) sample2;
-        dst[1] = (Sint8) sample1;
-        dst[0] = (Sint8) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 24;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S8, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    Sint16 last_sample4 = (Sint16) ((Sint8) src[4]);
-    Sint16 last_sample5 = (Sint16) ((Sint8) src[5]);
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        const Sint16 sample4 = (Sint16) ((Sint8) src[4]);
-        const Sint16 sample5 = (Sint16) ((Sint8) src[5]);
-        src += 24;
-        dst[0] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint8) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint8) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint8) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S8, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 8 * 2;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint16 last_sample7 = (Sint16) ((Sint8) src[7]);
-    Sint16 last_sample6 = (Sint16) ((Sint8) src[6]);
-    Sint16 last_sample5 = (Sint16) ((Sint8) src[5]);
-    Sint16 last_sample4 = (Sint16) ((Sint8) src[4]);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst >= target) {
-        const Sint16 sample7 = (Sint16) ((Sint8) src[7]);
-        const Sint16 sample6 = (Sint16) ((Sint8) src[6]);
-        const Sint16 sample5 = (Sint16) ((Sint8) src[5]);
-        const Sint16 sample4 = (Sint16) ((Sint8) src[4]);
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src -= 8;
-        dst[15] = (Sint8) ((sample7 + last_sample7) >> 1);
-        dst[14] = (Sint8) ((sample6 + last_sample6) >> 1);
-        dst[13] = (Sint8) ((sample5 + last_sample5) >> 1);
-        dst[12] = (Sint8) ((sample4 + last_sample4) >> 1);
-        dst[11] = (Sint8) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Sint8) sample7;
-        dst[6] = (Sint8) sample6;
-        dst[5] = (Sint8) sample5;
-        dst[4] = (Sint8) sample4;
-        dst[3] = (Sint8) sample3;
-        dst[2] = (Sint8) sample2;
-        dst[1] = (Sint8) sample1;
-        dst[0] = (Sint8) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S8, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    Sint16 last_sample4 = (Sint16) ((Sint8) src[4]);
-    Sint16 last_sample5 = (Sint16) ((Sint8) src[5]);
-    Sint16 last_sample6 = (Sint16) ((Sint8) src[6]);
-    Sint16 last_sample7 = (Sint16) ((Sint8) src[7]);
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        const Sint16 sample4 = (Sint16) ((Sint8) src[4]);
-        const Sint16 sample5 = (Sint16) ((Sint8) src[5]);
-        const Sint16 sample6 = (Sint16) ((Sint8) src[6]);
-        const Sint16 sample7 = (Sint16) ((Sint8) src[7]);
-        src += 16;
-        dst[0] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint8) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint8) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint8) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Sint8) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Sint8) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S8_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S8, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint8 *dst = ((Sint8 *) (cvt->buf + dstsize)) - 8 * 4;
-    const Sint8 *src = ((Sint8 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint8 *target = ((const Sint8 *) cvt->buf);
-    Sint16 last_sample7 = (Sint16) ((Sint8) src[7]);
-    Sint16 last_sample6 = (Sint16) ((Sint8) src[6]);
-    Sint16 last_sample5 = (Sint16) ((Sint8) src[5]);
-    Sint16 last_sample4 = (Sint16) ((Sint8) src[4]);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    while (dst >= target) {
-        const Sint16 sample7 = (Sint16) ((Sint8) src[7]);
-        const Sint16 sample6 = (Sint16) ((Sint8) src[6]);
-        const Sint16 sample5 = (Sint16) ((Sint8) src[5]);
-        const Sint16 sample4 = (Sint16) ((Sint8) src[4]);
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        src -= 8;
-        dst[31] = (Sint8) ((sample7 + (3 * last_sample7)) >> 2);
-        dst[30] = (Sint8) ((sample6 + (3 * last_sample6)) >> 2);
-        dst[29] = (Sint8) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[28] = (Sint8) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[27] = (Sint8) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[26] = (Sint8) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[25] = (Sint8) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[24] = (Sint8) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[23] = (Sint8) ((sample7 + last_sample7) >> 1);
-        dst[22] = (Sint8) ((sample6 + last_sample6) >> 1);
-        dst[21] = (Sint8) ((sample5 + last_sample5) >> 1);
-        dst[20] = (Sint8) ((sample4 + last_sample4) >> 1);
-        dst[19] = (Sint8) ((sample3 + last_sample3) >> 1);
-        dst[18] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[17] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[16] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[15] = (Sint8) (((3 * sample7) + last_sample7) >> 2);
-        dst[14] = (Sint8) (((3 * sample6) + last_sample6) >> 2);
-        dst[13] = (Sint8) (((3 * sample5) + last_sample5) >> 2);
-        dst[12] = (Sint8) (((3 * sample4) + last_sample4) >> 2);
-        dst[11] = (Sint8) (((3 * sample3) + last_sample3) >> 2);
-        dst[10] = (Sint8) (((3 * sample2) + last_sample2) >> 2);
-        dst[9] = (Sint8) (((3 * sample1) + last_sample1) >> 2);
-        dst[8] = (Sint8) (((3 * sample0) + last_sample0) >> 2);
-        dst[7] = (Sint8) sample7;
-        dst[6] = (Sint8) sample6;
-        dst[5] = (Sint8) sample5;
-        dst[4] = (Sint8) sample4;
-        dst[3] = (Sint8) sample3;
-        dst[2] = (Sint8) sample2;
-        dst[1] = (Sint8) sample1;
-        dst[0] = (Sint8) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 32;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S8_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S8, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint8 *dst = (Sint8 *) cvt->buf;
-    const Sint8 *src = (Sint8 *) cvt->buf;
-    const Sint8 *target = (const Sint8 *) (cvt->buf + dstsize);
-    Sint16 last_sample0 = (Sint16) ((Sint8) src[0]);
-    Sint16 last_sample1 = (Sint16) ((Sint8) src[1]);
-    Sint16 last_sample2 = (Sint16) ((Sint8) src[2]);
-    Sint16 last_sample3 = (Sint16) ((Sint8) src[3]);
-    Sint16 last_sample4 = (Sint16) ((Sint8) src[4]);
-    Sint16 last_sample5 = (Sint16) ((Sint8) src[5]);
-    Sint16 last_sample6 = (Sint16) ((Sint8) src[6]);
-    Sint16 last_sample7 = (Sint16) ((Sint8) src[7]);
-    while (dst < target) {
-        const Sint16 sample0 = (Sint16) ((Sint8) src[0]);
-        const Sint16 sample1 = (Sint16) ((Sint8) src[1]);
-        const Sint16 sample2 = (Sint16) ((Sint8) src[2]);
-        const Sint16 sample3 = (Sint16) ((Sint8) src[3]);
-        const Sint16 sample4 = (Sint16) ((Sint8) src[4]);
-        const Sint16 sample5 = (Sint16) ((Sint8) src[5]);
-        const Sint16 sample6 = (Sint16) ((Sint8) src[6]);
-        const Sint16 sample7 = (Sint16) ((Sint8) src[7]);
-        src += 32;
-        dst[0] = (Sint8) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint8) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint8) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint8) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint8) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint8) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Sint8) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Sint8) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U16LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 1 * 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src--;
-        dst[1] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[0] = (Uint16) sample0;
-        last_sample0 = sample0;
-        dst -= 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U16LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src += 2;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U16LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 1 * 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src--;
-        dst[3] = (Uint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[2] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[0] = (Uint16) sample0;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U16LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src += 4;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U16LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 2 * 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src -= 2;
-        dst[3] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U16LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        src += 4;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U16LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 2 * 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src -= 2;
-        dst[7] = (Uint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[6] = (Uint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[5] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Uint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[2] = (Uint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U16LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        src += 8;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U16LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 4 * 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src -= 4;
-        dst[7] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[6] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[5] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U16LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        src += 8;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U16LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 4 * 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src -= 4;
-        dst[15] = (Uint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[14] = (Uint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[13] = (Uint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[12] = (Uint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[11] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Uint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[6] = (Uint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[5] = (Uint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[4] = (Uint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U16LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        src += 16;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U16LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 6 * 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample5 = (Sint32) SDL_SwapLE16(src[5]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapLE16(src[4]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample5 = (Sint32) SDL_SwapLE16(src[5]);
-        const Sint32 sample4 = (Sint32) SDL_SwapLE16(src[4]);
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src -= 6;
-        dst[11] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[10] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[9] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[8] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[7] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[6] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[5] = (Uint16) sample5;
-        dst[4] = (Uint16) sample4;
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 12;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U16LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapLE16(src[4]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapLE16(src[5]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        const Sint32 sample4 = (Sint32) SDL_SwapLE16(src[4]);
-        const Sint32 sample5 = (Sint32) SDL_SwapLE16(src[5]);
-        src += 12;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint16) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U16LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 6 * 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample5 = (Sint32) SDL_SwapLE16(src[5]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapLE16(src[4]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample5 = (Sint32) SDL_SwapLE16(src[5]);
-        const Sint32 sample4 = (Sint32) SDL_SwapLE16(src[4]);
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src -= 6;
-        dst[23] = (Uint16) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[22] = (Uint16) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[21] = (Uint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[20] = (Uint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[19] = (Uint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[18] = (Uint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[17] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[16] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[15] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[14] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[13] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[12] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[11] = (Uint16) (((3 * sample5) + last_sample5) >> 2);
-        dst[10] = (Uint16) (((3 * sample4) + last_sample4) >> 2);
-        dst[9] = (Uint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[8] = (Uint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[7] = (Uint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[6] = (Uint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[5] = (Uint16) sample5;
-        dst[4] = (Uint16) sample4;
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 24;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U16LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapLE16(src[4]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapLE16(src[5]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        const Sint32 sample4 = (Sint32) SDL_SwapLE16(src[4]);
-        const Sint32 sample5 = (Sint32) SDL_SwapLE16(src[5]);
-        src += 24;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint16) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U16LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 8 * 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample7 = (Sint32) SDL_SwapLE16(src[7]);
-    Sint32 last_sample6 = (Sint32) SDL_SwapLE16(src[6]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapLE16(src[5]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapLE16(src[4]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample7 = (Sint32) SDL_SwapLE16(src[7]);
-        const Sint32 sample6 = (Sint32) SDL_SwapLE16(src[6]);
-        const Sint32 sample5 = (Sint32) SDL_SwapLE16(src[5]);
-        const Sint32 sample4 = (Sint32) SDL_SwapLE16(src[4]);
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src -= 8;
-        dst[15] = (Uint16) ((sample7 + last_sample7) >> 1);
-        dst[14] = (Uint16) ((sample6 + last_sample6) >> 1);
-        dst[13] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[12] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[11] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Uint16) sample7;
-        dst[6] = (Uint16) sample6;
-        dst[5] = (Uint16) sample5;
-        dst[4] = (Uint16) sample4;
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U16LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapLE16(src[4]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapLE16(src[5]);
-    Sint32 last_sample6 = (Sint32) SDL_SwapLE16(src[6]);
-    Sint32 last_sample7 = (Sint32) SDL_SwapLE16(src[7]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        const Sint32 sample4 = (Sint32) SDL_SwapLE16(src[4]);
-        const Sint32 sample5 = (Sint32) SDL_SwapLE16(src[5]);
-        const Sint32 sample6 = (Sint32) SDL_SwapLE16(src[6]);
-        const Sint32 sample7 = (Sint32) SDL_SwapLE16(src[7]);
-        src += 16;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Uint16) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Uint16) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16LSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U16LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 8 * 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample7 = (Sint32) SDL_SwapLE16(src[7]);
-    Sint32 last_sample6 = (Sint32) SDL_SwapLE16(src[6]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapLE16(src[5]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapLE16(src[4]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample7 = (Sint32) SDL_SwapLE16(src[7]);
-        const Sint32 sample6 = (Sint32) SDL_SwapLE16(src[6]);
-        const Sint32 sample5 = (Sint32) SDL_SwapLE16(src[5]);
-        const Sint32 sample4 = (Sint32) SDL_SwapLE16(src[4]);
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        src -= 8;
-        dst[31] = (Uint16) ((sample7 + (3 * last_sample7)) >> 2);
-        dst[30] = (Uint16) ((sample6 + (3 * last_sample6)) >> 2);
-        dst[29] = (Uint16) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[28] = (Uint16) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[27] = (Uint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[26] = (Uint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[25] = (Uint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[24] = (Uint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[23] = (Uint16) ((sample7 + last_sample7) >> 1);
-        dst[22] = (Uint16) ((sample6 + last_sample6) >> 1);
-        dst[21] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[20] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[19] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[18] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[17] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[16] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[15] = (Uint16) (((3 * sample7) + last_sample7) >> 2);
-        dst[14] = (Uint16) (((3 * sample6) + last_sample6) >> 2);
-        dst[13] = (Uint16) (((3 * sample5) + last_sample5) >> 2);
-        dst[12] = (Uint16) (((3 * sample4) + last_sample4) >> 2);
-        dst[11] = (Uint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[10] = (Uint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[9] = (Uint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[8] = (Uint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[7] = (Uint16) sample7;
-        dst[6] = (Uint16) sample6;
-        dst[5] = (Uint16) sample5;
-        dst[4] = (Uint16) sample4;
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 32;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16LSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U16LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapLE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapLE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapLE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapLE16(src[3]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapLE16(src[4]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapLE16(src[5]);
-    Sint32 last_sample6 = (Sint32) SDL_SwapLE16(src[6]);
-    Sint32 last_sample7 = (Sint32) SDL_SwapLE16(src[7]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapLE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapLE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapLE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapLE16(src[3]);
-        const Sint32 sample4 = (Sint32) SDL_SwapLE16(src[4]);
-        const Sint32 sample5 = (Sint32) SDL_SwapLE16(src[5]);
-        const Sint32 sample6 = (Sint32) SDL_SwapLE16(src[6]);
-        const Sint32 sample7 = (Sint32) SDL_SwapLE16(src[7]);
-        src += 32;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Uint16) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Uint16) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S16LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 1 * 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src--;
-        dst[1] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[0] = (Sint16) sample0;
-        last_sample0 = sample0;
-        dst -= 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S16LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src += 2;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S16LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 1 * 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src--;
-        dst[3] = (Sint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[2] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[0] = (Sint16) sample0;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S16LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src += 4;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S16LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 2 * 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src -= 2;
-        dst[3] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S16LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        src += 4;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S16LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 2 * 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src -= 2;
-        dst[7] = (Sint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[6] = (Sint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[5] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Sint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[2] = (Sint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S16LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        src += 8;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S16LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 4 * 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src -= 4;
-        dst[7] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[6] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[5] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S16LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        src += 8;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S16LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 4 * 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src -= 4;
-        dst[15] = (Sint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[14] = (Sint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[13] = (Sint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[12] = (Sint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[11] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Sint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[6] = (Sint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[5] = (Sint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[4] = (Sint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S16LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        src += 16;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S16LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 6 * 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src -= 6;
-        dst[11] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[10] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[9] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[8] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[7] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[6] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[5] = (Sint16) sample5;
-        dst[4] = (Sint16) sample4;
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 12;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S16LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-        src += 12;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint16) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S16LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 6 * 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src -= 6;
-        dst[23] = (Sint16) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[22] = (Sint16) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[21] = (Sint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[20] = (Sint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[19] = (Sint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[18] = (Sint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[17] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[16] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[15] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[14] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[13] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[12] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[11] = (Sint16) (((3 * sample5) + last_sample5) >> 2);
-        dst[10] = (Sint16) (((3 * sample4) + last_sample4) >> 2);
-        dst[9] = (Sint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[8] = (Sint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[7] = (Sint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[6] = (Sint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[5] = (Sint16) sample5;
-        dst[4] = (Sint16) sample4;
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 24;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S16LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-        src += 24;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint16) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S16LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 8 * 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample7 = (Sint32) ((Sint16) SDL_SwapLE16(src[7]));
-    Sint32 last_sample6 = (Sint32) ((Sint16) SDL_SwapLE16(src[6]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample7 = (Sint32) ((Sint16) SDL_SwapLE16(src[7]));
-        const Sint32 sample6 = (Sint32) ((Sint16) SDL_SwapLE16(src[6]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src -= 8;
-        dst[15] = (Sint16) ((sample7 + last_sample7) >> 1);
-        dst[14] = (Sint16) ((sample6 + last_sample6) >> 1);
-        dst[13] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[12] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[11] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Sint16) sample7;
-        dst[6] = (Sint16) sample6;
-        dst[5] = (Sint16) sample5;
-        dst[4] = (Sint16) sample4;
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S16LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-    Sint32 last_sample6 = (Sint32) ((Sint16) SDL_SwapLE16(src[6]));
-    Sint32 last_sample7 = (Sint32) ((Sint16) SDL_SwapLE16(src[7]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-        const Sint32 sample6 = (Sint32) ((Sint16) SDL_SwapLE16(src[6]));
-        const Sint32 sample7 = (Sint32) ((Sint16) SDL_SwapLE16(src[7]));
-        src += 16;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Sint16) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Sint16) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16LSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S16LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 8 * 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample7 = (Sint32) ((Sint16) SDL_SwapLE16(src[7]));
-    Sint32 last_sample6 = (Sint32) ((Sint16) SDL_SwapLE16(src[6]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample7 = (Sint32) ((Sint16) SDL_SwapLE16(src[7]));
-        const Sint32 sample6 = (Sint32) ((Sint16) SDL_SwapLE16(src[6]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        src -= 8;
-        dst[31] = (Sint16) ((sample7 + (3 * last_sample7)) >> 2);
-        dst[30] = (Sint16) ((sample6 + (3 * last_sample6)) >> 2);
-        dst[29] = (Sint16) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[28] = (Sint16) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[27] = (Sint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[26] = (Sint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[25] = (Sint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[24] = (Sint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[23] = (Sint16) ((sample7 + last_sample7) >> 1);
-        dst[22] = (Sint16) ((sample6 + last_sample6) >> 1);
-        dst[21] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[20] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[19] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[18] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[17] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[16] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[15] = (Sint16) (((3 * sample7) + last_sample7) >> 2);
-        dst[14] = (Sint16) (((3 * sample6) + last_sample6) >> 2);
-        dst[13] = (Sint16) (((3 * sample5) + last_sample5) >> 2);
-        dst[12] = (Sint16) (((3 * sample4) + last_sample4) >> 2);
-        dst[11] = (Sint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[10] = (Sint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[9] = (Sint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[8] = (Sint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[7] = (Sint16) sample7;
-        dst[6] = (Sint16) sample6;
-        dst[5] = (Sint16) sample5;
-        dst[4] = (Sint16) sample4;
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 32;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16LSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S16LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-    Sint32 last_sample6 = (Sint32) ((Sint16) SDL_SwapLE16(src[6]));
-    Sint32 last_sample7 = (Sint32) ((Sint16) SDL_SwapLE16(src[7]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapLE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapLE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapLE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapLE16(src[3]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapLE16(src[4]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapLE16(src[5]));
-        const Sint32 sample6 = (Sint32) ((Sint16) SDL_SwapLE16(src[6]));
-        const Sint32 sample7 = (Sint32) ((Sint16) SDL_SwapLE16(src[7]));
-        src += 32;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Sint16) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Sint16) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U16MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 1 * 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src--;
-        dst[1] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[0] = (Uint16) sample0;
-        last_sample0 = sample0;
-        dst -= 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U16MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src += 2;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U16MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 1 * 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src--;
-        dst[3] = (Uint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[2] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[0] = (Uint16) sample0;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U16MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src += 4;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U16MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 2 * 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src -= 2;
-        dst[3] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U16MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        src += 4;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U16MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 2 * 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src -= 2;
-        dst[7] = (Uint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[6] = (Uint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[5] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Uint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[2] = (Uint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U16MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        src += 8;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U16MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 4 * 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src -= 4;
-        dst[7] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[6] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[5] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U16MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        src += 8;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U16MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 4 * 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src -= 4;
-        dst[15] = (Uint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[14] = (Uint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[13] = (Uint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[12] = (Uint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[11] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Uint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[6] = (Uint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[5] = (Uint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[4] = (Uint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U16MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        src += 16;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U16MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 6 * 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample5 = (Sint32) SDL_SwapBE16(src[5]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapBE16(src[4]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample5 = (Sint32) SDL_SwapBE16(src[5]);
-        const Sint32 sample4 = (Sint32) SDL_SwapBE16(src[4]);
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src -= 6;
-        dst[11] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[10] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[9] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[8] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[7] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[6] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[5] = (Uint16) sample5;
-        dst[4] = (Uint16) sample4;
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 12;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U16MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapBE16(src[4]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapBE16(src[5]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        const Sint32 sample4 = (Sint32) SDL_SwapBE16(src[4]);
-        const Sint32 sample5 = (Sint32) SDL_SwapBE16(src[5]);
-        src += 12;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint16) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U16MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 6 * 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample5 = (Sint32) SDL_SwapBE16(src[5]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapBE16(src[4]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample5 = (Sint32) SDL_SwapBE16(src[5]);
-        const Sint32 sample4 = (Sint32) SDL_SwapBE16(src[4]);
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src -= 6;
-        dst[23] = (Uint16) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[22] = (Uint16) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[21] = (Uint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[20] = (Uint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[19] = (Uint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[18] = (Uint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[17] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[16] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[15] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[14] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[13] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[12] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[11] = (Uint16) (((3 * sample5) + last_sample5) >> 2);
-        dst[10] = (Uint16) (((3 * sample4) + last_sample4) >> 2);
-        dst[9] = (Uint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[8] = (Uint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[7] = (Uint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[6] = (Uint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[5] = (Uint16) sample5;
-        dst[4] = (Uint16) sample4;
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 24;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U16MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapBE16(src[4]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapBE16(src[5]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        const Sint32 sample4 = (Sint32) SDL_SwapBE16(src[4]);
-        const Sint32 sample5 = (Sint32) SDL_SwapBE16(src[5]);
-        src += 24;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint16) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_U16MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 8 * 2;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample7 = (Sint32) SDL_SwapBE16(src[7]);
-    Sint32 last_sample6 = (Sint32) SDL_SwapBE16(src[6]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapBE16(src[5]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapBE16(src[4]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample7 = (Sint32) SDL_SwapBE16(src[7]);
-        const Sint32 sample6 = (Sint32) SDL_SwapBE16(src[6]);
-        const Sint32 sample5 = (Sint32) SDL_SwapBE16(src[5]);
-        const Sint32 sample4 = (Sint32) SDL_SwapBE16(src[4]);
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src -= 8;
-        dst[15] = (Uint16) ((sample7 + last_sample7) >> 1);
-        dst[14] = (Uint16) ((sample6 + last_sample6) >> 1);
-        dst[13] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[12] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[11] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Uint16) sample7;
-        dst[6] = (Uint16) sample6;
-        dst[5] = (Uint16) sample5;
-        dst[4] = (Uint16) sample4;
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_U16MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapBE16(src[4]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapBE16(src[5]);
-    Sint32 last_sample6 = (Sint32) SDL_SwapBE16(src[6]);
-    Sint32 last_sample7 = (Sint32) SDL_SwapBE16(src[7]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        const Sint32 sample4 = (Sint32) SDL_SwapBE16(src[4]);
-        const Sint32 sample5 = (Sint32) SDL_SwapBE16(src[5]);
-        const Sint32 sample6 = (Sint32) SDL_SwapBE16(src[6]);
-        const Sint32 sample7 = (Sint32) SDL_SwapBE16(src[7]);
-        src += 16;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Uint16) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Uint16) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_U16MSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_U16MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Uint16 *dst = ((Uint16 *) (cvt->buf + dstsize)) - 8 * 4;
-    const Uint16 *src = ((Uint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Uint16 *target = ((const Uint16 *) cvt->buf);
-    Sint32 last_sample7 = (Sint32) SDL_SwapBE16(src[7]);
-    Sint32 last_sample6 = (Sint32) SDL_SwapBE16(src[6]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapBE16(src[5]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapBE16(src[4]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    while (dst >= target) {
-        const Sint32 sample7 = (Sint32) SDL_SwapBE16(src[7]);
-        const Sint32 sample6 = (Sint32) SDL_SwapBE16(src[6]);
-        const Sint32 sample5 = (Sint32) SDL_SwapBE16(src[5]);
-        const Sint32 sample4 = (Sint32) SDL_SwapBE16(src[4]);
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        src -= 8;
-        dst[31] = (Uint16) ((sample7 + (3 * last_sample7)) >> 2);
-        dst[30] = (Uint16) ((sample6 + (3 * last_sample6)) >> 2);
-        dst[29] = (Uint16) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[28] = (Uint16) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[27] = (Uint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[26] = (Uint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[25] = (Uint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[24] = (Uint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[23] = (Uint16) ((sample7 + last_sample7) >> 1);
-        dst[22] = (Uint16) ((sample6 + last_sample6) >> 1);
-        dst[21] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[20] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[19] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[18] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[17] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[16] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[15] = (Uint16) (((3 * sample7) + last_sample7) >> 2);
-        dst[14] = (Uint16) (((3 * sample6) + last_sample6) >> 2);
-        dst[13] = (Uint16) (((3 * sample5) + last_sample5) >> 2);
-        dst[12] = (Uint16) (((3 * sample4) + last_sample4) >> 2);
-        dst[11] = (Uint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[10] = (Uint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[9] = (Uint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[8] = (Uint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[7] = (Uint16) sample7;
-        dst[6] = (Uint16) sample6;
-        dst[5] = (Uint16) sample5;
-        dst[4] = (Uint16) sample4;
-        dst[3] = (Uint16) sample3;
-        dst[2] = (Uint16) sample2;
-        dst[1] = (Uint16) sample1;
-        dst[0] = (Uint16) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 32;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_U16MSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_U16MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Uint16 *dst = (Uint16 *) cvt->buf;
-    const Uint16 *src = (Uint16 *) cvt->buf;
-    const Uint16 *target = (const Uint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) SDL_SwapBE16(src[0]);
-    Sint32 last_sample1 = (Sint32) SDL_SwapBE16(src[1]);
-    Sint32 last_sample2 = (Sint32) SDL_SwapBE16(src[2]);
-    Sint32 last_sample3 = (Sint32) SDL_SwapBE16(src[3]);
-    Sint32 last_sample4 = (Sint32) SDL_SwapBE16(src[4]);
-    Sint32 last_sample5 = (Sint32) SDL_SwapBE16(src[5]);
-    Sint32 last_sample6 = (Sint32) SDL_SwapBE16(src[6]);
-    Sint32 last_sample7 = (Sint32) SDL_SwapBE16(src[7]);
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) SDL_SwapBE16(src[0]);
-        const Sint32 sample1 = (Sint32) SDL_SwapBE16(src[1]);
-        const Sint32 sample2 = (Sint32) SDL_SwapBE16(src[2]);
-        const Sint32 sample3 = (Sint32) SDL_SwapBE16(src[3]);
-        const Sint32 sample4 = (Sint32) SDL_SwapBE16(src[4]);
-        const Sint32 sample5 = (Sint32) SDL_SwapBE16(src[5]);
-        const Sint32 sample6 = (Sint32) SDL_SwapBE16(src[6]);
-        const Sint32 sample7 = (Sint32) SDL_SwapBE16(src[7]);
-        src += 32;
-        dst[0] = (Uint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Uint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Uint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Uint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Uint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Uint16) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Uint16) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Uint16) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S16MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 1 * 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src--;
-        dst[1] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[0] = (Sint16) sample0;
-        last_sample0 = sample0;
-        dst -= 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S16MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src += 2;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S16MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 1 * 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src--;
-        dst[3] = (Sint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[2] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[0] = (Sint16) sample0;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S16MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src += 4;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S16MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 2 * 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src -= 2;
-        dst[3] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S16MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        src += 4;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S16MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 2 * 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src -= 2;
-        dst[7] = (Sint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[6] = (Sint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[5] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Sint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[2] = (Sint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S16MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        src += 8;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S16MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 4 * 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src -= 4;
-        dst[7] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[6] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[5] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S16MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        src += 8;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S16MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 4 * 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src -= 4;
-        dst[15] = (Sint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[14] = (Sint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[13] = (Sint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[12] = (Sint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[11] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Sint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[6] = (Sint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[5] = (Sint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[4] = (Sint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S16MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        src += 16;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S16MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 6 * 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src -= 6;
-        dst[11] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[10] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[9] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[8] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[7] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[6] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[5] = (Sint16) sample5;
-        dst[4] = (Sint16) sample4;
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 12;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S16MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-        src += 12;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint16) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S16MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 6 * 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src -= 6;
-        dst[23] = (Sint16) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[22] = (Sint16) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[21] = (Sint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[20] = (Sint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[19] = (Sint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[18] = (Sint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[17] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[16] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[15] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[14] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[13] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[12] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[11] = (Sint16) (((3 * sample5) + last_sample5) >> 2);
-        dst[10] = (Sint16) (((3 * sample4) + last_sample4) >> 2);
-        dst[9] = (Sint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[8] = (Sint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[7] = (Sint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[6] = (Sint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[5] = (Sint16) sample5;
-        dst[4] = (Sint16) sample4;
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 24;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S16MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-        src += 24;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint16) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S16MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 8 * 2;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample7 = (Sint32) ((Sint16) SDL_SwapBE16(src[7]));
-    Sint32 last_sample6 = (Sint32) ((Sint16) SDL_SwapBE16(src[6]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample7 = (Sint32) ((Sint16) SDL_SwapBE16(src[7]));
-        const Sint32 sample6 = (Sint32) ((Sint16) SDL_SwapBE16(src[6]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src -= 8;
-        dst[15] = (Sint16) ((sample7 + last_sample7) >> 1);
-        dst[14] = (Sint16) ((sample6 + last_sample6) >> 1);
-        dst[13] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[12] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[11] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Sint16) sample7;
-        dst[6] = (Sint16) sample6;
-        dst[5] = (Sint16) sample5;
-        dst[4] = (Sint16) sample4;
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S16MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-    Sint32 last_sample6 = (Sint32) ((Sint16) SDL_SwapBE16(src[6]));
-    Sint32 last_sample7 = (Sint32) ((Sint16) SDL_SwapBE16(src[7]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-        const Sint32 sample6 = (Sint32) ((Sint16) SDL_SwapBE16(src[6]));
-        const Sint32 sample7 = (Sint32) ((Sint16) SDL_SwapBE16(src[7]));
-        src += 16;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Sint16) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Sint16) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S16MSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S16MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint16 *dst = ((Sint16 *) (cvt->buf + dstsize)) - 8 * 4;
-    const Sint16 *src = ((Sint16 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint16 *target = ((const Sint16 *) cvt->buf);
-    Sint32 last_sample7 = (Sint32) ((Sint16) SDL_SwapBE16(src[7]));
-    Sint32 last_sample6 = (Sint32) ((Sint16) SDL_SwapBE16(src[6]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    while (dst >= target) {
-        const Sint32 sample7 = (Sint32) ((Sint16) SDL_SwapBE16(src[7]));
-        const Sint32 sample6 = (Sint32) ((Sint16) SDL_SwapBE16(src[6]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        src -= 8;
-        dst[31] = (Sint16) ((sample7 + (3 * last_sample7)) >> 2);
-        dst[30] = (Sint16) ((sample6 + (3 * last_sample6)) >> 2);
-        dst[29] = (Sint16) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[28] = (Sint16) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[27] = (Sint16) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[26] = (Sint16) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[25] = (Sint16) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[24] = (Sint16) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[23] = (Sint16) ((sample7 + last_sample7) >> 1);
-        dst[22] = (Sint16) ((sample6 + last_sample6) >> 1);
-        dst[21] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[20] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[19] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[18] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[17] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[16] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[15] = (Sint16) (((3 * sample7) + last_sample7) >> 2);
-        dst[14] = (Sint16) (((3 * sample6) + last_sample6) >> 2);
-        dst[13] = (Sint16) (((3 * sample5) + last_sample5) >> 2);
-        dst[12] = (Sint16) (((3 * sample4) + last_sample4) >> 2);
-        dst[11] = (Sint16) (((3 * sample3) + last_sample3) >> 2);
-        dst[10] = (Sint16) (((3 * sample2) + last_sample2) >> 2);
-        dst[9] = (Sint16) (((3 * sample1) + last_sample1) >> 2);
-        dst[8] = (Sint16) (((3 * sample0) + last_sample0) >> 2);
-        dst[7] = (Sint16) sample7;
-        dst[6] = (Sint16) sample6;
-        dst[5] = (Sint16) sample5;
-        dst[4] = (Sint16) sample4;
-        dst[3] = (Sint16) sample3;
-        dst[2] = (Sint16) sample2;
-        dst[1] = (Sint16) sample1;
-        dst[0] = (Sint16) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 32;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S16MSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S16MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint16 *dst = (Sint16 *) cvt->buf;
-    const Sint16 *src = (Sint16 *) cvt->buf;
-    const Sint16 *target = (const Sint16 *) (cvt->buf + dstsize);
-    Sint32 last_sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-    Sint32 last_sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-    Sint32 last_sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-    Sint32 last_sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-    Sint32 last_sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-    Sint32 last_sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-    Sint32 last_sample6 = (Sint32) ((Sint16) SDL_SwapBE16(src[6]));
-    Sint32 last_sample7 = (Sint32) ((Sint16) SDL_SwapBE16(src[7]));
-    while (dst < target) {
-        const Sint32 sample0 = (Sint32) ((Sint16) SDL_SwapBE16(src[0]));
-        const Sint32 sample1 = (Sint32) ((Sint16) SDL_SwapBE16(src[1]));
-        const Sint32 sample2 = (Sint32) ((Sint16) SDL_SwapBE16(src[2]));
-        const Sint32 sample3 = (Sint32) ((Sint16) SDL_SwapBE16(src[3]));
-        const Sint32 sample4 = (Sint32) ((Sint16) SDL_SwapBE16(src[4]));
-        const Sint32 sample5 = (Sint32) ((Sint16) SDL_SwapBE16(src[5]));
-        const Sint32 sample6 = (Sint32) ((Sint16) SDL_SwapBE16(src[6]));
-        const Sint32 sample7 = (Sint32) ((Sint16) SDL_SwapBE16(src[7]));
-        src += 32;
-        dst[0] = (Sint16) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint16) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint16) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint16) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint16) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint16) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Sint16) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Sint16) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S32LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 1 * 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src--;
-        dst[1] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[0] = (Sint32) sample0;
-        last_sample0 = sample0;
-        dst -= 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S32LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src += 2;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S32LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 1 * 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src--;
-        dst[3] = (Sint32) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[2] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) (((3 * sample0) + last_sample0) >> 2);
-        dst[0] = (Sint32) sample0;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S32LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src += 4;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S32LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 2 * 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src -= 2;
-        dst[3] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S32LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        src += 4;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S32LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 2 * 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src -= 2;
-        dst[7] = (Sint32) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[6] = (Sint32) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[5] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Sint32) (((3 * sample1) + last_sample1) >> 2);
-        dst[2] = (Sint32) (((3 * sample0) + last_sample0) >> 2);
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S32LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        src += 8;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S32LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 4 * 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src -= 4;
-        dst[7] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[6] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[5] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S32LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        src += 8;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S32LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 4 * 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src -= 4;
-        dst[15] = (Sint32) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[14] = (Sint32) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[13] = (Sint32) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[12] = (Sint32) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[11] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Sint32) (((3 * sample3) + last_sample3) >> 2);
-        dst[6] = (Sint32) (((3 * sample2) + last_sample2) >> 2);
-        dst[5] = (Sint32) (((3 * sample1) + last_sample1) >> 2);
-        dst[4] = (Sint32) (((3 * sample0) + last_sample0) >> 2);
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S32LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        src += 16;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S32LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 6 * 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src -= 6;
-        dst[11] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[10] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[9] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[8] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[7] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[6] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[5] = (Sint32) sample5;
-        dst[4] = (Sint32) sample4;
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 12;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S32LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-        src += 12;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint32) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S32LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 6 * 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src -= 6;
-        dst[23] = (Sint32) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[22] = (Sint32) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[21] = (Sint32) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[20] = (Sint32) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[19] = (Sint32) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[18] = (Sint32) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[17] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[16] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[15] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[14] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[13] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[12] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[11] = (Sint32) (((3 * sample5) + last_sample5) >> 2);
-        dst[10] = (Sint32) (((3 * sample4) + last_sample4) >> 2);
-        dst[9] = (Sint32) (((3 * sample3) + last_sample3) >> 2);
-        dst[8] = (Sint32) (((3 * sample2) + last_sample2) >> 2);
-        dst[7] = (Sint32) (((3 * sample1) + last_sample1) >> 2);
-        dst[6] = (Sint32) (((3 * sample0) + last_sample0) >> 2);
-        dst[5] = (Sint32) sample5;
-        dst[4] = (Sint32) sample4;
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 24;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S32LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-        src += 24;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint32) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S32LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 8 * 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample7 = (Sint64) ((Sint32) SDL_SwapLE32(src[7]));
-    Sint64 last_sample6 = (Sint64) ((Sint32) SDL_SwapLE32(src[6]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample7 = (Sint64) ((Sint32) SDL_SwapLE32(src[7]));
-        const Sint64 sample6 = (Sint64) ((Sint32) SDL_SwapLE32(src[6]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src -= 8;
-        dst[15] = (Sint32) ((sample7 + last_sample7) >> 1);
-        dst[14] = (Sint32) ((sample6 + last_sample6) >> 1);
-        dst[13] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[12] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[11] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Sint32) sample7;
-        dst[6] = (Sint32) sample6;
-        dst[5] = (Sint32) sample5;
-        dst[4] = (Sint32) sample4;
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S32LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-    Sint64 last_sample6 = (Sint64) ((Sint32) SDL_SwapLE32(src[6]));
-    Sint64 last_sample7 = (Sint64) ((Sint32) SDL_SwapLE32(src[7]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-        const Sint64 sample6 = (Sint64) ((Sint32) SDL_SwapLE32(src[6]));
-        const Sint64 sample7 = (Sint64) ((Sint32) SDL_SwapLE32(src[7]));
-        src += 16;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Sint32) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Sint32) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32LSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S32LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 8 * 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample7 = (Sint64) ((Sint32) SDL_SwapLE32(src[7]));
-    Sint64 last_sample6 = (Sint64) ((Sint32) SDL_SwapLE32(src[6]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample7 = (Sint64) ((Sint32) SDL_SwapLE32(src[7]));
-        const Sint64 sample6 = (Sint64) ((Sint32) SDL_SwapLE32(src[6]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        src -= 8;
-        dst[31] = (Sint32) ((sample7 + (3 * last_sample7)) >> 2);
-        dst[30] = (Sint32) ((sample6 + (3 * last_sample6)) >> 2);
-        dst[29] = (Sint32) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[28] = (Sint32) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[27] = (Sint32) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[26] = (Sint32) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[25] = (Sint32) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[24] = (Sint32) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[23] = (Sint32) ((sample7 + last_sample7) >> 1);
-        dst[22] = (Sint32) ((sample6 + last_sample6) >> 1);
-        dst[21] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[20] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[19] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[18] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[17] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[16] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[15] = (Sint32) (((3 * sample7) + last_sample7) >> 2);
-        dst[14] = (Sint32) (((3 * sample6) + last_sample6) >> 2);
-        dst[13] = (Sint32) (((3 * sample5) + last_sample5) >> 2);
-        dst[12] = (Sint32) (((3 * sample4) + last_sample4) >> 2);
-        dst[11] = (Sint32) (((3 * sample3) + last_sample3) >> 2);
-        dst[10] = (Sint32) (((3 * sample2) + last_sample2) >> 2);
-        dst[9] = (Sint32) (((3 * sample1) + last_sample1) >> 2);
-        dst[8] = (Sint32) (((3 * sample0) + last_sample0) >> 2);
-        dst[7] = (Sint32) sample7;
-        dst[6] = (Sint32) sample6;
-        dst[5] = (Sint32) sample5;
-        dst[4] = (Sint32) sample4;
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 32;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32LSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S32LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-    Sint64 last_sample6 = (Sint64) ((Sint32) SDL_SwapLE32(src[6]));
-    Sint64 last_sample7 = (Sint64) ((Sint32) SDL_SwapLE32(src[7]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapLE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapLE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapLE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapLE32(src[3]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapLE32(src[4]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapLE32(src[5]));
-        const Sint64 sample6 = (Sint64) ((Sint32) SDL_SwapLE32(src[6]));
-        const Sint64 sample7 = (Sint64) ((Sint32) SDL_SwapLE32(src[7]));
-        src += 32;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Sint32) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Sint32) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S32MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 1 * 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src--;
-        dst[1] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[0] = (Sint32) sample0;
-        last_sample0 = sample0;
-        dst -= 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S32MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src += 2;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S32MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 1 * 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 1;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src--;
-        dst[3] = (Sint32) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[2] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) (((3 * sample0) + last_sample0) >> 2);
-        dst[0] = (Sint32) sample0;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S32MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src += 4;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S32MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 2 * 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src -= 2;
-        dst[3] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S32MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        src += 4;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S32MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 2 * 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 2;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src -= 2;
-        dst[7] = (Sint32) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[6] = (Sint32) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[5] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Sint32) (((3 * sample1) + last_sample1) >> 2);
-        dst[2] = (Sint32) (((3 * sample0) + last_sample0) >> 2);
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S32MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        src += 8;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S32MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 4 * 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src -= 4;
-        dst[7] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[6] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[5] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[4] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S32MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        src += 8;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S32MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 4 * 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 4;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src -= 4;
-        dst[15] = (Sint32) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[14] = (Sint32) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[13] = (Sint32) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[12] = (Sint32) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[11] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Sint32) (((3 * sample3) + last_sample3) >> 2);
-        dst[6] = (Sint32) (((3 * sample2) + last_sample2) >> 2);
-        dst[5] = (Sint32) (((3 * sample1) + last_sample1) >> 2);
-        dst[4] = (Sint32) (((3 * sample0) + last_sample0) >> 2);
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S32MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        src += 16;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S32MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 6 * 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src -= 6;
-        dst[11] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[10] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[9] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[8] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[7] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[6] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[5] = (Sint32) sample5;
-        dst[4] = (Sint32) sample4;
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 12;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S32MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-        src += 12;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint32) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S32MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 6 * 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 6;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src -= 6;
-        dst[23] = (Sint32) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[22] = (Sint32) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[21] = (Sint32) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[20] = (Sint32) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[19] = (Sint32) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[18] = (Sint32) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[17] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[16] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[15] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[14] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[13] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[12] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[11] = (Sint32) (((3 * sample5) + last_sample5) >> 2);
-        dst[10] = (Sint32) (((3 * sample4) + last_sample4) >> 2);
-        dst[9] = (Sint32) (((3 * sample3) + last_sample3) >> 2);
-        dst[8] = (Sint32) (((3 * sample2) + last_sample2) >> 2);
-        dst[7] = (Sint32) (((3 * sample1) + last_sample1) >> 2);
-        dst[6] = (Sint32) (((3 * sample0) + last_sample0) >> 2);
-        dst[5] = (Sint32) sample5;
-        dst[4] = (Sint32) sample4;
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 24;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S32MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-        src += 24;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint32) ((sample5 + last_sample5) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_S32MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 8 * 2;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample7 = (Sint64) ((Sint32) SDL_SwapBE32(src[7]));
-    Sint64 last_sample6 = (Sint64) ((Sint32) SDL_SwapBE32(src[6]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample7 = (Sint64) ((Sint32) SDL_SwapBE32(src[7]));
-        const Sint64 sample6 = (Sint64) ((Sint32) SDL_SwapBE32(src[6]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src -= 8;
-        dst[15] = (Sint32) ((sample7 + last_sample7) >> 1);
-        dst[14] = (Sint32) ((sample6 + last_sample6) >> 1);
-        dst[13] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[12] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[11] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[10] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[9] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[8] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[7] = (Sint32) sample7;
-        dst[6] = (Sint32) sample6;
-        dst[5] = (Sint32) sample5;
-        dst[4] = (Sint32) sample4;
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_S32MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-    Sint64 last_sample6 = (Sint64) ((Sint32) SDL_SwapBE32(src[6]));
-    Sint64 last_sample7 = (Sint64) ((Sint32) SDL_SwapBE32(src[7]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-        const Sint64 sample6 = (Sint64) ((Sint32) SDL_SwapBE32(src[6]));
-        const Sint64 sample7 = (Sint64) ((Sint32) SDL_SwapBE32(src[7]));
-        src += 16;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Sint32) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Sint32) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_S32MSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_S32MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    Sint32 *dst = ((Sint32 *) (cvt->buf + dstsize)) - 8 * 4;
-    const Sint32 *src = ((Sint32 *) (cvt->buf + cvt->len_cvt)) - 8;
-    const Sint32 *target = ((const Sint32 *) cvt->buf);
-    Sint64 last_sample7 = (Sint64) ((Sint32) SDL_SwapBE32(src[7]));
-    Sint64 last_sample6 = (Sint64) ((Sint32) SDL_SwapBE32(src[6]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    while (dst >= target) {
-        const Sint64 sample7 = (Sint64) ((Sint32) SDL_SwapBE32(src[7]));
-        const Sint64 sample6 = (Sint64) ((Sint32) SDL_SwapBE32(src[6]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        src -= 8;
-        dst[31] = (Sint32) ((sample7 + (3 * last_sample7)) >> 2);
-        dst[30] = (Sint32) ((sample6 + (3 * last_sample6)) >> 2);
-        dst[29] = (Sint32) ((sample5 + (3 * last_sample5)) >> 2);
-        dst[28] = (Sint32) ((sample4 + (3 * last_sample4)) >> 2);
-        dst[27] = (Sint32) ((sample3 + (3 * last_sample3)) >> 2);
-        dst[26] = (Sint32) ((sample2 + (3 * last_sample2)) >> 2);
-        dst[25] = (Sint32) ((sample1 + (3 * last_sample1)) >> 2);
-        dst[24] = (Sint32) ((sample0 + (3 * last_sample0)) >> 2);
-        dst[23] = (Sint32) ((sample7 + last_sample7) >> 1);
-        dst[22] = (Sint32) ((sample6 + last_sample6) >> 1);
-        dst[21] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[20] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[19] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[18] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[17] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[16] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[15] = (Sint32) (((3 * sample7) + last_sample7) >> 2);
-        dst[14] = (Sint32) (((3 * sample6) + last_sample6) >> 2);
-        dst[13] = (Sint32) (((3 * sample5) + last_sample5) >> 2);
-        dst[12] = (Sint32) (((3 * sample4) + last_sample4) >> 2);
-        dst[11] = (Sint32) (((3 * sample3) + last_sample3) >> 2);
-        dst[10] = (Sint32) (((3 * sample2) + last_sample2) >> 2);
-        dst[9] = (Sint32) (((3 * sample1) + last_sample1) >> 2);
-        dst[8] = (Sint32) (((3 * sample0) + last_sample0) >> 2);
-        dst[7] = (Sint32) sample7;
-        dst[6] = (Sint32) sample6;
-        dst[5] = (Sint32) sample5;
-        dst[4] = (Sint32) sample4;
-        dst[3] = (Sint32) sample3;
-        dst[2] = (Sint32) sample2;
-        dst[1] = (Sint32) sample1;
-        dst[0] = (Sint32) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 32;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_S32MSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_S32MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    Sint32 *dst = (Sint32 *) cvt->buf;
-    const Sint32 *src = (Sint32 *) cvt->buf;
-    const Sint32 *target = (const Sint32 *) (cvt->buf + dstsize);
-    Sint64 last_sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-    Sint64 last_sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-    Sint64 last_sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-    Sint64 last_sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-    Sint64 last_sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-    Sint64 last_sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-    Sint64 last_sample6 = (Sint64) ((Sint32) SDL_SwapBE32(src[6]));
-    Sint64 last_sample7 = (Sint64) ((Sint32) SDL_SwapBE32(src[7]));
-    while (dst < target) {
-        const Sint64 sample0 = (Sint64) ((Sint32) SDL_SwapBE32(src[0]));
-        const Sint64 sample1 = (Sint64) ((Sint32) SDL_SwapBE32(src[1]));
-        const Sint64 sample2 = (Sint64) ((Sint32) SDL_SwapBE32(src[2]));
-        const Sint64 sample3 = (Sint64) ((Sint32) SDL_SwapBE32(src[3]));
-        const Sint64 sample4 = (Sint64) ((Sint32) SDL_SwapBE32(src[4]));
-        const Sint64 sample5 = (Sint64) ((Sint32) SDL_SwapBE32(src[5]));
-        const Sint64 sample6 = (Sint64) ((Sint32) SDL_SwapBE32(src[6]));
-        const Sint64 sample7 = (Sint64) ((Sint32) SDL_SwapBE32(src[7]));
-        src += 32;
-        dst[0] = (Sint32) ((sample0 + last_sample0) >> 1);
-        dst[1] = (Sint32) ((sample1 + last_sample1) >> 1);
-        dst[2] = (Sint32) ((sample2 + last_sample2) >> 1);
-        dst[3] = (Sint32) ((sample3 + last_sample3) >> 1);
-        dst[4] = (Sint32) ((sample4 + last_sample4) >> 1);
-        dst[5] = (Sint32) ((sample5 + last_sample5) >> 1);
-        dst[6] = (Sint32) ((sample6 + last_sample6) >> 1);
-        dst[7] = (Sint32) ((sample7 + last_sample7) >> 1);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_F32LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 1 * 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 1;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst >= target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src--;
-        dst[1] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[0] = (float) sample0;
-        last_sample0 = sample0;
-        dst -= 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_F32LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src += 2;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_F32LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 1 * 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 1;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst >= target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src--;
-        dst[3] = (float) ((sample0 + (3.0 * last_sample0)) * 0.25);
-        dst[2] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) (((3.0 * sample0) + last_sample0) * 0.25);
-        dst[0] = (float) sample0;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_F32LSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src += 4;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_F32LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 2 * 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 2;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst >= target) {
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src -= 2;
-        dst[3] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_F32LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        src += 4;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_F32LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 2 * 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 2;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst >= target) {
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src -= 2;
-        dst[7] = (float) ((sample1 + (3.0 * last_sample1)) * 0.25);
-        dst[6] = (float) ((sample0 + (3.0 * last_sample0)) * 0.25);
-        dst[5] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[4] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[3] = (float) (((3.0 * sample1) + last_sample1) * 0.25);
-        dst[2] = (float) (((3.0 * sample0) + last_sample0) * 0.25);
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_F32LSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        src += 8;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_F32LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 4 * 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 4;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst >= target) {
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src -= 4;
-        dst[7] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[6] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[5] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[4] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_F32LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        src += 8;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_F32LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 4 * 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 4;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst >= target) {
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src -= 4;
-        dst[15] = (float) ((sample3 + (3.0 * last_sample3)) * 0.25);
-        dst[14] = (float) ((sample2 + (3.0 * last_sample2)) * 0.25);
-        dst[13] = (float) ((sample1 + (3.0 * last_sample1)) * 0.25);
-        dst[12] = (float) ((sample0 + (3.0 * last_sample0)) * 0.25);
-        dst[11] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[10] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[9] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[8] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[7] = (float) (((3.0 * sample3) + last_sample3) * 0.25);
-        dst[6] = (float) (((3.0 * sample2) + last_sample2) * 0.25);
-        dst[5] = (float) (((3.0 * sample1) + last_sample1) * 0.25);
-        dst[4] = (float) (((3.0 * sample0) + last_sample0) * 0.25);
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_F32LSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        src += 16;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_F32LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 6 * 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 6;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample5 = (double) SDL_SwapFloatLE(src[5]);
-    double last_sample4 = (double) SDL_SwapFloatLE(src[4]);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst >= target) {
-        const double sample5 = (double) SDL_SwapFloatLE(src[5]);
-        const double sample4 = (double) SDL_SwapFloatLE(src[4]);
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src -= 6;
-        dst[11] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[10] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[9] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[8] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[7] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[6] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[5] = (float) sample5;
-        dst[4] = (float) sample4;
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 12;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_F32LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    double last_sample4 = (double) SDL_SwapFloatLE(src[4]);
-    double last_sample5 = (double) SDL_SwapFloatLE(src[5]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        const double sample4 = (double) SDL_SwapFloatLE(src[4]);
-        const double sample5 = (double) SDL_SwapFloatLE(src[5]);
-        src += 12;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[4] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[5] = (float) ((sample5 + last_sample5) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_F32LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 6 * 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 6;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample5 = (double) SDL_SwapFloatLE(src[5]);
-    double last_sample4 = (double) SDL_SwapFloatLE(src[4]);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst >= target) {
-        const double sample5 = (double) SDL_SwapFloatLE(src[5]);
-        const double sample4 = (double) SDL_SwapFloatLE(src[4]);
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src -= 6;
-        dst[23] = (float) ((sample5 + (3.0 * last_sample5)) * 0.25);
-        dst[22] = (float) ((sample4 + (3.0 * last_sample4)) * 0.25);
-        dst[21] = (float) ((sample3 + (3.0 * last_sample3)) * 0.25);
-        dst[20] = (float) ((sample2 + (3.0 * last_sample2)) * 0.25);
-        dst[19] = (float) ((sample1 + (3.0 * last_sample1)) * 0.25);
-        dst[18] = (float) ((sample0 + (3.0 * last_sample0)) * 0.25);
-        dst[17] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[16] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[15] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[14] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[13] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[12] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[11] = (float) (((3.0 * sample5) + last_sample5) * 0.25);
-        dst[10] = (float) (((3.0 * sample4) + last_sample4) * 0.25);
-        dst[9] = (float) (((3.0 * sample3) + last_sample3) * 0.25);
-        dst[8] = (float) (((3.0 * sample2) + last_sample2) * 0.25);
-        dst[7] = (float) (((3.0 * sample1) + last_sample1) * 0.25);
-        dst[6] = (float) (((3.0 * sample0) + last_sample0) * 0.25);
-        dst[5] = (float) sample5;
-        dst[4] = (float) sample4;
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 24;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_F32LSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    double last_sample4 = (double) SDL_SwapFloatLE(src[4]);
-    double last_sample5 = (double) SDL_SwapFloatLE(src[5]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        const double sample4 = (double) SDL_SwapFloatLE(src[4]);
-        const double sample5 = (double) SDL_SwapFloatLE(src[5]);
-        src += 24;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[4] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[5] = (float) ((sample5 + last_sample5) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_F32LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 8 * 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 8;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample7 = (double) SDL_SwapFloatLE(src[7]);
-    double last_sample6 = (double) SDL_SwapFloatLE(src[6]);
-    double last_sample5 = (double) SDL_SwapFloatLE(src[5]);
-    double last_sample4 = (double) SDL_SwapFloatLE(src[4]);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst >= target) {
-        const double sample7 = (double) SDL_SwapFloatLE(src[7]);
-        const double sample6 = (double) SDL_SwapFloatLE(src[6]);
-        const double sample5 = (double) SDL_SwapFloatLE(src[5]);
-        const double sample4 = (double) SDL_SwapFloatLE(src[4]);
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src -= 8;
-        dst[15] = (float) ((sample7 + last_sample7) * 0.5);
-        dst[14] = (float) ((sample6 + last_sample6) * 0.5);
-        dst[13] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[12] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[11] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[10] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[9] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[8] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[7] = (float) sample7;
-        dst[6] = (float) sample6;
-        dst[5] = (float) sample5;
-        dst[4] = (float) sample4;
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_F32LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    double last_sample4 = (double) SDL_SwapFloatLE(src[4]);
-    double last_sample5 = (double) SDL_SwapFloatLE(src[5]);
-    double last_sample6 = (double) SDL_SwapFloatLE(src[6]);
-    double last_sample7 = (double) SDL_SwapFloatLE(src[7]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        const double sample4 = (double) SDL_SwapFloatLE(src[4]);
-        const double sample5 = (double) SDL_SwapFloatLE(src[5]);
-        const double sample6 = (double) SDL_SwapFloatLE(src[6]);
-        const double sample7 = (double) SDL_SwapFloatLE(src[7]);
-        src += 16;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[4] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[5] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[6] = (float) ((sample6 + last_sample6) * 0.5);
-        dst[7] = (float) ((sample7 + last_sample7) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32LSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_F32LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 8 * 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 8;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample7 = (double) SDL_SwapFloatLE(src[7]);
-    double last_sample6 = (double) SDL_SwapFloatLE(src[6]);
-    double last_sample5 = (double) SDL_SwapFloatLE(src[5]);
-    double last_sample4 = (double) SDL_SwapFloatLE(src[4]);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    while (dst >= target) {
-        const double sample7 = (double) SDL_SwapFloatLE(src[7]);
-        const double sample6 = (double) SDL_SwapFloatLE(src[6]);
-        const double sample5 = (double) SDL_SwapFloatLE(src[5]);
-        const double sample4 = (double) SDL_SwapFloatLE(src[4]);
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        src -= 8;
-        dst[31] = (float) ((sample7 + (3.0 * last_sample7)) * 0.25);
-        dst[30] = (float) ((sample6 + (3.0 * last_sample6)) * 0.25);
-        dst[29] = (float) ((sample5 + (3.0 * last_sample5)) * 0.25);
-        dst[28] = (float) ((sample4 + (3.0 * last_sample4)) * 0.25);
-        dst[27] = (float) ((sample3 + (3.0 * last_sample3)) * 0.25);
-        dst[26] = (float) ((sample2 + (3.0 * last_sample2)) * 0.25);
-        dst[25] = (float) ((sample1 + (3.0 * last_sample1)) * 0.25);
-        dst[24] = (float) ((sample0 + (3.0 * last_sample0)) * 0.25);
-        dst[23] = (float) ((sample7 + last_sample7) * 0.5);
-        dst[22] = (float) ((sample6 + last_sample6) * 0.5);
-        dst[21] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[20] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[19] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[18] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[17] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[16] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[15] = (float) (((3.0 * sample7) + last_sample7) * 0.25);
-        dst[14] = (float) (((3.0 * sample6) + last_sample6) * 0.25);
-        dst[13] = (float) (((3.0 * sample5) + last_sample5) * 0.25);
-        dst[12] = (float) (((3.0 * sample4) + last_sample4) * 0.25);
-        dst[11] = (float) (((3.0 * sample3) + last_sample3) * 0.25);
-        dst[10] = (float) (((3.0 * sample2) + last_sample2) * 0.25);
-        dst[9] = (float) (((3.0 * sample1) + last_sample1) * 0.25);
-        dst[8] = (float) (((3.0 * sample0) + last_sample0) * 0.25);
-        dst[7] = (float) sample7;
-        dst[6] = (float) sample6;
-        dst[5] = (float) sample5;
-        dst[4] = (float) sample4;
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 32;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32LSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_F32LSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatLE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatLE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatLE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatLE(src[3]);
-    double last_sample4 = (double) SDL_SwapFloatLE(src[4]);
-    double last_sample5 = (double) SDL_SwapFloatLE(src[5]);
-    double last_sample6 = (double) SDL_SwapFloatLE(src[6]);
-    double last_sample7 = (double) SDL_SwapFloatLE(src[7]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatLE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatLE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatLE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatLE(src[3]);
-        const double sample4 = (double) SDL_SwapFloatLE(src[4]);
-        const double sample5 = (double) SDL_SwapFloatLE(src[5]);
-        const double sample6 = (double) SDL_SwapFloatLE(src[6]);
-        const double sample7 = (double) SDL_SwapFloatLE(src[7]);
-        src += 32;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[4] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[5] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[6] = (float) ((sample6 + last_sample6) * 0.5);
-        dst[7] = (float) ((sample7 + last_sample7) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_F32MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 1 * 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 1;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst >= target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src--;
-        dst[1] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[0] = (float) sample0;
-        last_sample0 = sample0;
-        dst -= 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_1c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_F32MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src += 2;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_F32MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 1 * 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 1;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst >= target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src--;
-        dst[3] = (float) ((sample0 + (3.0 * last_sample0)) * 0.25);
-        dst[2] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) (((3.0 * sample0) + last_sample0) * 0.25);
-        dst[0] = (float) sample0;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_1c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_F32MSB, 1 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src += 4;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        last_sample0 = sample0;
-        dst++;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_F32MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 2 * 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 2;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst >= target) {
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src -= 2;
-        dst[3] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_2c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_F32MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        src += 4;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_F32MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 2 * 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 2;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst >= target) {
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src -= 2;
-        dst[7] = (float) ((sample1 + (3.0 * last_sample1)) * 0.25);
-        dst[6] = (float) ((sample0 + (3.0 * last_sample0)) * 0.25);
-        dst[5] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[4] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[3] = (float) (((3.0 * sample1) + last_sample1) * 0.25);
-        dst[2] = (float) (((3.0 * sample0) + last_sample0) * 0.25);
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_2c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_F32MSB, 2 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        src += 8;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        dst += 2;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_F32MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 4 * 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 4;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst >= target) {
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src -= 4;
-        dst[7] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[6] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[5] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[4] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_4c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_F32MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        src += 8;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_F32MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 4 * 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 4;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst >= target) {
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src -= 4;
-        dst[15] = (float) ((sample3 + (3.0 * last_sample3)) * 0.25);
-        dst[14] = (float) ((sample2 + (3.0 * last_sample2)) * 0.25);
-        dst[13] = (float) ((sample1 + (3.0 * last_sample1)) * 0.25);
-        dst[12] = (float) ((sample0 + (3.0 * last_sample0)) * 0.25);
-        dst[11] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[10] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[9] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[8] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[7] = (float) (((3.0 * sample3) + last_sample3) * 0.25);
-        dst[6] = (float) (((3.0 * sample2) + last_sample2) * 0.25);
-        dst[5] = (float) (((3.0 * sample1) + last_sample1) * 0.25);
-        dst[4] = (float) (((3.0 * sample0) + last_sample0) * 0.25);
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_4c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_F32MSB, 4 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        src += 16;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        dst += 4;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_F32MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 6 * 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 6;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample5 = (double) SDL_SwapFloatBE(src[5]);
-    double last_sample4 = (double) SDL_SwapFloatBE(src[4]);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst >= target) {
-        const double sample5 = (double) SDL_SwapFloatBE(src[5]);
-        const double sample4 = (double) SDL_SwapFloatBE(src[4]);
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src -= 6;
-        dst[11] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[10] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[9] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[8] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[7] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[6] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[5] = (float) sample5;
-        dst[4] = (float) sample4;
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 12;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_6c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_F32MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    double last_sample4 = (double) SDL_SwapFloatBE(src[4]);
-    double last_sample5 = (double) SDL_SwapFloatBE(src[5]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        const double sample4 = (double) SDL_SwapFloatBE(src[4]);
-        const double sample5 = (double) SDL_SwapFloatBE(src[5]);
-        src += 12;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[4] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[5] = (float) ((sample5 + last_sample5) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_F32MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 6 * 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 6;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample5 = (double) SDL_SwapFloatBE(src[5]);
-    double last_sample4 = (double) SDL_SwapFloatBE(src[4]);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst >= target) {
-        const double sample5 = (double) SDL_SwapFloatBE(src[5]);
-        const double sample4 = (double) SDL_SwapFloatBE(src[4]);
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src -= 6;
-        dst[23] = (float) ((sample5 + (3.0 * last_sample5)) * 0.25);
-        dst[22] = (float) ((sample4 + (3.0 * last_sample4)) * 0.25);
-        dst[21] = (float) ((sample3 + (3.0 * last_sample3)) * 0.25);
-        dst[20] = (float) ((sample2 + (3.0 * last_sample2)) * 0.25);
-        dst[19] = (float) ((sample1 + (3.0 * last_sample1)) * 0.25);
-        dst[18] = (float) ((sample0 + (3.0 * last_sample0)) * 0.25);
-        dst[17] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[16] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[15] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[14] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[13] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[12] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[11] = (float) (((3.0 * sample5) + last_sample5) * 0.25);
-        dst[10] = (float) (((3.0 * sample4) + last_sample4) * 0.25);
-        dst[9] = (float) (((3.0 * sample3) + last_sample3) * 0.25);
-        dst[8] = (float) (((3.0 * sample2) + last_sample2) * 0.25);
-        dst[7] = (float) (((3.0 * sample1) + last_sample1) * 0.25);
-        dst[6] = (float) (((3.0 * sample0) + last_sample0) * 0.25);
-        dst[5] = (float) sample5;
-        dst[4] = (float) sample4;
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 24;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_6c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_F32MSB, 6 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    double last_sample4 = (double) SDL_SwapFloatBE(src[4]);
-    double last_sample5 = (double) SDL_SwapFloatBE(src[5]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        const double sample4 = (double) SDL_SwapFloatBE(src[4]);
-        const double sample5 = (double) SDL_SwapFloatBE(src[5]);
-        src += 24;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[4] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[5] = (float) ((sample5 + last_sample5) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        dst += 6;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x2) AUDIO_F32MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 2;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 8 * 2;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 8;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample7 = (double) SDL_SwapFloatBE(src[7]);
-    double last_sample6 = (double) SDL_SwapFloatBE(src[6]);
-    double last_sample5 = (double) SDL_SwapFloatBE(src[5]);
-    double last_sample4 = (double) SDL_SwapFloatBE(src[4]);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst >= target) {
-        const double sample7 = (double) SDL_SwapFloatBE(src[7]);
-        const double sample6 = (double) SDL_SwapFloatBE(src[6]);
-        const double sample5 = (double) SDL_SwapFloatBE(src[5]);
-        const double sample4 = (double) SDL_SwapFloatBE(src[4]);
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src -= 8;
-        dst[15] = (float) ((sample7 + last_sample7) * 0.5);
-        dst[14] = (float) ((sample6 + last_sample6) * 0.5);
-        dst[13] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[12] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[11] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[10] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[9] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[8] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[7] = (float) sample7;
-        dst[6] = (float) sample6;
-        dst[5] = (float) sample5;
-        dst[4] = (float) sample4;
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 16;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_8c_x2(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x2) AUDIO_F32MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 2;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    double last_sample4 = (double) SDL_SwapFloatBE(src[4]);
-    double last_sample5 = (double) SDL_SwapFloatBE(src[5]);
-    double last_sample6 = (double) SDL_SwapFloatBE(src[6]);
-    double last_sample7 = (double) SDL_SwapFloatBE(src[7]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        const double sample4 = (double) SDL_SwapFloatBE(src[4]);
-        const double sample5 = (double) SDL_SwapFloatBE(src[5]);
-        const double sample6 = (double) SDL_SwapFloatBE(src[6]);
-        const double sample7 = (double) SDL_SwapFloatBE(src[7]);
-        src += 16;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[4] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[5] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[6] = (float) ((sample6 + last_sample6) * 0.5);
-        dst[7] = (float) ((sample7 + last_sample7) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Upsample_F32MSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Upsample (x4) AUDIO_F32MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt * 4;
-    float *dst = ((float *) (cvt->buf + dstsize)) - 8 * 4;
-    const float *src = ((float *) (cvt->buf + cvt->len_cvt)) - 8;
-    const float *target = ((const float *) cvt->buf);
-    double last_sample7 = (double) SDL_SwapFloatBE(src[7]);
-    double last_sample6 = (double) SDL_SwapFloatBE(src[6]);
-    double last_sample5 = (double) SDL_SwapFloatBE(src[5]);
-    double last_sample4 = (double) SDL_SwapFloatBE(src[4]);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    while (dst >= target) {
-        const double sample7 = (double) SDL_SwapFloatBE(src[7]);
-        const double sample6 = (double) SDL_SwapFloatBE(src[6]);
-        const double sample5 = (double) SDL_SwapFloatBE(src[5]);
-        const double sample4 = (double) SDL_SwapFloatBE(src[4]);
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        src -= 8;
-        dst[31] = (float) ((sample7 + (3.0 * last_sample7)) * 0.25);
-        dst[30] = (float) ((sample6 + (3.0 * last_sample6)) * 0.25);
-        dst[29] = (float) ((sample5 + (3.0 * last_sample5)) * 0.25);
-        dst[28] = (float) ((sample4 + (3.0 * last_sample4)) * 0.25);
-        dst[27] = (float) ((sample3 + (3.0 * last_sample3)) * 0.25);
-        dst[26] = (float) ((sample2 + (3.0 * last_sample2)) * 0.25);
-        dst[25] = (float) ((sample1 + (3.0 * last_sample1)) * 0.25);
-        dst[24] = (float) ((sample0 + (3.0 * last_sample0)) * 0.25);
-        dst[23] = (float) ((sample7 + last_sample7) * 0.5);
-        dst[22] = (float) ((sample6 + last_sample6) * 0.5);
-        dst[21] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[20] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[19] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[18] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[17] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[16] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[15] = (float) (((3.0 * sample7) + last_sample7) * 0.25);
-        dst[14] = (float) (((3.0 * sample6) + last_sample6) * 0.25);
-        dst[13] = (float) (((3.0 * sample5) + last_sample5) * 0.25);
-        dst[12] = (float) (((3.0 * sample4) + last_sample4) * 0.25);
-        dst[11] = (float) (((3.0 * sample3) + last_sample3) * 0.25);
-        dst[10] = (float) (((3.0 * sample2) + last_sample2) * 0.25);
-        dst[9] = (float) (((3.0 * sample1) + last_sample1) * 0.25);
-        dst[8] = (float) (((3.0 * sample0) + last_sample0) * 0.25);
-        dst[7] = (float) sample7;
-        dst[6] = (float) sample6;
-        dst[5] = (float) sample5;
-        dst[4] = (float) sample4;
-        dst[3] = (float) sample3;
-        dst[2] = (float) sample2;
-        dst[1] = (float) sample1;
-        dst[0] = (float) sample0;
-        last_sample7 = sample7;
-        last_sample6 = sample6;
-        last_sample5 = sample5;
-        last_sample4 = sample4;
-        last_sample3 = sample3;
-        last_sample2 = sample2;
-        last_sample1 = sample1;
-        last_sample0 = sample0;
-        dst -= 32;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-static void SDLCALL
-SDL_Downsample_F32MSB_8c_x4(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "Downsample (x4) AUDIO_F32MSB, 8 channels.\n");
-#endif
-
-    const int dstsize = cvt->len_cvt / 4;
-    float *dst = (float *) cvt->buf;
-    const float *src = (float *) cvt->buf;
-    const float *target = (const float *) (cvt->buf + dstsize);
-    double last_sample0 = (double) SDL_SwapFloatBE(src[0]);
-    double last_sample1 = (double) SDL_SwapFloatBE(src[1]);
-    double last_sample2 = (double) SDL_SwapFloatBE(src[2]);
-    double last_sample3 = (double) SDL_SwapFloatBE(src[3]);
-    double last_sample4 = (double) SDL_SwapFloatBE(src[4]);
-    double last_sample5 = (double) SDL_SwapFloatBE(src[5]);
-    double last_sample6 = (double) SDL_SwapFloatBE(src[6]);
-    double last_sample7 = (double) SDL_SwapFloatBE(src[7]);
-    while (dst < target) {
-        const double sample0 = (double) SDL_SwapFloatBE(src[0]);
-        const double sample1 = (double) SDL_SwapFloatBE(src[1]);
-        const double sample2 = (double) SDL_SwapFloatBE(src[2]);
-        const double sample3 = (double) SDL_SwapFloatBE(src[3]);
-        const double sample4 = (double) SDL_SwapFloatBE(src[4]);
-        const double sample5 = (double) SDL_SwapFloatBE(src[5]);
-        const double sample6 = (double) SDL_SwapFloatBE(src[6]);
-        const double sample7 = (double) SDL_SwapFloatBE(src[7]);
-        src += 32;
-        dst[0] = (float) ((sample0 + last_sample0) * 0.5);
-        dst[1] = (float) ((sample1 + last_sample1) * 0.5);
-        dst[2] = (float) ((sample2 + last_sample2) * 0.5);
-        dst[3] = (float) ((sample3 + last_sample3) * 0.5);
-        dst[4] = (float) ((sample4 + last_sample4) * 0.5);
-        dst[5] = (float) ((sample5 + last_sample5) * 0.5);
-        dst[6] = (float) ((sample6 + last_sample6) * 0.5);
-        dst[7] = (float) ((sample7 + last_sample7) * 0.5);
-        last_sample0 = sample0;
-        last_sample1 = sample1;
-        last_sample2 = sample2;
-        last_sample3 = sample3;
-        last_sample4 = sample4;
-        last_sample5 = sample5;
-        last_sample6 = sample6;
-        last_sample7 = sample7;
-        dst += 8;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-#endif  /* !LESS_RESAMPLERS */
-#endif  /* !NO_RESAMPLERS */
-
-
-const SDL_AudioRateFilters sdl_audio_rate_filters[] =
-{
-#if !NO_RESAMPLERS
-    { AUDIO_U8, 1, 0, 0, SDL_Downsample_U8_1c },
-    { AUDIO_U8, 1, 1, 0, SDL_Upsample_U8_1c },
-    { AUDIO_U8, 2, 0, 0, SDL_Downsample_U8_2c },
-    { AUDIO_U8, 2, 1, 0, SDL_Upsample_U8_2c },
-    { AUDIO_U8, 4, 0, 0, SDL_Downsample_U8_4c },
-    { AUDIO_U8, 4, 1, 0, SDL_Upsample_U8_4c },
-    { AUDIO_U8, 6, 0, 0, SDL_Downsample_U8_6c },
-    { AUDIO_U8, 6, 1, 0, SDL_Upsample_U8_6c },
-    { AUDIO_U8, 8, 0, 0, SDL_Downsample_U8_8c },
-    { AUDIO_U8, 8, 1, 0, SDL_Upsample_U8_8c },
-    { AUDIO_S8, 1, 0, 0, SDL_Downsample_S8_1c },
-    { AUDIO_S8, 1, 1, 0, SDL_Upsample_S8_1c },
-    { AUDIO_S8, 2, 0, 0, SDL_Downsample_S8_2c },
-    { AUDIO_S8, 2, 1, 0, SDL_Upsample_S8_2c },
-    { AUDIO_S8, 4, 0, 0, SDL_Downsample_S8_4c },
-    { AUDIO_S8, 4, 1, 0, SDL_Upsample_S8_4c },
-    { AUDIO_S8, 6, 0, 0, SDL_Downsample_S8_6c },
-    { AUDIO_S8, 6, 1, 0, SDL_Upsample_S8_6c },
-    { AUDIO_S8, 8, 0, 0, SDL_Downsample_S8_8c },
-    { AUDIO_S8, 8, 1, 0, SDL_Upsample_S8_8c },
-    { AUDIO_U16LSB, 1, 0, 0, SDL_Downsample_U16LSB_1c },
-    { AUDIO_U16LSB, 1, 1, 0, SDL_Upsample_U16LSB_1c },
-    { AUDIO_U16LSB, 2, 0, 0, SDL_Downsample_U16LSB_2c },
-    { AUDIO_U16LSB, 2, 1, 0, SDL_Upsample_U16LSB_2c },
-    { AUDIO_U16LSB, 4, 0, 0, SDL_Downsample_U16LSB_4c },
-    { AUDIO_U16LSB, 4, 1, 0, SDL_Upsample_U16LSB_4c },
-    { AUDIO_U16LSB, 6, 0, 0, SDL_Downsample_U16LSB_6c },
-    { AUDIO_U16LSB, 6, 1, 0, SDL_Upsample_U16LSB_6c },
-    { AUDIO_U16LSB, 8, 0, 0, SDL_Downsample_U16LSB_8c },
-    { AUDIO_U16LSB, 8, 1, 0, SDL_Upsample_U16LSB_8c },
-    { AUDIO_S16LSB, 1, 0, 0, SDL_Downsample_S16LSB_1c },
-    { AUDIO_S16LSB, 1, 1, 0, SDL_Upsample_S16LSB_1c },
-    { AUDIO_S16LSB, 2, 0, 0, SDL_Downsample_S16LSB_2c },
-    { AUDIO_S16LSB, 2, 1, 0, SDL_Upsample_S16LSB_2c },
-    { AUDIO_S16LSB, 4, 0, 0, SDL_Downsample_S16LSB_4c },
-    { AUDIO_S16LSB, 4, 1, 0, SDL_Upsample_S16LSB_4c },
-    { AUDIO_S16LSB, 6, 0, 0, SDL_Downsample_S16LSB_6c },
-    { AUDIO_S16LSB, 6, 1, 0, SDL_Upsample_S16LSB_6c },
-    { AUDIO_S16LSB, 8, 0, 0, SDL_Downsample_S16LSB_8c },
-    { AUDIO_S16LSB, 8, 1, 0, SDL_Upsample_S16LSB_8c },
-    { AUDIO_U16MSB, 1, 0, 0, SDL_Downsample_U16MSB_1c },
-    { AUDIO_U16MSB, 1, 1, 0, SDL_Upsample_U16MSB_1c },
-    { AUDIO_U16MSB, 2, 0, 0, SDL_Downsample_U16MSB_2c },
-    { AUDIO_U16MSB, 2, 1, 0, SDL_Upsample_U16MSB_2c },
-    { AUDIO_U16MSB, 4, 0, 0, SDL_Downsample_U16MSB_4c },
-    { AUDIO_U16MSB, 4, 1, 0, SDL_Upsample_U16MSB_4c },
-    { AUDIO_U16MSB, 6, 0, 0, SDL_Downsample_U16MSB_6c },
-    { AUDIO_U16MSB, 6, 1, 0, SDL_Upsample_U16MSB_6c },
-    { AUDIO_U16MSB, 8, 0, 0, SDL_Downsample_U16MSB_8c },
-    { AUDIO_U16MSB, 8, 1, 0, SDL_Upsample_U16MSB_8c },
-    { AUDIO_S16MSB, 1, 0, 0, SDL_Downsample_S16MSB_1c },
-    { AUDIO_S16MSB, 1, 1, 0, SDL_Upsample_S16MSB_1c },
-    { AUDIO_S16MSB, 2, 0, 0, SDL_Downsample_S16MSB_2c },
-    { AUDIO_S16MSB, 2, 1, 0, SDL_Upsample_S16MSB_2c },
-    { AUDIO_S16MSB, 4, 0, 0, SDL_Downsample_S16MSB_4c },
-    { AUDIO_S16MSB, 4, 1, 0, SDL_Upsample_S16MSB_4c },
-    { AUDIO_S16MSB, 6, 0, 0, SDL_Downsample_S16MSB_6c },
-    { AUDIO_S16MSB, 6, 1, 0, SDL_Upsample_S16MSB_6c },
-    { AUDIO_S16MSB, 8, 0, 0, SDL_Downsample_S16MSB_8c },
-    { AUDIO_S16MSB, 8, 1, 0, SDL_Upsample_S16MSB_8c },
-    { AUDIO_S32LSB, 1, 0, 0, SDL_Downsample_S32LSB_1c },
-    { AUDIO_S32LSB, 1, 1, 0, SDL_Upsample_S32LSB_1c },
-    { AUDIO_S32LSB, 2, 0, 0, SDL_Downsample_S32LSB_2c },
-    { AUDIO_S32LSB, 2, 1, 0, SDL_Upsample_S32LSB_2c },
-    { AUDIO_S32LSB, 4, 0, 0, SDL_Downsample_S32LSB_4c },
-    { AUDIO_S32LSB, 4, 1, 0, SDL_Upsample_S32LSB_4c },
-    { AUDIO_S32LSB, 6, 0, 0, SDL_Downsample_S32LSB_6c },
-    { AUDIO_S32LSB, 6, 1, 0, SDL_Upsample_S32LSB_6c },
-    { AUDIO_S32LSB, 8, 0, 0, SDL_Downsample_S32LSB_8c },
-    { AUDIO_S32LSB, 8, 1, 0, SDL_Upsample_S32LSB_8c },
-    { AUDIO_S32MSB, 1, 0, 0, SDL_Downsample_S32MSB_1c },
-    { AUDIO_S32MSB, 1, 1, 0, SDL_Upsample_S32MSB_1c },
-    { AUDIO_S32MSB, 2, 0, 0, SDL_Downsample_S32MSB_2c },
-    { AUDIO_S32MSB, 2, 1, 0, SDL_Upsample_S32MSB_2c },
-    { AUDIO_S32MSB, 4, 0, 0, SDL_Downsample_S32MSB_4c },
-    { AUDIO_S32MSB, 4, 1, 0, SDL_Upsample_S32MSB_4c },
-    { AUDIO_S32MSB, 6, 0, 0, SDL_Downsample_S32MSB_6c },
-    { AUDIO_S32MSB, 6, 1, 0, SDL_Upsample_S32MSB_6c },
-    { AUDIO_S32MSB, 8, 0, 0, SDL_Downsample_S32MSB_8c },
-    { AUDIO_S32MSB, 8, 1, 0, SDL_Upsample_S32MSB_8c },
-    { AUDIO_F32LSB, 1, 0, 0, SDL_Downsample_F32LSB_1c },
-    { AUDIO_F32LSB, 1, 1, 0, SDL_Upsample_F32LSB_1c },
-    { AUDIO_F32LSB, 2, 0, 0, SDL_Downsample_F32LSB_2c },
-    { AUDIO_F32LSB, 2, 1, 0, SDL_Upsample_F32LSB_2c },
-    { AUDIO_F32LSB, 4, 0, 0, SDL_Downsample_F32LSB_4c },
-    { AUDIO_F32LSB, 4, 1, 0, SDL_Upsample_F32LSB_4c },
-    { AUDIO_F32LSB, 6, 0, 0, SDL_Downsample_F32LSB_6c },
-    { AUDIO_F32LSB, 6, 1, 0, SDL_Upsample_F32LSB_6c },
-    { AUDIO_F32LSB, 8, 0, 0, SDL_Downsample_F32LSB_8c },
-    { AUDIO_F32LSB, 8, 1, 0, SDL_Upsample_F32LSB_8c },
-    { AUDIO_F32MSB, 1, 0, 0, SDL_Downsample_F32MSB_1c },
-    { AUDIO_F32MSB, 1, 1, 0, SDL_Upsample_F32MSB_1c },
-    { AUDIO_F32MSB, 2, 0, 0, SDL_Downsample_F32MSB_2c },
-    { AUDIO_F32MSB, 2, 1, 0, SDL_Upsample_F32MSB_2c },
-    { AUDIO_F32MSB, 4, 0, 0, SDL_Downsample_F32MSB_4c },
-    { AUDIO_F32MSB, 4, 1, 0, SDL_Upsample_F32MSB_4c },
-    { AUDIO_F32MSB, 6, 0, 0, SDL_Downsample_F32MSB_6c },
-    { AUDIO_F32MSB, 6, 1, 0, SDL_Upsample_F32MSB_6c },
-    { AUDIO_F32MSB, 8, 0, 0, SDL_Downsample_F32MSB_8c },
-    { AUDIO_F32MSB, 8, 1, 0, SDL_Upsample_F32MSB_8c },
-#if !LESS_RESAMPLERS
-    { AUDIO_U8, 1, 0, 2, SDL_Downsample_U8_1c_x2 },
-    { AUDIO_U8, 1, 1, 2, SDL_Upsample_U8_1c_x2 },
-    { AUDIO_U8, 1, 0, 4, SDL_Downsample_U8_1c_x4 },
-    { AUDIO_U8, 1, 1, 4, SDL_Upsample_U8_1c_x4 },
-    { AUDIO_U8, 2, 0, 2, SDL_Downsample_U8_2c_x2 },
-    { AUDIO_U8, 2, 1, 2, SDL_Upsample_U8_2c_x2 },
-    { AUDIO_U8, 2, 0, 4, SDL_Downsample_U8_2c_x4 },
-    { AUDIO_U8, 2, 1, 4, SDL_Upsample_U8_2c_x4 },
-    { AUDIO_U8, 4, 0, 2, SDL_Downsample_U8_4c_x2 },
-    { AUDIO_U8, 4, 1, 2, SDL_Upsample_U8_4c_x2 },
-    { AUDIO_U8, 4, 0, 4, SDL_Downsample_U8_4c_x4 },
-    { AUDIO_U8, 4, 1, 4, SDL_Upsample_U8_4c_x4 },
-    { AUDIO_U8, 6, 0, 2, SDL_Downsample_U8_6c_x2 },
-    { AUDIO_U8, 6, 1, 2, SDL_Upsample_U8_6c_x2 },
-    { AUDIO_U8, 6, 0, 4, SDL_Downsample_U8_6c_x4 },
-    { AUDIO_U8, 6, 1, 4, SDL_Upsample_U8_6c_x4 },
-    { AUDIO_U8, 8, 0, 2, SDL_Downsample_U8_8c_x2 },
-    { AUDIO_U8, 8, 1, 2, SDL_Upsample_U8_8c_x2 },
-    { AUDIO_U8, 8, 0, 4, SDL_Downsample_U8_8c_x4 },
-    { AUDIO_U8, 8, 1, 4, SDL_Upsample_U8_8c_x4 },
-    { AUDIO_S8, 1, 0, 2, SDL_Downsample_S8_1c_x2 },
-    { AUDIO_S8, 1, 1, 2, SDL_Upsample_S8_1c_x2 },
-    { AUDIO_S8, 1, 0, 4, SDL_Downsample_S8_1c_x4 },
-    { AUDIO_S8, 1, 1, 4, SDL_Upsample_S8_1c_x4 },
-    { AUDIO_S8, 2, 0, 2, SDL_Downsample_S8_2c_x2 },
-    { AUDIO_S8, 2, 1, 2, SDL_Upsample_S8_2c_x2 },
-    { AUDIO_S8, 2, 0, 4, SDL_Downsample_S8_2c_x4 },
-    { AUDIO_S8, 2, 1, 4, SDL_Upsample_S8_2c_x4 },
-    { AUDIO_S8, 4, 0, 2, SDL_Downsample_S8_4c_x2 },
-    { AUDIO_S8, 4, 1, 2, SDL_Upsample_S8_4c_x2 },
-    { AUDIO_S8, 4, 0, 4, SDL_Downsample_S8_4c_x4 },
-    { AUDIO_S8, 4, 1, 4, SDL_Upsample_S8_4c_x4 },
-    { AUDIO_S8, 6, 0, 2, SDL_Downsample_S8_6c_x2 },
-    { AUDIO_S8, 6, 1, 2, SDL_Upsample_S8_6c_x2 },
-    { AUDIO_S8, 6, 0, 4, SDL_Downsample_S8_6c_x4 },
-    { AUDIO_S8, 6, 1, 4, SDL_Upsample_S8_6c_x4 },
-    { AUDIO_S8, 8, 0, 2, SDL_Downsample_S8_8c_x2 },
-    { AUDIO_S8, 8, 1, 2, SDL_Upsample_S8_8c_x2 },
-    { AUDIO_S8, 8, 0, 4, SDL_Downsample_S8_8c_x4 },
-    { AUDIO_S8, 8, 1, 4, SDL_Upsample_S8_8c_x4 },
-    { AUDIO_U16LSB, 1, 0, 2, SDL_Downsample_U16LSB_1c_x2 },
-    { AUDIO_U16LSB, 1, 1, 2, SDL_Upsample_U16LSB_1c_x2 },
-    { AUDIO_U16LSB, 1, 0, 4, SDL_Downsample_U16LSB_1c_x4 },
-    { AUDIO_U16LSB, 1, 1, 4, SDL_Upsample_U16LSB_1c_x4 },
-    { AUDIO_U16LSB, 2, 0, 2, SDL_Downsample_U16LSB_2c_x2 },
-    { AUDIO_U16LSB, 2, 1, 2, SDL_Upsample_U16LSB_2c_x2 },
-    { AUDIO_U16LSB, 2, 0, 4, SDL_Downsample_U16LSB_2c_x4 },
-    { AUDIO_U16LSB, 2, 1, 4, SDL_Upsample_U16LSB_2c_x4 },
-    { AUDIO_U16LSB, 4, 0, 2, SDL_Downsample_U16LSB_4c_x2 },
-    { AUDIO_U16LSB, 4, 1, 2, SDL_Upsample_U16LSB_4c_x2 },
-    { AUDIO_U16LSB, 4, 0, 4, SDL_Downsample_U16LSB_4c_x4 },
-    { AUDIO_U16LSB, 4, 1, 4, SDL_Upsample_U16LSB_4c_x4 },
-    { AUDIO_U16LSB, 6, 0, 2, SDL_Downsample_U16LSB_6c_x2 },
-    { AUDIO_U16LSB, 6, 1, 2, SDL_Upsample_U16LSB_6c_x2 },
-    { AUDIO_U16LSB, 6, 0, 4, SDL_Downsample_U16LSB_6c_x4 },
-    { AUDIO_U16LSB, 6, 1, 4, SDL_Upsample_U16LSB_6c_x4 },
-    { AUDIO_U16LSB, 8, 0, 2, SDL_Downsample_U16LSB_8c_x2 },
-    { AUDIO_U16LSB, 8, 1, 2, SDL_Upsample_U16LSB_8c_x2 },
-    { AUDIO_U16LSB, 8, 0, 4, SDL_Downsample_U16LSB_8c_x4 },
-    { AUDIO_U16LSB, 8, 1, 4, SDL_Upsample_U16LSB_8c_x4 },
-    { AUDIO_S16LSB, 1, 0, 2, SDL_Downsample_S16LSB_1c_x2 },
-    { AUDIO_S16LSB, 1, 1, 2, SDL_Upsample_S16LSB_1c_x2 },
-    { AUDIO_S16LSB, 1, 0, 4, SDL_Downsample_S16LSB_1c_x4 },
-    { AUDIO_S16LSB, 1, 1, 4, SDL_Upsample_S16LSB_1c_x4 },
-    { AUDIO_S16LSB, 2, 0, 2, SDL_Downsample_S16LSB_2c_x2 },
-    { AUDIO_S16LSB, 2, 1, 2, SDL_Upsample_S16LSB_2c_x2 },
-    { AUDIO_S16LSB, 2, 0, 4, SDL_Downsample_S16LSB_2c_x4 },
-    { AUDIO_S16LSB, 2, 1, 4, SDL_Upsample_S16LSB_2c_x4 },
-    { AUDIO_S16LSB, 4, 0, 2, SDL_Downsample_S16LSB_4c_x2 },
-    { AUDIO_S16LSB, 4, 1, 2, SDL_Upsample_S16LSB_4c_x2 },
-    { AUDIO_S16LSB, 4, 0, 4, SDL_Downsample_S16LSB_4c_x4 },
-    { AUDIO_S16LSB, 4, 1, 4, SDL_Upsample_S16LSB_4c_x4 },
-    { AUDIO_S16LSB, 6, 0, 2, SDL_Downsample_S16LSB_6c_x2 },
-    { AUDIO_S16LSB, 6, 1, 2, SDL_Upsample_S16LSB_6c_x2 },
-    { AUDIO_S16LSB, 6, 0, 4, SDL_Downsample_S16LSB_6c_x4 },
-    { AUDIO_S16LSB, 6, 1, 4, SDL_Upsample_S16LSB_6c_x4 },
-    { AUDIO_S16LSB, 8, 0, 2, SDL_Downsample_S16LSB_8c_x2 },
-    { AUDIO_S16LSB, 8, 1, 2, SDL_Upsample_S16LSB_8c_x2 },
-    { AUDIO_S16LSB, 8, 0, 4, SDL_Downsample_S16LSB_8c_x4 },
-    { AUDIO_S16LSB, 8, 1, 4, SDL_Upsample_S16LSB_8c_x4 },
-    { AUDIO_U16MSB, 1, 0, 2, SDL_Downsample_U16MSB_1c_x2 },
-    { AUDIO_U16MSB, 1, 1, 2, SDL_Upsample_U16MSB_1c_x2 },
-    { AUDIO_U16MSB, 1, 0, 4, SDL_Downsample_U16MSB_1c_x4 },
-    { AUDIO_U16MSB, 1, 1, 4, SDL_Upsample_U16MSB_1c_x4 },
-    { AUDIO_U16MSB, 2, 0, 2, SDL_Downsample_U16MSB_2c_x2 },
-    { AUDIO_U16MSB, 2, 1, 2, SDL_Upsample_U16MSB_2c_x2 },
-    { AUDIO_U16MSB, 2, 0, 4, SDL_Downsample_U16MSB_2c_x4 },
-    { AUDIO_U16MSB, 2, 1, 4, SDL_Upsample_U16MSB_2c_x4 },
-    { AUDIO_U16MSB, 4, 0, 2, SDL_Downsample_U16MSB_4c_x2 },
-    { AUDIO_U16MSB, 4, 1, 2, SDL_Upsample_U16MSB_4c_x2 },
-    { AUDIO_U16MSB, 4, 0, 4, SDL_Downsample_U16MSB_4c_x4 },
-    { AUDIO_U16MSB, 4, 1, 4, SDL_Upsample_U16MSB_4c_x4 },
-    { AUDIO_U16MSB, 6, 0, 2, SDL_Downsample_U16MSB_6c_x2 },
-    { AUDIO_U16MSB, 6, 1, 2, SDL_Upsample_U16MSB_6c_x2 },
-    { AUDIO_U16MSB, 6, 0, 4, SDL_Downsample_U16MSB_6c_x4 },
-    { AUDIO_U16MSB, 6, 1, 4, SDL_Upsample_U16MSB_6c_x4 },
-    { AUDIO_U16MSB, 8, 0, 2, SDL_Downsample_U16MSB_8c_x2 },
-    { AUDIO_U16MSB, 8, 1, 2, SDL_Upsample_U16MSB_8c_x2 },
-    { AUDIO_U16MSB, 8, 0, 4, SDL_Downsample_U16MSB_8c_x4 },
-    { AUDIO_U16MSB, 8, 1, 4, SDL_Upsample_U16MSB_8c_x4 },
-    { AUDIO_S16MSB, 1, 0, 2, SDL_Downsample_S16MSB_1c_x2 },
-    { AUDIO_S16MSB, 1, 1, 2, SDL_Upsample_S16MSB_1c_x2 },
-    { AUDIO_S16MSB, 1, 0, 4, SDL_Downsample_S16MSB_1c_x4 },
-    { AUDIO_S16MSB, 1, 1, 4, SDL_Upsample_S16MSB_1c_x4 },
-    { AUDIO_S16MSB, 2, 0, 2, SDL_Downsample_S16MSB_2c_x2 },
-    { AUDIO_S16MSB, 2, 1, 2, SDL_Upsample_S16MSB_2c_x2 },
-    { AUDIO_S16MSB, 2, 0, 4, SDL_Downsample_S16MSB_2c_x4 },
-    { AUDIO_S16MSB, 2, 1, 4, SDL_Upsample_S16MSB_2c_x4 },
-    { AUDIO_S16MSB, 4, 0, 2, SDL_Downsample_S16MSB_4c_x2 },
-    { AUDIO_S16MSB, 4, 1, 2, SDL_Upsample_S16MSB_4c_x2 },
-    { AUDIO_S16MSB, 4, 0, 4, SDL_Downsample_S16MSB_4c_x4 },
-    { AUDIO_S16MSB, 4, 1, 4, SDL_Upsample_S16MSB_4c_x4 },
-    { AUDIO_S16MSB, 6, 0, 2, SDL_Downsample_S16MSB_6c_x2 },
-    { AUDIO_S16MSB, 6, 1, 2, SDL_Upsample_S16MSB_6c_x2 },
-    { AUDIO_S16MSB, 6, 0, 4, SDL_Downsample_S16MSB_6c_x4 },
-    { AUDIO_S16MSB, 6, 1, 4, SDL_Upsample_S16MSB_6c_x4 },
-    { AUDIO_S16MSB, 8, 0, 2, SDL_Downsample_S16MSB_8c_x2 },
-    { AUDIO_S16MSB, 8, 1, 2, SDL_Upsample_S16MSB_8c_x2 },
-    { AUDIO_S16MSB, 8, 0, 4, SDL_Downsample_S16MSB_8c_x4 },
-    { AUDIO_S16MSB, 8, 1, 4, SDL_Upsample_S16MSB_8c_x4 },
-    { AUDIO_S32LSB, 1, 0, 2, SDL_Downsample_S32LSB_1c_x2 },
-    { AUDIO_S32LSB, 1, 1, 2, SDL_Upsample_S32LSB_1c_x2 },
-    { AUDIO_S32LSB, 1, 0, 4, SDL_Downsample_S32LSB_1c_x4 },
-    { AUDIO_S32LSB, 1, 1, 4, SDL_Upsample_S32LSB_1c_x4 },
-    { AUDIO_S32LSB, 2, 0, 2, SDL_Downsample_S32LSB_2c_x2 },
-    { AUDIO_S32LSB, 2, 1, 2, SDL_Upsample_S32LSB_2c_x2 },
-    { AUDIO_S32LSB, 2, 0, 4, SDL_Downsample_S32LSB_2c_x4 },
-    { AUDIO_S32LSB, 2, 1, 4, SDL_Upsample_S32LSB_2c_x4 },
-    { AUDIO_S32LSB, 4, 0, 2, SDL_Downsample_S32LSB_4c_x2 },
-    { AUDIO_S32LSB, 4, 1, 2, SDL_Upsample_S32LSB_4c_x2 },
-    { AUDIO_S32LSB, 4, 0, 4, SDL_Downsample_S32LSB_4c_x4 },
-    { AUDIO_S32LSB, 4, 1, 4, SDL_Upsample_S32LSB_4c_x4 },
-    { AUDIO_S32LSB, 6, 0, 2, SDL_Downsample_S32LSB_6c_x2 },
-    { AUDIO_S32LSB, 6, 1, 2, SDL_Upsample_S32LSB_6c_x2 },
-    { AUDIO_S32LSB, 6, 0, 4, SDL_Downsample_S32LSB_6c_x4 },
-    { AUDIO_S32LSB, 6, 1, 4, SDL_Upsample_S32LSB_6c_x4 },
-    { AUDIO_S32LSB, 8, 0, 2, SDL_Downsample_S32LSB_8c_x2 },
-    { AUDIO_S32LSB, 8, 1, 2, SDL_Upsample_S32LSB_8c_x2 },
-    { AUDIO_S32LSB, 8, 0, 4, SDL_Downsample_S32LSB_8c_x4 },
-    { AUDIO_S32LSB, 8, 1, 4, SDL_Upsample_S32LSB_8c_x4 },
-    { AUDIO_S32MSB, 1, 0, 2, SDL_Downsample_S32MSB_1c_x2 },
-    { AUDIO_S32MSB, 1, 1, 2, SDL_Upsample_S32MSB_1c_x2 },
-    { AUDIO_S32MSB, 1, 0, 4, SDL_Downsample_S32MSB_1c_x4 },
-    { AUDIO_S32MSB, 1, 1, 4, SDL_Upsample_S32MSB_1c_x4 },
-    { AUDIO_S32MSB, 2, 0, 2, SDL_Downsample_S32MSB_2c_x2 },
-    { AUDIO_S32MSB, 2, 1, 2, SDL_Upsample_S32MSB_2c_x2 },
-    { AUDIO_S32MSB, 2, 0, 4, SDL_Downsample_S32MSB_2c_x4 },
-    { AUDIO_S32MSB, 2, 1, 4, SDL_Upsample_S32MSB_2c_x4 },
-    { AUDIO_S32MSB, 4, 0, 2, SDL_Downsample_S32MSB_4c_x2 },
-    { AUDIO_S32MSB, 4, 1, 2, SDL_Upsample_S32MSB_4c_x2 },
-    { AUDIO_S32MSB, 4, 0, 4, SDL_Downsample_S32MSB_4c_x4 },
-    { AUDIO_S32MSB, 4, 1, 4, SDL_Upsample_S32MSB_4c_x4 },
-    { AUDIO_S32MSB, 6, 0, 2, SDL_Downsample_S32MSB_6c_x2 },
-    { AUDIO_S32MSB, 6, 1, 2, SDL_Upsample_S32MSB_6c_x2 },
-    { AUDIO_S32MSB, 6, 0, 4, SDL_Downsample_S32MSB_6c_x4 },
-    { AUDIO_S32MSB, 6, 1, 4, SDL_Upsample_S32MSB_6c_x4 },
-    { AUDIO_S32MSB, 8, 0, 2, SDL_Downsample_S32MSB_8c_x2 },
-    { AUDIO_S32MSB, 8, 1, 2, SDL_Upsample_S32MSB_8c_x2 },
-    { AUDIO_S32MSB, 8, 0, 4, SDL_Downsample_S32MSB_8c_x4 },
-    { AUDIO_S32MSB, 8, 1, 4, SDL_Upsample_S32MSB_8c_x4 },
-    { AUDIO_F32LSB, 1, 0, 2, SDL_Downsample_F32LSB_1c_x2 },
-    { AUDIO_F32LSB, 1, 1, 2, SDL_Upsample_F32LSB_1c_x2 },
-    { AUDIO_F32LSB, 1, 0, 4, SDL_Downsample_F32LSB_1c_x4 },
-    { AUDIO_F32LSB, 1, 1, 4, SDL_Upsample_F32LSB_1c_x4 },
-    { AUDIO_F32LSB, 2, 0, 2, SDL_Downsample_F32LSB_2c_x2 },
-    { AUDIO_F32LSB, 2, 1, 2, SDL_Upsample_F32LSB_2c_x2 },
-    { AUDIO_F32LSB, 2, 0, 4, SDL_Downsample_F32LSB_2c_x4 },
-    { AUDIO_F32LSB, 2, 1, 4, SDL_Upsample_F32LSB_2c_x4 },
-    { AUDIO_F32LSB, 4, 0, 2, SDL_Downsample_F32LSB_4c_x2 },
-    { AUDIO_F32LSB, 4, 1, 2, SDL_Upsample_F32LSB_4c_x2 },
-    { AUDIO_F32LSB, 4, 0, 4, SDL_Downsample_F32LSB_4c_x4 },
-    { AUDIO_F32LSB, 4, 1, 4, SDL_Upsample_F32LSB_4c_x4 },
-    { AUDIO_F32LSB, 6, 0, 2, SDL_Downsample_F32LSB_6c_x2 },
-    { AUDIO_F32LSB, 6, 1, 2, SDL_Upsample_F32LSB_6c_x2 },
-    { AUDIO_F32LSB, 6, 0, 4, SDL_Downsample_F32LSB_6c_x4 },
-    { AUDIO_F32LSB, 6, 1, 4, SDL_Upsample_F32LSB_6c_x4 },
-    { AUDIO_F32LSB, 8, 0, 2, SDL_Downsample_F32LSB_8c_x2 },
-    { AUDIO_F32LSB, 8, 1, 2, SDL_Upsample_F32LSB_8c_x2 },
-    { AUDIO_F32LSB, 8, 0, 4, SDL_Downsample_F32LSB_8c_x4 },
-    { AUDIO_F32LSB, 8, 1, 4, SDL_Upsample_F32LSB_8c_x4 },
-    { AUDIO_F32MSB, 1, 0, 2, SDL_Downsample_F32MSB_1c_x2 },
-    { AUDIO_F32MSB, 1, 1, 2, SDL_Upsample_F32MSB_1c_x2 },
-    { AUDIO_F32MSB, 1, 0, 4, SDL_Downsample_F32MSB_1c_x4 },
-    { AUDIO_F32MSB, 1, 1, 4, SDL_Upsample_F32MSB_1c_x4 },
-    { AUDIO_F32MSB, 2, 0, 2, SDL_Downsample_F32MSB_2c_x2 },
-    { AUDIO_F32MSB, 2, 1, 2, SDL_Upsample_F32MSB_2c_x2 },
-    { AUDIO_F32MSB, 2, 0, 4, SDL_Downsample_F32MSB_2c_x4 },
-    { AUDIO_F32MSB, 2, 1, 4, SDL_Upsample_F32MSB_2c_x4 },
-    { AUDIO_F32MSB, 4, 0, 2, SDL_Downsample_F32MSB_4c_x2 },
-    { AUDIO_F32MSB, 4, 1, 2, SDL_Upsample_F32MSB_4c_x2 },
-    { AUDIO_F32MSB, 4, 0, 4, SDL_Downsample_F32MSB_4c_x4 },
-    { AUDIO_F32MSB, 4, 1, 4, SDL_Upsample_F32MSB_4c_x4 },
-    { AUDIO_F32MSB, 6, 0, 2, SDL_Downsample_F32MSB_6c_x2 },
-    { AUDIO_F32MSB, 6, 1, 2, SDL_Upsample_F32MSB_6c_x2 },
-    { AUDIO_F32MSB, 6, 0, 4, SDL_Downsample_F32MSB_6c_x4 },
-    { AUDIO_F32MSB, 6, 1, 4, SDL_Upsample_F32MSB_6c_x4 },
-    { AUDIO_F32MSB, 8, 0, 2, SDL_Downsample_F32MSB_8c_x2 },
-    { AUDIO_F32MSB, 8, 1, 2, SDL_Upsample_F32MSB_8c_x2 },
-    { AUDIO_F32MSB, 8, 0, 4, SDL_Downsample_F32MSB_8c_x4 },
-    { AUDIO_F32MSB, 8, 1, 4, SDL_Upsample_F32MSB_8c_x4 },
-#endif  /* !LESS_RESAMPLERS */
-#endif  /* !NO_RESAMPLERS */
-    { 0, 0, 0, 0, NULL }
-};
-
-/* 390 converters generated. */
-
-/* *INDENT-ON* */
-
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/SDL_mixer.c b/src/audio/SDL_mixer.c
index e021939..36d1695 100644
--- a/src/audio/SDL_mixer.c
+++ b/src/audio/SDL_mixer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/audio/SDL_sysaudio.h b/src/audio/SDL_sysaudio.h
index 943169b..d095b77 100644
--- a/src/audio/SDL_sysaudio.h
+++ b/src/audio/SDL_sysaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,11 +20,13 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_sysaudio_h
-#define _SDL_sysaudio_h
+#ifndef SDL_sysaudio_h_
+#define SDL_sysaudio_h_
 
 #include "SDL_mutex.h"
 #include "SDL_thread.h"
+#include "../SDL_dataqueue.h"
+#include "./SDL_audio_c.h"
 
 /* !!! FIXME: These are wordy and unlocalized... */
 #define DEFAULT_OUTPUT_DEVNAME "System audio output device"
@@ -49,7 +51,6 @@ extern void SDL_RemoveAudioDevice(const int iscapture, void *handle);
    as appropriate so SDL's list of devices is accurate. */
 extern void SDL_OpenedAudioDeviceDisconnected(SDL_AudioDevice *device);
 
-
 /* This is the size of a packet when using SDL_QueueAudio(). We allocate
    these as necessary and pool them, under the assumption that we'll
    eventually end up with a handful that keep recycling, meeting whatever
@@ -61,20 +62,12 @@ extern void SDL_OpenedAudioDeviceDisconnected(SDL_AudioDevice *device);
    The system preallocates enough packets for 2 callbacks' worth of data. */
 #define SDL_AUDIOBUFFERQUEUE_PACKETLEN (8 * 1024)
 
-/* Used by apps that queue audio instead of using the callback. */
-typedef struct SDL_AudioBufferQueue
-{
-    Uint8 data[SDL_AUDIOBUFFERQUEUE_PACKETLEN];  /* packet data. */
-    Uint32 datalen;  /* bytes currently in use in this packet. */
-    Uint32 startpos;  /* bytes currently consumed in this packet. */
-    struct SDL_AudioBufferQueue *next;  /* next item in linked list. */
-} SDL_AudioBufferQueue;
-
 typedef struct SDL_AudioDriverImpl
 {
     void (*DetectDevices) (void);
     int (*OpenDevice) (_THIS, void *handle, const char *devname, int iscapture);
     void (*ThreadInit) (_THIS); /* Called by audio thread at start */
+    void (*ThreadDeinit) (_THIS); /* Called by audio thread at end */
     void (*WaitDevice) (_THIS);
     void (*PlayDevice) (_THIS);
     int (*GetPendingBytes) (_THIS);
@@ -105,11 +98,7 @@ typedef struct SDL_AudioDeviceItem
 {
     void *handle;
     struct SDL_AudioDeviceItem *next;
-    #if (defined(__GNUC__) && (__GNUC__ <= 2))
-    char name[1];  /* actually variable length. */
-    #else
-    char name[];
-    #endif
+    char name[SDL_VARIABLE_LENGTH_ARRAY];
 } SDL_AudioDeviceItem;
 
 
@@ -136,15 +125,6 @@ typedef struct SDL_AudioDriver
 } SDL_AudioDriver;
 
 
-/* Streamer */
-typedef struct
-{
-    Uint8 *buffer;
-    int max_len;                /* the maximum length in bytes */
-    int read_pos, write_pos;    /* the position of the write and read heads in bytes */
-} SDL_AudioStreamer;
-
-
 /* Define the SDL audio driver structure */
 struct SDL_AudioDevice
 {
@@ -152,15 +132,14 @@ struct SDL_AudioDevice
     /* Data common to all devices */
     SDL_AudioDeviceID id;
 
-    /* The current audio specification (shared with audio thread) */
+    /* The device's current audio specification */
     SDL_AudioSpec spec;
 
-    /* An audio conversion block for audio format emulation */
-    SDL_AudioCVT convert;
+    /* The callback's expected audio specification (converted vs device's spec). */
+    SDL_AudioSpec callbackspec;
 
-    /* The streamer, if sample rate conversion necessitates it */
-    int use_streamer;
-    SDL_AudioStreamer streamer;
+    /* Stream that converts and resamples. NULL if not needed. */
+    SDL_AudioStream *stream;
 
     /* Current state flags */
     SDL_atomic_t shutdown; /* true if we are signaling the play thread to end. */
@@ -168,8 +147,11 @@ struct SDL_AudioDevice
     SDL_atomic_t paused;
     SDL_bool iscapture;
 
-    /* Fake audio buffer for when the audio hardware is busy */
-    Uint8 *fake_stream;
+    /* Scratch buffer used in the bridge between SDL and the user callback. */
+    Uint8 *work_buffer;
+
+    /* Size, in bytes, of work_buffer. */
+    Uint32 work_buffer_len;
 
     /* A mutex for locking the mixing buffers */
     SDL_mutex *mixer_lock;
@@ -179,10 +161,7 @@ struct SDL_AudioDevice
     SDL_threadID threadid;
 
     /* Queued buffers (if app not using callback). */
-    SDL_AudioBufferQueue *buffer_queue_head; /* device fed from here. */
-    SDL_AudioBufferQueue *buffer_queue_tail; /* queue fills to here. */
-    SDL_AudioBufferQueue *buffer_queue_pool; /* these are unused packets. */
-    Uint32 queued_bytes;  /* number of bytes of audio data in the queue. */
+    SDL_DataQueue *buffer_queue;
 
     /* * * */
     /* Data private to this driver */
@@ -200,6 +179,33 @@ typedef struct AudioBootStrap
     int demand_only;  /* 1==request explicitly, or it won't be available. */
 } AudioBootStrap;
 
-#endif /* _SDL_sysaudio_h */
+/* Not all of these are available in a given build. Use #ifdefs, etc. */
+extern AudioBootStrap PULSEAUDIO_bootstrap;
+extern AudioBootStrap ALSA_bootstrap;
+extern AudioBootStrap JACK_bootstrap;
+extern AudioBootStrap SNDIO_bootstrap;
+extern AudioBootStrap NETBSDAUDIO_bootstrap;
+extern AudioBootStrap DSP_bootstrap;
+extern AudioBootStrap QSAAUDIO_bootstrap;
+extern AudioBootStrap SUNAUDIO_bootstrap;
+extern AudioBootStrap ARTS_bootstrap;
+extern AudioBootStrap ESD_bootstrap;
+extern AudioBootStrap NACLAUDIO_bootstrap;
+extern AudioBootStrap NAS_bootstrap;
+extern AudioBootStrap WASAPI_bootstrap;
+extern AudioBootStrap XAUDIO2_bootstrap;
+extern AudioBootStrap DSOUND_bootstrap;
+extern AudioBootStrap WINMM_bootstrap;
+extern AudioBootStrap PAUDIO_bootstrap;
+extern AudioBootStrap HAIKUAUDIO_bootstrap;
+extern AudioBootStrap COREAUDIO_bootstrap;
+extern AudioBootStrap DISKAUDIO_bootstrap;
+extern AudioBootStrap DUMMYAUDIO_bootstrap;
+extern AudioBootStrap FUSIONSOUND_bootstrap;
+extern AudioBootStrap ANDROIDAUDIO_bootstrap;
+extern AudioBootStrap PSPAUDIO_bootstrap;
+extern AudioBootStrap EMSCRIPTENAUDIO_bootstrap;
+
+#endif /* SDL_sysaudio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/SDL_wave.c b/src/audio/SDL_wave.c
index d173b4a..2c286aa 100644
--- a/src/audio/SDL_wave.c
+++ b/src/audio/SDL_wave.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -403,6 +403,47 @@ IMA_ADPCM_decode(Uint8 ** audio_buf, Uint32 * audio_len)
     return (0);
 }
 
+
+static int
+ConvertSint24ToSint32(Uint8 ** audio_buf, Uint32 * audio_len)
+{
+    const double DIVBY8388608 = 0.00000011920928955078125;
+    const Uint32 original_len = *audio_len;
+    const Uint32 samples = original_len / 3;
+    const Uint32 expanded_len = samples * sizeof (Uint32);
+    Uint8 *ptr = (Uint8 *) SDL_realloc(*audio_buf, expanded_len);
+    const Uint8 *src;
+    Uint32 *dst;
+    Uint32 i;
+
+    if (!ptr) {
+        return SDL_OutOfMemory();
+    }
+
+    *audio_buf = ptr;
+    *audio_len = expanded_len;
+
+    /* work from end to start, since we're expanding in-place. */
+    src = (ptr + original_len) - 3;
+    dst = ((Uint32 *) (ptr + expanded_len)) - 1;
+    for (i = 0; i < samples; i++) {
+        /* There's probably a faster way to do all this. */
+        const Sint32 converted = ((Sint32) ( (((Uint32) src[2]) << 24) |
+                                             (((Uint32) src[1]) << 16) |
+                                             (((Uint32) src[0]) << 8) )) >> 8;
+        const double scaled = (((double) converted) * DIVBY8388608);
+        src -= 3;
+        *(dst--) = (Sint32) (scaled * 2147483647.0);
+    }
+
+    return 0;
+}
+
+
+/* GUIDs that are used by WAVE_FORMAT_EXTENSIBLE */
+static const Uint8 extensible_pcm_guid[16] = { 1, 0, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113 };
+static const Uint8 extensible_ieee_guid[16] = { 3, 0, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113 };
+
 SDL_AudioSpec *
 SDL_LoadWAV_RW(SDL_RWops * src, int freesrc,
                SDL_AudioSpec * spec, Uint8 ** audio_buf, Uint32 * audio_len)
@@ -421,6 +462,7 @@ SDL_LoadWAV_RW(SDL_RWops * src, int freesrc,
 
     /* FMT chunk */
     WaveFMT *format = NULL;
+    WaveExtensibleFMT *ext = NULL;
 
     SDL_zero(chunk);
 
@@ -494,6 +536,24 @@ SDL_LoadWAV_RW(SDL_RWops * src, int freesrc,
         }
         IMA_ADPCM_encoded = 1;
         break;
+    case EXTENSIBLE_CODE:
+        /* note that this ignores channel masks, smaller valid bit counts
+           inside a larger container, and most subtypes. This is just enough
+           to get things that didn't really _need_ WAVE_FORMAT_EXTENSIBLE
+           to be useful working when they use this format flag. */
+        ext = (WaveExtensibleFMT *) format;
+        if (SDL_SwapLE16(ext->size) < 22) {
+            SDL_SetError("bogus extended .wav header");
+            was_error = 1;
+            goto done;
+        }
+        if (SDL_memcmp(ext->subformat, extensible_pcm_guid, 16) == 0) {
+            break;  /* cool. */
+        } else if (SDL_memcmp(ext->subformat, extensible_ieee_guid, 16) == 0) {
+            IEEE_float_encoded = 1;
+            break;
+        }
+        break;
     case MP3_CODE:
         SDL_SetError("MPEG Layer 3 data not supported");
         was_error = 1;
@@ -528,6 +588,9 @@ SDL_LoadWAV_RW(SDL_RWops * src, int freesrc,
         case 16:
             spec->format = AUDIO_S16;
             break;
+        case 24:  /* convert this. */
+            spec->format = AUDIO_S32;
+            break;
         case 32:
             spec->format = AUDIO_S32;
             break;
@@ -575,6 +638,13 @@ SDL_LoadWAV_RW(SDL_RWops * src, int freesrc,
         }
     }
 
+    if (SDL_SwapLE16(format->bitspersample) == 24) {
+        if (ConvertSint24ToSint32(audio_buf, audio_len) < 0) {
+            was_error = 1;
+            goto done;
+        }
+    }
+
     /* Don't return a buffer that isn't a multiple of samplesize */
     samplesize = ((SDL_AUDIO_BITSIZE(spec->format)) / 8) * spec->channels;
     *audio_len &= ~(samplesize - 1);
diff --git a/src/audio/SDL_wave.h b/src/audio/SDL_wave.h
index f2f9398..5762f51 100644
--- a/src/audio/SDL_wave.h
+++ b/src/audio/SDL_wave.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -38,6 +38,7 @@
 #define IEEE_FLOAT_CODE 0x0003
 #define IMA_ADPCM_CODE  0x0011
 #define MP3_CODE        0x0055
+#define EXTENSIBLE_CODE 0xFFFE
 #define WAVE_MONO       1
 #define WAVE_STEREO     2
 
@@ -64,4 +65,13 @@ typedef struct Chunk
     Uint8 *data;
 } Chunk;
 
+typedef struct WaveExtensibleFMT
+{
+    WaveFMT format;
+    Uint16 size;
+    Uint16 validbits;
+    Uint32 channelmask;
+    Uint8 subformat[16];  /* a GUID. */
+} WaveExtensibleFMT;
+
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/alsa/SDL_alsa_audio.c b/src/audio/alsa/SDL_alsa_audio.c
index 574d51b..68a72d2 100644
--- a/src/audio/alsa/SDL_alsa_audio.c
+++ b/src/audio/alsa/SDL_alsa_audio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -26,7 +26,6 @@
 
 #include <sys/types.h>
 #include <signal.h>             /* For kill() */
-#include <errno.h>
 #include <string.h>
 
 #include "SDL_assert.h"
@@ -91,6 +90,10 @@ static int (*ALSA_snd_pcm_reset)(snd_pcm_t *);
 static int (*ALSA_snd_device_name_hint) (int, const char *, void ***);
 static char* (*ALSA_snd_device_name_get_hint) (const void *, const char *);
 static int (*ALSA_snd_device_name_free_hint) (void **);
+#ifdef SND_CHMAP_API_VERSION
+static snd_pcm_chmap_t* (*ALSA_snd_pcm_get_chmap) (snd_pcm_t *);
+static int (*ALSA_snd_pcm_chmap_print) (const snd_pcm_chmap_t *map, size_t maxlen, char *buf);
+#endif
 
 #ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC
 #define snd_pcm_hw_params_sizeof ALSA_snd_pcm_hw_params_sizeof
@@ -155,6 +158,10 @@ load_alsa_syms(void)
     SDL_ALSA_SYM(snd_device_name_hint);
     SDL_ALSA_SYM(snd_device_name_get_hint);
     SDL_ALSA_SYM(snd_device_name_free_hint);
+#ifdef SND_CHMAP_API_VERSION
+    SDL_ALSA_SYM(snd_pcm_get_chmap);
+    SDL_ALSA_SYM(snd_pcm_chmap_print);
+#endif
 
     return 0;
 }
@@ -255,25 +262,25 @@ ALSA_WaitDevice(_THIS)
         tmp = ptr[3]; ptr[3] = ptr[5]; ptr[5] = tmp; \
     }
 
-static SDL_INLINE void
+static void
 swizzle_alsa_channels_6_64bit(void *buffer, Uint32 bufferlen)
 {
     SWIZ6(Uint64, buffer, bufferlen);
 }
 
-static SDL_INLINE void
+static void
 swizzle_alsa_channels_6_32bit(void *buffer, Uint32 bufferlen)
 {
     SWIZ6(Uint32, buffer, bufferlen);
 }
 
-static SDL_INLINE void
+static void
 swizzle_alsa_channels_6_16bit(void *buffer, Uint32 bufferlen)
 {
     SWIZ6(Uint16, buffer, bufferlen);
 }
 
-static SDL_INLINE void
+static void
 swizzle_alsa_channels_6_8bit(void *buffer, Uint32 bufferlen)
 {
     SWIZ6(Uint8, buffer, bufferlen);
@@ -286,7 +293,7 @@ swizzle_alsa_channels_6_8bit(void *buffer, Uint32 bufferlen)
  * Called right before feeding this->hidden->mixbuf to the hardware. Swizzle
  *  channels from Windows/Mac order to the format alsalib will want.
  */
-static SDL_INLINE void
+static void
 swizzle_alsa_channels(_THIS, void *buffer, Uint32 bufferlen)
 {
     if (this->spec.channels == 6) {
@@ -302,6 +309,15 @@ swizzle_alsa_channels(_THIS, void *buffer, Uint32 bufferlen)
     /* !!! FIXME: update this for 7.1 if needed, later. */
 }
 
+#ifdef SND_CHMAP_API_VERSION
+/* Some devices have the right channel map, no swizzling necessary */
+static void
+no_swizzle(_THIS, void *buffer, Uint32 bufferlen)
+{
+    return;
+}
+#endif /* SND_CHMAP_API_VERSION */
+
 
 static void
 ALSA_PlayDevice(_THIS)
@@ -311,23 +327,10 @@ ALSA_PlayDevice(_THIS)
                                 this->spec.channels;
     snd_pcm_uframes_t frames_left = ((snd_pcm_uframes_t) this->spec.samples);
 
-    swizzle_alsa_channels(this, this->hidden->mixbuf, frames_left);
+    this->hidden->swizzle_func(this, this->hidden->mixbuf, frames_left);
 
     while ( frames_left > 0 && SDL_AtomicGet(&this->enabled) ) {
-        int status;
-
-        /* This wait is a work-around for a hang when USB devices are
-           unplugged.  Normally it should not result in any waiting,
-           but in the case of a USB unplug, it serves as a way to
-           join the playback thread after the timeout occurs */
-        status = ALSA_snd_pcm_wait(this->hidden->pcm_handle, 1000);
-        if (status == 0) {
-            /*fprintf(stderr, "ALSA timeout waiting for available buffer space\n");*/
-            SDL_OpenedAudioDeviceDisconnected(this);
-            return;
-        }
-
-        status = ALSA_snd_pcm_writei(this->hidden->pcm_handle,
+        int status = ALSA_snd_pcm_writei(this->hidden->pcm_handle,
                                          sample_buf, frames_left);
 
         if (status < 0) {
@@ -347,6 +350,13 @@ ALSA_PlayDevice(_THIS)
             }
             continue;
         }
+        else if (status == 0) {
+            /* No frames were written (no available space in pcm device).
+               Allow other threads to catch up. */
+            Uint32 delay = (frames_left / 2 * 1000) / this->spec.freq;
+            SDL_Delay(delay);
+        }
+
         sample_buf += status * frame_size;
         frames_left -= status;
     }
@@ -366,23 +376,22 @@ ALSA_CaptureFromDevice(_THIS, void *buffer, int buflen)
                                 this->spec.channels;
     const int total_frames = buflen / frame_size;
     snd_pcm_uframes_t frames_left = total_frames;
+    snd_pcm_uframes_t wait_time = frame_size / 2;
 
     SDL_assert((buflen % frame_size) == 0);
 
     while ( frames_left > 0 && SDL_AtomicGet(&this->enabled) ) {
-        /* !!! FIXME: This works, but needs more testing before going live */
-        /* ALSA_snd_pcm_wait(this->hidden->pcm_handle, -1); */
-        int status = ALSA_snd_pcm_readi(this->hidden->pcm_handle,
+        int status;
+
+        status = ALSA_snd_pcm_readi(this->hidden->pcm_handle,
                                         sample_buf, frames_left);
 
-        if (status < 0) {
+        if (status == -EAGAIN) {
+            ALSA_snd_pcm_wait(this->hidden->pcm_handle, wait_time);
+            status = 0;
+        }
+        else if (status < 0) {
             /*printf("ALSA: capture error %d\n", status);*/
-            if (status == -EAGAIN) {
-                /* Apparently snd_pcm_recover() doesn't handle this case -
-                   does it assume snd_pcm_wait() above? */
-                SDL_Delay(1);
-                continue;
-            }
             status = ALSA_snd_pcm_recover(this->hidden->pcm_handle, status, 0);
             if (status < 0) {
                 /* Hmm, not much we can do - abort */
@@ -398,7 +407,7 @@ ALSA_CaptureFromDevice(_THIS, void *buffer, int buflen)
         frames_left -= status;
     }
 
-    swizzle_alsa_channels(this, buffer, total_frames - frames_left);
+    this->hidden->swizzle_func(this, buffer, total_frames - frames_left);
 
     return (total_frames - frames_left) * frame_size;
 }
@@ -548,6 +557,10 @@ ALSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
     SDL_AudioFormat test_format = 0;
     unsigned int rate = 0;
     unsigned int channels = 0;
+#ifdef SND_CHMAP_API_VERSION
+    snd_pcm_chmap_t *chmap;
+    char chmap_str[64];
+#endif
 
     /* Initialize all variables that we clean on shutdown */
     this->hidden = (struct SDL_PrivateAudioData *)
@@ -640,6 +653,22 @@ ALSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
     }
     this->spec.format = test_format;
 
+    /* Validate number of channels and determine if swizzling is necessary
+     * Assume original swizzling, until proven otherwise.
+     */
+    this->hidden->swizzle_func = swizzle_alsa_channels;
+#ifdef SND_CHMAP_API_VERSION
+    chmap = ALSA_snd_pcm_get_chmap(pcm_handle);
+    if (chmap) {
+        ALSA_snd_pcm_chmap_print(chmap, sizeof(chmap_str), chmap_str);
+        if (SDL_strcmp("FL FR FC LFE RL RR", chmap_str) == 0 ||
+            SDL_strcmp("FL FR FC LFE SL SR", chmap_str) == 0) {
+            this->hidden->swizzle_func = no_swizzle;
+        }
+        free(chmap);
+    }
+#endif /* SND_CHMAP_API_VERSION */
+
     /* Set the number of channels */
     status = ALSA_snd_pcm_hw_params_set_channels(pcm_handle, hwparams,
                                                  this->spec.channels);
@@ -708,8 +737,9 @@ ALSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
         SDL_memset(this->hidden->mixbuf, this->spec.silence, this->hidden->mixlen);
     }
 
-    /* Switch to blocking mode for playback */
-    ALSA_snd_pcm_nonblock(pcm_handle, 0);
+    if (!iscapture) {
+        ALSA_snd_pcm_nonblock(pcm_handle, 0);
+    }
 
     /* We're ready to rock and roll. :-) */
     return 0;
@@ -726,18 +756,28 @@ static void
 add_device(const int iscapture, const char *name, void *hint, ALSA_Device **pSeen)
 {
     ALSA_Device *dev = SDL_malloc(sizeof (ALSA_Device));
-    char *desc = ALSA_snd_device_name_get_hint(hint, "DESC");
+    char *desc;
     char *handle = NULL;
     char *ptr;
 
-    if (!desc) {
-        SDL_free(dev);
-        return;
-    } else if (!dev) {
-        free(desc);
+    if (!dev) {
         return;
     }
 
+    /* Not all alsa devices are enumerable via snd_device_name_get_hint
+       (i.e. bluetooth devices).  Therefore if hint is passed in to this
+       function as  NULL, assume name contains desc.
+       Make sure not to free the storage associated with desc in this case */
+    if (hint) {
+        desc = ALSA_snd_device_name_get_hint(hint, "DESC");
+        if (!desc) {
+            SDL_free(dev);
+            return;
+        }
+    } else {
+        desc = (char *) name;
+    }
+
     SDL_assert(name != NULL);
 
     /* some strings have newlines, like "HDA NVidia, HDMI 0\nHDMI Audio Output".
@@ -751,14 +791,16 @@ add_device(const int iscapture, const char *name, void *hint, ALSA_Device **pSee
 
     handle = SDL_strdup(name);
     if (!handle) {
-        free(desc);
+        if (hint) {
+            free(desc);
+        }
         SDL_free(dev);
         return;
     }
 
     SDL_AddAudioDevice(iscapture, desc, handle);
-    free(desc);
-
+    if (hint)
+        free(desc);
     dev->name = handle;
     dev->iscapture = iscapture;
     dev->next = *pSeen;
@@ -778,12 +820,15 @@ ALSA_HotplugThread(void *arg)
     ALSA_Device *dev;
     Uint32 ticks;
 
+    SDL_SetThreadPriority(SDL_THREAD_PRIORITY_LOW);
+
     while (!SDL_AtomicGet(&ALSA_hotplug_shutdown)) {
         void **hints = NULL;
+        ALSA_Device *unseen;
+        ALSA_Device *seen;
+        ALSA_Device *prev;
+
         if (ALSA_snd_device_name_hint(-1, "pcm", &hints) != -1) {
-            ALSA_Device *unseen = devices;
-            ALSA_Device *seen = NULL;
-            ALSA_Device *prev;
             int i, j;
             const char *match = NULL;
             int bestmatch = 0xFFFF;
@@ -793,6 +838,8 @@ ALSA_HotplugThread(void *arg)
                 "hw:", "sysdefault:", "default:", NULL
             };
 
+            unseen = devices;
+            seen = NULL;
             /* Apparently there are several different ways that ALSA lists
                actual hardware. It could be prefixed with "hw:" or "default:"
                or "sysdefault:" and maybe others. Go through the list and see
@@ -887,7 +934,7 @@ ALSA_HotplugThread(void *arg)
 
             /* report anything still in unseen as removed. */
             for (dev = unseen; dev; dev = next) {
-                /*printf("ALSA: removing %s device '%s'\n", dev->iscapture ? "capture" : "output", dev->name);*/
+                /*printf("ALSA: removing usb %s device '%s'\n", dev->iscapture ? "capture" : "output", dev->name);*/
                 next = dev->next;
                 SDL_RemoveAudioDevice(dev->iscapture, dev->name);
                 SDL_free(dev->name);
diff --git a/src/audio/alsa/SDL_alsa_audio.h b/src/audio/alsa/SDL_alsa_audio.h
index 3080aea..74bfa8f 100644
--- a/src/audio/alsa/SDL_alsa_audio.h
+++ b/src/audio/alsa/SDL_alsa_audio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_ALSA_audio_h
-#define _SDL_ALSA_audio_h
+#ifndef SDL_ALSA_audio_h_
+#define SDL_ALSA_audio_h_
 
 #include <alsa/asoundlib.h>
 
@@ -38,8 +38,11 @@ struct SDL_PrivateAudioData
     /* Raw mixing buffer */
     Uint8 *mixbuf;
     int mixlen;
+
+    /* swizzle function */
+    void (*swizzle_func)(_THIS, void *buffer, Uint32 bufferlen);
 };
 
-#endif /* _SDL_ALSA_audio_h */
+#endif /* SDL_ALSA_audio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/android/SDL_androidaudio.c b/src/audio/android/SDL_androidaudio.c
index 96f6d63..81369c6 100644
--- a/src/audio/android/SDL_androidaudio.c
+++ b/src/audio/android/SDL_androidaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -215,6 +215,10 @@ void ANDROIDAUDIO_ResumeDevices(void)
     }
 }
 
+#else 
+
+void ANDROIDAUDIO_ResumeDevices(void) {}
+void ANDROIDAUDIO_PauseDevices(void) {}
 
 #endif /* SDL_AUDIO_DRIVER_ANDROID */
 
diff --git a/src/audio/android/SDL_androidaudio.h b/src/audio/android/SDL_androidaudio.h
index 1336153..370acbb 100644
--- a/src/audio/android/SDL_androidaudio.h
+++ b/src/audio/android/SDL_androidaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_androidaudio_h
-#define _SDL_androidaudio_h
+#ifndef SDL_androidaudio_h_
+#define SDL_androidaudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -34,6 +34,9 @@ struct SDL_PrivateAudioData
     int resume;
 };
 
-#endif /* _SDL_androidaudio_h */
+void ANDROIDAUDIO_ResumeDevices(void);
+void ANDROIDAUDIO_PauseDevices(void);
+
+#endif /* SDL_androidaudio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/arts/SDL_artsaudio.c b/src/audio/arts/SDL_artsaudio.c
index 6054e36..92f88cb 100644
--- a/src/audio/arts/SDL_artsaudio.c
+++ b/src/audio/arts/SDL_artsaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/audio/arts/SDL_artsaudio.h b/src/audio/arts/SDL_artsaudio.h
index 6b9bf30..50c9ae0 100644
--- a/src/audio/arts/SDL_artsaudio.h
+++ b/src/audio/arts/SDL_artsaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_artscaudio_h
-#define _SDL_artscaudio_h
+#ifndef SDL_artsaudio_h_
+#define SDL_artsaudio_h_
 
 #include <artsc.h>
 
@@ -42,11 +42,12 @@ struct SDL_PrivateAudioData
     Uint8 *mixbuf;
     int mixlen;
 
-    /* Support for audio timing using a timer, in addition to select() */
+    /* Support for audio timing using a timer, in addition to SDL_IOReady() */
     float frame_ticks;
     float next_frame;
 };
 #define FUDGE_TICKS 10      /* The scheduler overhead ticks per frame */
 
-#endif /* _SDL_artscaudio_h */
+#endif /* SDL_artsaudio_h_ */
+
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/coreaudio/SDL_coreaudio.h b/src/audio/coreaudio/SDL_coreaudio.h
index b7e5b8e..87d0f83 100644
--- a/src/audio/coreaudio/SDL_coreaudio.h
+++ b/src/audio/coreaudio/SDL_coreaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_coreaudio_h
-#define _SDL_coreaudio_h
+#ifndef SDL_coreaudio_h_
+#define SDL_coreaudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -47,7 +47,7 @@ struct SDL_PrivateAudioData
 {
     SDL_Thread *thread;
     AudioQueueRef audioQueue;
-    AudioQueueBufferRef audioBuffer[2];
+    AudioQueueBufferRef *audioBuffer;
     void *buffer;
     UInt32 bufferOffset;
     UInt32 bufferSize;
@@ -63,5 +63,6 @@ struct SDL_PrivateAudioData
 #endif
 };
 
-#endif /* _SDL_coreaudio_h */
+#endif /* SDL_coreaudio_h_ */
+
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/coreaudio/SDL_coreaudio.m b/src/audio/coreaudio/SDL_coreaudio.m
index 8512905..33c239d 100644
--- a/src/audio/coreaudio/SDL_coreaudio.m
+++ b/src/audio/coreaudio/SDL_coreaudio.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,6 +25,7 @@
 /* !!! FIXME: clean out some of the macro salsa in here. */
 
 #include "SDL_audio.h"
+#include "SDL_hints.h"
 #include "../SDL_audio_c.h"
 #include "../SDL_sysaudio.h"
 #include "SDL_coreaudio.h"
@@ -285,9 +286,9 @@ static void interruption_begin(_THIS)
 static void interruption_end(_THIS)
 {
     if (this != NULL && this->hidden != NULL && this->hidden->audioQueue != NULL
-    && this->hidden->interrupted) {
+    && this->hidden->interrupted
+    && AudioQueueStart(this->hidden->audioQueue, NULL) == AVAudioSessionErrorCodeNone) {
         this->hidden->interrupted = SDL_FALSE;
-        AudioQueueStart(this->hidden->audioQueue, NULL);
     }
 }
 
@@ -325,7 +326,8 @@ static BOOL update_audio_session(_THIS, SDL_bool open)
     @autoreleasepool {
         AVAudioSession *session = [AVAudioSession sharedInstance];
         NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
-        NSString *category;
+        /* Set category to ambient by default so that other music continues playing. */
+        NSString *category = AVAudioSessionCategoryAmbient;
         NSError *err = nil;
 
         if (open_playback_devices && open_capture_devices) {
@@ -333,10 +335,17 @@ static BOOL update_audio_session(_THIS, SDL_bool open)
         } else if (open_capture_devices) {
             category = AVAudioSessionCategoryRecord;
         } else {
-            /* Set category to ambient so that other music continues playing.
-             You can change this at runtime in your own code if you need different
-             behavior. If this is common, we can add an SDL hint for this. */
-            category = AVAudioSessionCategoryAmbient;
+            const char *hint = SDL_GetHint(SDL_HINT_AUDIO_CATEGORY);
+            if (hint) {
+                if (SDL_strcasecmp(hint, "AVAudioSessionCategoryAmbient") == 0) {
+                    category = AVAudioSessionCategoryAmbient;
+                } else if (SDL_strcasecmp(hint, "AVAudioSessionCategorySoloAmbient") == 0) {
+                    category = AVAudioSessionCategorySoloAmbient;
+                } else if (SDL_strcasecmp(hint, "AVAudioSessionCategoryPlayback") == 0 ||
+                           SDL_strcasecmp(hint, "playback") == 0) {
+                    category = AVAudioSessionCategoryPlayback;
+                }
+            }
         }
 
         if (![session setCategory:category error:&err]) {
@@ -400,8 +409,12 @@ static void
 outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer)
 {
     SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData;
+    if (SDL_AtomicGet(&this->hidden->shutdown)) {
+        return;  /* don't do anything. */
+    }
+
     if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) {
-        /* Supply silence if audio is enabled and not paused */
+        /* Supply silence if audio is not enabled or paused */
         SDL_memset(inBuffer->mAudioData, this->spec.silence, inBuffer->mAudioDataBytesCapacity);
     } else {
         UInt32 remaining = inBuffer->mAudioDataBytesCapacity;
@@ -412,7 +425,7 @@ outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffe
             if (this->hidden->bufferOffset >= this->hidden->bufferSize) {
                 /* Generate the data */
                 SDL_LockMutex(this->mixer_lock);
-                (*this->spec.callback)(this->spec.userdata,
+                (*this->callbackspec.callback)(this->callbackspec.userdata,
                             this->hidden->buffer, this->hidden->bufferSize);
                 SDL_UnlockMutex(this->mixer_lock);
                 this->hidden->bufferOffset = 0;
@@ -430,9 +443,7 @@ outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffe
         }
     }
 
-    if (!SDL_AtomicGet(&this->hidden->shutdown)) {
-        AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
-    }
+    AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
 
     inBuffer->mAudioDataByteSize = inBuffer->mAudioDataBytesCapacity;
 }
@@ -443,7 +454,13 @@ inputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer
               const AudioStreamPacketDescription *inPacketDescs )
 {
     SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData;
-    if (SDL_AtomicGet(&this->enabled) && !SDL_AtomicGet(&this->paused)) {  /* ignore unless we're active. */
+
+    if (SDL_AtomicGet(&this->shutdown)) {
+        return;  /* don't do anything. */
+    }
+
+    /* ignore unless we're active. */
+    if (!SDL_AtomicGet(&this->paused) && SDL_AtomicGet(&this->enabled) && !SDL_AtomicGet(&this->paused)) {
         const Uint8 *ptr = (const Uint8 *) inBuffer->mAudioData;
         UInt32 remaining = inBuffer->mAudioDataByteSize;
         while (remaining > 0) {
@@ -459,16 +476,14 @@ inputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer
 
             if (this->hidden->bufferOffset >= this->hidden->bufferSize) {
                 SDL_LockMutex(this->mixer_lock);
-                (*this->spec.callback)(this->spec.userdata, this->hidden->buffer, this->hidden->bufferSize);
+                (*this->callbackspec.callback)(this->callbackspec.userdata, this->hidden->buffer, this->hidden->bufferSize);
                 SDL_UnlockMutex(this->mixer_lock);
                 this->hidden->bufferOffset = 0;
             }
         }
     }
 
-    if (!SDL_AtomicGet(&this->hidden->shutdown)) {
-        AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
-    }
+    AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
 }
 
 
@@ -514,7 +529,6 @@ static void
 COREAUDIO_CloseDevice(_THIS)
 {
     const SDL_bool iscapture = this->iscapture;
-    int i;
 
 /* !!! FIXME: what does iOS do when a bluetooth audio device vanishes? Headphones unplugged? */
 /* !!! FIXME: (we only do a "default" device on iOS right now...can we do more?) */
@@ -533,11 +547,6 @@ COREAUDIO_CloseDevice(_THIS)
     }
 
     if (this->hidden->audioQueue) {
-        for (i = 0; i < SDL_arraysize(this->hidden->audioBuffer); i++) {
-            if (this->hidden->audioBuffer[i]) {
-                AudioQueueFreeBuffer(this->hidden->audioQueue, this->hidden->audioBuffer[i]);
-            }
-        }
         AudioQueueDispose(this->hidden->audioQueue, 1);
     }
 
@@ -545,6 +554,8 @@ COREAUDIO_CloseDevice(_THIS)
         SDL_DestroySemaphore(this->hidden->ready_semaphore);
     }
 
+    /* AudioQueueDispose() frees the actual buffer objects. */
+    SDL_free(this->hidden->audioBuffer);
     SDL_free(this->hidden->thread_error);
     SDL_free(this->hidden->buffer);
     SDL_free(this->hidden);
@@ -663,7 +674,31 @@ prepare_audioqueue(_THIS)
         return 0;
     }
 
-    for (i = 0; i < SDL_arraysize(this->hidden->audioBuffer); i++) {
+    /* Make sure we can feed the device a minimum amount of time */
+    double MINIMUM_AUDIO_BUFFER_TIME_MS = 15.0;
+#if defined(__IPHONEOS__)
+    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
+        /* Older iOS hardware, use 40 ms as a minimum time */
+        MINIMUM_AUDIO_BUFFER_TIME_MS = 40.0;
+    }
+#endif
+    const double msecs = (this->spec.samples / ((double) this->spec.freq)) * 1000.0;
+    int numAudioBuffers = 2;
+    if (msecs < MINIMUM_AUDIO_BUFFER_TIME_MS) {  /* use more buffers if we have a VERY small sample set. */
+        numAudioBuffers = ((int)SDL_ceil(MINIMUM_AUDIO_BUFFER_TIME_MS / msecs) * 2);
+    }
+
+    this->hidden->audioBuffer = SDL_calloc(1, sizeof (AudioQueueBufferRef) * numAudioBuffers);
+    if (this->hidden->audioBuffer == NULL) {
+        SDL_OutOfMemory();
+        return 0;
+    }
+
+#if DEBUG_COREAUDIO
+    printf("COREAUDIO: numAudioBuffers == %d\n", numAudioBuffers);
+#endif
+
+    for (i = 0; i < numAudioBuffers; i++) {
         result = AudioQueueAllocateBuffer(this->hidden->audioQueue, this->spec.size, &this->hidden->audioBuffer[i]);
         CHECK_RESULT("AudioQueueAllocateBuffer");
         SDL_memset(this->hidden->audioBuffer[i]->mAudioData, this->spec.silence, this->hidden->audioBuffer[i]->mAudioDataBytesCapacity);
@@ -699,9 +734,9 @@ audioqueue_thread(void *arg)
     if (this->iscapture) {  /* just stop immediately for capture devices. */
         AudioQueueStop(this->hidden->audioQueue, 1);
     } else {  /* Drain off any pending playback. */
-        AudioQueueStop(this->hidden->audioQueue, 0);
         const CFTimeInterval secs = (((this->spec.size / (SDL_AUDIO_BITSIZE(this->spec.format) / 8)) / this->spec.channels) / ((CFTimeInterval) this->spec.freq)) * 2.0;
         CFRunLoopRunInMode(kCFRunLoopDefaultMode, secs, 0);
+        AudioQueueStop(this->hidden->audioQueue, 0);
     }
 
     return 0;
@@ -734,6 +769,13 @@ COREAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
     if (!update_audio_session(this, SDL_TRUE)) {
         return -1;
     }
+
+    /* Stop CoreAudio from doing expensive audio rate conversion */
+    @autoreleasepool {
+        AVAudioSession* session = [AVAudioSession sharedInstance];
+        [session setPreferredSampleRate:this->spec.freq error:nil];
+        this->spec.freq = (int)session.sampleRate;
+    }
 #endif
 
     /* Setup a AudioStreamBasicDescription with the requested format */
diff --git a/src/audio/directsound/SDL_directsound.c b/src/audio/directsound/SDL_directsound.c
index 5d261c9..df8b5c9 100644
--- a/src/audio/directsound/SDL_directsound.c
+++ b/src/audio/directsound/SDL_directsound.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -434,7 +434,6 @@ CreateCaptureBuffer(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt)
     LPDIRECTSOUNDCAPTURE capture = this->hidden->capture;
     LPDIRECTSOUNDCAPTUREBUFFER *capturebuf = &this->hidden->capturebuf;
     DSCBUFFERDESC format;
-//    DWORD junk, cursor;
     HRESULT result;
 
     SDL_zero(format);
@@ -523,8 +522,8 @@ DSOUND_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
             bufsize = numchunks * this->spec.size;
             if ((bufsize < DSBSIZE_MIN) || (bufsize > DSBSIZE_MAX)) {
                 SDL_SetError("Sound buffer size must be between %d and %d",
-                             (DSBSIZE_MIN < numchunks) ? 1 : DSBSIZE_MIN / numchunks,
-                             DSBSIZE_MAX / numchunks);
+                             (int) ((DSBSIZE_MIN < numchunks) ? 1 : DSBSIZE_MIN / numchunks),
+                             (int) (DSBSIZE_MAX / numchunks));
             } else {
                 int rc;
 				WAVEFORMATEX wfmt;
diff --git a/src/audio/directsound/SDL_directsound.h b/src/audio/directsound/SDL_directsound.h
index d646c30..c19dc63 100644
--- a/src/audio/directsound/SDL_directsound.h
+++ b/src/audio/directsound/SDL_directsound.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_directsound_h
-#define _SDL_directsound_h
+#ifndef SDL_directsound_h_
+#define SDL_directsound_h_
 
 #include "../../core/windows/SDL_directx.h"
 
@@ -42,6 +42,6 @@ struct SDL_PrivateAudioData
     Uint8 *locked_buf;
 };
 
-#endif /* _SDL_directsound_h */
+#endif /* SDL_directsound_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/disk/SDL_diskaudio.c b/src/audio/disk/SDL_diskaudio.c
index ee53688..cfa7e76 100644
--- a/src/audio/disk/SDL_diskaudio.c
+++ b/src/audio/disk/SDL_diskaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,6 +33,7 @@
 #include "SDL_audio.h"
 #include "../SDL_audio_c.h"
 #include "SDL_diskaudio.h"
+#include "SDL_log.h"
 
 /* !!! FIXME: these should be SDL hints, not environment variables. */
 /* environment variables and defaults. */
@@ -160,12 +161,11 @@ DISKAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
         SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);
     }
 
-#if HAVE_STDIO_H
-    fprintf(stderr,
-            "WARNING: You are using the SDL disk i/o audio driver!\n"
-            " %s file [%s].\n", iscapture ? "Reading from" : "Writing to",
-            fname);
-#endif
+    SDL_LogCritical(SDL_LOG_CATEGORY_AUDIO,
+                "You are using the SDL disk i/o audio driver!\n");
+    SDL_LogCritical(SDL_LOG_CATEGORY_AUDIO,
+                " %s file [%s].\n", iscapture ? "Reading from" : "Writing to",
+                fname);
 
     /* We're ready to rock and roll. :-) */
     return 0;
diff --git a/src/audio/disk/SDL_diskaudio.h b/src/audio/disk/SDL_diskaudio.h
index ad152a9..8652e77 100644
--- a/src/audio/disk/SDL_diskaudio.h
+++ b/src/audio/disk/SDL_diskaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_diskaudio_h
-#define _SDL_diskaudio_h
+#ifndef SDL_diskaudio_h_
+#define SDL_diskaudio_h_
 
 #include "SDL_rwops.h"
 #include "../SDL_sysaudio.h"
@@ -37,5 +37,5 @@ struct SDL_PrivateAudioData
     Uint8 *mixbuf;
 };
 
-#endif /* _SDL_diskaudio_h */
+#endif /* SDL_diskaudio_h_ */
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/dsp/SDL_dspaudio.c b/src/audio/dsp/SDL_dspaudio.c
index a5a31b3..63869a6 100644
--- a/src/audio/dsp/SDL_dspaudio.c
+++ b/src/audio/dsp/SDL_dspaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/audio/dsp/SDL_dspaudio.h b/src/audio/dsp/SDL_dspaudio.h
index 0e4acfc..fbefb48 100644
--- a/src/audio/dsp/SDL_dspaudio.h
+++ b/src/audio/dsp/SDL_dspaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_dspaudio_h
-#define _SDL_dspaudio_h
+#ifndef SDL_dspaudio_h_
+#define SDL_dspaudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -39,5 +39,5 @@ struct SDL_PrivateAudioData
 };
 #define FUDGE_TICKS 10      /* The scheduler overhead ticks per frame */
 
-#endif /* _SDL_dspaudio_h */
+#endif /* SDL_dspaudio_h_ */
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/dummy/SDL_dummyaudio.c b/src/audio/dummy/SDL_dummyaudio.c
index b39f8e3..74d85c3 100644
--- a/src/audio/dummy/SDL_dummyaudio.c
+++ b/src/audio/dummy/SDL_dummyaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/audio/dummy/SDL_dummyaudio.h b/src/audio/dummy/SDL_dummyaudio.h
index b1f88b1..c4798e8 100644
--- a/src/audio/dummy/SDL_dummyaudio.h
+++ b/src/audio/dummy/SDL_dummyaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_dummyaudio_h
-#define _SDL_dummyaudio_h
+#ifndef SDL_dummyaudio_h_
+#define SDL_dummyaudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -37,5 +37,5 @@ struct SDL_PrivateAudioData
     Uint32 initial_calls;
 };
 
-#endif /* _SDL_dummyaudio_h */
+#endif /* SDL_dummyaudio_h_ */
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/emscripten/SDL_emscriptenaudio.c b/src/audio/emscripten/SDL_emscriptenaudio.c
index 839d445..ee38e53 100644
--- a/src/audio/emscripten/SDL_emscriptenaudio.c
+++ b/src/audio/emscripten/SDL_emscriptenaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -26,175 +26,121 @@
 #include "SDL_log.h"
 #include "../SDL_audio_c.h"
 #include "SDL_emscriptenaudio.h"
+#include "SDL_assert.h"
 
 #include <emscripten/emscripten.h>
 
-static int
-copyData(_THIS)
+static void
+FeedAudioDevice(_THIS, const void *buf, const int buflen)
 {
-    int byte_len;
-
-    if (this->hidden->write_off + this->convert.len_cvt > this->hidden->mixlen) {
-        if (this->hidden->write_off > this->hidden->read_off) {
-            SDL_memmove(this->hidden->mixbuf,
-                        this->hidden->mixbuf + this->hidden->read_off,
-                        this->hidden->mixlen - this->hidden->read_off);
-            this->hidden->write_off = this->hidden->write_off - this->hidden->read_off;
-        } else {
-            this->hidden->write_off = 0;
-        }
-        this->hidden->read_off = 0;
-    }
-
-    SDL_memcpy(this->hidden->mixbuf + this->hidden->write_off,
-               this->convert.buf,
-               this->convert.len_cvt);
-    this->hidden->write_off += this->convert.len_cvt;
-    byte_len = this->hidden->write_off - this->hidden->read_off;
+    const int framelen = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels;
+    EM_ASM_ARGS({
+        var numChannels = SDL2.audio.currentOutputBuffer['numberOfChannels'];
+        for (var c = 0; c < numChannels; ++c) {
+            var channelData = SDL2.audio.currentOutputBuffer['getChannelData'](c);
+            if (channelData.length != $1) {
+                throw 'Web Audio output buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!';
+            }
 
-    return byte_len;
+            for (var j = 0; j < $1; ++j) {
+                channelData[j] = HEAPF32[$0 + ((j*numChannels + c) << 2) >> 2];  /* !!! FIXME: why are these shifts here? */
+            }
+        }
+    }, buf, buflen / framelen);
 }
 
 static void
 HandleAudioProcess(_THIS)
 {
-    Uint8 *buf = NULL;
-    int byte_len = 0;
-    int bytes = SDL_AUDIO_BITSIZE(this->spec.format) / 8;
+    SDL_AudioCallback callback = this->callbackspec.callback;
+    const int stream_len = this->callbackspec.size;
 
     /* Only do something if audio is enabled */
     if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) {
+        if (this->stream) {
+            SDL_AudioStreamClear(this->stream);
+        }
         return;
     }
 
-    if (this->convert.needed) {
-        const int bytes_in = SDL_AUDIO_BITSIZE(this->convert.src_format) / 8;
-
-        if (this->hidden->conv_in_len != 0) {
-            this->convert.len = this->hidden->conv_in_len * bytes_in * this->spec.channels;
-        }
-
-        (*this->spec.callback) (this->spec.userdata,
-                                 this->convert.buf,
-                                 this->convert.len);
-        SDL_ConvertAudio(&this->convert);
-        buf = this->convert.buf;
-        byte_len = this->convert.len_cvt;
-
-        /* size mismatch*/
-        if (byte_len != this->spec.size) {
-            if (!this->hidden->mixbuf) {
-                this->hidden->mixlen = this->spec.size > byte_len ? this->spec.size * 2 : byte_len * 2;
-                this->hidden->mixbuf = SDL_malloc(this->hidden->mixlen);
-            }
-
-            /* copy existing data */
-            byte_len = copyData(this);
-
-            /* read more data*/
-            while (byte_len < this->spec.size) {
-                (*this->spec.callback) (this->spec.userdata,
-                                         this->convert.buf,
-                                         this->convert.len);
-                SDL_ConvertAudio(&this->convert);
-                byte_len = copyData(this);
+    if (this->stream == NULL) {  /* no conversion necessary. */
+        SDL_assert(this->spec.size == stream_len);
+        callback(this->callbackspec.userdata, this->work_buffer, stream_len);
+    } else {  /* streaming/converting */
+        int got;
+        while (SDL_AudioStreamAvailable(this->stream) < ((int) this->spec.size)) {
+            callback(this->callbackspec.userdata, this->work_buffer, stream_len);
+            if (SDL_AudioStreamPut(this->stream, this->work_buffer, stream_len) == -1) {
+                SDL_AudioStreamClear(this->stream);
+                SDL_AtomicSet(&this->enabled, 0);
+                break;
             }
-
-            byte_len = this->spec.size;
-            buf = this->hidden->mixbuf + this->hidden->read_off;
-            this->hidden->read_off += byte_len;
         }
 
-    } else {
-        if (!this->hidden->mixbuf) {
-            this->hidden->mixlen = this->spec.size;
-            this->hidden->mixbuf = SDL_malloc(this->hidden->mixlen);
+        got = SDL_AudioStreamGet(this->stream, this->work_buffer, this->spec.size);
+        SDL_assert((got < 0) || (got == this->spec.size));
+        if (got != this->spec.size) {
+            SDL_memset(this->work_buffer, this->spec.silence, this->spec.size);
         }
-        (*this->spec.callback) (this->spec.userdata,
-                                 this->hidden->mixbuf,
-                                 this->hidden->mixlen);
-        buf = this->hidden->mixbuf;
-        byte_len = this->hidden->mixlen;
     }
 
-    if (buf) {
-        EM_ASM_ARGS({
-            var numChannels = SDL2.audio.currentOutputBuffer['numberOfChannels'];
-            for (var c = 0; c < numChannels; ++c) {
-                var channelData = SDL2.audio.currentOutputBuffer['getChannelData'](c);
-                if (channelData.length != $1) {
-                    throw 'Web Audio output buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!';
-                }
-
-                for (var j = 0; j < $1; ++j) {
-                    channelData[j] = HEAPF32[$0 + ((j*numChannels + c) << 2) >> 2];
-                }
-            }
-        }, buf, byte_len / bytes / this->spec.channels);
-    }
+    FeedAudioDevice(this, this->work_buffer, this->spec.size);
 }
 
 static void
 HandleCaptureProcess(_THIS)
 {
-    Uint8 *buf;
-    int buflen;
+    SDL_AudioCallback callback = this->callbackspec.callback;
+    const int stream_len = this->callbackspec.size;
 
     /* Only do something if audio is enabled */
     if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) {
+        SDL_AudioStreamClear(this->stream);
         return;
     }
 
-    if (this->convert.needed) {
-        buf = this->convert.buf;
-        buflen = this->convert.len_cvt;
-    } else {
-        if (!this->hidden->mixbuf) {
-            this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->spec.size);
-            if (!this->hidden->mixbuf) {
-                return;  /* oh well. */
-            }
-        }
-        buf = this->hidden->mixbuf;
-        buflen = this->spec.size;
-    }
-
     EM_ASM_ARGS({
         var numChannels = SDL2.capture.currentCaptureBuffer.numberOfChannels;
-        if (numChannels == 1) {  /* fastpath this a little for the common (mono) case. */
-            var channelData = SDL2.capture.currentCaptureBuffer.getChannelData(0);
+        for (var c = 0; c < numChannels; ++c) {
+            var channelData = SDL2.capture.currentCaptureBuffer.getChannelData(c);
             if (channelData.length != $1) {
                 throw 'Web Audio capture buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!';
             }
-            for (var j = 0; j < $1; ++j) {
-                setValue($0 + (j * 4), channelData[j], 'float');
-            }
-        } else {
-            for (var c = 0; c < numChannels; ++c) {
-                var channelData = SDL2.capture.currentCaptureBuffer.getChannelData(c);
-                if (channelData.length != $1) {
-                    throw 'Web Audio capture buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!';
-                }
 
+            if (numChannels == 1) {  /* fastpath this a little for the common (mono) case. */
+                for (var j = 0; j < $1; ++j) {
+                    setValue($0 + (j * 4), channelData[j], 'float');
+                }
+            } else {
                 for (var j = 0; j < $1; ++j) {
                     setValue($0 + (((j * numChannels) + c) * 4), channelData[j], 'float');
                 }
             }
         }
-    }, buf, (this->spec.size / sizeof (float)) / this->spec.channels);
+    }, this->work_buffer, (this->spec.size / sizeof (float)) / this->spec.channels);
 
     /* okay, we've got an interleaved float32 array in C now. */
 
-    if (this->convert.needed) {
-        SDL_ConvertAudio(&this->convert);
-    }
+    if (this->stream == NULL) {  /* no conversion necessary. */
+        SDL_assert(this->spec.size == stream_len);
+        callback(this->callbackspec.userdata, this->work_buffer, stream_len);
+    } else {  /* streaming/converting */
+        if (SDL_AudioStreamPut(this->stream, this->work_buffer, this->spec.size) == -1) {
+            SDL_AtomicSet(&this->enabled, 0);
+        }
 
-    /* Send it to the app. */
-    (*this->spec.callback) (this->spec.userdata, buf, buflen);
+        while (SDL_AudioStreamAvailable(this->stream) >= stream_len) {
+            const int got = SDL_AudioStreamGet(this->stream, this->work_buffer, stream_len);
+            SDL_assert((got < 0) || (got == stream_len));
+            if (got != stream_len) {
+                SDL_memset(this->work_buffer, this->callbackspec.silence, stream_len);
+            }
+            callback(this->callbackspec.userdata, this->work_buffer, stream_len);  /* Send it to the app. */
+        }
+    }
 }
 
 
-
 static void
 EMSCRIPTENAUDIO_CloseDevice(_THIS)
 {
@@ -236,8 +182,9 @@ EMSCRIPTENAUDIO_CloseDevice(_THIS)
         }
     }, this->iscapture);
 
-    SDL_free(this->hidden->mixbuf);
+#if 0  /* !!! FIXME: currently not used. Can we move some stuff off the SDL2 namespace? --ryan. */
     SDL_free(this->hidden);
+#endif
 }
 
 static int
@@ -245,8 +192,6 @@ EMSCRIPTENAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscaptu
 {
     SDL_bool valid_format = SDL_FALSE;
     SDL_AudioFormat test_format;
-    int i;
-    float f;
     int result;
 
     /* based on parts of library_sdl.js */
@@ -293,29 +238,17 @@ EMSCRIPTENAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscaptu
     }
 
     /* Initialize all variables that we clean on shutdown */
+#if 0  /* !!! FIXME: currently not used. Can we move some stuff off the SDL2 namespace? --ryan. */
     this->hidden = (struct SDL_PrivateAudioData *)
         SDL_malloc((sizeof *this->hidden));
     if (this->hidden == NULL) {
         return SDL_OutOfMemory();
     }
     SDL_zerop(this->hidden);
+#endif
 
     /* limit to native freq */
-    const int sampleRate = EM_ASM_INT_V({
-        return SDL2.audioContext.sampleRate;
-    });
-
-    if(this->spec.freq != sampleRate) {
-        for (i = this->spec.samples; i > 0; i--) {
-            f = (float)i / (float)sampleRate * (float)this->spec.freq;
-            if (SDL_floor(f) == f) {
-                this->hidden->conv_in_len = SDL_floor(f);
-                break;
-            }
-        }
-
-        this->spec.freq = sampleRate;
-    }
+    this->spec.freq = EM_ASM_INT_V({ return SDL2.audioContext.sampleRate; });
 
     SDL_CalculateAudioSpec(&this->spec);
 
@@ -395,6 +328,9 @@ EMSCRIPTENAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscaptu
 static int
 EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl * impl)
 {
+    int available;
+    int capture_available;
+
     /* Set the function pointers */
     impl->OpenDevice = EMSCRIPTENAUDIO_OpenDevice;
     impl->CloseDevice = EMSCRIPTENAUDIO_CloseDevice;
@@ -406,7 +342,7 @@ EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl * impl)
     impl->ProvidesOwnCallbackThread = 1;
 
     /* check availability */
-    const int available = EM_ASM_INT_V({
+    available = EM_ASM_INT_V({
         if (typeof(AudioContext) !== 'undefined') {
             return 1;
         } else if (typeof(webkitAudioContext) !== 'undefined') {
@@ -419,7 +355,7 @@ EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl * impl)
         SDL_SetError("No audio context available");
     }
 
-    const int capture_available = available && EM_ASM_INT_V({
+    capture_available = available && EM_ASM_INT_V({
         if ((typeof(navigator.mediaDevices) !== 'undefined') && (typeof(navigator.mediaDevices.getUserMedia) !== 'undefined')) {
             return 1;
         } else if (typeof(navigator.webkitGetUserMedia) !== 'undefined') {
diff --git a/src/audio/emscripten/SDL_emscriptenaudio.h b/src/audio/emscripten/SDL_emscriptenaudio.h
index cd5377d..aeaef4a 100644
--- a/src/audio/emscripten/SDL_emscriptenaudio.h
+++ b/src/audio/emscripten/SDL_emscriptenaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_emscriptenaudio_h
-#define _SDL_emscriptenaudio_h
+#ifndef SDL_emscriptenaudio_h_
+#define SDL_emscriptenaudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -30,13 +30,9 @@
 
 struct SDL_PrivateAudioData
 {
-    Uint8 *mixbuf;
-    Uint32 mixlen;
-
-    Uint32 conv_in_len;
-
-    Uint32 write_off, read_off;
+    int unused;
 };
 
-#endif /* _SDL_emscriptenaudio_h */
+#endif /* SDL_emscriptenaudio_h_ */
+
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/esd/SDL_esdaudio.c b/src/audio/esd/SDL_esdaudio.c
index 3eb7197..849fe7c 100644
--- a/src/audio/esd/SDL_esdaudio.c
+++ b/src/audio/esd/SDL_esdaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/audio/esd/SDL_esdaudio.h b/src/audio/esd/SDL_esdaudio.h
index d362b16..fd4ca96 100644
--- a/src/audio/esd/SDL_esdaudio.h
+++ b/src/audio/esd/SDL_esdaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_esdaudio_h
-#define _SDL_esdaudio_h
+#ifndef SDL_esdaudio_h_
+#define SDL_esdaudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -46,5 +46,6 @@ struct SDL_PrivateAudioData
 };
 #define FUDGE_TICKS 10      /* The scheduler overhead ticks per frame */
 
-#endif /* _SDL_esdaudio_h */
+#endif /* SDL_esdaudio_h_ */
+
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/fusionsound/SDL_fsaudio.c b/src/audio/fusionsound/SDL_fsaudio.c
index daa0f9d..2c004bf 100644
--- a/src/audio/fusionsound/SDL_fsaudio.c
+++ b/src/audio/fusionsound/SDL_fsaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/audio/fusionsound/SDL_fsaudio.h b/src/audio/fusionsound/SDL_fsaudio.h
index 5cf8a20..67bd5c2 100644
--- a/src/audio/fusionsound/SDL_fsaudio.h
+++ b/src/audio/fusionsound/SDL_fsaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_fsaudio_h
-#define _SDL_fsaudio_h
+#ifndef SDL_fsaudio_h_
+#define SDL_fsaudio_h_
 
 #include <fusionsound/fusionsound.h>
 
@@ -45,5 +45,6 @@ struct SDL_PrivateAudioData
 
 };
 
-#endif /* _SDL_fsaudio_h */
+#endif /* SDL_fsaudio_h_ */
+
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/haiku/SDL_haikuaudio.cc b/src/audio/haiku/SDL_haikuaudio.cc
index 25b1fa2..96a7dd7 100644
--- a/src/audio/haiku/SDL_haikuaudio.cc
+++ b/src/audio/haiku/SDL_haikuaudio.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -36,6 +36,7 @@ extern "C"
 #include "../SDL_audio_c.h"
 #include "../SDL_sysaudio.h"
 #include "SDL_haikuaudio.h"
+#include "SDL_assert.h"
 
 }
 
@@ -47,26 +48,39 @@ FillSound(void *device, void *stream, size_t len,
           const media_raw_audio_format & format)
 {
     SDL_AudioDevice *audio = (SDL_AudioDevice *) device;
+    SDL_AudioCallback callback = audio->callbackspec.callback;
 
-    /* Only do soemthing if audio is enabled */
-    if (!SDL_AtomicGet(&audio->enabled)) {
+    /* Only do something if audio is enabled */
+    if (!SDL_AtomicGet(&audio->enabled) || SDL_AtomicGet(&audio->paused)) {
+        if (audio->stream) {
+            SDL_AudioStreamClear(audio->stream);
+        }
+        SDL_memset(stream, audio->spec.silence, len);
         return;
     }
 
-    if (!SDL_AtomicGet(&audio->paused)) {
-        if (audio->convert.needed) {
-            SDL_LockMutex(audio->mixer_lock);
-            (*audio->spec.callback) (audio->spec.userdata,
-                                     (Uint8 *) audio->convert.buf,
-                                     audio->convert.len);
-            SDL_UnlockMutex(audio->mixer_lock);
-            SDL_ConvertAudio(&audio->convert);
-            SDL_memcpy(stream, audio->convert.buf, audio->convert.len_cvt);
-        } else {
-            SDL_LockMutex(audio->mixer_lock);
-            (*audio->spec.callback) (audio->spec.userdata,
-                                     (Uint8 *) stream, len);
-            SDL_UnlockMutex(audio->mixer_lock);
+    SDL_assert(audio->spec.size == len);
+
+    if (audio->stream == NULL) {  /* no conversion necessary. */
+        SDL_LockMutex(audio->mixer_lock);
+        callback(audio->callbackspec.userdata, (Uint8 *) stream, len);
+        SDL_UnlockMutex(audio->mixer_lock);
+    } else {  /* streaming/converting */
+        const int stream_len = audio->callbackspec.size;
+        const int ilen = (int) len;
+        while (SDL_AudioStreamAvailable(audio->stream) < ilen) {
+            callback(audio->callbackspec.userdata, audio->work_buffer, stream_len);
+            if (SDL_AudioStreamPut(audio->stream, audio->work_buffer, stream_len) == -1) {
+                SDL_AudioStreamClear(audio->stream);
+                SDL_AtomicSet(&audio->enabled, 0);
+                break;
+            }
+        }
+
+        const int got = SDL_AudioStreamGet(audio->stream, stream, ilen);
+        SDL_assert((got < 0) || (got == ilen));
+        if (got != ilen) {
+            SDL_memset(stream, audio->spec.silence, len);
         }
     }
 }
diff --git a/src/audio/haiku/SDL_haikuaudio.h b/src/audio/haiku/SDL_haikuaudio.h
index 23e5a76..6ed5b26 100644
--- a/src/audio/haiku/SDL_haikuaudio.h
+++ b/src/audio/haiku/SDL_haikuaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_beaudio_h
-#define _SDL_beaudio_h
+#ifndef SDL_haikuaudio_h_
+#define SDL_haikuaudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -33,6 +33,6 @@ struct SDL_PrivateAudioData
     BSoundPlayer *audio_obj;
 };
 
-#endif /* _SDL_beaudio_h */
+#endif /* SDL_haikuaudio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/jack/SDL_jackaudio.c b/src/audio/jack/SDL_jackaudio.c
new file mode 100644
index 0000000..44a40e6
--- /dev/null
+++ b/src/audio/jack/SDL_jackaudio.c
@@ -0,0 +1,429 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+
+#if SDL_AUDIO_DRIVER_JACK
+
+#include "SDL_assert.h"
+#include "SDL_timer.h"
+#include "SDL_audio.h"
+#include "../SDL_audio_c.h"
+#include "SDL_jackaudio.h"
+#include "SDL_loadso.h"
+#include "../../thread/SDL_systhread.h"
+
+
+static jack_client_t * (*JACK_jack_client_open) (const char *, jack_options_t, jack_status_t *, ...);
+static int (*JACK_jack_client_close) (jack_client_t *);
+static void (*JACK_jack_on_shutdown) (jack_client_t *, JackShutdownCallback, void *);
+static int (*JACK_jack_activate) (jack_client_t *);
+static int (*JACK_jack_deactivate) (jack_client_t *);
+static void * (*JACK_jack_port_get_buffer) (jack_port_t *, jack_nframes_t);
+static int (*JACK_jack_port_unregister) (jack_client_t *, jack_port_t *);
+static void (*JACK_jack_free) (void *);
+static const char ** (*JACK_jack_get_ports) (jack_client_t *, const char *, const char *, unsigned long);
+static jack_nframes_t (*JACK_jack_get_sample_rate) (jack_client_t *);
+static jack_nframes_t (*JACK_jack_get_buffer_size) (jack_client_t *);
+static jack_port_t * (*JACK_jack_port_register) (jack_client_t *, const char *, const char *, unsigned long, unsigned long);
+static const char * (*JACK_jack_port_name) (const jack_port_t *);
+static int (*JACK_jack_connect) (jack_client_t *, const char *, const char *);
+static int (*JACK_jack_set_process_callback) (jack_client_t *, JackProcessCallback, void *);
+
+static int load_jack_syms(void);
+
+
+#ifdef SDL_AUDIO_DRIVER_JACK_DYNAMIC
+
+static const char *jack_library = SDL_AUDIO_DRIVER_JACK_DYNAMIC;
+static void *jack_handle = NULL;
+
+/* !!! FIXME: this is copy/pasted in several places now */
+static int
+load_jack_sym(const char *fn, void **addr)
+{
+    *addr = SDL_LoadFunction(jack_handle, fn);
+    if (*addr == NULL) {
+        /* Don't call SDL_SetError(): SDL_LoadFunction already did. */
+        return 0;
+    }
+
+    return 1;
+}
+
+/* cast funcs to char* first, to please GCC's strict aliasing rules. */
+#define SDL_JACK_SYM(x) \
+    if (!load_jack_sym(#x, (void **) (char *) &JACK_##x)) return -1
+
+static void
+UnloadJackLibrary(void)
+{
+    if (jack_handle != NULL) {
+        SDL_UnloadObject(jack_handle);
+        jack_handle = NULL;
+    }
+}
+
+static int
+LoadJackLibrary(void)
+{
+    int retval = 0;
+    if (jack_handle == NULL) {
+        jack_handle = SDL_LoadObject(jack_library);
+        if (jack_handle == NULL) {
+            retval = -1;
+            /* Don't call SDL_SetError(): SDL_LoadObject already did. */
+        } else {
+            retval = load_jack_syms();
+            if (retval < 0) {
+                UnloadJackLibrary();
+            }
+        }
+    }
+    return retval;
+}
+
+#else
+
+#define SDL_JACK_SYM(x) JACK_##x = x
+
+static void
+UnloadJackLibrary(void)
+{
+}
+
+static int
+LoadJackLibrary(void)
+{
+    load_jack_syms();
+    return 0;
+}
+
+#endif /* SDL_AUDIO_DRIVER_JACK_DYNAMIC */
+
+
+static int
+load_jack_syms(void)
+{
+    SDL_JACK_SYM(jack_client_open);
+    SDL_JACK_SYM(jack_client_close);
+    SDL_JACK_SYM(jack_on_shutdown);
+    SDL_JACK_SYM(jack_activate);
+    SDL_JACK_SYM(jack_deactivate);
+    SDL_JACK_SYM(jack_port_get_buffer);
+    SDL_JACK_SYM(jack_port_unregister);
+    SDL_JACK_SYM(jack_free);
+    SDL_JACK_SYM(jack_get_ports);
+    SDL_JACK_SYM(jack_get_sample_rate);
+    SDL_JACK_SYM(jack_get_buffer_size);
+    SDL_JACK_SYM(jack_port_register);
+    SDL_JACK_SYM(jack_port_name);
+    SDL_JACK_SYM(jack_connect);
+    SDL_JACK_SYM(jack_set_process_callback);
+    return 0;
+}
+
+
+static void
+jackShutdownCallback(void *arg)  /* JACK went away; device is lost. */
+{
+    SDL_AudioDevice *this = (SDL_AudioDevice *) arg;
+    SDL_OpenedAudioDeviceDisconnected(this);
+    SDL_SemPost(this->hidden->iosem);  /* unblock the SDL thread. */
+}
+
+// !!! FIXME: implement and register these!
+//typedef int(* JackSampleRateCallback)(jack_nframes_t nframes, void *arg)
+//typedef int(* JackBufferSizeCallback)(jack_nframes_t nframes, void *arg)
+
+static int
+jackProcessPlaybackCallback(jack_nframes_t nframes, void *arg)
+{
+    SDL_AudioDevice *this = (SDL_AudioDevice *) arg;
+    jack_port_t **ports = this->hidden->sdlports;
+    const int total_channels = this->spec.channels;
+    const int total_frames = this->spec.samples;
+    int channelsi;
+
+    if (!SDL_AtomicGet(&this->enabled)) {
+        /* silence the buffer to avoid repeats and corruption. */
+        SDL_memset(this->hidden->iobuffer, '\0', this->spec.size);
+    }
+
+    for (channelsi = 0; channelsi < total_channels; channelsi++) {
+        float *dst = (float *) JACK_jack_port_get_buffer(ports[channelsi], nframes);
+        if (dst) {
+            const float *src = ((float *) this->hidden->iobuffer) + channelsi;
+            int framesi;
+            for (framesi = 0; framesi < total_frames; framesi++) {
+                *(dst++) = *src;
+                src += total_channels;
+            }
+        }
+    }
+
+    SDL_SemPost(this->hidden->iosem);  /* tell SDL thread we're done; refill the buffer. */
+    return 0;  /* success */
+}
+
+
+/* This function waits until it is possible to write a full sound buffer */
+static void
+JACK_WaitDevice(_THIS)
+{
+    if (SDL_AtomicGet(&this->enabled)) {
+        if (SDL_SemWait(this->hidden->iosem) == -1) {
+            SDL_OpenedAudioDeviceDisconnected(this);
+        }
+    }
+}
+
+static Uint8 *
+JACK_GetDeviceBuf(_THIS)
+{
+    return (Uint8 *) this->hidden->iobuffer;
+}
+
+
+static int
+jackProcessCaptureCallback(jack_nframes_t nframes, void *arg)
+{
+    SDL_AudioDevice *this = (SDL_AudioDevice *) arg;
+    if (SDL_AtomicGet(&this->enabled)) {
+        jack_port_t **ports = this->hidden->sdlports;
+        const int total_channels = this->spec.channels;
+        const int total_frames = this->spec.samples;
+        int channelsi;
+    
+        for (channelsi = 0; channelsi < total_channels; channelsi++) {
+            const float *src = (const float *) JACK_jack_port_get_buffer(ports[channelsi], nframes);
+            if (src) {
+                float *dst = ((float *) this->hidden->iobuffer) + channelsi;
+                int framesi;
+                for (framesi = 0; framesi < total_frames; framesi++) {
+                    *dst = *(src++);
+                    dst += total_channels;
+                }
+            }
+        }
+    }
+
+    SDL_SemPost(this->hidden->iosem);  /* tell SDL thread we're done; new buffer is ready! */
+    return 0;  /* success */
+}
+
+static int
+JACK_CaptureFromDevice(_THIS, void *buffer, int buflen)
+{
+    SDL_assert(buflen == this->spec.size);  /* we always fill a full buffer. */
+
+    /* Wait for JACK to fill the iobuffer */
+    if (SDL_SemWait(this->hidden->iosem) == -1) {
+        return -1;
+    }
+
+    SDL_memcpy(buffer, this->hidden->iobuffer, buflen);
+    return buflen;
+}
+
+static void
+JACK_FlushCapture(_THIS)
+{
+    SDL_SemWait(this->hidden->iosem);
+}
+
+
+static void
+JACK_CloseDevice(_THIS)
+{
+    if (this->hidden->client) {
+        JACK_jack_deactivate(this->hidden->client);
+
+        if (this->hidden->sdlports) {
+            const int channels = this->spec.channels;
+            int i;
+            for (i = 0; i < channels; i++) {
+                JACK_jack_port_unregister(this->hidden->client, this->hidden->sdlports[i]);
+            }
+            SDL_free(this->hidden->sdlports);
+        }
+
+        JACK_jack_client_close(this->hidden->client);
+    }
+
+    if (this->hidden->iosem) {
+        SDL_DestroySemaphore(this->hidden->iosem);
+    }
+
+    if (this->hidden->devports) {
+        JACK_jack_free(this->hidden->devports);
+    }
+
+    SDL_free(this->hidden->iobuffer);
+}
+
+static int
+JACK_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
+{
+    /* Note that JACK uses "output" for capture devices (they output audio
+        data to us) and "input" for playback (we input audio data to them).
+        Likewise, SDL's playback port will be "output" (we write data out)
+        and capture will be "input" (we read data in). */
+    const unsigned long sysportflags = iscapture ? JackPortIsOutput : JackPortIsInput;
+    const unsigned long sdlportflags = iscapture ? JackPortIsInput : JackPortIsOutput;
+    const JackProcessCallback callback = iscapture ? jackProcessCaptureCallback : jackProcessPlaybackCallback;
+    const char *sdlportstr = iscapture ? "input" : "output";
+    const char **devports = NULL;
+    jack_client_t *client = NULL;
+    jack_status_t status;
+    int channels = 0;
+    int i;
+
+    /* Initialize all variables that we clean on shutdown */
+    this->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, sizeof (*this->hidden));
+    if (this->hidden == NULL) {
+        return SDL_OutOfMemory();
+    }
+
+    /* !!! FIXME: we _still_ need an API to specify an app name */
+    client = JACK_jack_client_open("SDL", JackNoStartServer, &status, NULL);
+    this->hidden->client = client;
+    if (client == NULL) {
+        return SDL_SetError("Can't open JACK client");
+    }
+
+    devports = JACK_jack_get_ports(client, NULL, NULL, JackPortIsPhysical | sysportflags);
+    this->hidden->devports = devports;
+    if (!devports || !devports[0]) {
+        return SDL_SetError("No physical JACK ports available");
+    }
+
+    while (devports[++channels]) {
+        /* spin to count devports */
+    }
+
+    /* !!! FIXME: docs say about buffer size: "This size may change, clients that depend on it must register a bufsize_callback so they will be notified if it does." */
+
+    /* Jack pretty much demands what it wants. */
+    this->spec.format = AUDIO_F32SYS;
+    this->spec.freq = JACK_jack_get_sample_rate(client);
+    this->spec.channels = channels;
+    this->spec.samples = JACK_jack_get_buffer_size(client);
+
+    SDL_CalculateAudioSpec(&this->spec);
+
+    this->hidden->iosem = SDL_CreateSemaphore(0);
+    if (!this->hidden->iosem) {
+        return -1;  /* error was set by SDL_CreateSemaphore */
+    }
+
+    this->hidden->iobuffer = (float *) SDL_calloc(1, this->spec.size);
+    if (!this->hidden->iobuffer) {
+        return SDL_OutOfMemory();
+    }
+
+    /* Build SDL's ports, which we will connect to the device ports. */
+    this->hidden->sdlports = (jack_port_t **) SDL_calloc(channels, sizeof (jack_port_t *));
+    if (this->hidden->sdlports == NULL) {
+        return SDL_OutOfMemory();
+    }
+
+    for (i = 0; i < channels; i++) {
+        char portname[32];
+        SDL_snprintf(portname, sizeof (portname), "sdl_jack_%s_%d", sdlportstr, i);
+        this->hidden->sdlports[i] = JACK_jack_port_register(client, portname, JACK_DEFAULT_AUDIO_TYPE, sdlportflags, 0);
+        if (this->hidden->sdlports[i] == NULL) {
+            return SDL_SetError("jack_port_register failed");
+        }
+    }
+
+    if (JACK_jack_set_process_callback(client, callback, this) != 0) {
+        return SDL_SetError("JACK: Couldn't set process callback");
+    }
+
+    JACK_jack_on_shutdown(client, jackShutdownCallback, this);
+
+    if (JACK_jack_activate(client) != 0) {
+        return SDL_SetError("Failed to activate JACK client");
+    }
+
+    /* once activated, we can connect all the ports. */
+    for (i = 0; i < channels; i++) {
+        const char *sdlport = JACK_jack_port_name(this->hidden->sdlports[i]);
+        const char *srcport = iscapture ? devports[i] : sdlport;
+        const char *dstport = iscapture ? sdlport : devports[i];
+        if (JACK_jack_connect(client, srcport, dstport) != 0) {
+            return SDL_SetError("Couldn't connect JACK ports: %s => %s", srcport, dstport);
+        }
+    }
+
+    /* don't need these anymore. */
+    this->hidden->devports = NULL;
+    JACK_jack_free(devports);
+
+    /* We're ready to rock and roll. :-) */
+    return 0;
+}
+
+static void
+JACK_Deinitialize(void)
+{
+    UnloadJackLibrary();
+}
+
+static int
+JACK_Init(SDL_AudioDriverImpl * impl)
+{
+    if (LoadJackLibrary() < 0) {
+        return 0;
+    } else {
+        /* Make sure a JACK server is running and available. */
+        jack_status_t status;
+        jack_client_t *client = JACK_jack_client_open("SDL", JackNoStartServer, &status, NULL);
+        if (client == NULL) {
+            UnloadJackLibrary();
+            return 0;
+        }
+        JACK_jack_client_close(client);
+    }
+
+    /* Set the function pointers */
+    impl->OpenDevice = JACK_OpenDevice;
+    impl->WaitDevice = JACK_WaitDevice;
+    impl->GetDeviceBuf = JACK_GetDeviceBuf;
+    impl->CloseDevice = JACK_CloseDevice;
+    impl->Deinitialize = JACK_Deinitialize;
+    impl->CaptureFromDevice = JACK_CaptureFromDevice;
+    impl->FlushCapture = JACK_FlushCapture;
+    impl->OnlyHasDefaultOutputDevice = SDL_TRUE;
+    impl->OnlyHasDefaultCaptureDevice = SDL_TRUE;
+    impl->HasCaptureSupport = SDL_TRUE;
+
+    return 1;   /* this audio target is available. */
+}
+
+AudioBootStrap JACK_bootstrap = {
+    "jack", "JACK Audio Connection Kit", JACK_Init, 0
+};
+
+#endif /* SDL_AUDIO_DRIVER_JACK */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/haiku/SDL_haikuaudio.h b/src/audio/jack/SDL_jackaudio.h
similarity index 76%
copy from src/audio/haiku/SDL_haikuaudio.h
copy to src/audio/jack/SDL_jackaudio.h
index 23e5a76..91fc696 100644
--- a/src/audio/haiku/SDL_haikuaudio.h
+++ b/src/audio/jack/SDL_jackaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,21 +18,25 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../../SDL_internal.h"
+#ifndef SDL_jackaudio_h_
+#define SDL_jackaudio_h_
 
-#ifndef _SDL_beaudio_h
-#define _SDL_beaudio_h
+#include <jack/jack.h>
 
 #include "../SDL_sysaudio.h"
 
 /* Hidden "this" pointer for the audio functions */
-#define _THIS   SDL_AudioDevice *_this
+#define _THIS SDL_AudioDevice *this
 
 struct SDL_PrivateAudioData
 {
-    BSoundPlayer *audio_obj;
+    jack_client_t *client;
+    SDL_sem *iosem;
+    float *iobuffer;
+    const char **devports;
+    jack_port_t **sdlports;
 };
 
-#endif /* _SDL_beaudio_h */
+#endif /* SDL_jackaudio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/nacl/SDL_naclaudio.c b/src/audio/nacl/SDL_naclaudio.c
index 33cbe1c..dc5930b 100644
--- a/src/audio/nacl/SDL_naclaudio.c
+++ b/src/audio/nacl/SDL_naclaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -45,29 +45,46 @@
 static void nacl_audio_callback(void* samples, uint32_t buffer_size, PP_TimeDelta latency, void* data);
 
 /* FIXME: Make use of latency if needed */
-static void nacl_audio_callback(void* samples, uint32_t buffer_size, PP_TimeDelta latency, void* data) {
+static void nacl_audio_callback(void* stream, uint32_t buffer_size, PP_TimeDelta latency, void* data) {
+    const int len = (int) buffer_size;
     SDL_AudioDevice* _this = (SDL_AudioDevice*) data;
+    SDL_AudioCallback callback = _this->callbackspec.callback;
     
     SDL_LockMutex(private->mutex);  /* !!! FIXME: is this mutex necessary? */
 
-    if (SDL_AtomicGet(&_this->enabled) && !SDL_AtomicGet(&_this->paused)) {
-        if (_this->convert.needed) {
-            SDL_LockMutex(_this->mixer_lock);
-            (*_this->spec.callback) (_this->spec.userdata,
-                                     (Uint8 *) _this->convert.buf,
-                                     _this->convert.len);
-            SDL_UnlockMutex(_this->mixer_lock);
-            SDL_ConvertAudio(&_this->convert);
-            SDL_memcpy(samples, _this->convert.buf, _this->convert.len_cvt);
-        } else {
-            SDL_LockMutex(_this->mixer_lock);
-            (*_this->spec.callback) (_this->spec.userdata, (Uint8 *) samples, buffer_size);
-            SDL_UnlockMutex(_this->mixer_lock);
+    /* Only do something if audio is enabled */
+    if (!SDL_AtomicGet(&_this->enabled) || SDL_AtomicGet(&_this->paused)) {
+        if (_this->stream) {
+            SDL_AudioStreamClear(_this->stream);
         }
-    } else {
-        SDL_memset(samples, _this->spec.silence, buffer_size);
+        SDL_memset(stream, _this->spec.silence, len);
+        return;
     }
-    
+
+    SDL_assert(_this->spec.size == len);
+
+    if (_this->stream == NULL) {  /* no conversion necessary. */
+        SDL_LockMutex(_this->mixer_lock);
+        callback(_this->callbackspec.userdata, stream, len);
+        SDL_UnlockMutex(_this->mixer_lock);
+    } else {  /* streaming/converting */
+        const int stream_len = _this->callbackspec.size;
+        while (SDL_AudioStreamAvailable(_this->stream) < len) {
+            callback(_this->callbackspec.userdata, _this->work_buffer, stream_len);
+            if (SDL_AudioStreamPut(_this->stream, _this->work_buffer, stream_len) == -1) {
+                SDL_AudioStreamClear(_this->stream);
+                SDL_AtomicSet(&_this->enabled, 0);
+                break;
+            }
+        }
+
+        const int got = SDL_AudioStreamGet(_this->stream, stream, len);
+        SDL_assert((got < 0) || (got == len));
+        if (got != len) {
+            SDL_memset(stream, _this->spec.silence, len);
+        }
+    }
+
     SDL_UnlockMutex(private->mutex);
 }
 
@@ -89,8 +106,7 @@ NACLAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) {
     
     private = (SDL_PrivateAudioData *) SDL_calloc(1, (sizeof *private));
     if (private == NULL) {
-        SDL_OutOfMemory();
-        return 0;
+        return SDL_OutOfMemory();
     }
     
     private->mutex = SDL_CreateMutex();
@@ -114,7 +130,7 @@ NACLAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) {
     /* Start audio playback while we are still on the main thread. */
     ppb_audio->StartPlayback(private->audio);
     
-    return 1;
+    return 0;
 }
 
 static int
diff --git a/src/audio/nacl/SDL_naclaudio.h b/src/audio/nacl/SDL_naclaudio.h
index 90ff544..12249ae 100644
--- a/src/audio/nacl/SDL_naclaudio.h
+++ b/src/audio/nacl/SDL_naclaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_naclaudio_h
-#define _SDL_naclaudio_h
+#ifndef SDL_naclaudio_h_
+#define SDL_naclaudio_h_
 
 #include "SDL_audio.h"
 #include "../SDL_sysaudio.h"
@@ -38,4 +38,6 @@ typedef struct SDL_PrivateAudioData {
   PP_Resource audio;
 } SDL_PrivateAudioData;
 
-#endif /* _SDL_naclaudio_h */
+#endif /* SDL_naclaudio_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/nas/SDL_nasaudio.c b/src/audio/nas/SDL_nasaudio.c
index fe15cd6..d5a0caa 100644
--- a/src/audio/nas/SDL_nasaudio.c
+++ b/src/audio/nas/SDL_nasaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -116,7 +116,7 @@ LoadNASLibrary(void)
             char *err = (char *) alloca(len);
             SDL_strlcpy(err, origerr, len);
             retval = -1;
-            SDL_SetError("NAS: SDL_LoadObject('%s') failed: %s\n",
+            SDL_SetError("NAS: SDL_LoadObject('%s') failed: %s",
                          nas_library, err);
         } else {
             retval = load_nas_syms();
diff --git a/src/audio/nas/SDL_nasaudio.h b/src/audio/nas/SDL_nasaudio.h
index 2f46b0b..343b452 100644
--- a/src/audio/nas/SDL_nasaudio.h
+++ b/src/audio/nas/SDL_nasaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_nasaudio_h
-#define _SDL_nasaudio_h
+#ifndef SDL_nasaudio_h_
+#define SDL_nasaudio_h_
 
 #ifdef __sgi
 #include <nas/audiolib.h>
@@ -51,6 +51,6 @@ struct SDL_PrivateAudioData
     struct timeval last_tv;
     int buf_free;
 };
-#endif /* _SDL_nasaudio_h */
+#endif /* SDL_nasaudio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/bsd/SDL_bsdaudio.c b/src/audio/netbsd/SDL_netbsdaudio.c
similarity index 88%
rename from src/audio/bsd/SDL_bsdaudio.c
rename to src/audio/netbsd/SDL_netbsdaudio.c
index 6a970b9..fc9aa03 100644
--- a/src/audio/bsd/SDL_bsdaudio.c
+++ b/src/audio/netbsd/SDL_netbsdaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,10 +20,10 @@
 */
 #include "../../SDL_internal.h"
 
-#if SDL_AUDIO_DRIVER_BSD
+#if SDL_AUDIO_DRIVER_NETBSD
 
 /*
- * Driver for native OpenBSD/NetBSD audio(4).
+ * Driver for native NetBSD audio(4).
  * vedge at vedge.com.ar.
  */
 
@@ -38,9 +38,10 @@
 
 #include "SDL_timer.h"
 #include "SDL_audio.h"
+#include "../../core/unix/SDL_poll.h"
 #include "../SDL_audio_c.h"
 #include "../SDL_audiodev_c.h"
-#include "SDL_bsdaudio.h"
+#include "SDL_netbsdaudio.h"
 
 /* Use timer for synchronization */
 /* #define USE_TIMER_SYNC */
@@ -50,14 +51,14 @@
 
 
 static void
-BSDAUDIO_DetectDevices(void)
+NETBSDAUDIO_DetectDevices(void)
 {
     SDL_EnumUnixAudioDevices(0, NULL);
 }
 
 
 static void
-BSDAUDIO_Status(_THIS)
+NETBSDAUDIO_Status(_THIS)
 {
 #ifdef DEBUG_AUDIO
     /* *INDENT-OFF* */
@@ -121,7 +122,7 @@ BSDAUDIO_Status(_THIS)
 
 /* This function waits until it is possible to write a full sound buffer */
 static void
-BSDAUDIO_WaitDevice(_THIS)
+NETBSDAUDIO_WaitDevice(_THIS)
 {
 #ifndef USE_BLOCKING_WRITES     /* Not necessary when using blocking writes */
     /* See if we need to use timed audio synchronization */
@@ -134,18 +135,11 @@ BSDAUDIO_WaitDevice(_THIS)
             SDL_Delay(ticks);
         }
     } else {
-        /* Use select() for audio synchronization */
-        fd_set fdset;
-        struct timeval timeout;
-
-        FD_ZERO(&fdset);
-        FD_SET(this->hidden->audio_fd, &fdset);
-        timeout.tv_sec = 10;
-        timeout.tv_usec = 0;
+        /* Use SDL_IOReady() for audio synchronization */
 #ifdef DEBUG_AUDIO
         fprintf(stderr, "Waiting for audio to get ready\n");
 #endif
-        if (select(this->hidden->audio_fd + 1, NULL, &fdset, NULL, &timeout)
+        if (SDL_IOReady(this->hidden->audio_fd, SDL_TRUE, 10 * 1000)
             <= 0) {
             const char *message =
                 "Audio timeout - buggy audio driver? (disabled)";
@@ -169,7 +163,7 @@ BSDAUDIO_WaitDevice(_THIS)
 }
 
 static void
-BSDAUDIO_PlayDevice(_THIS)
+NETBSDAUDIO_PlayDevice(_THIS)
 {
     int written, p = 0;
 
@@ -208,19 +202,19 @@ BSDAUDIO_PlayDevice(_THIS)
 }
 
 static Uint8 *
-BSDAUDIO_GetDeviceBuf(_THIS)
+NETBSDAUDIO_GetDeviceBuf(_THIS)
 {
     return (this->hidden->mixbuf);
 }
 
 
 static int
-BSDAUDIO_CaptureFromDevice(_THIS, void *_buffer, int buflen)
+NETBSDAUDIO_CaptureFromDevice(_THIS, void *_buffer, int buflen)
 {
     Uint8 *buffer = (Uint8 *) _buffer;
     int br, p = 0;
 
-    /* Write the audio data, checking for EAGAIN on broken audio drivers */
+    /* Capture the audio data, checking for EAGAIN on broken audio drivers */
     do {
         br = read(this->hidden->audio_fd, buffer + p, buflen - p);
         if (br > 0)
@@ -243,7 +237,7 @@ BSDAUDIO_CaptureFromDevice(_THIS, void *_buffer, int buflen)
 }
 
 static void
-BSDAUDIO_FlushCapture(_THIS)
+NETBSDAUDIO_FlushCapture(_THIS)
 {
     audio_info_t info;
     size_t remain;
@@ -265,7 +259,7 @@ BSDAUDIO_FlushCapture(_THIS)
 }
 
 static void
-BSDAUDIO_CloseDevice(_THIS)
+NETBSDAUDIO_CloseDevice(_THIS)
 {
     if (this->hidden->audio_fd >= 0) {
         close(this->hidden->audio_fd);
@@ -275,7 +269,7 @@ BSDAUDIO_CloseDevice(_THIS)
 }
 
 static int
-BSDAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
+NETBSDAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
 {
     const int flags = iscapture ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT;
     SDL_AudioFormat format = 0;
@@ -383,24 +377,24 @@ BSDAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
         SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);
     }
 
-    BSDAUDIO_Status(this);
+    NETBSDAUDIO_Status(this);
 
     /* We're ready to rock and roll. :-) */
     return 0;
 }
 
 static int
-BSDAUDIO_Init(SDL_AudioDriverImpl * impl)
+NETBSDAUDIO_Init(SDL_AudioDriverImpl * impl)
 {
     /* Set the function pointers */
-    impl->DetectDevices = BSDAUDIO_DetectDevices;
-    impl->OpenDevice = BSDAUDIO_OpenDevice;
-    impl->PlayDevice = BSDAUDIO_PlayDevice;
-    impl->WaitDevice = BSDAUDIO_WaitDevice;
-    impl->GetDeviceBuf = BSDAUDIO_GetDeviceBuf;
-    impl->CloseDevice = BSDAUDIO_CloseDevice;
-    impl->CaptureFromDevice = BSDAUDIO_CaptureFromDevice;
-    impl->FlushCapture = BSDAUDIO_FlushCapture;
+    impl->DetectDevices = NETBSDAUDIO_DetectDevices;
+    impl->OpenDevice = NETBSDAUDIO_OpenDevice;
+    impl->PlayDevice = NETBSDAUDIO_PlayDevice;
+    impl->WaitDevice = NETBSDAUDIO_WaitDevice;
+    impl->GetDeviceBuf = NETBSDAUDIO_GetDeviceBuf;
+    impl->CloseDevice = NETBSDAUDIO_CloseDevice;
+    impl->CaptureFromDevice = NETBSDAUDIO_CaptureFromDevice;
+    impl->FlushCapture = NETBSDAUDIO_FlushCapture;
 
     impl->HasCaptureSupport = SDL_TRUE;
     impl->AllowsArbitraryDeviceNames = 1;
@@ -409,10 +403,10 @@ BSDAUDIO_Init(SDL_AudioDriverImpl * impl)
 }
 
 
-AudioBootStrap BSD_AUDIO_bootstrap = {
-    "bsd", "BSD audio", BSDAUDIO_Init, 0
+AudioBootStrap NETBSDAUDIO_bootstrap = {
+    "netbsd", "NetBSD audio", NETBSDAUDIO_Init, 0
 };
 
-#endif /* SDL_AUDIO_DRIVER_BSD */
+#endif /* SDL_AUDIO_DRIVER_NETBSD */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/bsd/SDL_bsdaudio.h b/src/audio/netbsd/SDL_netbsdaudio.h
similarity index 81%
rename from src/audio/bsd/SDL_bsdaudio.h
rename to src/audio/netbsd/SDL_netbsdaudio.h
index 7fe141b..a4ec89c 100644
--- a/src/audio/bsd/SDL_bsdaudio.h
+++ b/src/audio/netbsd/SDL_netbsdaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_bsdaudio_h
-#define _SDL_bsdaudio_h
+#ifndef SDL_netbsdaudio_h_
+#define SDL_netbsdaudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -32,20 +32,17 @@ struct SDL_PrivateAudioData
     /* The file descriptor for the audio device */
     int audio_fd;
 
-    /* The parent process id, to detect when application quits */
-    pid_t parent;
-
     /* Raw mixing buffer */
     Uint8 *mixbuf;
     int mixlen;
 
-    /* Support for audio timing using a timer, in addition to select() */
+    /* Support for audio timing using a timer, in addition to SDL_IOReady() */
     float frame_ticks;
     float next_frame;
 };
 
 #define FUDGE_TICKS 10      /* The scheduler overhead ticks per frame */
 
-#endif /* _SDL_bsdaudio_h */
+#endif /* SDL_netbsdaudio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/paudio/SDL_paudio.c b/src/audio/paudio/SDL_paudio.c
index 5720224..cd9eb11 100644
--- a/src/audio/paudio/SDL_paudio.c
+++ b/src/audio/paudio/SDL_paudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -36,9 +36,10 @@
 #include "SDL_audio.h"
 #include "SDL_stdinc.h"
 #include "../SDL_audio_c.h"
+#include "../../core/unix/SDL_poll.h"
 #include "SDL_paudio.h"
 
-#define DEBUG_AUDIO 0
+/* #define DEBUG_AUDIO */
 
 /* A conflict within AIX 4.3.3 <sys/> headers and probably others as well.
  * I guess nobody ever uses audio... Shame over AIX header files.  */
@@ -137,44 +138,31 @@ PAUDIO_WaitDevice(_THIS)
             SDL_Delay(ticks);
         }
     } else {
+        int timeoutMS;
         audio_buffer paud_bufinfo;
 
-        /* Use select() for audio synchronization */
-        struct timeval timeout;
-        FD_ZERO(&fdset);
-        FD_SET(this->hidden->audio_fd, &fdset);
-
         if (ioctl(this->hidden->audio_fd, AUDIO_BUFFER, &paud_bufinfo) < 0) {
 #ifdef DEBUG_AUDIO
             fprintf(stderr, "Couldn't get audio buffer information\n");
 #endif
-            timeout.tv_sec = 10;
-            timeout.tv_usec = 0;
+            timeoutMS = 10 * 1000;
         } else {
-            long ms_in_buf = paud_bufinfo.write_buf_time;
-            timeout.tv_sec = ms_in_buf / 1000;
-            ms_in_buf = ms_in_buf - timeout.tv_sec * 1000;
-            timeout.tv_usec = ms_in_buf * 1000;
+            timeoutMS = paud_bufinfo.write_buf_time;
 #ifdef DEBUG_AUDIO
-            fprintf(stderr,
-                    "Waiting for write_buf_time=%ld,%ld\n",
-                    timeout.tv_sec, timeout.tv_usec);
+            fprintf(stderr, "Waiting for write_buf_time=%d ms\n", timeoutMS);
 #endif
         }
 
 #ifdef DEBUG_AUDIO
         fprintf(stderr, "Waiting for audio to get ready\n");
 #endif
-        if (select(this->hidden->audio_fd + 1, NULL, &fdset, NULL, &timeout)
-            <= 0) {
-            const char *message =
-                "Audio timeout - buggy audio driver? (disabled)";
+        if (SDL_IOReady(this->hidden->audio_fd, SDL_TRUE, timeoutMS) <= 0) {
             /*
              * In general we should never print to the screen,
              * but in this case we have no other way of letting
              * the user know what happened.
              */
-            fprintf(stderr, "SDL: %s - %s\n", strerror(errno), message);
+            fprintf(stderr, "SDL: %s - Audio timeout - buggy audio driver? (disabled)\n", strerror(errno));
             SDL_OpenedAudioDeviceDisconnected(this);
             /* Don't try to close - may hang */
             this->hidden->audio_fd = -1;
@@ -245,7 +233,6 @@ PAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
     SDL_AudioFormat test_format;
     audio_init paud_init;
     audio_buffer paud_bufinfo;
-    audio_status paud_status;
     audio_control paud_control;
     audio_change paud_change;
     int fd = -1;
@@ -487,7 +474,7 @@ PAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
         return SDL_SetError("Can't start audio play");
     }
 
-    /* Check to see if we need to use select() workaround */
+    /* Check to see if we need to use SDL_IOReady() workaround */
     if (workaround != NULL) {
         this->hidden->frame_ticks = (float) (this->spec.samples * 1000) /
             this->spec.freq;
@@ -510,11 +497,11 @@ PAUDIO_Init(SDL_AudioDriverImpl * impl)
     close(fd);
 
     /* Set the function pointers */
-    impl->OpenDevice = DSP_OpenDevice;
-    impl->PlayDevice = DSP_PlayDevice;
-    impl->PlayDevice = DSP_WaitDevice;
-    impl->GetDeviceBuf = DSP_GetDeviceBuf;
-    impl->CloseDevice = DSP_CloseDevice;
+    impl->OpenDevice = PAUDIO_OpenDevice;
+    impl->PlayDevice = PAUDIO_PlayDevice;
+    impl->PlayDevice = PAUDIO_WaitDevice;
+    impl->GetDeviceBuf = PAUDIO_GetDeviceBuf;
+    impl->CloseDevice = PAUDIO_CloseDevice;
     impl->OnlyHasDefaultOutputDevice = 1;       /* !!! FIXME: add device enum! */
 
     return 1;   /* this audio target is available. */
diff --git a/src/audio/paudio/SDL_paudio.h b/src/audio/paudio/SDL_paudio.h
index ebc8bb5..c2938ee 100644
--- a/src/audio/paudio/SDL_paudio.h
+++ b/src/audio/paudio/SDL_paudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_paudaudio_h
-#define _SDL_paudaudio_h
+#ifndef SDL_paudio_h_
+#define SDL_paudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -37,11 +37,12 @@ struct SDL_PrivateAudioData
     Uint8 *mixbuf;
     int mixlen;
 
-    /* Support for audio timing using a timer, in addition to select() */
+    /* Support for audio timing using a timer, in addition to SDL_IOReady() */
     float frame_ticks;
     float next_frame;
 };
 #define FUDGE_TICKS 10      /* The scheduler overhead ticks per frame */
 
-#endif /* _SDL_paudaudio_h */
+#endif /* SDL_paudio_h_ */
+
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/psp/SDL_pspaudio.c b/src/audio/psp/SDL_pspaudio.c
index bd3456d..83b7bcb 100644
--- a/src/audio/psp/SDL_pspaudio.c
+++ b/src/audio/psp/SDL_pspaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -80,6 +80,7 @@ PSPAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
     if (this->spec.channels == 1) {
         format = PSP_AUDIO_FORMAT_MONO;
     } else {
+        this->spec.channels = 2;
         format = PSP_AUDIO_FORMAT_STEREO;
     }
     this->hidden->channel = sceAudioChReserve(PSP_AUDIO_NEXT_CHANNEL, this->spec.samples, format);
diff --git a/src/audio/psp/SDL_pspaudio.h b/src/audio/psp/SDL_pspaudio.h
index 6b266bd..df56d82 100644
--- a/src/audio/psp/SDL_pspaudio.h
+++ b/src/audio/psp/SDL_pspaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_pspaudio_h
-#define _SDL_pspaudio_h
+#ifndef SDL_pspaudio_h_
+#define SDL_pspaudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -40,6 +40,6 @@ struct SDL_PrivateAudioData {
     int     next_buffer;
 };
 
-#endif /* _SDL_pspaudio_h */
-/* vim: ts=4 sw=4
- */
+#endif /* SDL_pspaudio_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/pulseaudio/SDL_pulseaudio.c b/src/audio/pulseaudio/SDL_pulseaudio.c
index 9ced49d..b7d1bfe 100644
--- a/src/audio/pulseaudio/SDL_pulseaudio.c
+++ b/src/audio/pulseaudio/SDL_pulseaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -37,7 +37,6 @@
 #endif
 #include <unistd.h>
 #include <sys/types.h>
-#include <errno.h>
 #include <pulse/pulseaudio.h>
 
 #include "SDL_timer.h"
diff --git a/src/audio/pulseaudio/SDL_pulseaudio.h b/src/audio/pulseaudio/SDL_pulseaudio.h
index e12000f..6e45a9e 100644
--- a/src/audio/pulseaudio/SDL_pulseaudio.h
+++ b/src/audio/pulseaudio/SDL_pulseaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_pulseaudio_h
-#define _SDL_pulseaudio_h
+#ifndef SDL_pulseaudio_h_
+#define SDL_pulseaudio_h_
 
 #include <pulse/simple.h>
 
@@ -47,6 +47,6 @@ struct SDL_PrivateAudioData
     int capturelen;
 };
 
-#endif /* _SDL_pulseaudio_h */
+#endif /* SDL_pulseaudio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/qsa/SDL_qsa_audio.c b/src/audio/qsa/SDL_qsa_audio.c
index 149cad9..0c77799 100644
--- a/src/audio/qsa/SDL_qsa_audio.c
+++ b/src/audio/qsa/SDL_qsa_audio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -45,6 +45,7 @@
 
 #include "SDL_timer.h"
 #include "SDL_audio.h"
+#include "../../core/unix/SDL_poll.h"
 #include "../SDL_audio_c.h"
 #include "SDL_qsa_audio.h"
 
@@ -56,24 +57,6 @@
 #define DEFAULT_CPARAMS_FRAGS_MIN 1
 #define DEFAULT_CPARAMS_FRAGS_MAX 1
 
-#define QSA_NO_WORKAROUNDS  0x00000000
-#define QSA_MMAP_WORKAROUND 0x00000001
-
-struct BuggyCards
-{
-    char *cardname;
-    unsigned long bugtype;
-};
-
-#define QSA_WA_CARDS             3
-#define QSA_MAX_CARD_NAME_LENGTH 33
-
-struct BuggyCards buggycards[QSA_WA_CARDS] = {
-    {"Sound Blaster Live!", QSA_MMAP_WORKAROUND},
-    {"Vortex 8820", QSA_MMAP_WORKAROUND},
-    {"Vortex 8830", QSA_MMAP_WORKAROUND},
-};
-
 /* List of found devices */
 #define QSA_MAX_DEVICES       32
 #define QSA_MAX_NAME_LENGTH   81+16     /* Hardcoded in QSA, can't be changed */
@@ -97,40 +80,16 @@ QSA_SetError(const char *fn, int status)
     return SDL_SetError("QSA: %s() failed: %s", fn, snd_strerror(status));
 }
 
-/* card names check to apply the workarounds */
-static int
-QSA_CheckBuggyCards(_THIS, unsigned long checkfor)
-{
-    char scardname[QSA_MAX_CARD_NAME_LENGTH];
-    int it;
-
-    if (snd_card_get_name
-        (this->hidden->cardno, scardname, QSA_MAX_CARD_NAME_LENGTH - 1) < 0) {
-        return 0;
-    }
-
-    for (it = 0; it < QSA_WA_CARDS; it++) {
-        if (SDL_strcmp(buggycards[it].cardname, scardname) == 0) {
-            if (buggycards[it].bugtype == checkfor) {
-                return 1;
-            }
-        }
-    }
-
-    return 0;
-}
-
 /* !!! FIXME: does this need to be here? Does the SDL version not work? */
 static void
 QSA_ThreadInit(_THIS)
 {
-    struct sched_param param;
-    int status;
-
     /* Increase default 10 priority to 25 to avoid jerky sound */
-    status = SchedGet(0, 0, &param);
-    param.sched_priority = param.sched_curpriority + 15;
-    status = SchedSet(0, 0, SCHED_NOCHANGE, &param);
+    struct sched_param param;
+    if (SchedGet(0, 0, &param) != -1) {
+        param.sched_priority = param.sched_curpriority + 15;
+        SchedSet(0, 0, SCHED_NOCHANGE, &param);
+    }
 }
 
 /* PCM channel parameters initialize function */
@@ -155,67 +114,25 @@ QSA_InitAudioParams(snd_pcm_channel_params_t * cpars)
 static void
 QSA_WaitDevice(_THIS)
 {
-    fd_set wfds;
-    fd_set rfds;
-    int selectret;
-    struct timeval timeout;
-
-    if (!this->hidden->iscapture) {
-        FD_ZERO(&wfds);
-        FD_SET(this->hidden->audio_fd, &wfds);
-    } else {
-        FD_ZERO(&rfds);
-        FD_SET(this->hidden->audio_fd, &rfds);
-    }
-
-    do {
-        /* Setup timeout for playing one fragment equal to 2 seconds          */
-        /* If timeout occured than something wrong with hardware or driver    */
-        /* For example, Vortex 8820 audio driver stucks on second DAC because */
-        /* it doesn't exist !                                                 */
-        timeout.tv_sec = 2;
-        timeout.tv_usec = 0;
+    int result;
+
+    /* Setup timeout for playing one fragment equal to 2 seconds          */
+    /* If timeout occured than something wrong with hardware or driver    */
+    /* For example, Vortex 8820 audio driver stucks on second DAC because */
+    /* it doesn't exist !                                                 */
+    result = SDL_IOReady(this->hidden->audio_fd, !this->hidden->iscapture, 2 * 1000);
+    switch (result) {
+    case -1:
+        SDL_SetError("QSA: SDL_IOReady() failed: %s", strerror(errno));
+        break;
+    case 0:
+        SDL_SetError("QSA: timeout on buffer waiting occured");
+        this->hidden->timeout_on_wait = 1;
+        break;
+    default:
         this->hidden->timeout_on_wait = 0;
-
-        if (!this->hidden->iscapture) {
-            selectret =
-                select(this->hidden->audio_fd + 1, NULL, &wfds, NULL,
-                       &timeout);
-        } else {
-            selectret =
-                select(this->hidden->audio_fd + 1, &rfds, NULL, NULL,
-                       &timeout);
-        }
-
-        switch (selectret) {
-        case -1:
-            {
-                SDL_SetError("QSA: select() failed: %s", strerror(errno));
-                return;
-            }
-            break;
-        case 0:
-            {
-                SDL_SetError("QSA: timeout on buffer waiting occured");
-                this->hidden->timeout_on_wait = 1;
-                return;
-            }
-            break;
-        default:
-            {
-                if (!this->hidden->iscapture) {
-                    if (FD_ISSET(this->hidden->audio_fd, &wfds)) {
-                        return;
-                    }
-                } else {
-                    if (FD_ISSET(this->hidden->audio_fd, &rfds)) {
-                        return;
-                    }
-                }
-            }
-            break;
-        }
-    } while (1);
+        break;
+    }
 }
 
 static void
@@ -357,7 +274,6 @@ QSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
     if (this->hidden == NULL) {
         return SDL_OutOfMemory();
     }
-    SDL_zerop(this->hidden);
 
     /* Initialize channel transfer parameters to default */
     QSA_InitAudioParams(&cparams);
@@ -371,13 +287,13 @@ QSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
         this->hidden->cardno = device->cardno;
         status = snd_pcm_open(&this->hidden->audio_handle,
                               device->cardno, device->deviceno,
-                              iscapture ? SND_PCM_OPEN_PLAYBACK : SND_PCM_OPEN_CAPTURE);
+                              iscapture ? SND_PCM_OPEN_CAPTURE : SND_PCM_OPEN_PLAYBACK);
     } else {
         /* Open system default audio device */
         status = snd_pcm_open_preferred(&this->hidden->audio_handle,
                                         &this->hidden->cardno,
                                         &this->hidden->deviceno,
-                                        iscapture ? SND_PCM_OPEN_PLAYBACK : SND_PCM_OPEN_CAPTURE);
+                                        iscapture ? SND_PCM_OPEN_CAPTURE : SND_PCM_OPEN_PLAYBACK);
     }
 
     /* Check if requested device is opened */
@@ -386,16 +302,6 @@ QSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
         return QSA_SetError("snd_pcm_open", status);
     }
 
-    if (!QSA_CheckBuggyCards(this, QSA_MMAP_WORKAROUND)) {
-        /* Disable QSA MMAP plugin for buggy audio drivers */
-        status =
-            snd_pcm_plugin_set_disable(this->hidden->audio_handle,
-                                       PLUGIN_DISABLE_MMAP);
-        if (status < 0) {
-            return QSA_SetError("snd_pcm_plugin_set_disable", status);
-        }
-    }
-
     /* Try for a closest match on audio format */
     format = 0;
     /* can't use format as SND_PCM_SFMT_U8 = 0 in qsa */
@@ -494,7 +400,7 @@ QSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
     /* Setup the transfer parameters according to cparams */
     status = snd_pcm_plugin_params(this->hidden->audio_handle, &cparams);
     if (status < 0) {
-        return QSA_SetError("snd_pcm_channel_params", status);
+        return QSA_SetError("snd_pcm_plugin_params", status);
     }
 
     /* Make sure channel is setup right one last time */
@@ -722,9 +628,6 @@ QSA_Deinitialize(void)
 static int
 QSA_Init(SDL_AudioDriverImpl * impl)
 {
-    snd_pcm_t *handle = NULL;
-    int32_t status = 0;
-
     /* Clear devices array */
     SDL_zero(qsa_playback_device);
     SDL_zero(qsa_capture_device);
@@ -745,20 +648,12 @@ QSA_Init(SDL_AudioDriverImpl * impl)
     impl->LockDevice = NULL;
     impl->UnlockDevice = NULL;
 
-    impl->OnlyHasDefaultOutputDevice = 0;
     impl->ProvidesOwnCallbackThread = 0;
     impl->SkipMixerLock = 0;
     impl->HasCaptureSupport = 1;
     impl->OnlyHasDefaultOutputDevice = 0;
     impl->OnlyHasDefaultCaptureDevice = 0;
 
-    /* Check if io-audio manager is running or not */
-    status = snd_cards();
-    if (status == 0) {
-        /* if no, return immediately */
-        return 1;
-    }
-
     return 1;   /* this audio target is available. */
 }
 
diff --git a/src/audio/qsa/SDL_qsa_audio.h b/src/audio/qsa/SDL_qsa_audio.h
index 19a2215..a5b4946 100644
--- a/src/audio/qsa/SDL_qsa_audio.h
+++ b/src/audio/qsa/SDL_qsa_audio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/audio/sdlgenaudiocvt.pl b/src/audio/sdlgenaudiocvt.pl
deleted file mode 100755
index c53f1c3..0000000
--- a/src/audio/sdlgenaudiocvt.pl
+++ /dev/null
@@ -1,761 +0,0 @@
-#!/usr/bin/perl -w
-
-use warnings;
-use strict;
-
-my @audiotypes = qw(
-    U8
-    S8
-    U16LSB
-    S16LSB
-    U16MSB
-    S16MSB
-    S32LSB
-    S32MSB
-    F32LSB
-    F32MSB
-);
-
-my @channels = ( 1, 2, 4, 6, 8 );
-my %funcs;
-my $custom_converters = 0;
-
-
-sub getTypeConvertHashId {
-    my ($from, $to) = @_;
-    return "TYPECONVERTER $from/$to";
-}
-
-
-sub getResamplerHashId {
-    my ($from, $channels, $upsample, $multiple) = @_;
-    return "RESAMPLER $from/$channels/$upsample/$multiple";
-}
-
-
-sub outputHeader {
-    print <<EOF;
-/* DO NOT EDIT!  This file is generated by sdlgenaudiocvt.pl */
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken\@libsdl.org>
-
-  This software is provided 'as-is', without any express or implied
-  warranty.  In no event will the authors be held liable for any damages
-  arising from the use of this software.
-
-  Permission is granted to anyone to use this software for any purpose,
-  including commercial applications, and to alter it and redistribute it
-  freely, subject to the following restrictions:
-
-  1. The origin of this software must not be misrepresented; you must not
-     claim that you wrote the original software. If you use this software
-     in a product, an acknowledgment in the product documentation would be
-     appreciated but is not required.
-  2. Altered source versions must be plainly marked as such, and must not be
-     misrepresented as being the original software.
-  3. This notice may not be removed or altered from any source distribution.
-*/
-
-#include "../SDL_internal.h"
-#include "SDL_audio.h"
-#include "SDL_audio_c.h"
-
-#ifndef DEBUG_CONVERT
-#define DEBUG_CONVERT 0
-#endif
-
-
-/* If you can guarantee your data and need space, you can eliminate code... */
-
-/* Just build the arbitrary resamplers if you're saving code space. */
-#ifndef LESS_RESAMPLERS
-#define LESS_RESAMPLERS 0
-#endif
-
-/* Don't build any resamplers if you're REALLY saving code space. */
-#ifndef NO_RESAMPLERS
-#define NO_RESAMPLERS 0
-#endif
-
-/* Don't build any type converters if you're saving code space. */
-#ifndef NO_CONVERTERS
-#define NO_CONVERTERS 0
-#endif
-
-
-/* *INDENT-OFF* */
-
-EOF
-
-    my @vals = ( 127, 32767, 2147483647 );
-    foreach (@vals) {
-        my $val = $_;
-        my $fval = 1.0 / $val;
-        print("#define DIVBY${val} ${fval}f\n");
-    }
-
-    print("\n");
-}
-
-sub outputFooter {
-    print <<EOF;
-/* $custom_converters converters generated. */
-
-/* *INDENT-ON* */
-
-/* vi: set ts=4 sw=4 expandtab: */
-EOF
-}
-
-sub splittype {
-    my $t = shift;
-    my ($signed, $size, $endian) = $t =~ /([USF])(\d+)([LM]SB|)/;
-    my $float = ($signed eq 'F') ? 1 : 0;
-    $signed = (($float) or ($signed eq 'S')) ? 1 : 0;
-    $endian = 'NONE' if ($endian eq '');
-
-    my $ctype = '';
-    if ($float) {
-        $ctype = (($size == 32) ? 'float' : 'double');
-    } else {
-        $ctype = (($signed) ? 'S' : 'U') . "int${size}";
-    }
-
-    return ($signed, $float, $size, $endian, $ctype);
-}
-
-sub getSwapFunc {
-    my ($size, $signed, $float, $endian, $val) = @_;
-    my $BEorLE = (($endian eq 'MSB') ? 'BE' : 'LE');
-    my $code = '';
-
-    if ($float) {
-        $code = "SDL_SwapFloat${BEorLE}($val)";
-    } else {
-        if ($size > 8) {
-            $code = "SDL_Swap${BEorLE}${size}($val)";
-        } else {
-            $code = $val;
-        }
-
-        if (($signed) and (!$float)) {
-            $code = "((Sint${size}) $code)";
-        }
-    }
-
-    return "${code}";
-}
-
-
-sub maxIntVal {
-    my $size = shift;
-    if ($size == 8) {
-        return 0x7F;
-    } elsif ($size == 16) {
-        return 0x7FFF;
-    } elsif ($size == 32) {
-        return 0x7FFFFFFF;
-    }
-
-    die("bug in script.\n");
-}
-
-sub getFloatToIntMult {
-    my $size = shift;
-    my $val = maxIntVal($size) . '.0';
-    $val .= 'f' if ($size < 32);
-    return $val;
-}
-
-sub getIntToFloatDivBy {
-    my $size = shift;
-    return 'DIVBY' . maxIntVal($size);
-}
-
-sub getSignFlipVal {
-    my $size = shift;
-    if ($size == 8) {
-        return '0x80';
-    } elsif ($size == 16) {
-        return '0x8000';
-    } elsif ($size == 32) {
-        return '0x80000000';
-    }
-
-    die("bug in script.\n");
-}
-
-sub buildCvtFunc {
-    my ($from, $to) = @_;
-    my ($fsigned, $ffloat, $fsize, $fendian, $fctype) = splittype($from);
-    my ($tsigned, $tfloat, $tsize, $tendian, $tctype) = splittype($to);
-    my $diffs = 0;
-    $diffs++ if ($fsize != $tsize);
-    $diffs++ if ($fsigned != $tsigned);
-    $diffs++ if ($ffloat != $tfloat);
-    $diffs++ if ($fendian ne $tendian);
-
-    return if ($diffs == 0);
-
-    my $hashid = getTypeConvertHashId($from, $to);
-    if (1) { # !!! FIXME: if ($diffs > 1) {
-        my $sym = "SDL_Convert_${from}_to_${to}";
-        $funcs{$hashid} = $sym;
-        $custom_converters++;
-
-        # Always unsigned for ints, for possible byteswaps.
-        my $srctype = (($ffloat) ? 'float' : "Uint${fsize}");
-
-        print <<EOF;
-static void SDLCALL
-${sym}(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-    int i;
-    const $srctype *src;
-    $tctype *dst;
-
-#if DEBUG_CONVERT
-    fprintf(stderr, "Converting AUDIO_${from} to AUDIO_${to}.\\n");
-#endif
-
-EOF
-
-        if ($fsize < $tsize) {
-            my $mult = $tsize / $fsize;
-            print <<EOF;
-    src = ((const $srctype *) (cvt->buf + cvt->len_cvt)) - 1;
-    dst = (($tctype *) (cvt->buf + cvt->len_cvt * $mult)) - 1;
-    for (i = cvt->len_cvt / sizeof ($srctype); i; --i, --src, --dst) {
-EOF
-        } else {
-            print <<EOF;
-    src = (const $srctype *) cvt->buf;
-    dst = ($tctype *) cvt->buf;
-    for (i = cvt->len_cvt / sizeof ($srctype); i; --i, ++src, ++dst) {
-EOF
-        }
-
-        # Have to convert to/from float/int.
-        # !!! FIXME: cast through double for int32<->float?
-        my $code = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, '*src');
-        if ($ffloat != $tfloat) {
-            if ($ffloat) {
-                my $mult = getFloatToIntMult($tsize);
-                if (!$tsigned) {   # bump from -1.0f/1.0f to 0.0f/2.0f
-                    $code = "($code + 1.0f)";
-                }
-                $code = "(($tctype) ($code * $mult))";
-            } else {
-                # $divby will be the reciprocal, to avoid pipeline stalls
-                #  from floating point division...so multiply it.
-                my $divby = getIntToFloatDivBy($fsize);
-                $code = "(((float) $code) * $divby)";
-                if (!$fsigned) {   # bump from 0.0f/2.0f to -1.0f/1.0f.
-                    $code = "($code - 1.0f)";
-                }
-            }
-        } else {
-            # All integer conversions here.
-            if ($fsigned != $tsigned) {
-                my $signflipval = getSignFlipVal($fsize);
-                $code = "(($code) ^ $signflipval)";
-            }
-
-            my $shiftval = abs($fsize - $tsize);
-            if ($fsize < $tsize) {
-                $code = "((($tctype) $code) << $shiftval)";
-            } elsif ($fsize > $tsize) {
-                $code = "(($tctype) ($code >> $shiftval))";
-            }
-        }
-
-        my $swap = getSwapFunc($tsize, $tsigned, $tfloat, $tendian, 'val');
-
-        print <<EOF;
-        const $tctype val = $code;
-        *dst = ${swap};
-    }
-
-EOF
-
-        if ($fsize > $tsize) {
-            my $divby = $fsize / $tsize;
-            print("    cvt->len_cvt /= $divby;\n");
-        } elsif ($fsize < $tsize) {
-            my $mult = $tsize / $fsize;
-            print("    cvt->len_cvt *= $mult;\n");
-        }
-
-        print <<EOF;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, AUDIO_$to);
-    }
-}
-
-EOF
-
-    } else {
-        if ($fsigned != $tsigned) {
-            $funcs{$hashid} = 'SDL_ConvertSigned';
-        } elsif ($ffloat != $tfloat) {
-            $funcs{$hashid} = 'SDL_ConvertFloat';
-        } elsif ($fsize != $tsize) {
-            $funcs{$hashid} = 'SDL_ConvertSize';
-        } elsif ($fendian ne $tendian) {
-            $funcs{$hashid} = 'SDL_ConvertEndian';
-        } else {
-            die("error in script.\n");
-        }
-    }
-}
-
-
-sub buildTypeConverters {
-    print "#if !NO_CONVERTERS\n\n";
-    foreach (@audiotypes) {
-        my $from = $_;
-        foreach (@audiotypes) {
-            my $to = $_;
-            buildCvtFunc($from, $to);
-        }
-    }
-    print "#endif  /* !NO_CONVERTERS */\n\n\n";
-
-    print "const SDL_AudioTypeFilters sdl_audio_type_filters[] =\n{\n";
-    print "#if !NO_CONVERTERS\n";
-    foreach (@audiotypes) {
-        my $from = $_;
-        foreach (@audiotypes) {
-            my $to = $_;
-            if ($from ne $to) {
-                my $hashid = getTypeConvertHashId($from, $to);
-                my $sym = $funcs{$hashid};
-                print("    { AUDIO_$from, AUDIO_$to, $sym },\n");
-            }
-        }
-    }
-    print "#endif  /* !NO_CONVERTERS */\n";
-
-    print("    { 0, 0, NULL }\n");
-    print "};\n\n\n";
-}
-
-sub getBiggerCtype {
-    my ($isfloat, $size) = @_;
-
-    if ($isfloat) {
-        if ($size == 32) {
-            return 'double';
-        }
-        die("bug in script.\n");
-    }
-
-    if ($size == 8) {
-        return 'Sint16';
-    } elsif ($size == 16) {
-        return 'Sint32'
-    } elsif ($size == 32) {
-        return 'Sint64'
-    }
-
-    die("bug in script.\n");
-}
-
-
-# These handle arbitrary resamples...44100Hz to 48000Hz, for example.
-# Man, this code is skanky.
-sub buildArbitraryResampleFunc {
-    # !!! FIXME: we do a lot of unnecessary and ugly casting in here, due to getSwapFunc().
-    my ($from, $channels, $upsample) = @_;
-    my ($fsigned, $ffloat, $fsize, $fendian, $fctype) = splittype($from);
-
-    my $bigger = getBiggerCtype($ffloat, $fsize);
-    my $interp = ($ffloat) ? '* 0.5' : '>> 1';
-
-    my $resample = ($upsample) ? 'Upsample' : 'Downsample';
-    my $hashid = getResamplerHashId($from, $channels, $upsample, 0);
-    my $sym = "SDL_${resample}_${from}_${channels}c";
-    $funcs{$hashid} = $sym;
-    $custom_converters++;
-
-    my $fudge = $fsize * $channels * 2;  # !!! FIXME
-    my $eps_adjust = ($upsample) ? 'dstsize' : 'srcsize';
-    my $incr = '';
-    my $incr2 = '';
-    my $block_align = $channels * $fsize/8;
-
-
-    # !!! FIXME: DEBUG_CONVERT should report frequencies.
-    print <<EOF;
-static void SDLCALL
-${sym}(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "$resample arbitrary (x%f) AUDIO_${from}, ${channels} channels.\\n", cvt->rate_incr);
-#endif
-
-    const int srcsize = cvt->len_cvt - $fudge;
-    const int dstsize = (int) (((double)(cvt->len_cvt/${block_align})) * cvt->rate_incr) * ${block_align};
-    register int eps = 0;
-EOF
-
-    my $endcomparison = '!=';
-
-    # Upsampling (growing the buffer) needs to work backwards, since we
-    #  overwrite the buffer as we go.
-    if ($upsample) {
-        $endcomparison = '>=';  # dst > target
-        print <<EOF;
-    $fctype *dst = (($fctype *) (cvt->buf + dstsize)) - $channels;
-    const $fctype *src = (($fctype *) (cvt->buf + cvt->len_cvt)) - $channels;
-    const $fctype *target = ((const $fctype *) cvt->buf);
-EOF
-    } else {
-        $endcomparison = '<';  # dst < target
-        print <<EOF;
-    $fctype *dst = ($fctype *) cvt->buf;
-    const $fctype *src = ($fctype *) cvt->buf;
-    const $fctype *target = (const $fctype *) (cvt->buf + dstsize);
-EOF
-    }
-
-    for (my $i = 0; $i < $channels; $i++) {
-        my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
-        my $val = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "src[$idx]");
-        print <<EOF;
-    $fctype sample${idx} = $val;
-EOF
-    }
-
-    for (my $i = 0; $i < $channels; $i++) {
-        my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
-        print <<EOF;
-    $fctype last_sample${idx} = sample${idx};
-EOF
-    }
-
-    print <<EOF;
-    while (dst $endcomparison target) {
-EOF
-
-    if ($upsample) {
-        for (my $i = 0; $i < $channels; $i++) {
-            # !!! FIXME: don't do this swap every write, just when the samples change.
-            my $idx = (($channels - $i) - 1);
-            my $val = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "sample${idx}");
-            print <<EOF;
-        dst[$idx] = $val;
-EOF
-        }
-
-        $incr = ($channels == 1) ? 'dst--' : "dst -= $channels";
-        $incr2 = ($channels == 1) ? 'src--' : "src -= $channels";
-
-        print <<EOF;
-        $incr;
-        eps += srcsize;
-        if ((eps << 1) >= dstsize) {
-            $incr2;
-EOF
-    } else {  # downsample.
-        $incr = ($channels == 1) ? 'src++' : "src += $channels";
-        print <<EOF;
-        $incr;
-        eps += dstsize;
-        if ((eps << 1) >= srcsize) {
-EOF
-        for (my $i = 0; $i < $channels; $i++) {
-            my $val = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "sample${i}");
-            print <<EOF;
-            dst[$i] = $val;
-EOF
-        }
-
-        $incr = ($channels == 1) ? 'dst++' : "dst += $channels";
-        print <<EOF;
-            $incr;
-EOF
-    }
-
-    for (my $i = 0; $i < $channels; $i++) {
-        my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
-        my $swapped = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "src[$idx]");
-        print <<EOF;
-            sample${idx} = ($fctype) (((($bigger) $swapped) + (($bigger) last_sample${idx})) $interp);
-EOF
-    }
-
-    for (my $i = 0; $i < $channels; $i++) {
-        my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
-        print <<EOF;
-            last_sample${idx} = sample${idx};
-EOF
-    }
-
-    print <<EOF;
-            eps -= $eps_adjust;
-        }
-    }
-EOF
-
-        print <<EOF;
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-EOF
-
-}
-
-# These handle clean resamples...doubling and quadrupling the sample rate, etc.
-sub buildMultipleResampleFunc {
-    # !!! FIXME: we do a lot of unnecessary and ugly casting in here, due to getSwapFunc().
-    my ($from, $channels, $upsample, $multiple) = @_;
-    my ($fsigned, $ffloat, $fsize, $fendian, $fctype) = splittype($from);
-
-    my $bigger = getBiggerCtype($ffloat, $fsize);
-    my $interp = ($ffloat) ? '* 0.5' : '>> 1';
-    my $interp2 = ($ffloat) ? '* 0.25' : '>> 2';
-    my $mult3 = ($ffloat) ? '3.0' : '3';
-    my $lencvtop = ($upsample) ? '*' : '/';
-
-    my $resample = ($upsample) ? 'Upsample' : 'Downsample';
-    my $hashid = getResamplerHashId($from, $channels, $upsample, $multiple);
-    my $sym = "SDL_${resample}_${from}_${channels}c_x${multiple}";
-    $funcs{$hashid} = $sym;
-    $custom_converters++;
-
-    # !!! FIXME: DEBUG_CONVERT should report frequencies.
-    print <<EOF;
-static void SDLCALL
-${sym}(SDL_AudioCVT * cvt, SDL_AudioFormat format)
-{
-#if DEBUG_CONVERT
-    fprintf(stderr, "$resample (x${multiple}) AUDIO_${from}, ${channels} channels.\\n");
-#endif
-
-    const int dstsize = cvt->len_cvt $lencvtop $multiple;
-EOF
-
-    my $endcomparison = '!=';
-
-    # Upsampling (growing the buffer) needs to work backwards, since we
-    #  overwrite the buffer as we go.
-    if ($upsample) {
-        $endcomparison = '>=';  # dst > target
-        print <<EOF;
-    $fctype *dst = (($fctype *) (cvt->buf + dstsize)) - $channels * $multiple;
-    const $fctype *src = (($fctype *) (cvt->buf + cvt->len_cvt)) - $channels;
-    const $fctype *target = ((const $fctype *) cvt->buf);
-EOF
-    } else {
-        $endcomparison = '<';  # dst < target
-        print <<EOF;
-    $fctype *dst = ($fctype *) cvt->buf;
-    const $fctype *src = ($fctype *) cvt->buf;
-    const $fctype *target = (const $fctype *) (cvt->buf + dstsize);
-EOF
-    }
-
-    for (my $i = 0; $i < $channels; $i++) {
-        my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
-        my $val = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "src[$idx]");
-        print <<EOF;
-    $bigger last_sample${idx} = ($bigger) $val;
-EOF
-    }
-
-    print <<EOF;
-    while (dst $endcomparison target) {
-EOF
-
-    for (my $i = 0; $i < $channels; $i++) {
-        my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
-        my $val = getSwapFunc($fsize, $fsigned, $ffloat, $fendian, "src[$idx]");
-        print <<EOF;
-        const $bigger sample${idx} = ($bigger) $val;
-EOF
-    }
-
-    my $incr = '';
-    if ($upsample) {
-        $incr = ($channels == 1) ? 'src--' : "src -= $channels";
-    } else {
-        my $amount = $channels * $multiple;
-        $incr = "src += $amount";  # can't ever be 1, so no "++" version.
-    }
-
-
-    print <<EOF;
-        $incr;
-EOF
-
-    # !!! FIXME: This really begs for some Altivec or SSE, etc.
-    if ($upsample) {
-        if ($multiple == 2) {
-            for (my $i = $channels-1; $i >= 0; $i--) {
-                my $dsti = $i + $channels;
-                print <<EOF;
-        dst[$dsti] = ($fctype) ((sample${i} + last_sample${i}) $interp);
-EOF
-            }
-            for (my $i = $channels-1; $i >= 0; $i--) {
-                my $dsti = $i;
-                print <<EOF;
-        dst[$dsti] = ($fctype) sample${i};
-EOF
-            }
-        } elsif ($multiple == 4) {
-            for (my $i = $channels-1; $i >= 0; $i--) {
-                my $dsti = $i + ($channels * 3);
-                print <<EOF;
-        dst[$dsti] = ($fctype) ((sample${i} + ($mult3 * last_sample${i})) $interp2);
-EOF
-            }
-
-            for (my $i = $channels-1; $i >= 0; $i--) {
-                my $dsti = $i + ($channels * 2);
-                print <<EOF;
-        dst[$dsti] = ($fctype) ((sample${i} + last_sample${i}) $interp);
-EOF
-            }
-
-            for (my $i = $channels-1; $i >= 0; $i--) {
-                my $dsti = $i + ($channels * 1);
-                print <<EOF;
-        dst[$dsti] = ($fctype) ((($mult3 * sample${i}) + last_sample${i}) $interp2);
-EOF
-            }
-
-            for (my $i = $channels-1; $i >= 0; $i--) {
-                my $dsti = $i + ($channels * 0);
-                print <<EOF;
-        dst[$dsti] = ($fctype) sample${i};
-EOF
-            }
-        } else {
-            die('bug in program.');  # we only handle x2 and x4.
-        }
-    } else {  # downsample.
-        if ($multiple == 2) {
-            for (my $i = 0; $i < $channels; $i++) {
-                print <<EOF;
-        dst[$i] = ($fctype) ((sample${i} + last_sample${i}) $interp);
-EOF
-            }
-        } elsif ($multiple == 4) {
-            # !!! FIXME: interpolate all 4 samples?
-            for (my $i = 0; $i < $channels; $i++) {
-                print <<EOF;
-        dst[$i] = ($fctype) ((sample${i} + last_sample${i}) $interp);
-EOF
-            }
-        } else {
-            die('bug in program.');  # we only handle x2 and x4.
-        }
-    }
-
-    for (my $i = 0; $i < $channels; $i++) {
-        my $idx = ($upsample) ? (($channels - $i) - 1) : $i;
-        print <<EOF;
-        last_sample${idx} = sample${idx};
-EOF
-    }
-
-    if ($upsample) {
-        my $amount = $channels * $multiple;
-        $incr = "dst -= $amount";  # can't ever be 1, so no "--" version.
-    } else {
-        $incr = ($channels == 1) ? 'dst++' : "dst += $channels";
-    }
-
-    print <<EOF;
-        $incr;
-    }
-
-    cvt->len_cvt = dstsize;
-    if (cvt->filters[++cvt->filter_index]) {
-        cvt->filters[cvt->filter_index] (cvt, format);
-    }
-}
-
-EOF
-
-}
-
-sub buildResamplers {
-    print "#if !NO_RESAMPLERS\n\n";
-    foreach (@audiotypes) {
-        my $from = $_;
-        foreach (@channels) {
-            my $channel = $_;
-            buildArbitraryResampleFunc($from, $channel, 1);
-            buildArbitraryResampleFunc($from, $channel, 0);
-        }
-    }
-
-    print "\n#if !LESS_RESAMPLERS\n\n";
-    foreach (@audiotypes) {
-        my $from = $_;
-        foreach (@channels) {
-            my $channel = $_;
-            for (my $multiple = 2; $multiple <= 4; $multiple += 2) {
-                buildMultipleResampleFunc($from, $channel, 1, $multiple);
-                buildMultipleResampleFunc($from, $channel, 0, $multiple);
-            }
-        }
-    }
-
-    print "#endif  /* !LESS_RESAMPLERS */\n";
-    print "#endif  /* !NO_RESAMPLERS */\n\n\n";
-
-    print "const SDL_AudioRateFilters sdl_audio_rate_filters[] =\n{\n";
-    print "#if !NO_RESAMPLERS\n";
-    foreach (@audiotypes) {
-        my $from = $_;
-        foreach (@channels) {
-            my $channel = $_;
-            for (my $upsample = 0; $upsample <= 1; $upsample++) {
-                my $hashid = getResamplerHashId($from, $channel, $upsample, 0);
-                my $sym = $funcs{$hashid};
-                print("    { AUDIO_$from, $channel, $upsample, 0, $sym },\n");
-            }
-        }
-    }
-
-    print "#if !LESS_RESAMPLERS\n";
-    foreach (@audiotypes) {
-        my $from = $_;
-        foreach (@channels) {
-            my $channel = $_;
-            for (my $multiple = 2; $multiple <= 4; $multiple += 2) {
-                for (my $upsample = 0; $upsample <= 1; $upsample++) {
-                    my $hashid = getResamplerHashId($from, $channel, $upsample, $multiple);
-                    my $sym = $funcs{$hashid};
-                    print("    { AUDIO_$from, $channel, $upsample, $multiple, $sym },\n");
-                }
-            }
-        }
-    }
-
-    print "#endif  /* !LESS_RESAMPLERS */\n";
-    print "#endif  /* !NO_RESAMPLERS */\n";
-    print("    { 0, 0, 0, 0, NULL }\n");
-    print "};\n\n";
-}
-
-
-# mainline ...
-
-outputHeader();
-buildTypeConverters();
-buildResamplers();
-outputFooter();
-
-exit 0;
-
-# end of sdlgenaudiocvt.pl ...
-
diff --git a/src/audio/sndio/SDL_sndioaudio.c b/src/audio/sndio/SDL_sndioaudio.c
index fb7d78f..45fef50 100644
--- a/src/audio/sndio/SDL_sndioaudio.c
+++ b/src/audio/sndio/SDL_sndioaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,6 +33,7 @@
 #include <signal.h>
 #endif
 
+#include <poll.h>
 #include <unistd.h>
 
 #include "SDL_audio.h"
@@ -43,6 +44,14 @@
 #include "SDL_loadso.h"
 #endif
 
+#ifndef INFTIM
+#define INFTIM -1
+#endif
+
+#ifndef SIO_DEVANY
+#define SIO_DEVANY "default"
+#endif
+
 static struct sio_hdl * (*SNDIO_sio_open)(const char *, unsigned int, int);
 static void (*SNDIO_sio_close)(struct sio_hdl *);
 static int (*SNDIO_sio_setpar)(struct sio_hdl *, struct sio_par *);
@@ -51,6 +60,10 @@ static int (*SNDIO_sio_start)(struct sio_hdl *);
 static int (*SNDIO_sio_stop)(struct sio_hdl *);
 static size_t (*SNDIO_sio_read)(struct sio_hdl *, void *, size_t);
 static size_t (*SNDIO_sio_write)(struct sio_hdl *, const void *, size_t);
+static int (*SNDIO_sio_nfds)(struct sio_hdl *);
+static int (*SNDIO_sio_pollfd)(struct sio_hdl *, struct pollfd *, int);
+static int (*SNDIO_sio_revents)(struct sio_hdl *, struct pollfd *);
+static int (*SNDIO_sio_eof)(struct sio_hdl *);
 static void (*SNDIO_sio_initpar)(struct sio_par *);
 
 #ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
@@ -87,6 +100,10 @@ load_sndio_syms(void)
     SDL_SNDIO_SYM(sio_stop);
     SDL_SNDIO_SYM(sio_read);
     SDL_SNDIO_SYM(sio_write);
+    SDL_SNDIO_SYM(sio_nfds);
+    SDL_SNDIO_SYM(sio_pollfd);
+    SDL_SNDIO_SYM(sio_revents);
+    SDL_SNDIO_SYM(sio_eof);
     SDL_SNDIO_SYM(sio_initpar);
     return 0;
 }
@@ -164,6 +181,41 @@ SNDIO_PlayDevice(_THIS)
 #endif
 }
 
+static int
+SNDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
+{
+    size_t r;
+    int revents;
+    int nfds;
+
+    /* Emulate a blocking read */
+    r = SNDIO_sio_read(this->hidden->dev, buffer, buflen);
+    while (r == 0 && !SNDIO_sio_eof(this->hidden->dev)) {
+        if ((nfds = SNDIO_sio_pollfd(this->hidden->dev, this->hidden->pfd, POLLIN)) <= 0
+            || poll(this->hidden->pfd, nfds, INFTIM) < 0) {
+            return -1;
+        }
+        revents = SNDIO_sio_revents(this->hidden->dev, this->hidden->pfd);
+        if (revents & POLLIN) {
+            r = SNDIO_sio_read(this->hidden->dev, buffer, buflen);
+        }
+        if (revents & POLLHUP) {
+            break;
+        }
+    }
+    return (int) r;
+}
+
+static void
+SNDIO_FlushCapture(_THIS)
+{
+    char buf[512];
+
+    while (SNDIO_sio_read(this->hidden->dev, buf, sizeof(buf)) != 0) {
+        /* do nothing */;
+    }
+}
+
 static Uint8 *
 SNDIO_GetDeviceBuf(_THIS)
 {
@@ -173,6 +225,9 @@ SNDIO_GetDeviceBuf(_THIS)
 static void
 SNDIO_CloseDevice(_THIS)
 {
+    if ( this->hidden->pfd != NULL ) {
+        SDL_free(this->hidden->pfd);
+    }
     if ( this->hidden->dev != NULL ) {
         SNDIO_sio_stop(this->hidden->dev);
         SNDIO_sio_close(this->hidden->dev);
@@ -197,11 +252,19 @@ SNDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
 
     this->hidden->mixlen = this->spec.size;
 
-    /* !!! FIXME: SIO_DEVANY can be a specific device... */
-    if ((this->hidden->dev = SNDIO_sio_open(SIO_DEVANY, SIO_PLAY, 0)) == NULL) {
+    /* Capture devices must be non-blocking for SNDIO_FlushCapture */
+    if ((this->hidden->dev =
+        SNDIO_sio_open(devname != NULL ? devname : SIO_DEVANY,
+                       iscapture ? SIO_REC : SIO_PLAY, iscapture)) == NULL) {
         return SDL_SetError("sio_open() failed");
     }
 
+    /* Allocate the pollfd array for capture devices */
+    if (iscapture && (this->hidden->pfd =
+        SDL_malloc(sizeof(struct pollfd) * SNDIO_sio_nfds(this->hidden->dev))) == NULL) {
+        return SDL_OutOfMemory();
+    }
+
     SNDIO_sio_initpar(&par);
 
     par.rate = this->spec.freq;
@@ -300,8 +363,12 @@ SNDIO_Init(SDL_AudioDriverImpl * impl)
     impl->PlayDevice = SNDIO_PlayDevice;
     impl->GetDeviceBuf = SNDIO_GetDeviceBuf;
     impl->CloseDevice = SNDIO_CloseDevice;
+    impl->CaptureFromDevice = SNDIO_CaptureFromDevice;
+    impl->FlushCapture = SNDIO_FlushCapture;
     impl->Deinitialize = SNDIO_Deinitialize;
-    impl->OnlyHasDefaultOutputDevice = 1;  /* !!! FIXME: sndio can handle multiple devices. */
+
+    impl->AllowsArbitraryDeviceNames = 1;
+    impl->HasCaptureSupport = SDL_TRUE;
 
     return 1;   /* this audio target is available. */
 }
diff --git a/src/audio/sndio/SDL_sndioaudio.h b/src/audio/sndio/SDL_sndioaudio.h
index 1e748ac..e6733b4 100644
--- a/src/audio/sndio/SDL_sndioaudio.h
+++ b/src/audio/sndio/SDL_sndioaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,9 +20,10 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_sndioaudio_h
-#define _SDL_sndioaudio_h
+#ifndef SDL_sndioaudio_h_
+#define SDL_sndioaudio_h_
 
+#include <poll.h>
 #include <sndio.h>
 
 #include "../SDL_sysaudio.h"
@@ -38,8 +39,11 @@ struct SDL_PrivateAudioData
     /* Raw mixing buffer */
     Uint8 *mixbuf;
     int mixlen;
+
+    /* Polling structures for non-blocking sndio devices */
+    struct pollfd *pfd;
 };
 
-#endif /* _SDL_sndioaudio_h */
+#endif /* SDL_sndioaudio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/sun/SDL_sunaudio.c b/src/audio/sun/SDL_sunaudio.c
index b994c12..4b7c759 100644
--- a/src/audio/sun/SDL_sunaudio.c
+++ b/src/audio/sun/SDL_sunaudio.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -40,6 +40,7 @@
 
 #include "SDL_timer.h"
 #include "SDL_audio.h"
+#include "../../core/unix/SDL_poll.h"
 #include "../SDL_audio_c.h"
 #include "../SDL_audiodev_c.h"
 #include "SDL_sunaudio.h"
@@ -97,11 +98,7 @@ SUNAUDIO_WaitDevice(_THIS)
         }
     }
 #else
-    fd_set fdset;
-
-    FD_ZERO(&fdset);
-    FD_SET(this->hidden->audio_fd, &fdset);
-    select(this->hidden->audio_fd + 1, NULL, &fdset, NULL, NULL);
+    SDL_IOReady(this->hidden->audio_fd, SDL_TRUE, -1);
 #endif
 }
 
@@ -193,6 +190,10 @@ SUNAUDIO_CloseDevice(_THIS)
 static int
 SUNAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
 {
+#ifdef AUDIO_SETINFO
+    int enc;
+#endif
+    int desired_freq = 0;
     const int flags = ((iscapture) ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT);
     SDL_AudioFormat format = 0;
     audio_info_t info;
@@ -220,10 +221,7 @@ SUNAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
         return SDL_SetError("Couldn't open %s: %s", devname, strerror(errno));
     }
 
-#ifdef AUDIO_SETINFO
-    int enc;
-#endif
-    int desired_freq = this->spec.freq;
+    desired_freq = this->spec.freq;
 
     /* Determine the audio parameters from the AudioSpec */
     switch (SDL_AUDIO_BITSIZE(this->spec.format)) {
diff --git a/src/audio/sun/SDL_sunaudio.h b/src/audio/sun/SDL_sunaudio.h
index ecced0f..5cf0458 100644
--- a/src/audio/sun/SDL_sunaudio.h
+++ b/src/audio/sun/SDL_sunaudio.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_sunaudio_h
-#define _SDL_sunaudio_h
+#ifndef SDL_sunaudio_h_
+#define SDL_sunaudio_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -42,6 +42,6 @@ struct SDL_PrivateAudioData
     int frequency;              /* The audio frequency in KHz */
 };
 
-#endif /* _SDL_sunaudio_h */
+#endif /* SDL_sunaudio_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/wasapi/SDL_wasapi.c b/src/audio/wasapi/SDL_wasapi.c
new file mode 100644
index 0000000..c448c37
--- /dev/null
+++ b/src/audio/wasapi/SDL_wasapi.c
@@ -0,0 +1,964 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+
+#if SDL_AUDIO_DRIVER_WASAPI
+
+#include "../../core/windows/SDL_windows.h"
+#include "SDL_audio.h"
+#include "SDL_timer.h"
+#include "../SDL_audio_c.h"
+#include "../SDL_sysaudio.h"
+#include "SDL_assert.h"
+#include "SDL_log.h"
+
+#define COBJMACROS
+#include <mmdeviceapi.h>
+#include <audioclient.h>
+
+#include "SDL_wasapi.h"
+
+static const ERole SDL_WASAPI_role = eConsole;  /* !!! FIXME: should this be eMultimedia? Should be a hint? */
+
+/* This is global to the WASAPI target, to handle hotplug and default device lookup. */
+static IMMDeviceEnumerator *enumerator = NULL;
+
+/* these increment as default devices change. Opened default devices pick up changes in their threads. */
+static SDL_atomic_t default_playback_generation;
+static SDL_atomic_t default_capture_generation;
+
+/* This is a list of device id strings we have inflight, so we have consistent pointers to the same device. */
+typedef struct DevIdList
+{
+    WCHAR *str;
+    struct DevIdList *next;
+} DevIdList;
+
+static DevIdList *deviceid_list = NULL;
+
+/* handle to Avrt.dll--Vista and later!--for flagging the callback thread as "Pro Audio" (low latency). */
+#ifndef __WINRT__
+static HMODULE libavrt = NULL;
+#endif
+typedef HANDLE (WINAPI *pfnAvSetMmThreadCharacteristicsW)(LPWSTR,LPDWORD);
+typedef BOOL (WINAPI *pfnAvRevertMmThreadCharacteristics)(HANDLE);
+static pfnAvSetMmThreadCharacteristicsW pAvSetMmThreadCharacteristicsW = NULL;
+static pfnAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL;
+
+/* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
+static const CLSID SDL_CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c, { 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } };
+static const IID SDL_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35, { 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } };
+static const IID SDL_IID_IMMNotificationClient = { 0x7991eec9, 0x7e89, 0x4d85, { 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0 } };
+static const IID SDL_IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089, { 0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5 } };
+static const IID SDL_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32, { 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2 } };
+static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483, { 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
+static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0, { 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } };
+static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
+static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
+static const PROPERTYKEY SDL_PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, } }, 14 };
+
+/* PropVariantInit() is an inline function/macro in PropIdl.h that calls the C runtime's memset() directly. Use ours instead, to avoid dependency. */ 
+#ifdef PropVariantInit
+#undef PropVariantInit
+#endif
+#define PropVariantInit(p) SDL_zerop(p)
+
+static void AddWASAPIDevice(const SDL_bool iscapture, IMMDevice *device, LPCWSTR devid);
+static void RemoveWASAPIDevice(const SDL_bool iscapture, LPCWSTR devid);
+
+/* We need a COM subclass of IMMNotificationClient for hotplug support, which is
+   easy in C++, but we have to tapdance more to make work in C.
+   Thanks to this page for coaching on how to make this work:
+     https://www.codeproject.com/Articles/13601/COM-in-plain-C */
+
+typedef struct SDLMMNotificationClient
+{
+    const IMMNotificationClientVtbl *lpVtbl;
+    SDL_atomic_t refcount;
+} SDLMMNotificationClient;
+
+static HRESULT STDMETHODCALLTYPE
+SDLMMNotificationClient_QueryInterface(IMMNotificationClient *this, REFIID iid, void **ppv)
+{
+    if ((WIN_IsEqualIID(iid, &IID_IUnknown)) || (WIN_IsEqualIID(iid, &SDL_IID_IMMNotificationClient)))
+    {
+        *ppv = this;
+        this->lpVtbl->AddRef(this);
+        return S_OK;
+    }
+
+    *ppv = NULL;
+    return E_NOINTERFACE;
+}
+
+static ULONG STDMETHODCALLTYPE
+SDLMMNotificationClient_AddRef(IMMNotificationClient *ithis)
+{
+    SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis;
+    return (ULONG) (SDL_AtomicIncRef(&this->refcount) + 1);
+}
+
+static ULONG STDMETHODCALLTYPE
+SDLMMNotificationClient_Release(IMMNotificationClient *ithis)
+{
+    /* this is a static object; we don't ever free it. */
+    SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis;
+    const ULONG retval = SDL_AtomicDecRef(&this->refcount);
+    if (retval == 0) {
+        SDL_AtomicSet(&this->refcount, 0);  /* uhh... */
+        return 0;
+    }
+    return retval - 1;
+}
+
+/* These are the entry points called when WASAPI device endpoints change. */
+static HRESULT STDMETHODCALLTYPE
+SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *ithis, EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId)
+{
+    if (role != SDL_WASAPI_role) {
+        return S_OK;  /* ignore it. */
+    }
+
+    /* Increment the "generation," so opened devices will pick this up in their threads. */
+    switch (flow) {
+        case eRender:
+            SDL_AtomicAdd(&default_playback_generation, 1);
+            break;
+
+        case eCapture:
+            SDL_AtomicAdd(&default_capture_generation, 1);
+            break;
+
+        case eAll:
+            SDL_AtomicAdd(&default_playback_generation, 1);
+            SDL_AtomicAdd(&default_capture_generation, 1);
+            break;
+
+        default:
+            SDL_assert(!"uhoh, unexpected OnDefaultDeviceChange flow!");
+            break;
+    }
+
+    return S_OK;
+}
+
+static HRESULT STDMETHODCALLTYPE
+SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
+{
+    /* we ignore this; devices added here then progress to ACTIVE, if appropriate, in 
+       OnDeviceStateChange, making that a better place to deal with device adds. More 
+       importantly: the first time you plug in a USB audio device, this callback will 
+       fire, but when you unplug it, it isn't removed (it's state changes to NOTPRESENT).
+       Plugging it back in won't fire this callback again. */
+    return S_OK;
+}
+
+static HRESULT STDMETHODCALLTYPE
+SDLMMNotificationClient_OnDeviceRemoved(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
+{
+    /* See notes in OnDeviceAdded handler about why we ignore this. */
+    return S_OK;
+}
+
+static HRESULT STDMETHODCALLTYPE
+SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId, DWORD dwNewState)
+{
+    IMMDevice *device = NULL;
+
+    if (SUCCEEDED(IMMDeviceEnumerator_GetDevice(enumerator, pwstrDeviceId, &device))) {
+        IMMEndpoint *endpoint = NULL;
+        if (SUCCEEDED(IMMDevice_QueryInterface(device, &SDL_IID_IMMEndpoint, (void **) &endpoint))) {
+            EDataFlow flow;
+            if (SUCCEEDED(IMMEndpoint_GetDataFlow(endpoint, &flow))) {
+                const SDL_bool iscapture = (flow == eCapture);
+                if (dwNewState == DEVICE_STATE_ACTIVE) {
+                    AddWASAPIDevice(iscapture, device, pwstrDeviceId);
+                } else {
+                    RemoveWASAPIDevice(iscapture, pwstrDeviceId);
+                }
+            }
+            IMMEndpoint_Release(endpoint);
+        }
+        IMMDevice_Release(device);
+    }
+
+    return S_OK;
+}
+
+static HRESULT STDMETHODCALLTYPE
+SDLMMNotificationClient_OnPropertyValueChanged(IMMNotificationClient *this, LPCWSTR pwstrDeviceId, const PROPERTYKEY key)
+{
+    return S_OK;  /* we don't care about these. */
+}
+
+static const IMMNotificationClientVtbl notification_client_vtbl = {
+    SDLMMNotificationClient_QueryInterface,
+    SDLMMNotificationClient_AddRef,
+    SDLMMNotificationClient_Release,
+    SDLMMNotificationClient_OnDeviceStateChanged,
+    SDLMMNotificationClient_OnDeviceAdded,
+    SDLMMNotificationClient_OnDeviceRemoved,
+    SDLMMNotificationClient_OnDefaultDeviceChanged,
+    SDLMMNotificationClient_OnPropertyValueChanged
+};
+
+static SDLMMNotificationClient notification_client = { &notification_client_vtbl, { 1 } };
+
+static SDL_bool
+WStrEqual(const WCHAR *a, const WCHAR *b)
+{
+    while (*a) {
+        if (*a != *b) {
+            return SDL_FALSE;
+        }
+        a++;
+        b++;
+    }
+    return *b == 0;
+}
+
+static WCHAR *
+WStrDupe(const WCHAR *wstr)
+{
+    const int len = (lstrlenW(wstr) + 1) * sizeof (WCHAR);
+    WCHAR *retval = (WCHAR *) SDL_malloc(len);
+    if (retval) {
+        SDL_memcpy(retval, wstr, len);
+    }
+    return retval;
+}
+
+static void 
+RemoveWASAPIDevice(const SDL_bool iscapture, LPCWSTR devid)
+{
+    DevIdList *i;
+    DevIdList *next;
+    DevIdList *prev = NULL;
+    for (i = deviceid_list; i; i = next) {
+        next = i->next;
+        if (WStrEqual(i->str, devid)) {
+            if (prev) {
+                prev->next = next;
+            } else {
+                deviceid_list = next;
+            }
+            SDL_RemoveAudioDevice(iscapture, i->str);
+            SDL_free(i->str);
+            SDL_free(i);
+        }
+        prev = i;
+    }
+}
+
+static void
+AddWASAPIDevice(const SDL_bool iscapture, IMMDevice *device, LPCWSTR devid)
+{
+    IPropertyStore *props = NULL;
+    char *utf8dev = NULL;
+    DevIdList *devidlist;
+    PROPVARIANT var;
+
+    /* You can have multiple endpoints on a device that are mutually exclusive ("Speakers" vs "Line Out" or whatever).
+       In a perfect world, things that are unplugged won't be in this collection. The only gotcha is probably for
+       phones and tablets, where you might have an internal speaker and a headphone jack and expect both to be
+       available and switch automatically. (!!! FIXME...?) */
+
+    /* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be
+       "SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in
+       its own UIs, like Volume Control, etc. */
+
+    /* see if we already have this one. */
+    for (devidlist = deviceid_list; devidlist; devidlist = devidlist->next) {
+        if (WStrEqual(devidlist->str, devid)) {
+            return;  /* we already have this. */
+        }
+    }
+
+    devidlist = (DevIdList *) SDL_malloc(sizeof (*devidlist));
+    if (!devidlist) {
+        return;  /* oh well. */
+    }
+
+    devid = WStrDupe(devid);
+    if (!devid) {
+        SDL_free(devidlist);
+        return;  /* oh well. */
+    }
+
+    devidlist->str = (WCHAR *) devid;
+    devidlist->next = deviceid_list;
+    deviceid_list = devidlist;
+
+    if (SUCCEEDED(IMMDevice_OpenPropertyStore(device, STGM_READ, &props))) {
+        PropVariantInit(&var);
+        if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_Device_FriendlyName, &var))) {
+            utf8dev = WIN_StringToUTF8(var.pwszVal);
+            if (utf8dev) {
+                SDL_AddAudioDevice(iscapture, utf8dev, (void *) devid);
+                SDL_free(utf8dev);
+            }
+        }
+        PropVariantClear(&var);
+        IPropertyStore_Release(props);
+    }
+}
+
+static void
+EnumerateEndpoints(const SDL_bool iscapture)
+{
+    IMMDeviceCollection *collection = NULL;
+    UINT i, total;
+
+    /* Note that WASAPI separates "adapter devices" from "audio endpoint devices"
+       ...one adapter device ("SoundBlaster Pro") might have multiple endpoint devices ("Speakers", "Line-Out"). */
+
+    if (FAILED(IMMDeviceEnumerator_EnumAudioEndpoints(enumerator, iscapture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &collection))) {
+        return;
+    }
+
+    if (FAILED(IMMDeviceCollection_GetCount(collection, &total))) {
+        IMMDeviceCollection_Release(collection);
+        return;
+    }
+
+    for (i = 0; i < total; i++) {
+        IMMDevice *device = NULL;
+        if (SUCCEEDED(IMMDeviceCollection_Item(collection, i, &device))) {
+            LPWSTR devid = NULL;
+            if (SUCCEEDED(IMMDevice_GetId(device, &devid))) {
+                AddWASAPIDevice(iscapture, device, devid);
+                CoTaskMemFree(devid);
+            }
+            IMMDevice_Release(device);
+        }
+    }
+
+    IMMDeviceCollection_Release(collection);
+}
+
+static void
+WASAPI_DetectDevices(void)
+{
+    EnumerateEndpoints(SDL_FALSE);  /* playback */
+    EnumerateEndpoints(SDL_TRUE);   /* capture */
+
+    /* if this fails, we just won't get hotplug events. Carry on anyhow. */
+    IMMDeviceEnumerator_RegisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *) &notification_client);
+}
+
+static int
+WASAPI_GetPendingBytes(_THIS)
+{
+    UINT32 frames = 0;
+
+    /* it's okay to fail here; we'll deal with failures in the audio thread. */
+    /* FIXME: need a lock around checking this->hidden->client */
+    if (!this->hidden->client || FAILED(IAudioClient_GetCurrentPadding(this->hidden->client, &frames))) {
+        return 0;  /* oh well. */
+    }
+
+    return ((int) frames) * this->hidden->framesize;
+}
+
+static SDL_INLINE SDL_bool
+WasapiFailed(_THIS, const HRESULT err)
+{
+    if (err == S_OK) {
+        return SDL_FALSE;
+    }
+
+    if (err == AUDCLNT_E_DEVICE_INVALIDATED) {
+        this->hidden->device_lost = SDL_TRUE;
+    } else if (SDL_AtomicGet(&this->enabled)) {
+        IAudioClient_Stop(this->hidden->client);
+        SDL_OpenedAudioDeviceDisconnected(this);
+        SDL_assert(!SDL_AtomicGet(&this->enabled));
+    }
+
+    return SDL_TRUE;
+}
+
+static int PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device);
+static void ReleaseWasapiDevice(_THIS);
+
+static SDL_bool
+RecoverWasapiDevice(_THIS)
+{
+    const SDL_AudioSpec oldspec = this->spec;
+    IMMDevice *device = NULL;
+    HRESULT ret = S_OK;
+
+    if (this->hidden->default_device_generation) {
+        const EDataFlow dataflow = this->iscapture ? eCapture : eRender;
+        ReleaseWasapiDevice(this);  /* dump the lost device's handles. */
+        this->hidden->default_device_generation = SDL_AtomicGet(this->iscapture ?  &default_capture_generation : &default_playback_generation);
+        ret = IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_WASAPI_role, &device);
+        if (FAILED(ret)) {
+            return SDL_FALSE;  /* can't find a new default device! */
+        }
+    } else {
+        device = this->hidden->device;
+        this->hidden->device = NULL;  /* don't release this in ReleaseWasapiDevice(). */
+        ReleaseWasapiDevice(this);  /* dump the lost device's handles. */
+    }
+
+    SDL_assert(device != NULL);
+
+    /* this can fail for lots of reasons, but the most likely is we had a 
+       non-default device that was disconnected, so we can't recover. Default
+       devices try to reinitialize whatever the new default is, so it's more
+       likely to carry on here, but this handles a non-default device that
+       simply had its format changed in the Windows Control Panel. */
+    if (PrepWasapiDevice(this, this->iscapture, device) == -1) {
+        return SDL_FALSE;
+    }
+
+    /* Since WASAPI requires us to handle all audio conversion, and our
+       device format might have changed, we might have to add/remove/change
+       the audio stream that the higher level uses to convert data, so
+       SDL keeps firing the callback as if nothing happened here. */
+
+    if ( (this->callbackspec.channels == this->spec.channels) &&
+         (this->callbackspec.format == this->spec.format) &&
+         (this->callbackspec.freq == this->spec.freq) &&
+         (this->callbackspec.samples == this->spec.samples) ) {
+        /* no need to buffer/convert in an AudioStream! */
+        SDL_FreeAudioStream(this->stream);
+        this->stream = NULL;
+    } else if ( (oldspec.channels == this->spec.channels) &&
+         (oldspec.format == this->spec.format) &&
+         (oldspec.freq == this->spec.freq) ) {
+        /* The existing audio stream is okay to keep using. */
+    } else {
+        /* replace the audiostream for new format */
+        SDL_FreeAudioStream(this->stream);
+        if (this->iscapture) {
+            this->stream = SDL_NewAudioStream(this->spec.format,
+                                this->spec.channels, this->spec.freq,
+                                this->callbackspec.format,
+                                this->callbackspec.channels,
+                                this->callbackspec.freq);
+        } else {
+            this->stream = SDL_NewAudioStream(this->callbackspec.format,
+                                this->callbackspec.channels,
+                                this->callbackspec.freq, this->spec.format,
+                                this->spec.channels, this->spec.freq);
+        }
+
+        if (!this->stream) {
+            return SDL_FALSE;
+        }
+    }
+
+    /* make sure our scratch buffer can cover the new device spec. */
+    if (this->spec.size > this->work_buffer_len) {
+        Uint8 *ptr = (Uint8 *) SDL_realloc(this->work_buffer, this->spec.size);
+        if (ptr == NULL) {
+            SDL_OutOfMemory();
+            return SDL_FALSE;
+        }
+        this->work_buffer = ptr;
+        this->work_buffer_len = this->spec.size;
+    }
+
+    this->hidden->device_lost = SDL_FALSE;
+
+    return SDL_TRUE;  /* okay, carry on with new device details! */
+}
+
+static SDL_bool
+RecoverWasapiIfLost(_THIS)
+{
+    const int generation = this->hidden->default_device_generation;
+    SDL_bool lost = this->hidden->device_lost;
+
+    if (!SDL_AtomicGet(&this->enabled)) {
+        return SDL_FALSE;  /* already failed. */
+    }
+
+    if (!lost && (generation > 0)) { /* is a default device? */
+        const int newgen = SDL_AtomicGet(this->iscapture ? &default_capture_generation : &default_playback_generation);
+        if (generation != newgen) {  /* the desired default device was changed, jump over to it. */
+            lost = SDL_TRUE;
+        }
+    }
+
+    return lost ? RecoverWasapiDevice(this) : SDL_TRUE;
+}
+
+static Uint8 *
+WASAPI_GetDeviceBuf(_THIS)
+{
+    /* get an endpoint buffer from WASAPI. */
+    BYTE *buffer = NULL;
+
+    while (RecoverWasapiIfLost(this)) {
+        if (!WasapiFailed(this, IAudioRenderClient_GetBuffer(this->hidden->render, this->spec.samples, &buffer))) {
+            return (Uint8 *) buffer;
+        }
+        SDL_assert(buffer == NULL);
+    }
+
+    return (Uint8 *) buffer;
+}
+
+static void
+WASAPI_PlayDevice(_THIS)
+{
+    /* WasapiFailed() will mark the device for reacquisition or removal elsewhere. */
+    WasapiFailed(this, IAudioRenderClient_ReleaseBuffer(this->hidden->render, this->spec.samples, 0));
+}
+
+static void
+WASAPI_WaitDevice(_THIS)
+{
+    const UINT32 maxpadding = this->spec.samples;
+    while (RecoverWasapiIfLost(this)) {
+        UINT32 padding = 0;
+
+        if (!WasapiFailed(this, IAudioClient_GetCurrentPadding(this->hidden->client, &padding))) {
+            if (padding <= maxpadding) {
+                break;
+            }
+            /* Sleep long enough for half the buffer to be free. */
+            SDL_Delay(((padding - maxpadding) * 1000) / this->spec.freq);
+        }
+    }
+}
+
+static int
+WASAPI_CaptureFromDevice(_THIS, void *buffer, int buflen)
+{
+    SDL_AudioStream *stream = this->hidden->capturestream;
+    const int avail = SDL_AudioStreamAvailable(stream);
+    if (avail > 0) {
+        const int cpy = SDL_min(buflen, avail);
+        SDL_AudioStreamGet(stream, buffer, cpy);
+        return cpy;
+    }
+
+    while (RecoverWasapiIfLost(this)) {
+        HRESULT ret;
+        BYTE *ptr = NULL;
+        UINT32 frames = 0;
+        DWORD flags = 0;
+
+        ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
+        if (ret != AUDCLNT_S_BUFFER_EMPTY) {
+            WasapiFailed(this, ret); /* mark device lost/failed if necessary. */
+        }
+
+        if ((ret == AUDCLNT_S_BUFFER_EMPTY) || !frames) {
+            WASAPI_WaitDevice(this);
+        } else if (ret == S_OK) {
+            const int total = ((int) frames) * this->hidden->framesize;
+            const int cpy = SDL_min(buflen, total);
+            const int leftover = total - cpy;
+            const SDL_bool silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) ? SDL_TRUE : SDL_FALSE;
+
+            if (silent) {
+                SDL_memset(buffer, this->spec.silence, cpy);
+            } else {
+                SDL_memcpy(buffer, ptr, cpy);
+            }
+            
+            if (leftover > 0) {
+                ptr += cpy;
+                if (silent) {
+                    SDL_memset(ptr, this->spec.silence, leftover);  /* I guess this is safe? */
+                }
+
+                if (SDL_AudioStreamPut(stream, ptr, leftover) == -1) {
+                    return -1;  /* uhoh, out of memory, etc. Kill device.  :( */
+                }
+            }
+
+            ret = IAudioCaptureClient_ReleaseBuffer(this->hidden->capture, frames);
+            WasapiFailed(this, ret); /* mark device lost/failed if necessary. */
+
+            return cpy;
+        }
+    }
+
+    return -1;  /* unrecoverable error. */
+}
+
+static void
+WASAPI_FlushCapture(_THIS)
+{
+    BYTE *ptr = NULL;
+    UINT32 frames = 0;
+    DWORD flags = 0;
+
+    /* just read until we stop getting packets, throwing them away. */
+    while (SDL_TRUE) {
+        const HRESULT ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
+        if (ret == AUDCLNT_S_BUFFER_EMPTY) {
+            break;  /* no more buffered data; we're done. */
+        } else if (WasapiFailed(this, ret)) {
+            break;  /* failed for some other reason, abort. */
+        } else if (WasapiFailed(this, IAudioCaptureClient_ReleaseBuffer(this->hidden->capture, frames))) {
+            break;  /* something broke. */
+        }
+    }
+    SDL_AudioStreamClear(this->hidden->capturestream);
+}
+
+static void
+ReleaseWasapiDevice(_THIS)
+{
+    if (this->hidden->client) {
+        IAudioClient_Stop(this->hidden->client);
+        this->hidden->client = NULL;
+    }
+
+    if (this->hidden->render) {
+        IAudioRenderClient_Release(this->hidden->render);
+        this->hidden->render = NULL;
+    }
+
+    if (this->hidden->capture) {
+        IAudioCaptureClient_Release(this->hidden->capture);
+        this->hidden->capture = NULL;
+    }
+
+    if (this->hidden->waveformat) {
+        CoTaskMemFree(this->hidden->waveformat);
+        this->hidden->waveformat = NULL;
+    }
+
+    if (this->hidden->device) {
+        IMMDevice_Release(this->hidden->device);
+        this->hidden->device = NULL;
+    }
+
+    if (this->hidden->capturestream) {
+        SDL_FreeAudioStream(this->hidden->capturestream);
+        this->hidden->capturestream = NULL;
+    }
+}
+
+static void
+WASAPI_CloseDevice(_THIS)
+{
+    /* don't touch this->hidden->task in here; it has to be reverted from
+      our callback thread. We do that in WASAPI_ThreadDeinit().
+      (likewise for this->hidden->coinitialized). */
+    ReleaseWasapiDevice(this);
+    SDL_free(this->hidden);
+}
+
+
+static int
+PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device)
+{
+    /* !!! FIXME: we could request an exclusive mode stream, which is lower latency;
+       !!!  it will write into the kernel's audio buffer directly instead of
+       !!!  shared memory that a user-mode mixer then writes to the kernel with
+       !!!  everything else. Doing this means any other sound using this device will
+       !!!  stop playing, including the user's MP3 player and system notification
+       !!!  sounds. You'd probably need to release the device when the app isn't in
+       !!!  the foreground, to be a good citizen of the system. It's doable, but it's
+       !!!  more work and causes some annoyances, and I don't know what the latency
+       !!!  wins actually look like. Maybe add a hint to force exclusive mode at
+       !!!  some point. To be sure, defaulting to shared mode is the right thing to
+       !!!  do in any case. */
+    const AUDCLNT_SHAREMODE sharemode = AUDCLNT_SHAREMODE_SHARED;
+    UINT32 bufsize = 0;  /* this is in sample frames, not samples, not bytes. */
+    REFERENCE_TIME duration = 0;
+    IAudioClient *client = NULL;
+    IAudioRenderClient *render = NULL;
+    IAudioCaptureClient *capture = NULL;
+    WAVEFORMATEX *waveformat = NULL;
+    SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
+    SDL_AudioFormat wasapi_format = 0;
+    SDL_bool valid_format = SDL_FALSE;
+    HRESULT ret = S_OK;
+
+    this->hidden->device = device;
+
+    ret = IMMDevice_Activate(device, &SDL_IID_IAudioClient, CLSCTX_ALL, NULL, (void **) &client);
+    if (FAILED(ret)) {
+        return WIN_SetErrorFromHRESULT("WASAPI can't activate audio endpoint", ret);
+    }
+
+    SDL_assert(client != NULL);
+    this->hidden->client = client;
+
+    ret = IAudioClient_GetMixFormat(client, &waveformat);
+    if (FAILED(ret)) {
+        return WIN_SetErrorFromHRESULT("WASAPI can't determine mix format", ret);
+    }
+
+    SDL_assert(waveformat != NULL);
+    this->hidden->waveformat = waveformat;
+
+    /* WASAPI will not do any conversion on our behalf. Force channels and sample rate. */
+    this->spec.channels = (Uint8) waveformat->nChannels;
+    this->spec.freq = waveformat->nSamplesPerSec;
+
+    /* Make sure we have a valid format that we can convert to whatever WASAPI wants. */
+    if ((waveformat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) && (waveformat->wBitsPerSample == 32)) {
+        wasapi_format = AUDIO_F32SYS;
+    } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 16)) {
+        wasapi_format = AUDIO_S16SYS;
+    } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 32)) {
+        wasapi_format = AUDIO_S32SYS;
+    } else if (waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
+        const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *) waveformat;
+        if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
+            wasapi_format = AUDIO_F32SYS;
+        } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 16)) {
+            wasapi_format = AUDIO_S16SYS;
+        } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
+            wasapi_format = AUDIO_S32SYS;
+        }
+    }
+
+    while ((!valid_format) && (test_format)) {
+        if (test_format == wasapi_format) {
+            this->spec.format = test_format;
+            valid_format = SDL_TRUE;
+            break;
+        }
+        test_format = SDL_NextAudioFormat();
+    }
+
+    if (!valid_format) {
+        return SDL_SetError("WASAPI: Unsupported audio format");
+    }
+
+    ret = IAudioClient_GetDevicePeriod(client, NULL, &duration);
+    if (FAILED(ret)) {
+        return WIN_SetErrorFromHRESULT("WASAPI can't determine minimum device period", ret);
+    }
+
+    ret = IAudioClient_Initialize(client, sharemode, 0, duration, sharemode == AUDCLNT_SHAREMODE_SHARED ? 0 : duration, waveformat, NULL);
+    if (FAILED(ret)) {
+        return WIN_SetErrorFromHRESULT("WASAPI can't initialize audio client", ret);
+    }
+
+    ret = IAudioClient_GetBufferSize(client, &bufsize);
+    if (FAILED(ret)) {
+        return WIN_SetErrorFromHRESULT("WASAPI can't determine buffer size", ret);
+    }
+
+    this->spec.samples = (Uint16) bufsize;
+    if (!iscapture) {
+        this->spec.samples /= 2;  /* fill half of the DMA buffer on each run. */
+    }
+
+    /* Update the fragment size as size in bytes */
+    SDL_CalculateAudioSpec(&this->spec);
+
+    this->hidden->framesize = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels;
+
+    if (iscapture) {
+        this->hidden->capturestream = SDL_NewAudioStream(this->spec.format, this->spec.channels, this->spec.freq, this->spec.format, this->spec.channels, this->spec.freq);
+        if (!this->hidden->capturestream) {
+            return -1;  /* already set SDL_Error */
+        }
+
+        ret = IAudioClient_GetService(client, &SDL_IID_IAudioCaptureClient, (void**) &capture);
+        if (FAILED(ret)) {
+            return WIN_SetErrorFromHRESULT("WASAPI can't get capture client service", ret);
+        }
+
+        SDL_assert(capture != NULL);
+        this->hidden->capture = capture;
+        ret = IAudioClient_Start(client);
+        if (FAILED(ret)) {
+            return WIN_SetErrorFromHRESULT("WASAPI can't start capture", ret);
+        }
+
+        WASAPI_FlushCapture(this);  /* MSDN says you should flush capture endpoint right after startup. */
+    } else {
+        ret = IAudioClient_GetService(client, &SDL_IID_IAudioRenderClient, (void**) &render);
+        if (FAILED(ret)) {
+            return WIN_SetErrorFromHRESULT("WASAPI can't get render client service", ret);
+        }
+
+        SDL_assert(render != NULL);
+        this->hidden->render = render;
+        ret = IAudioClient_Start(client);
+        if (FAILED(ret)) {
+            return WIN_SetErrorFromHRESULT("WASAPI can't start playback", ret);
+        }
+    }
+
+    return 0;  /* good to go. */
+}
+
+static int
+WASAPI_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
+{
+    const SDL_bool is_default_device = (handle == NULL);
+    IMMDevice *device = NULL;
+    HRESULT ret = S_OK;
+
+    /* Initialize all variables that we clean on shutdown */
+    this->hidden = (struct SDL_PrivateAudioData *)
+        SDL_malloc((sizeof *this->hidden));
+    if (this->hidden == NULL) {
+        return SDL_OutOfMemory();
+    }
+    SDL_zerop(this->hidden);
+
+    if (is_default_device) {
+        const EDataFlow dataflow = iscapture ? eCapture : eRender;
+        this->hidden->default_device_generation = SDL_AtomicGet(iscapture ? &default_capture_generation : &default_playback_generation);
+        ret = IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_WASAPI_role, &device);
+    } else {
+        ret = IMMDeviceEnumerator_GetDevice(enumerator, (LPCWSTR) handle, &device);
+    }
+
+    if (FAILED(ret)) {
+        return WIN_SetErrorFromHRESULT("WASAPI can't find requested audio endpoint", ret);
+    }
+
+    SDL_assert(device != NULL);
+    return PrepWasapiDevice(this, iscapture, device);
+}
+
+static void
+WASAPI_ThreadInit(_THIS)
+{
+    /* this thread uses COM. */
+    if (SUCCEEDED(WIN_CoInitialize())) {    /* can't report errors, hope it worked! */
+        this->hidden->coinitialized = SDL_TRUE;
+    }
+
+    /* Set this thread to very high "Pro Audio" priority. */
+    if (pAvSetMmThreadCharacteristicsW) {
+        DWORD idx = 0;
+        this->hidden->task = pAvSetMmThreadCharacteristicsW(TEXT("Pro Audio"), &idx);
+    }
+}
+
+static void
+WASAPI_ThreadDeinit(_THIS)
+{
+    /* Set this thread to very high "Pro Audio" priority. */
+    if (this->hidden->task && pAvRevertMmThreadCharacteristics) {
+        pAvRevertMmThreadCharacteristics(this->hidden->task);
+        this->hidden->task = NULL;
+    }
+
+    if (this->hidden->coinitialized) {
+        WIN_CoUninitialize();
+    }
+}
+
+static void
+WASAPI_Deinitialize(void)
+{
+    DevIdList *devidlist;
+    DevIdList *next;
+
+    if (enumerator) {
+        IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *) &notification_client);
+        IMMDeviceEnumerator_Release(enumerator);
+        enumerator = NULL;
+    }
+
+    #ifndef __WINRT__
+    if (libavrt) {
+        FreeLibrary(libavrt);
+        libavrt = NULL;
+    }
+    #endif
+
+    pAvSetMmThreadCharacteristicsW = NULL;
+    pAvRevertMmThreadCharacteristics = NULL;
+
+    for (devidlist = deviceid_list; devidlist; devidlist = next) {
+        next = devidlist->next;
+        SDL_free(devidlist->str);
+        SDL_free(devidlist);
+    }
+    deviceid_list = NULL;
+
+    WIN_CoUninitialize();
+}
+
+static int
+WASAPI_Init(SDL_AudioDriverImpl * impl)
+{
+    HRESULT ret;
+
+    /* just skip the discussion with COM here. */
+    if (!WIN_IsWindowsVistaOrGreater()) {
+        SDL_SetError("WASAPI support requires Windows Vista or later");
+        return 0;
+    }
+
+    SDL_AtomicSet(&default_playback_generation, 1);
+    SDL_AtomicSet(&default_capture_generation, 1);
+
+    if (FAILED(WIN_CoInitialize())) {
+        SDL_SetError("WASAPI: CoInitialize() failed");
+        return 0;
+    }
+
+    ret = CoCreateInstance(&SDL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &SDL_IID_IMMDeviceEnumerator, (LPVOID) &enumerator);
+    if (FAILED(ret)) {
+        WIN_CoUninitialize();
+        WIN_SetErrorFromHRESULT("WASAPI CoCreateInstance(MMDeviceEnumerator)", ret);
+        return 0;  /* oh well. */
+    }
+
+    #ifdef __WINRT__
+    pAvSetMmThreadCharacteristicsW = AvSetMmThreadCharacteristicsW;
+    pAvRevertMmThreadCharacteristics = AvRevertMmThreadCharacteristics;
+    #else
+    libavrt = LoadLibraryW(L"avrt.dll");  /* this library is available in Vista and later. No WinXP, so have to LoadLibrary to use it for now! */
+    if (libavrt) {
+        pAvSetMmThreadCharacteristicsW = (pfnAvSetMmThreadCharacteristicsW) GetProcAddress(libavrt, "AvSetMmThreadCharacteristicsW");
+        pAvRevertMmThreadCharacteristics = (pfnAvRevertMmThreadCharacteristics) GetProcAddress(libavrt, "AvRevertMmThreadCharacteristics");
+    }
+    #endif
+
+    /* Set the function pointers */
+    impl->DetectDevices = WASAPI_DetectDevices;
+    impl->ThreadInit = WASAPI_ThreadInit;
+    impl->ThreadDeinit = WASAPI_ThreadDeinit;
+    impl->OpenDevice = WASAPI_OpenDevice;
+    impl->PlayDevice = WASAPI_PlayDevice;
+    impl->WaitDevice = WASAPI_WaitDevice;
+    impl->GetPendingBytes = WASAPI_GetPendingBytes;
+    impl->GetDeviceBuf = WASAPI_GetDeviceBuf;
+    impl->CaptureFromDevice = WASAPI_CaptureFromDevice;
+    impl->FlushCapture = WASAPI_FlushCapture;
+    impl->CloseDevice = WASAPI_CloseDevice;
+    impl->Deinitialize = WASAPI_Deinitialize;
+    impl->HasCaptureSupport = 1;
+
+    return 1;   /* this audio target is available. */
+}
+
+AudioBootStrap WASAPI_bootstrap = {
+    "wasapi", "WASAPI", WASAPI_Init, 0
+};
+
+#endif  /* SDL_AUDIO_DRIVER_WASAPI */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/pulseaudio/SDL_pulseaudio.h b/src/audio/wasapi/SDL_wasapi.h
similarity index 71%
copy from src/audio/pulseaudio/SDL_pulseaudio.h
copy to src/audio/wasapi/SDL_wasapi.h
index e12000f..530c73d 100644
--- a/src/audio/pulseaudio/SDL_pulseaudio.h
+++ b/src/audio/wasapi/SDL_wasapi.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,10 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_pulseaudio_h
-#define _SDL_pulseaudio_h
-
-#include <pulse/simple.h>
+#ifndef SDL_wasapi_h_
+#define SDL_wasapi_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -32,21 +30,19 @@
 
 struct SDL_PrivateAudioData
 {
-    char *device_name;
-
-    /* pulseaudio structures */
-    pa_mainloop *mainloop;
-    pa_context *context;
-    pa_stream *stream;
-
-    /* Raw mixing buffer */
-    Uint8 *mixbuf;
-    int mixlen;
-
-    const Uint8 *capturebuf;
-    int capturelen;
+    IMMDevice *device;
+    WAVEFORMATEX *waveformat;
+    IAudioClient *client;
+    IAudioRenderClient *render;
+    IAudioCaptureClient *capture;
+    SDL_AudioStream *capturestream;
+    HANDLE task;
+    SDL_bool coinitialized;
+    int framesize;
+    int default_device_generation;
+    SDL_bool device_lost;
 };
 
-#endif /* _SDL_pulseaudio_h */
+#endif /* SDL_wasapi_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/winmm/SDL_winmm.c b/src/audio/winmm/SDL_winmm.c
index 34f543d..71a5dc9 100644
--- a/src/audio/winmm/SDL_winmm.c
+++ b/src/audio/winmm/SDL_winmm.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,6 +33,40 @@
 #include "../SDL_audio_c.h"
 #include "SDL_winmm.h"
 
+/* MinGW32 mmsystem.h doesn't include these structures */
+#if defined(__MINGW32__) && defined(_MMSYSTEM_H)
+
+typedef struct tagWAVEINCAPS2W 
+{
+    WORD wMid;
+    WORD wPid;
+    MMVERSION vDriverVersion;
+    WCHAR szPname[MAXPNAMELEN];
+    DWORD dwFormats;
+    WORD wChannels;
+    WORD wReserved1;
+    GUID ManufacturerGuid;
+    GUID ProductGuid;
+    GUID NameGuid;
+} WAVEINCAPS2W,*PWAVEINCAPS2W,*NPWAVEINCAPS2W,*LPWAVEINCAPS2W;
+
+typedef struct tagWAVEOUTCAPS2W
+{
+    WORD wMid;
+    WORD wPid;
+    MMVERSION vDriverVersion;
+    WCHAR szPname[MAXPNAMELEN];
+    DWORD dwFormats;
+    WORD wChannels;
+    WORD wReserved1;
+    DWORD dwSupport;
+    GUID ManufacturerGuid;
+    GUID ProductGuid;
+    GUID NameGuid;
+} WAVEOUTCAPS2W,*PWAVEOUTCAPS2W,*NPWAVEOUTCAPS2W,*LPWAVEOUTCAPS2W;
+
+#endif /* defined(__MINGW32__) && defined(_MMSYSTEM_H) */
+
 #ifndef WAVE_FORMAT_IEEE_FLOAT
 #define WAVE_FORMAT_IEEE_FLOAT 0x0003
 #endif
diff --git a/src/audio/winmm/SDL_winmm.h b/src/audio/winmm/SDL_winmm.h
index 401db39..9628f08 100644
--- a/src/audio/winmm/SDL_winmm.h
+++ b/src/audio/winmm/SDL_winmm.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_winmm_h
-#define _SDL_winmm_h
+#ifndef SDL_winmm_h_
+#define SDL_winmm_h_
 
 #include "../SDL_sysaudio.h"
 
@@ -40,6 +40,6 @@ struct SDL_PrivateAudioData
     int next_buffer;
 };
 
-#endif /* _SDL_winmm_h */
+#endif /* SDL_winmm_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/xaudio2/SDL_xaudio2.c b/src/audio/xaudio2/SDL_xaudio2.c
index a18e5d2..6faa170 100644
--- a/src/audio/xaudio2/SDL_xaudio2.c
+++ b/src/audio/xaudio2/SDL_xaudio2.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -78,8 +78,8 @@
 #else
 #  define SDL_XAUDIO2_HAS_SDK 1
 #endif
-#endif
 #endif /* 0 */
+#endif /* __GNUC__ */
 
 #ifdef SDL_XAUDIO2_HAS_SDK
 
@@ -90,7 +90,7 @@
 #endif
 #endif
 
-#if !defined(_SDL_XAUDIO2_H)
+#if !defined(SDL_XAUDIO2_H_)
 #define INITGUID 1
 #include <xaudio2.h>
 #endif
@@ -453,6 +453,7 @@ XAUDIO2_Init(SDL_AudioDriverImpl * impl)
 #else
     /* XAudio2Create() is a macro that uses COM; we don't load the .dll */
     IXAudio2 *ixa2 = NULL;
+    HRESULT hr = S_FALSE;
 #if defined(__WIN32__)
     // TODO, WinRT: Investigate using CoInitializeEx here
     if (FAILED(WIN_CoInitialize())) {
@@ -461,11 +462,12 @@ XAUDIO2_Init(SDL_AudioDriverImpl * impl)
     }
 #endif
 
-    if (XAudio2Create(&ixa2, 0, XAUDIO2_DEFAULT_PROCESSOR) != S_OK) {
+    hr = XAudio2Create( &ixa2, 0, XAUDIO2_DEFAULT_PROCESSOR );
+    if ( hr != S_OK) {
 #if defined(__WIN32__)
         WIN_CoUninitialize();
 #endif
-        SDL_SetError("XAudio2: XAudio2Create() failed at initialization");
+        SDL_SetError("XAudio2: XAudio2Create() failed at initialization: 0x%.8x", hr );
         return 0;  /* not available. */
     }
     IXAudio2_Release(ixa2);
diff --git a/src/audio/xaudio2/SDL_xaudio2.h b/src/audio/xaudio2/SDL_xaudio2.h
index 864eba4..cbfd3cd 100644
--- a/src/audio/xaudio2/SDL_xaudio2.h
+++ b/src/audio/xaudio2/SDL_xaudio2.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_XAUDIO2_H
-#define _SDL_XAUDIO2_H
+#ifndef SDL_XAUDIO2_H_
+#define SDL_XAUDIO2_H_
 
 #include <windows.h>
 #include <mmreg.h>
@@ -381,6 +381,6 @@ const struct IXAudio2VoiceCallbackVtbl
 
 #pragma pack(pop)   /* Undo pragma push */
 
-#endif  /* _SDL_XAUDIO2_H */
+#endif  /* SDL_XAUDIO2_H_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/xaudio2/SDL_xaudio2_winrthelpers.cpp b/src/audio/xaudio2/SDL_xaudio2_winrthelpers.cpp
index b2d67c7..8915023 100644
--- a/src/audio/xaudio2/SDL_xaudio2_winrthelpers.cpp
+++ b/src/audio/xaudio2/SDL_xaudio2_winrthelpers.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/audio/xaudio2/SDL_xaudio2_winrthelpers.h b/src/audio/xaudio2/SDL_xaudio2_winrthelpers.h
index aa6486f..ff08faf 100644
--- a/src/audio/xaudio2/SDL_xaudio2_winrthelpers.h
+++ b/src/audio/xaudio2/SDL_xaudio2_winrthelpers.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/core/android/SDL_android.c b/src/core/android/SDL_android.c
index b93b162..a7f4e52 100644
--- a/src/core/android/SDL_android.c
+++ b/src/core/android/SDL_android.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,6 +23,7 @@
 #include "SDL_assert.h"
 #include "SDL_hints.h"
 #include "SDL_log.h"
+#include "SDL_main.h"
 
 #ifdef __ANDROID__
 
@@ -37,17 +38,135 @@
 #include "../../video/android/SDL_androidvideo.h"
 #include "../../video/android/SDL_androidwindow.h"
 #include "../../joystick/android/SDL_sysjoystick_c.h"
+#include "../../haptic/android/SDL_syshaptic_c.h"
 
 #include <android/log.h>
 #include <pthread.h>
 #include <sys/types.h>
 #include <unistd.h>
-#define LOG_TAG "SDL_android"
+#include <dlfcn.h>
+/* #define LOG_TAG "SDL_android" */
 /* #define LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) */
 /* #define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) */
 #define LOGI(...) do {} while (0)
 #define LOGE(...) do {} while (0)
 
+
+#define SDL_JAVA_PREFIX                                 org_libsdl_app
+#define CONCAT1(prefix, class, function)                CONCAT2(prefix, class, function)
+#define CONCAT2(prefix, class, function)                Java_ ## prefix ## _ ## class ## _ ## function
+#define SDL_JAVA_INTERFACE(function)                    CONCAT1(SDL_JAVA_PREFIX, SDLActivity, function)
+#define SDL_JAVA_INTERFACE_INPUT_CONNECTION(function)   CONCAT1(SDL_JAVA_PREFIX, SDLInputConnection, function)
+
+
+/* Java class SDLActivity */
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(
+        JNIEnv* mEnv, jclass cls);
+
+JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeRunMain)(
+        JNIEnv* env, jclass cls,
+        jstring library, jstring function, jobject array);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
+        JNIEnv* env, jclass jcls,
+        jstring filename);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeResize)(
+        JNIEnv* env, jclass jcls,
+        jint width, jint height, jint format, jfloat rate);
+
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(onNativePadDown)(
+        JNIEnv* env, jclass jcls,
+        jint device_id, jint keycode);
+
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(onNativePadUp)(
+        JNIEnv* env, jclass jcls,
+        jint device_id, jint keycode);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeJoy)(
+        JNIEnv* env, jclass jcls,
+        jint device_id, jint axis, jfloat value);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeHat)(
+        JNIEnv* env, jclass jcls,
+        jint device_id, jint hat_id, jint x, jint y);
+
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeAddJoystick)(
+        JNIEnv* env, jclass jcls,
+        jint device_id, jstring device_name, jstring device_desc, jint is_accelerometer,
+        jint nbuttons, jint naxes, jint nhats, jint nballs);
+
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeRemoveJoystick)(
+        JNIEnv* env, jclass jcls,
+        jint device_id);
+
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeAddHaptic)(
+        JNIEnv* env, jclass jcls,
+        jint device_id, jstring device_name);
+
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeRemoveHaptic)(
+        JNIEnv* env, jclass jcls,
+        jint device_id);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceChanged)(
+        JNIEnv* env, jclass jcls);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceDestroyed)(
+        JNIEnv* env, jclass jcls);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyDown)(
+        JNIEnv* env, jclass jcls,
+        jint keycode);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyUp)(
+        JNIEnv* env, jclass jcls,
+        jint keycode);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost)(
+        JNIEnv* env, jclass jcls);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
+        JNIEnv* env, jclass jcls,
+        jint touch_device_id_in, jint pointer_finger_id_in,
+        jint action, jfloat x, jfloat y, jfloat p);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeMouse)(
+        JNIEnv* env, jclass jcls,
+        jint button, jint action, jfloat x, jfloat y);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeAccel)(
+        JNIEnv* env, jclass jcls,
+        jfloat x, jfloat y, jfloat z);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeClipboardChanged)(
+        JNIEnv* env, jclass jcls);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeLowMemory)(
+        JNIEnv* env, jclass cls);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeQuit)(
+        JNIEnv* env, jclass cls);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePause)(
+        JNIEnv* env, jclass cls);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeResume)(
+        JNIEnv* env, jclass cls);
+
+JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetHint)(
+        JNIEnv* env, jclass cls,
+        jstring name);
+
+/* Java class SDLInputConnection */
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText)(
+        JNIEnv* env, jclass cls,
+        jstring text, jint newCursorPosition);
+
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeSetComposingText)(
+        JNIEnv* env, jclass cls,
+        jstring text, jint newCursorPosition);
+
+
 /* Uncomment this to log messages entering and exiting methods in this file */
 /* #define DEBUG_JNI */
 
@@ -57,7 +176,6 @@ static void Android_JNI_ThreadDestroyed(void*);
  This file links the Java side of Android with libsdl
 *******************************************************************************/
 #include <jni.h>
-#include <android/log.h>
 
 
 /*******************************************************************************
@@ -80,6 +198,22 @@ static jmethodID midCaptureReadShortBuffer;
 static jmethodID midCaptureReadByteBuffer;
 static jmethodID midCaptureClose;
 static jmethodID midPollInputDevices;
+static jmethodID midPollHapticDevices;
+static jmethodID midHapticRun;
+static jmethodID midSetActivityTitle;
+static jmethodID midSetOrientation;
+static jmethodID midGetContext;
+static jmethodID midInputGetInputDeviceIds;
+static jmethodID midSendMessage;
+static jmethodID midShowTextInput;
+static jmethodID midIsScreenKeyboardShown;
+static jmethodID midClipboardSetText;
+static jmethodID midClipboardGetText;
+static jmethodID midClipboardHasText;
+
+
+/* static fields */
+static jfieldID fidSeparateMouseAndTouch;
 
 /* Accelerometer data storage */
 static float fLastAccelerometer[3];
@@ -112,9 +246,9 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
 }
 
 /* Called before SDL_main() to initialize JNI bindings */
-JNIEXPORT void JNICALL SDL_Android_Init(JNIEnv* mEnv, jclass cls)
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(JNIEnv* mEnv, jclass cls)
 {
-    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init()");
+    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeSetupJNI()");
 
     Android_JNI_SetupThread();
 
@@ -140,20 +274,135 @@ JNIEXPORT void JNICALL SDL_Android_Init(JNIEnv* mEnv, jclass cls)
                                 "captureClose", "()V");
     midPollInputDevices = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
                                 "pollInputDevices", "()V");
+    midPollHapticDevices = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "pollHapticDevices", "()V");
+    midHapticRun = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "hapticRun", "(II)V");
+    midSetActivityTitle = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "setActivityTitle","(Ljava/lang/String;)Z");
+    midSetOrientation = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "setOrientation","(IIZLjava/lang/String;)V");
+    midGetContext = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "getContext","()Landroid/content/Context;");
+    midInputGetInputDeviceIds = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "inputGetInputDeviceIds", "(I)[I");
+    midSendMessage = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "sendMessage", "(II)Z");
+    midShowTextInput =  (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "showTextInput", "(IIII)Z");
+    midIsScreenKeyboardShown = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "isScreenKeyboardShown","()Z");
+    midClipboardSetText = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "clipboardSetText", "(Ljava/lang/String;)V");
+    midClipboardGetText = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "clipboardGetText", "()Ljava/lang/String;");
+    midClipboardHasText = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
+                                "clipboardHasText", "()Z");
 
     bHasNewData = SDL_FALSE;
 
     if (!midGetNativeSurface ||
        !midAudioOpen || !midAudioWriteShortBuffer || !midAudioWriteByteBuffer || !midAudioClose ||
        !midCaptureOpen || !midCaptureReadShortBuffer || !midCaptureReadByteBuffer || !midCaptureClose ||
-       !midPollInputDevices) {
-        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL: Couldn't locate Java callbacks, check that they're named and typed correctly");
+       !midPollInputDevices || !midPollHapticDevices || !midHapticRun ||
+       !midSetActivityTitle || !midSetOrientation || !midGetContext || !midInputGetInputDeviceIds ||
+       !midSendMessage || !midShowTextInput || !midIsScreenKeyboardShown || 
+       !midClipboardSetText || !midClipboardGetText || !midClipboardHasText) {
+        __android_log_print(ANDROID_LOG_WARN, "SDL", "Missing some Java callbacks, do you have the latest version of SDLActivity.java?");
+    }
+
+    fidSeparateMouseAndTouch = (*mEnv)->GetStaticFieldID(mEnv, mActivityClass, "mSeparateMouseAndTouch", "Z");
+
+    if (!fidSeparateMouseAndTouch) {
+        __android_log_print(ANDROID_LOG_WARN, "SDL", "Missing some Java static fields, do you have the latest version of SDLActivity.java?");
     }
-    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init() finished!");
+
+    SDL_SetMainReady();
+}
+
+/* SDL main function prototype */
+typedef int (*SDL_main_func)(int argc, char *argv[]);
+
+/* Start up the SDL app */
+JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeRunMain)(JNIEnv* env, jclass cls, jstring library, jstring function, jobject array)
+{
+    int status = -1;
+    const char *library_file;
+    void *library_handle;
+
+    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeRunMain()");
+
+    library_file = (*env)->GetStringUTFChars(env, library, NULL);
+    library_handle = dlopen(library_file, RTLD_GLOBAL);
+    if (library_handle) {
+        const char *function_name;
+        SDL_main_func SDL_main;
+
+        function_name = (*env)->GetStringUTFChars(env, function, NULL);
+        SDL_main = (SDL_main_func)dlsym(library_handle, function_name);
+        if (SDL_main) {
+            int i;
+            int argc;
+            int len;
+            char **argv;
+
+            /* Prepare the arguments. */
+            len = (*env)->GetArrayLength(env, array);
+            argv = SDL_stack_alloc(char*, 1 + len + 1);
+            argc = 0;
+            /* Use the name "app_process" so PHYSFS_platformCalcBaseDir() works.
+               https://bitbucket.org/MartinFelis/love-android-sdl2/issue/23/release-build-crash-on-start
+             */
+            argv[argc++] = SDL_strdup("app_process");
+            for (i = 0; i < len; ++i) {
+                const char* utf;
+                char* arg = NULL;
+                jstring string = (*env)->GetObjectArrayElement(env, array, i);
+                if (string) {
+                    utf = (*env)->GetStringUTFChars(env, string, 0);
+                    if (utf) {
+                        arg = SDL_strdup(utf);
+                        (*env)->ReleaseStringUTFChars(env, string, utf);
+                    }
+                    (*env)->DeleteLocalRef(env, string);
+                }
+                if (!arg) {
+                    arg = SDL_strdup("");
+                }
+                argv[argc++] = arg;
+            }
+            argv[argc] = NULL;
+
+
+            /* Run the application. */
+            status = SDL_main(argc, argv);
+
+            /* Release the arguments. */
+            for (i = 0; i < argc; ++i) {
+                SDL_free(argv[i]);
+            }
+            SDL_stack_free(argv);
+
+        } else {
+            __android_log_print(ANDROID_LOG_ERROR, "SDL", "nativeRunMain(): Couldn't find function %s in library %s", function_name, library_file);
+        }
+        (*env)->ReleaseStringUTFChars(env, function, function_name);
+
+        dlclose(library_handle);
+
+    } else {
+        __android_log_print(ANDROID_LOG_ERROR, "SDL", "nativeRunMain(): Couldn't load library %s", library_file);
+    }
+    (*env)->ReleaseStringUTFChars(env, library, library_file);
+
+    /* Do not issue an exit or the whole application will terminate instead of just the SDL thread */
+    /* exit(status); */
+
+    return status;
 }
 
 /* Drop file */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeDropFile(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
                                     JNIEnv* env, jclass jcls,
                                     jstring filename)
 {
@@ -164,7 +413,7 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeDropFile(
 }
 
 /* Resize */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeResize(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeResize)(
                                     JNIEnv* env, jclass jcls,
                                     jint width, jint height, jint format, jfloat rate)
 {
@@ -172,7 +421,7 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeResize(
 }
 
 /* Paddown */
-JNIEXPORT jint JNICALL Java_org_libsdl_app_SDLActivity_onNativePadDown(
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(onNativePadDown)(
                                     JNIEnv* env, jclass jcls,
                                     jint device_id, jint keycode)
 {
@@ -180,15 +429,15 @@ JNIEXPORT jint JNICALL Java_org_libsdl_app_SDLActivity_onNativePadDown(
 }
 
 /* Padup */
-JNIEXPORT jint JNICALL Java_org_libsdl_app_SDLActivity_onNativePadUp(
-                                   JNIEnv* env, jclass jcls,
-                                   jint device_id, jint keycode)
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(onNativePadUp)(
+                                    JNIEnv* env, jclass jcls,
+                                    jint device_id, jint keycode)
 {
     return Android_OnPadUp(device_id, keycode);
 }
 
 /* Joy */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeJoy(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeJoy)(
                                     JNIEnv* env, jclass jcls,
                                     jint device_id, jint axis, jfloat value)
 {
@@ -196,7 +445,7 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeJoy(
 }
 
 /* POV Hat */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeHat(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeHat)(
                                     JNIEnv* env, jclass jcls,
                                     jint device_id, jint hat_id, jint x, jint y)
 {
@@ -204,30 +453,52 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeHat(
 }
 
 
-JNIEXPORT jint JNICALL Java_org_libsdl_app_SDLActivity_nativeAddJoystick(
-    JNIEnv* env, jclass jcls,
-    jint device_id, jstring device_name, jint is_accelerometer, 
-    jint nbuttons, jint naxes, jint nhats, jint nballs)
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeAddJoystick)(
+                                    JNIEnv* env, jclass jcls,
+                                    jint device_id, jstring device_name, jstring device_desc, jint is_accelerometer,
+                                    jint nbuttons, jint naxes, jint nhats, jint nballs)
 {
     int retval;
     const char *name = (*env)->GetStringUTFChars(env, device_name, NULL);
+    const char *desc = (*env)->GetStringUTFChars(env, device_desc, NULL);
 
-    retval = Android_AddJoystick(device_id, name, (SDL_bool) is_accelerometer, nbuttons, naxes, nhats, nballs);
+    retval = Android_AddJoystick(device_id, name, desc, (SDL_bool) is_accelerometer, nbuttons, naxes, nhats, nballs);
 
     (*env)->ReleaseStringUTFChars(env, device_name, name);
-    
+    (*env)->ReleaseStringUTFChars(env, device_desc, desc);
+
     return retval;
 }
 
-JNIEXPORT jint JNICALL Java_org_libsdl_app_SDLActivity_nativeRemoveJoystick(
-    JNIEnv* env, jclass jcls, jint device_id)
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeRemoveJoystick)(
+                                    JNIEnv* env, jclass jcls,
+                                    jint device_id)
 {
     return Android_RemoveJoystick(device_id);
 }
 
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeAddHaptic)(
+    JNIEnv* env, jclass jcls, jint device_id, jstring device_name)
+{
+    int retval;
+    const char *name = (*env)->GetStringUTFChars(env, device_name, NULL);
+
+    retval = Android_AddHaptic(device_id, name);
+
+    (*env)->ReleaseStringUTFChars(env, device_name, name);
+
+    return retval;
+}
+
+JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeRemoveHaptic)(
+    JNIEnv* env, jclass jcls, jint device_id)
+{
+    return Android_RemoveHaptic(device_id);
+}
+
 
 /* Surface Created */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeSurfaceChanged(JNIEnv* env, jclass jcls)
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceChanged)(JNIEnv* env, jclass jcls)
 {
     SDL_WindowData *data;
     SDL_VideoDevice *_this;
@@ -235,10 +506,10 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeSurfaceChanged(JN
     if (Android_Window == NULL || Android_Window->driverdata == NULL ) {
         return;
     }
-    
+
     _this =  SDL_GetVideoDevice();
     data =  (SDL_WindowData *) Android_Window->driverdata;
-    
+
     /* If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here */
     if (data->egl_surface == EGL_NO_SURFACE) {
         if(data->native_window) {
@@ -247,13 +518,13 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeSurfaceChanged(JN
         data->native_window = Android_JNI_GetNativeWindow();
         data->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) data->native_window);
     }
-    
+
     /* GL Context handling is done in the event loop because this function is run from the Java thread */
-    
+
 }
 
 /* Surface Destroyed */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeSurfaceDestroyed(JNIEnv* env, jclass jcls)
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceDestroyed)(JNIEnv* env, jclass jcls)
 {
     /* We have to clear the current context and destroy the egl surface here
      * Otherwise there's BAD_NATIVE_WINDOW errors coming from eglCreateWindowSurface on resume
@@ -261,40 +532,42 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeSurfaceDestroyed(
      */
     SDL_WindowData *data;
     SDL_VideoDevice *_this;
-    
+
     if (Android_Window == NULL || Android_Window->driverdata == NULL ) {
         return;
     }
-    
+
     _this =  SDL_GetVideoDevice();
     data = (SDL_WindowData *) Android_Window->driverdata;
-    
+
     if (data->egl_surface != EGL_NO_SURFACE) {
         SDL_EGL_MakeCurrent(_this, NULL, NULL);
         SDL_EGL_DestroySurface(_this, data->egl_surface);
         data->egl_surface = EGL_NO_SURFACE;
     }
-    
+
     /* GL Context handling is done in the event loop because this function is run from the Java thread */
 
 }
 
 /* Keydown */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeKeyDown(
-                                    JNIEnv* env, jclass jcls, jint keycode)
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyDown)(
+                                    JNIEnv* env, jclass jcls,
+                                    jint keycode)
 {
     Android_OnKeyDown(keycode);
 }
 
 /* Keyup */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeKeyUp(
-                                    JNIEnv* env, jclass jcls, jint keycode)
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyUp)(
+                                    JNIEnv* env, jclass jcls,
+                                    jint keycode)
 {
     Android_OnKeyUp(keycode);
 }
 
 /* Keyboard Focus Lost */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeKeyboardFocusLost(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost)(
                                     JNIEnv* env, jclass jcls)
 {
     /* Calling SDL_StopTextInput will take care of hiding the keyboard and cleaning up the DummyText widget */
@@ -303,7 +576,7 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeKeyboardFocusLost
 
 
 /* Touch */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeTouch(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
                                     JNIEnv* env, jclass jcls,
                                     jint touch_device_id_in, jint pointer_finger_id_in,
                                     jint action, jfloat x, jfloat y, jfloat p)
@@ -312,7 +585,7 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeTouch(
 }
 
 /* Mouse */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeMouse(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeMouse)(
                                     JNIEnv* env, jclass jcls,
                                     jint button, jint action, jfloat x, jfloat y)
 {
@@ -320,7 +593,7 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeMouse(
 }
 
 /* Accelerometer */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeAccel(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeAccel)(
                                     JNIEnv* env, jclass jcls,
                                     jfloat x, jfloat y, jfloat z)
 {
@@ -330,15 +603,22 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeAccel(
     bHasNewData = SDL_TRUE;
 }
 
+/* Clipboard */
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeClipboardChanged)(
+                                    JNIEnv* env, jclass jcls)
+{
+    SDL_SendClipboardUpdate();
+}
+
 /* Low memory */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_nativeLowMemory(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeLowMemory)(
                                     JNIEnv* env, jclass cls)
 {
     SDL_SendAppEvent(SDL_APP_LOWMEMORY);
 }
 
 /* Quit */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_nativeQuit(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeQuit)(
                                     JNIEnv* env, jclass cls)
 {
     /* Discard previous events. The user should have handled state storage
@@ -354,24 +634,25 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_nativeQuit(
 }
 
 /* Pause */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_nativePause(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePause)(
                                     JNIEnv* env, jclass cls)
 {
     __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativePause()");
+
     if (Android_Window) {
         SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
         SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
         SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
         SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
-    
-        /* *After* sending the relevant events, signal the pause semaphore 
+
+        /* *After* sending the relevant events, signal the pause semaphore
          * so the event loop knows to pause and (optionally) block itself */
         if (!SDL_SemValue(Android_PauseSem)) SDL_SemPost(Android_PauseSem);
     }
 }
 
 /* Resume */
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_nativeResume(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeResume)(
                                     JNIEnv* env, jclass cls)
 {
     __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeResume()");
@@ -389,7 +670,7 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_nativeResume(
     }
 }
 
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLInputConnection_nativeCommitText(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText)(
                                     JNIEnv* env, jclass cls,
                                     jstring text, jint newCursorPosition)
 {
@@ -400,7 +681,7 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLInputConnection_nativeCommitText(
     (*env)->ReleaseStringUTFChars(env, text, utftext);
 }
 
-JNIEXPORT void JNICALL Java_org_libsdl_app_SDLInputConnection_nativeSetComposingText(
+JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeSetComposingText)(
                                     JNIEnv* env, jclass cls,
                                     jstring text, jint newCursorPosition)
 {
@@ -411,7 +692,10 @@ JNIEXPORT void JNICALL Java_org_libsdl_app_SDLInputConnection_nativeSetComposing
     (*env)->ReleaseStringUTFChars(env, text, utftext);
 }
 
-JNIEXPORT jstring JNICALL Java_org_libsdl_app_SDLActivity_nativeGetHint(JNIEnv* env, jclass cls, jstring name) {
+JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetHint)(
+                                    JNIEnv* env, jclass cls,
+                                    jstring name)
+{
     const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
     const char *hint = SDL_GetHint(utfname);
 
@@ -481,20 +765,26 @@ ANativeWindow* Android_JNI_GetNativeWindow(void)
     s = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetNativeSurface);
     anw = ANativeWindow_fromSurface(env, s);
     (*env)->DeleteLocalRef(env, s);
-  
+
     return anw;
 }
 
 void Android_JNI_SetActivityTitle(const char *title)
 {
-    jmethodID mid;
     JNIEnv *mEnv = Android_JNI_GetEnv();
-    mid = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,"setActivityTitle","(Ljava/lang/String;)Z");
-    if (mid) {
-        jstring jtitle = (jstring)((*mEnv)->NewStringUTF(mEnv, title));
-        (*mEnv)->CallStaticBooleanMethod(mEnv, mActivityClass, mid, jtitle);
-        (*mEnv)->DeleteLocalRef(mEnv, jtitle);
-    }
+
+    jstring jtitle = (jstring)((*mEnv)->NewStringUTF(mEnv, title));
+    (*mEnv)->CallStaticBooleanMethod(mEnv, mActivityClass, midSetActivityTitle, jtitle);
+    (*mEnv)->DeleteLocalRef(mEnv, jtitle);
+}
+
+void Android_JNI_SetOrientation(int w, int h, int resizable, const char *hint)
+{
+    JNIEnv *mEnv = Android_JNI_GetEnv();
+
+    jstring jhint = (jstring)((*mEnv)->NewStringUTF(mEnv, (hint ? hint : "")));
+    (*mEnv)->CallStaticVoidMethod(mEnv, mActivityClass, midSetOrientation, w, h, (resizable? 1 : 0), jhint);
+    (*mEnv)->DeleteLocalRef(mEnv, jhint);
 }
 
 SDL_bool Android_JNI_GetAccelerometerValues(float values[3])
@@ -708,7 +998,7 @@ int Android_JNI_CaptureAudioBuffer(void *buffer, int buflen)
 void Android_JNI_FlushCapturedAudio(void)
 {
     JNIEnv *env = Android_JNI_GetEnv();
-    #if 0  /* !!! FIXME: this needs API 23, or it'll do blocking reads and never end. */
+#if 0  /* !!! FIXME: this needs API 23, or it'll do blocking reads and never end. */
     if (captureBuffer16Bit) {
         const jint len = (*env)->GetArrayLength(env, (jshortArray)captureBuffer);
         while ((*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadShortBuffer, (jshortArray)captureBuffer, JNI_FALSE) == len) { /* spin */ }
@@ -716,13 +1006,13 @@ void Android_JNI_FlushCapturedAudio(void)
         const jint len = (*env)->GetArrayLength(env, (jbyteArray)captureBuffer);
         while ((*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadByteBuffer, (jbyteArray)captureBuffer, JNI_FALSE) == len) { /* spin */ }
     }
-    #else
+#else
     if (captureBuffer16Bit) {
         (*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadShortBuffer, (jshortArray)captureBuffer, JNI_FALSE);
     } else {
         (*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadByteBuffer, (jbyteArray)captureBuffer, JNI_FALSE);
     }
-    #endif
+#endif
 }
 
 void Android_JNI_CloseAudioDevice(const int iscapture)
@@ -818,10 +1108,7 @@ static int Internal_Android_JNI_FileOpen(SDL_RWops* ctx)
     ctx->hidden.androidio.position = 0;
 
     /* context = SDLActivity.getContext(); */
-    mid = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
-            "getContext","()Landroid/content/Context;");
-    context = (*mEnv)->CallStaticObjectMethod(mEnv, mActivityClass, mid);
-
+    context = (*mEnv)->CallStaticObjectMethod(mEnv, mActivityClass, midGetContext);
 
     /* assetManager = context.getAssets(); */
     mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, context),
@@ -897,7 +1184,7 @@ fallback:
          * android/apis/content/ReadAsset.java imply that Android's
          * AssetInputStream.available() /will/ always return the total file size
         */
-        
+
         /* size = inputStream.available(); */
         mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream),
                 "available", "()I");
@@ -945,7 +1232,7 @@ failure:
         }
 
     }
-    
+
     LocalReferenceHolder_Cleanup(&refs);
     return result;
 }
@@ -959,7 +1246,7 @@ int Android_JNI_FileOpen(SDL_RWops* ctx,
     jstring fileNameJString;
 
     if (!LocalReferenceHolder_Init(&refs, mEnv)) {
-        LocalReferenceHolder_Cleanup(&refs);        
+        LocalReferenceHolder_Cleanup(&refs);
         return -1;
     }
 
@@ -1013,7 +1300,7 @@ size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
 
         mEnv = Android_JNI_GetEnv();
         if (!LocalReferenceHolder_Init(&refs, mEnv)) {
-            LocalReferenceHolder_Cleanup(&refs);            
+            LocalReferenceHolder_Cleanup(&refs);
             return 0;
         }
 
@@ -1026,7 +1313,7 @@ size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
             int result = (*mEnv)->CallIntMethod(mEnv, readableByteChannel, readMethod, byteBuffer);
 
             if (Android_JNI_ExceptionOccurred(SDL_FALSE)) {
-                LocalReferenceHolder_Cleanup(&refs);            
+                LocalReferenceHolder_Cleanup(&refs);
                 return 0;
             }
 
@@ -1038,7 +1325,7 @@ size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
             bytesRead += result;
             ctx->hidden.androidio.position += result;
         }
-        LocalReferenceHolder_Cleanup(&refs);                    
+        LocalReferenceHolder_Cleanup(&refs);
         return bytesRead / size;
     }
 }
@@ -1195,120 +1482,41 @@ int Android_JNI_FileClose(SDL_RWops* ctx)
     return Internal_Android_JNI_FileClose(ctx, SDL_TRUE);
 }
 
-/* returns a new global reference which needs to be released later */
-static jobject Android_JNI_GetSystemServiceObject(const char* name)
-{
-    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
-    JNIEnv* env = Android_JNI_GetEnv();
-    jobject retval = NULL;
-    jstring service;
-    jmethodID mid;
-    jobject context;
-    jobject manager;
-
-    if (!LocalReferenceHolder_Init(&refs, env)) {
-        LocalReferenceHolder_Cleanup(&refs);
-        return NULL;
-    }
-
-    service = (*env)->NewStringUTF(env, name);
-
-    mid = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/content/Context;");
-    context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
-
-    mid = (*env)->GetMethodID(env, mActivityClass, "getSystemServiceFromUiThread", "(Ljava/lang/String;)Ljava/lang/Object;");
-    manager = (*env)->CallObjectMethod(env, context, mid, service);
-
-    (*env)->DeleteLocalRef(env, service);
-
-    retval = manager ? (*env)->NewGlobalRef(env, manager) : NULL;
-    LocalReferenceHolder_Cleanup(&refs);
-    return retval;
-}
-
-#define SETUP_CLIPBOARD(error) \
-    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__); \
-    JNIEnv* env = Android_JNI_GetEnv(); \
-    jobject clipboard; \
-    if (!LocalReferenceHolder_Init(&refs, env)) { \
-        LocalReferenceHolder_Cleanup(&refs); \
-        return error; \
-    } \
-    clipboard = Android_JNI_GetSystemServiceObject("clipboard"); \
-    if (!clipboard) { \
-        LocalReferenceHolder_Cleanup(&refs); \
-        return error; \
-    }
-
-#define CLEANUP_CLIPBOARD() \
-    LocalReferenceHolder_Cleanup(&refs);
-
 int Android_JNI_SetClipboardText(const char* text)
 {
-    /* Watch out for C89 scoping rules because of the macro */
-    SETUP_CLIPBOARD(-1)
-
-    /* Nest the following in a scope to avoid C89 declaration rules triggered by the macro */
-    {
-        jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "setText", "(Ljava/lang/CharSequence;)V");
-        jstring string = (*env)->NewStringUTF(env, text);
-        (*env)->CallVoidMethod(env, clipboard, mid, string);
-        (*env)->DeleteGlobalRef(env, clipboard);
-        (*env)->DeleteLocalRef(env, string);
-    }
-    CLEANUP_CLIPBOARD();
-
+    JNIEnv* env = Android_JNI_GetEnv();
+    jstring string = (*env)->NewStringUTF(env, text);
+    (*env)->CallStaticVoidMethod(env, mActivityClass, midClipboardSetText, string);
+    (*env)->DeleteLocalRef(env, string);
     return 0;
 }
 
 char* Android_JNI_GetClipboardText(void)
 {
-    /* Watch out for C89 scoping rules because of the macro */
-    SETUP_CLIPBOARD(SDL_strdup(""))
-
-    /* Nest the following in a scope to avoid C89 declaration rules triggered by the macro */
-    {
-        jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "getText", "()Ljava/lang/CharSequence;");
-        jobject sequence = (*env)->CallObjectMethod(env, clipboard, mid);
-        (*env)->DeleteGlobalRef(env, clipboard);
-        if (sequence) {
-            jstring string;
-            const char* utf;
-            mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, sequence), "toString", "()Ljava/lang/String;");
-            string = (jstring)((*env)->CallObjectMethod(env, sequence, mid));
-            utf = (*env)->GetStringUTFChars(env, string, 0);
-            if (utf) {
-                char* text = SDL_strdup(utf);
-                (*env)->ReleaseStringUTFChars(env, string, utf);
-
-                CLEANUP_CLIPBOARD();
-
-                return text;
-            }
+    JNIEnv* env = Android_JNI_GetEnv();
+    char* text = NULL;
+    jstring string;
+    
+    string = (*env)->CallStaticObjectMethod(env, mActivityClass, midClipboardGetText);
+    if (string) {
+        const char* utf = (*env)->GetStringUTFChars(env, string, 0);
+        if (utf) {
+            text = SDL_strdup(utf);
+            (*env)->ReleaseStringUTFChars(env, string, utf);
         }
+        (*env)->DeleteLocalRef(env, string);
     }
-    CLEANUP_CLIPBOARD();    
-
-    return SDL_strdup("");
+    
+    return (text == NULL) ? SDL_strdup("") : text;
 }
 
 SDL_bool Android_JNI_HasClipboardText(void)
 {
-    jmethodID mid;
-    jboolean has;
-    /* Watch out for C89 scoping rules because of the macro */
-    SETUP_CLIPBOARD(SDL_FALSE)
-
-    mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "hasText", "()Z");
-    has = (*env)->CallBooleanMethod(env, clipboard, mid);
-    (*env)->DeleteGlobalRef(env, clipboard);
-
-    CLEANUP_CLIPBOARD();
-    
-    return has ? SDL_TRUE : SDL_FALSE;
+    JNIEnv* env = Android_JNI_GetEnv();
+    jboolean retval = (*env)->CallStaticBooleanMethod(env, mActivityClass, midClipboardHasText);
+    return (retval == JNI_TRUE) ? SDL_TRUE : SDL_FALSE;
 }
 
-
 /* returns 0 on success or -1 on error (others undefined then)
  * returns truthy or falsy value in plugged, charged and battery
  * returns the value in seconds and percent or -1 if not available
@@ -1333,8 +1541,8 @@ int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seco
     }
 
 
-    mid = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/content/Context;");
-    context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
+    /* context = SDLActivity.getContext(); */
+    context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
 
     action = (*env)->NewStringUTF(env, "android.intent.action.BATTERY_CHANGED");
 
@@ -1405,7 +1613,7 @@ int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seco
     if (percent) {
         int level;
         int scale;
-        
+
         /* Watch out for C89 scoping rules because of the macro */
         {
             GET_INT_EXTRA(level_temp, "level") /* == BatteryManager.EXTRA_LEVEL (API 5) */
@@ -1416,7 +1624,7 @@ int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seco
             GET_INT_EXTRA(scale_temp, "scale") /* == BatteryManager.EXTRA_SCALE (API 5) */
             scale = scale_temp;
         }
-        
+
         if ((level == -1) || (scale == -1)) {
             LocalReferenceHolder_Cleanup(&refs);
             return -1;
@@ -1434,8 +1642,7 @@ int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seco
 int Android_JNI_GetTouchDeviceIds(int **ids) {
     JNIEnv *env = Android_JNI_GetEnv();
     jint sources = 4098; /* == InputDevice.SOURCE_TOUCHSCREEN */
-    jmethodID mid = (*env)->GetStaticMethodID(env, mActivityClass, "inputGetInputDeviceIds", "(I)[I");
-    jintArray array = (jintArray) (*env)->CallStaticObjectMethod(env, mActivityClass, mid, sources);
+    jintArray array = (jintArray) (*env)->CallStaticObjectMethod(env, mActivityClass, midInputGetInputDeviceIds, sources);
     int number = 0;
     *ids = NULL;
     if (array) {
@@ -1456,12 +1663,32 @@ int Android_JNI_GetTouchDeviceIds(int **ids) {
     return number;
 }
 
+/* sets the mSeparateMouseAndTouch field */
+void Android_JNI_SetSeparateMouseAndTouch(SDL_bool new_value)
+{
+    JNIEnv *env = Android_JNI_GetEnv();
+    (*env)->SetStaticBooleanField(env, mActivityClass, fidSeparateMouseAndTouch, new_value ? JNI_TRUE : JNI_FALSE);
+}
+
 void Android_JNI_PollInputDevices(void)
 {
     JNIEnv *env = Android_JNI_GetEnv();
-    (*env)->CallStaticVoidMethod(env, mActivityClass, midPollInputDevices);    
+    (*env)->CallStaticVoidMethod(env, mActivityClass, midPollInputDevices);
 }
 
+void Android_JNI_PollHapticDevices(void)
+{
+    JNIEnv *env = Android_JNI_GetEnv();
+    (*env)->CallStaticVoidMethod(env, mActivityClass, midPollHapticDevices);
+}
+
+void Android_JNI_HapticRun(int device_id, int length)
+{
+    JNIEnv *env = Android_JNI_GetEnv();
+    (*env)->CallStaticVoidMethod(env, mActivityClass, midHapticRun, device_id, length);
+}
+
+
 /* See SDLActivity.java for constants. */
 #define COMMAND_SET_KEEP_SCREEN_ON    5
 
@@ -1469,16 +1696,8 @@ void Android_JNI_PollInputDevices(void)
 int Android_JNI_SendMessage(int command, int param)
 {
     JNIEnv *env = Android_JNI_GetEnv();
-    jmethodID mid;
     jboolean success;
-    if (!env) {
-        return -1;
-    }
-    mid = (*env)->GetStaticMethodID(env, mActivityClass, "sendMessage", "(II)Z");
-    if (!mid) {
-        return -1;
-    }
-    success = (*env)->CallStaticBooleanMethod(env, mActivityClass, mid, command, param);
+    success = (*env)->CallStaticBooleanMethod(env, mActivityClass, midSendMessage, command, param);
     return success ? 0 : -1;
 }
 
@@ -1490,16 +1709,7 @@ void Android_JNI_SuspendScreenSaver(SDL_bool suspend)
 void Android_JNI_ShowTextInput(SDL_Rect *inputRect)
 {
     JNIEnv *env = Android_JNI_GetEnv();
-    jmethodID mid;
-    if (!env) {
-        return;
-    }
-
-    mid = (*env)->GetStaticMethodID(env, mActivityClass, "showTextInput", "(IIII)Z");
-    if (!mid) {
-        return;
-    }
-    (*env)->CallStaticBooleanMethod(env, mActivityClass, mid,
+    (*env)->CallStaticBooleanMethod(env, mActivityClass, midShowTextInput,
                                inputRect->x,
                                inputRect->y,
                                inputRect->w,
@@ -1513,6 +1723,15 @@ void Android_JNI_HideTextInput(void)
     Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
 }
 
+SDL_bool Android_JNI_IsScreenKeyboardShown()
+{
+    JNIEnv *mEnv = Android_JNI_GetEnv();
+    jboolean is_shown = 0;
+    is_shown = (*mEnv)->CallStaticBooleanMethod(mEnv, mActivityClass, midIsScreenKeyboardShown);
+    return is_shown;
+}
+
+
 int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
 {
     JNIEnv *env;
@@ -1567,11 +1786,8 @@ int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *bu
 
     (*env)->DeleteLocalRef(env, clazz);
 
-    /* call function */
-
-    mid = (*env)->GetStaticMethodID(env, mActivityClass, "getContext","()Landroid/content/Context;");
-
-    context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
+    /* context = SDLActivity.getContext(); */
+    context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
 
     clazz = (*env)->GetObjectClass(env, context);
 
@@ -1608,31 +1824,25 @@ int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *bu
 //////////////////////////////////////////////////////////////////////////////
 */
 
-void *SDL_AndroidGetJNIEnv()
+void *SDL_AndroidGetJNIEnv(void)
 {
     return Android_JNI_GetEnv();
 }
 
-
-
-void *SDL_AndroidGetActivity()
+void *SDL_AndroidGetActivity(void)
 {
     /* See SDL_system.h for caveats on using this function. */
 
-    jmethodID mid;
-
     JNIEnv *env = Android_JNI_GetEnv();
     if (!env) {
         return NULL;
     }
 
     /* return SDLActivity.getContext(); */
-    mid = (*env)->GetStaticMethodID(env, mActivityClass,
-            "getContext","()Landroid/content/Context;");
-    return (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
+    return (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
 }
 
-const char * SDL_AndroidGetInternalStoragePath()
+const char * SDL_AndroidGetInternalStoragePath(void)
 {
     static char *s_AndroidInternalFilesPath = NULL;
 
@@ -1651,9 +1861,7 @@ const char * SDL_AndroidGetInternalStoragePath()
         }
 
         /* context = SDLActivity.getContext(); */
-        mid = (*env)->GetStaticMethodID(env, mActivityClass,
-                "getContext","()Landroid/content/Context;");
-        context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
+        context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
 
         /* fileObj = context.getFilesDir(); */
         mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
@@ -1679,7 +1887,7 @@ const char * SDL_AndroidGetInternalStoragePath()
     return s_AndroidInternalFilesPath;
 }
 
-int SDL_AndroidGetExternalStorageState()
+int SDL_AndroidGetExternalStorageState(void)
 {
     struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
     jmethodID mid;
@@ -1718,7 +1926,7 @@ int SDL_AndroidGetExternalStorageState()
     return stateFlags;
 }
 
-const char * SDL_AndroidGetExternalStoragePath()
+const char * SDL_AndroidGetExternalStoragePath(void)
 {
     static char *s_AndroidExternalFilesPath = NULL;
 
@@ -1737,9 +1945,7 @@ const char * SDL_AndroidGetExternalStoragePath()
         }
 
         /* context = SDLActivity.getContext(); */
-        mid = (*env)->GetStaticMethodID(env, mActivityClass,
-                "getContext","()Landroid/content/Context;");
-        context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
+        context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
 
         /* fileObj = context.getExternalFilesDir(); */
         mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
@@ -1765,12 +1971,6 @@ const char * SDL_AndroidGetExternalStoragePath()
     return s_AndroidExternalFilesPath;
 }
 
-jclass Android_JNI_GetActivityClass(void)
-{
-    return mActivityClass;
-}
-
 #endif /* __ANDROID__ */
 
 /* vi: set ts=4 sw=4 expandtab: */
-
diff --git a/src/core/android/SDL_android.h b/src/core/android/SDL_android.h
index cb7ff07..e0ae7b5 100644
--- a/src/core/android/SDL_android.h
+++ b/src/core/android/SDL_android.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -34,9 +34,12 @@ extern "C" {
 
 /* Interface from the SDL library into the Android Java activity */
 extern void Android_JNI_SetActivityTitle(const char *title);
+extern void Android_JNI_SetOrientation(int w, int h, int resizable, const char *hint);
+
 extern SDL_bool Android_JNI_GetAccelerometerValues(float values[3]);
 extern void Android_JNI_ShowTextInput(SDL_Rect *inputRect);
 extern void Android_JNI_HideTextInput(void);
+extern SDL_bool Android_JNI_IsScreenKeyboardShown(void);
 extern ANativeWindow* Android_JNI_GetNativeWindow(void);
 
 /* Audio support */
@@ -67,21 +70,32 @@ int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seco
 /* Joystick support */
 void Android_JNI_PollInputDevices(void);
 
+/* Haptic support */
+void Android_JNI_PollHapticDevices(void);
+void Android_JNI_HapticRun(int device_id, int length);
+
 /* Video */
 void Android_JNI_SuspendScreenSaver(SDL_bool suspend);
 
 /* Touch support */
 int Android_JNI_GetTouchDeviceIds(int **ids);
+void Android_JNI_SetSeparateMouseAndTouch(SDL_bool new_value);
 
 /* Threads */
 #include <jni.h>
 JNIEnv *Android_JNI_GetEnv(void);
 int Android_JNI_SetupThread(void);
-jclass Android_JNI_GetActivityClass(void);
 
 /* Generic messages */
 int Android_JNI_SendMessage(int command, int param);
 
+/* Init */
+JNIEXPORT void JNICALL SDL_Android_Init(JNIEnv* mEnv, jclass cls);
+
+/* MessageBox */
+#include "SDL_messagebox.h"
+int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid);
+
 /* Ends C function definitions when using C++ */
 #ifdef __cplusplus
 /* *INDENT-OFF* */
diff --git a/src/core/linux/SDL_dbus.c b/src/core/linux/SDL_dbus.c
index ab73ca1..5f47836 100644
--- a/src/core/linux/SDL_dbus.c
+++ b/src/core/linux/SDL_dbus.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -56,7 +56,9 @@ LoadDBUSSyms(void)
     SDL_DBUS_SYM(message_is_signal);
     SDL_DBUS_SYM(message_new_method_call);
     SDL_DBUS_SYM(message_append_args);
+    SDL_DBUS_SYM(message_append_args_valist);
     SDL_DBUS_SYM(message_get_args);
+    SDL_DBUS_SYM(message_get_args_valist);
     SDL_DBUS_SYM(message_iter_init);
     SDL_DBUS_SYM(message_iter_next);
     SDL_DBUS_SYM(message_iter_get_basic);
@@ -68,6 +70,7 @@ LoadDBUSSyms(void)
     SDL_DBUS_SYM(error_free);
     SDL_DBUS_SYM(get_local_machine_id);
     SDL_DBUS_SYM(free);
+    SDL_DBUS_SYM(free_string_array);
     SDL_DBUS_SYM(shutdown);
 
     #undef SDL_DBUS_SYM
@@ -112,14 +115,15 @@ SDL_DBus_Init(void)
         DBusError err;
         dbus.error_init(&err);
         dbus.session_conn = dbus.bus_get_private(DBUS_BUS_SESSION, &err);
+        if (!dbus.error_is_set(&err)) {
+            dbus.system_conn = dbus.bus_get_private(DBUS_BUS_SYSTEM, &err);
+        }
         if (dbus.error_is_set(&err)) {
             dbus.error_free(&err);
-            if (dbus.session_conn) {
-                dbus.connection_unref(dbus.session_conn);
-                dbus.session_conn = NULL;
-            }
+            SDL_DBus_Quit();
             return;  /* oh well */
         }
+        dbus.connection_set_exit_on_disconnect(dbus.system_conn, 0);
         dbus.connection_set_exit_on_disconnect(dbus.session_conn, 0);
     }
 }
@@ -127,12 +131,18 @@ SDL_DBus_Init(void)
 void
 SDL_DBus_Quit(void)
 {
+    if (dbus.system_conn) {
+        dbus.connection_close(dbus.system_conn);
+        dbus.connection_unref(dbus.system_conn);
+    }
     if (dbus.session_conn) {
         dbus.connection_close(dbus.session_conn);
         dbus.connection_unref(dbus.session_conn);
+    }
+    if (dbus.shutdown) {
         dbus.shutdown();
-        SDL_memset(&dbus, 0, sizeof(dbus));
     }
+    SDL_zero(dbus);
     UnloadDBUSLibrary();
 }
 
@@ -150,90 +160,171 @@ SDL_DBus_GetContext(void)
     }
 }
 
-void
-SDL_DBus_ScreensaverTickle(void)
+static SDL_bool
+SDL_DBus_CallMethodInternal(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, va_list ap)
 {
-    DBusConnection *conn = dbus.session_conn;
-    if (conn != NULL) {
-        DBusMessage *msg = dbus.message_new_method_call("org.gnome.ScreenSaver",
-                                                        "/org/gnome/ScreenSaver",
-                                                        "org.gnome.ScreenSaver",
-                                                        "SimulateUserActivity");
-        if (msg != NULL) {
-            if (dbus.connection_send(conn, msg, NULL)) {
-                dbus.connection_flush(conn);
+    SDL_bool retval = SDL_FALSE;
+
+    if (conn) {
+        DBusMessage *msg = dbus.message_new_method_call(node, path, interface, method);
+        if (msg) {
+            int firstarg = va_arg(ap, int);
+            if ((firstarg == DBUS_TYPE_INVALID) || dbus.message_append_args_valist(msg, firstarg, ap)) {
+                DBusMessage *reply = dbus.connection_send_with_reply_and_block(conn, msg, 300, NULL);
+                if (reply) {
+                    firstarg = va_arg(ap, int);
+                    if ((firstarg == DBUS_TYPE_INVALID) || dbus.message_get_args_valist(reply, NULL, firstarg, ap)) {
+                        retval = SDL_TRUE;
+                    }
+                    dbus.message_unref(reply);
+                }
             }
             dbus.message_unref(msg);
         }
     }
+
+    return retval;
 }
 
 SDL_bool
-SDL_DBus_ScreensaverInhibit(SDL_bool inhibit)
+SDL_DBus_CallMethodOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, ...)
 {
-    DBusConnection *conn = dbus.session_conn;
+    SDL_bool retval;
+    va_list ap;
+    va_start(ap, method);
+    retval = SDL_DBus_CallMethodInternal(conn, node, path, interface, method, ap);
+    va_end(ap);
+    return retval;
+}
 
-    if (conn == NULL)
-        return SDL_FALSE;
+SDL_bool
+SDL_DBus_CallMethod(const char *node, const char *path, const char *interface, const char *method, ...)
+{
+    SDL_bool retval;
+    va_list ap;
+    va_start(ap, method);
+    retval = SDL_DBus_CallMethodInternal(dbus.session_conn, node, path, interface, method, ap);
+    va_end(ap);
+    return retval;
+}
 
-    if (inhibit &&
-        screensaver_cookie != 0)
-        return SDL_TRUE;
-    if (!inhibit &&
-        screensaver_cookie == 0)
-        return SDL_TRUE;
+static SDL_bool
+SDL_DBus_CallVoidMethodInternal(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, va_list ap)
+{
+    SDL_bool retval = SDL_FALSE;
+
+    if (conn) {
+        DBusMessage *msg = dbus.message_new_method_call(node, path, interface, method);
+        if (msg) {
+            int firstarg = va_arg(ap, int);
+            if ((firstarg == DBUS_TYPE_INVALID) || dbus.message_append_args_valist(msg, firstarg, ap)) {
+                if (dbus.connection_send(conn, msg, NULL)) {
+                    dbus.connection_flush(conn);
+                    retval = SDL_TRUE;
+                }
+            }
 
-    if (inhibit) {
-        const char *app = "My SDL application";
-        const char *reason = "Playing a game";
-
-        DBusMessage *msg = dbus.message_new_method_call("org.freedesktop.ScreenSaver",
-                                                         "/org/freedesktop/ScreenSaver",
-                                                         "org.freedesktop.ScreenSaver",
-                                                         "Inhibit");
-        if (msg != NULL) {
-            dbus.message_append_args (msg,
-                                      DBUS_TYPE_STRING, &app,
-                                      DBUS_TYPE_STRING, &reason,
-                                      DBUS_TYPE_INVALID);
+            dbus.message_unref(msg);
         }
+    }
 
-        if (msg != NULL) {
-            DBusMessage *reply;
+    return retval;
+}
 
-            reply = dbus.connection_send_with_reply_and_block(conn, msg, 300, NULL);
-            if (reply) {
-                if (!dbus.message_get_args(reply, NULL,
-                                           DBUS_TYPE_UINT32, &screensaver_cookie,
-                                           DBUS_TYPE_INVALID))
-                    screensaver_cookie = 0;
-                dbus.message_unref(reply);
-            }
+SDL_bool
+SDL_DBus_CallVoidMethodOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, ...)
+{
+    SDL_bool retval;
+    va_list ap;
+    va_start(ap, method);
+    retval = SDL_DBus_CallVoidMethodInternal(conn, node, path, interface, method, ap);
+    va_end(ap);
+    return retval;
+}
 
+SDL_bool
+SDL_DBus_CallVoidMethod(const char *node, const char *path, const char *interface, const char *method, ...)
+{
+    SDL_bool retval;
+    va_list ap;
+    va_start(ap, method);
+    retval = SDL_DBus_CallVoidMethodInternal(dbus.session_conn, node, path, interface, method, ap);
+    va_end(ap);
+    return retval;
+}
+
+SDL_bool
+SDL_DBus_QueryPropertyOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *property, const int expectedtype, void *result)
+{
+    SDL_bool retval = SDL_FALSE;
+
+    if (conn) {
+        DBusMessage *msg = dbus.message_new_method_call(node, path, "org.freedesktop.DBus.Properties", "Get");
+        if (msg) {
+            if (dbus.message_append_args(msg, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID)) {
+                DBusMessage *reply = dbus.connection_send_with_reply_and_block(conn, msg, 300, NULL);
+                if (reply) {
+                    DBusMessageIter iter, sub;
+                    dbus.message_iter_init(reply, &iter);
+                    if (dbus.message_iter_get_arg_type(&iter) == DBUS_TYPE_VARIANT) {
+                        dbus.message_iter_recurse(&iter, &sub);
+                        if (dbus.message_iter_get_arg_type(&sub) == expectedtype) {
+                            dbus.message_iter_get_basic(&sub, result);
+                            retval = SDL_TRUE;
+                        }
+                    }
+                    dbus.message_unref(reply);
+                }
+            }
             dbus.message_unref(msg);
         }
+    }
 
-        if (screensaver_cookie == 0) {
-            return SDL_FALSE;
-        }
+    return retval;
+}
+
+SDL_bool
+SDL_DBus_QueryProperty(const char *node, const char *path, const char *interface, const char *property, const int expectedtype, void *result)
+{
+    return SDL_DBus_QueryPropertyOnConnection(dbus.session_conn, node, path, interface, property, expectedtype, result);
+}
+
+
+void
+SDL_DBus_ScreensaverTickle(void)
+{
+    SDL_DBus_CallVoidMethod("org.gnome.ScreenSaver", "/org/gnome/ScreenSaver", "org.gnome.ScreenSaver", "SimulateUserActivity", DBUS_TYPE_INVALID);
+}
+
+SDL_bool
+SDL_DBus_ScreensaverInhibit(SDL_bool inhibit)
+{
+    if ( (inhibit && (screensaver_cookie != 0)) || (!inhibit && (screensaver_cookie == 0)) ) {
         return SDL_TRUE;
     } else {
-        DBusMessage *msg = dbus.message_new_method_call("org.freedesktop.ScreenSaver",
-                                                        "/org/freedesktop/ScreenSaver",
-                                                        "org.freedesktop.ScreenSaver",
-                                                        "UnInhibit");
-        dbus.message_append_args (msg,
-                                  DBUS_TYPE_UINT32, &screensaver_cookie,
-                                  DBUS_TYPE_INVALID);
-        if (msg != NULL) {
-            if (dbus.connection_send(conn, msg, NULL)) {
-                dbus.connection_flush(conn);
+        const char *node = "org.freedesktop.ScreenSaver";
+        const char *path = "/org/freedesktop/ScreenSaver";
+        const char *interface = "org.freedesktop.ScreenSaver";
+
+        if (inhibit) {
+            const char *app = "My SDL application";
+            const char *reason = "Playing a game";
+            if (!SDL_DBus_CallMethod(node, path, interface, "Inhibit",
+                    DBUS_TYPE_STRING, &app, DBUS_TYPE_STRING, &reason, DBUS_TYPE_INVALID,
+                    DBUS_TYPE_UINT32, &screensaver_cookie, DBUS_TYPE_INVALID)) {
+                return SDL_FALSE;
             }
-            dbus.message_unref(msg);
+            return (screensaver_cookie != 0) ? SDL_TRUE : SDL_FALSE;
+        } else {
+            if (!SDL_DBus_CallVoidMethod(node, path, interface, "UnInhibit", DBUS_TYPE_UINT32, &screensaver_cookie, DBUS_TYPE_INVALID)) {
+                return SDL_FALSE;
+            }
+            screensaver_cookie = 0;
         }
-
-        screensaver_cookie = 0;
-        return SDL_TRUE;
     }
+
+    return SDL_TRUE;
 }
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_dbus.h b/src/core/linux/SDL_dbus.h
index c064381..1069a5c 100644
--- a/src/core/linux/SDL_dbus.h
+++ b/src/core/linux/SDL_dbus.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_dbus_h
-#define _SDL_dbus_h
+#ifndef SDL_dbus_h_
+#define SDL_dbus_h_
 
 #ifdef HAVE_DBUS_DBUS_H
 #define SDL_USE_LIBDBUS 1
@@ -32,6 +32,7 @@
 
 typedef struct SDL_DBusContext {
     DBusConnection *session_conn;
+    DBusConnection *system_conn;
 
     DBusConnection *(*bus_get_private)(DBusBusType, DBusError *);
     dbus_bool_t (*bus_register)(DBusConnection *, DBusError *);
@@ -53,7 +54,9 @@ typedef struct SDL_DBusContext {
     dbus_bool_t (*message_is_signal)(DBusMessage *, const char *, const char *); 	
     DBusMessage *(*message_new_method_call)(const char *, const char *, const char *, const char *);
     dbus_bool_t (*message_append_args)(DBusMessage *, int, ...);
+    dbus_bool_t (*message_append_args_valist)(DBusMessage *, int, va_list);
     dbus_bool_t (*message_get_args)(DBusMessage *, DBusError *, int, ...);
+    dbus_bool_t (*message_get_args_valist)(DBusMessage *, DBusError *, int, va_list);
     dbus_bool_t (*message_iter_init)(DBusMessage *, DBusMessageIter *);
     dbus_bool_t (*message_iter_next)(DBusMessageIter *);
     void (*message_iter_get_basic)(DBusMessageIter *, void *);
@@ -65,6 +68,7 @@ typedef struct SDL_DBusContext {
     void (*error_free)(DBusError *);
     char *(*get_local_machine_id)(void);
     void (*free)(void *);
+    void (*free_string_array)(char **);
     void (*shutdown)(void);
 
 } SDL_DBusContext;
@@ -72,11 +76,22 @@ typedef struct SDL_DBusContext {
 extern void SDL_DBus_Init(void);
 extern void SDL_DBus_Quit(void);
 extern SDL_DBusContext * SDL_DBus_GetContext(void);
+
+/* These use the built-in Session connection. */
+extern SDL_bool SDL_DBus_CallMethod(const char *node, const char *path, const char *interface, const char *method, ...);
+extern SDL_bool SDL_DBus_CallVoidMethod(const char *node, const char *path, const char *interface, const char *method, ...);
+extern SDL_bool SDL_DBus_QueryProperty(const char *node, const char *path, const char *interface, const char *property, const int expectedtype, void *result);
+
+/* These use whatever connection you like. */
+extern SDL_bool SDL_DBus_CallMethodOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, ...);
+extern SDL_bool SDL_DBus_CallVoidMethodOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *method, ...);
+extern SDL_bool SDL_DBus_QueryPropertyOnConnection(DBusConnection *conn, const char *node, const char *path, const char *interface, const char *property, const int expectedtype, void *result);
+
 extern void SDL_DBus_ScreensaverTickle(void);
 extern SDL_bool SDL_DBus_ScreensaverInhibit(SDL_bool inhibit);
 
 #endif /* HAVE_DBUS_DBUS_H */
 
-#endif /* _SDL_dbus_h */
+#endif /* SDL_dbus_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_evdev.c b/src/core/linux/SDL_evdev.c
index 4761f3e..8f3c8bc 100644
--- a/src/core/linux/SDL_evdev.c
+++ b/src/core/linux/SDL_evdev.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -30,51 +30,51 @@
  */
 
 #include "SDL_evdev.h"
+#include "SDL_evdev_kbd.h"
 
 #include <sys/stat.h>
 #include <unistd.h>
 #include <fcntl.h>
 #include <sys/ioctl.h>
-#include <limits.h>             /* For the definition of PATH_MAX */
 #include <linux/input.h>
-#ifdef SDL_INPUT_LINUXKD
-#include <linux/kd.h>
-#include <linux/keyboard.h>
-#include <linux/vt.h>
-#include <linux/tiocl.h> /* for TIOCL_GETSHIFTSTATE */
-#endif
 
 #include "SDL.h"
 #include "SDL_assert.h"
 #include "SDL_endian.h"
-#include "../../core/linux/SDL_udev.h"
 #include "SDL_scancode.h"
 #include "../../events/SDL_events_c.h"
 #include "../../events/scancodes_linux.h" /* adds linux_scancode_table */
+#include "../../core/linux/SDL_udev.h"
 
-/* This isn't defined in older Linux kernel headers */
+/* These are not defined in older Linux kernel headers */
 #ifndef SYN_DROPPED
 #define SYN_DROPPED 3
 #endif
+#ifndef ABS_MT_SLOT
+#define ABS_MT_SLOT         0x2f
+#define ABS_MT_POSITION_X   0x35
+#define ABS_MT_POSITION_Y   0x36
+#define ABS_MT_TRACKING_ID  0x39
+#endif
 
 typedef struct SDL_evdevlist_item
 {
     char *path;
     int fd;
-    
+
     /* TODO: use this for every device, not just touchscreen */
     int out_of_sync;
-    
+
     /* TODO: expand on this to have data for every possible class (mouse,
        keyboard, touchpad, etc.). Also there's probably some things in here we
        can pull out to the SDL_evdevlist_item i.e. name */
     int is_touchscreen;
     struct {
         char* name;
-        
+
         int min_x, max_x, range_x;
         int min_y, max_y, range_y;
-        
+
         int max_slots;
         int current_slot;
         struct {
@@ -88,18 +88,17 @@ typedef struct SDL_evdevlist_item
             int x, y;
         } * slots;
     } * touchscreen_data;
-    
+
     struct SDL_evdevlist_item *next;
 } SDL_evdevlist_item;
 
 typedef struct SDL_EVDEV_PrivateData
 {
+    int ref_count;
+    int num_devices;
     SDL_evdevlist_item *first;
     SDL_evdevlist_item *last;
-    int num_devices;
-    int ref_count;
-    int console_fd;
-    int kb_mode;
+    SDL_EVDEV_keyboard_state *kbd;
 } SDL_EVDEV_PrivateData;
 
 #define _THIS SDL_EVDEV_PrivateData *_this
@@ -111,7 +110,7 @@ static int SDL_EVDEV_device_removed(const char *dev_path);
 
 #if SDL_USE_LIBUDEV
 static int SDL_EVDEV_device_added(const char *dev_path, int udev_class);
-void SDL_EVDEV_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class,
+static void SDL_EVDEV_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class,
     const char *dev_path);
 #endif /* SDL_USE_LIBUDEV */
 
@@ -126,93 +125,6 @@ static Uint8 EVDEV_MouseButtons[] = {
     SDL_BUTTON_X2 + 3           /*  BTN_TASK        0x117 */
 };
 
-static const char* EVDEV_consoles[] = {
-    /* "/proc/self/fd/0",
-    "/dev/tty",
-    "/dev/tty0", */ /* the tty ioctl's prohibit these */
-    "/dev/tty1",
-    "/dev/tty2",
-    "/dev/tty3",
-    "/dev/tty4",
-    "/dev/tty5",
-    "/dev/tty6",
-    "/dev/tty7", /* usually X is spawned in tty7 */
-    "/dev/vc/0",
-    "/dev/console"
-};
-
-static int SDL_EVDEV_is_console(int fd) {
-    int type;
-    
-    return isatty(fd) && ioctl(fd, KDGKBTYPE, &type) == 0 &&
-        (type == KB_101 || type == KB_84);
-}
-
-/* Prevent keystrokes from reaching the tty */
-static int SDL_EVDEV_mute_keyboard(int tty_fd, int* old_kb_mode)
-{
-    if (!SDL_EVDEV_is_console(tty_fd)) {
-        return SDL_SetError("Tried to mute an invalid tty");
-    }
-    
-    if (ioctl(tty_fd, KDGKBMODE, old_kb_mode) < 0) {
-        return SDL_SetError("Failed to get keyboard mode during muting");
-    }
-    
-    /* FIXME: atm this absolutely ruins the vt, and KDSKBMUTE isn't implemented
-       in the kernel */
-    /*
-    if (ioctl(tty_fd, KDSKBMODE, K_OFF) < 0) {
-        return SDL_SetError("Failed to set keyboard mode during muting");
-    }
-    */
-    
-    return 0;  
-}
-
-/* Restore the keyboard mode for given tty */
-static void SDL_EVDEV_unmute_keyboard(int tty_fd, int kb_mode)
-{
-    /* read above */
-    /*
-    if (ioctl(tty_fd, KDSKBMODE, kb_mode) < 0) {
-        SDL_Log("Failed to unmute keyboard");
-    }
-    */
-}
-
-static int SDL_EVDEV_get_active_tty()
-{  
-    int i, fd, ret, tty = 0;
-    char tiocl;
-    struct vt_stat vt_state;
-    char path[PATH_MAX + 1];
-    
-    for(i = 0; i < SDL_arraysize(EVDEV_consoles); i++) {
-        fd = open(EVDEV_consoles[i], O_RDONLY);
-        
-        if (fd < 0 && !SDL_EVDEV_is_console(fd))
-            break;
-        
-        tiocl = TIOCL_GETFGCONSOLE;
-        if ((ret = ioctl(fd, TIOCLINUX, &tiocl)) >= 0)
-            tty = ret + 1;
-        else if (ioctl(fd, VT_GETSTATE, &vt_state) == 0)
-            tty = vt_state.v_active;
-        
-        close(fd);
-        
-        if (tty) {
-            sprintf(path, "/dev/tty%u", tty);
-            fd = open(path, O_RDONLY);
-            if (fd >= 0 && SDL_EVDEV_is_console(fd))
-                return fd;
-        }
-    }
-    
-    return SDL_SetError("Failed to determine active tty");
-}
-
 int
 SDL_EVDEV_Init(void)
 {
@@ -236,24 +148,18 @@ SDL_EVDEV_Init(void)
             _this = NULL;
             return -1;
         }
-        
+
         /* Force a scan to build the initial device list */
         SDL_UDEV_Scan();
 #else
         /* TODO: Scan the devices manually, like a caveman */
 #endif /* SDL_USE_LIBUDEV */
-        
-        /* We need a physical terminal (not PTS) to be able to translate key
-           code to symbols via the kernel tables */
-        _this->console_fd = SDL_EVDEV_get_active_tty();
-        
-        /* Mute the keyboard so keystrokes only generate evdev events and do not
-           leak through to the console */
-        SDL_EVDEV_mute_keyboard(_this->console_fd, &_this->kb_mode);
+
+        _this->kbd = SDL_EVDEV_kbd_init();
     }
-    
+
     _this->ref_count += 1;
-    
+
     return 0;
 }
 
@@ -263,42 +169,39 @@ SDL_EVDEV_Quit(void)
     if (_this == NULL) {
         return;
     }
-    
+
     _this->ref_count -= 1;
-    
+
     if (_this->ref_count < 1) {
 #if SDL_USE_LIBUDEV
         SDL_UDEV_DelCallback(SDL_EVDEV_udev_callback);
         SDL_UDEV_Quit();
 #endif /* SDL_USE_LIBUDEV */
-       
-        if (_this->console_fd >= 0) {
-            SDL_EVDEV_unmute_keyboard(_this->console_fd, _this->kb_mode);
-            close(_this->console_fd);
-        }
-        
+
+        SDL_EVDEV_kbd_quit(_this->kbd);
+
         /* Remove existing devices */
         while(_this->first != NULL) {
             SDL_EVDEV_device_removed(_this->first->path);
         }
-        
+
         SDL_assert(_this->first == NULL);
         SDL_assert(_this->last == NULL);
         SDL_assert(_this->num_devices == 0);
-        
+
         SDL_free(_this);
         _this = NULL;
     }
 }
 
 #if SDL_USE_LIBUDEV
-void SDL_EVDEV_udev_callback(SDL_UDEV_deviceevent udev_event, int udev_class,
+static void SDL_EVDEV_udev_callback(SDL_UDEV_deviceevent udev_event, int udev_class,
     const char* dev_path)
 {
     if (dev_path == NULL) {
         return;
     }
-    
+
     switch(udev_event) {
     case SDL_UDEV_DEVICEADDED:
         if (!(udev_class & (SDL_UDEV_DEVICE_MOUSE | SDL_UDEV_DEVICE_KEYBOARD |
@@ -316,82 +219,6 @@ void SDL_EVDEV_udev_callback(SDL_UDEV_deviceevent udev_event, int udev_class,
 }
 #endif /* SDL_USE_LIBUDEV */
 
-#ifdef SDL_INPUT_LINUXKD
-/* this logic is pulled from kbd_keycode() in drivers/tty/vt/keyboard.c in the
-   Linux kernel source */
-static void SDL_EVDEV_do_text_input(unsigned short keycode) {
-    char shift_state;
-    int locks_state;
-    struct kbentry kbe;
-    unsigned char type;
-    char text[2] = { 0 };
-    
-    if (_this->console_fd < 0)
-        return;
-    
-    shift_state = TIOCL_GETSHIFTSTATE;
-    if (ioctl(_this->console_fd, TIOCLINUX, &shift_state) < 0) {
-        /* TODO: error */
-        return;
-    }
-
-    kbe.kb_table = shift_state;
-    kbe.kb_index = keycode;
-    
-    if (ioctl(_this->console_fd, KDGKBENT, &kbe) < 0) {
-        /* TODO: error */
-        return;
-    }
-    
-    type = KTYP(kbe.kb_value);
-    
-    if (type < 0xf0) {
-        /* 
-         * FIXME: keysyms with a type below 0xf0 represent a unicode character
-         * which requires special handling due to dead characters, diacritics,
-         * etc. For perfect input a proper way to deal with such characters
-         * should be implemented.
-         *
-         * For reference, the only place I was able to find out about this
-         * special 0xf0 value was in an unused? couple of patches listed below.
-         *
-         * http://ftp.tc.edu.tw/pub/docs/Unicode/utf8/linux-2.3.12-keyboard.diff
-         * http://ftp.tc.edu.tw/pub/docs/Unicode/utf8/linux-2.3.12-console.diff
-         */
-        
-        return;
-    }
-    
-    type -= 0xf0;
-    
-    /* if type is KT_LETTER then it can be affected by Caps Lock */
-    if (type == KT_LETTER) {
-        type = KT_LATIN;
-    
-        if (ioctl(_this->console_fd, KDGKBLED, &locks_state) < 0) {
-            /* TODO: error */
-            return;
-        }
-        
-        if (locks_state & K_CAPSLOCK) {
-            kbe.kb_table = shift_state ^ (1 << KG_SHIFT);
-            
-            if (ioctl(_this->console_fd, KDGKBENT, &kbe) < 0) {
-                /* TODO: error */
-                return;
-            }
-        }
-    }
-    
-    /* TODO: convert values >= 0x80 from ISO-8859-1? to UTF-8 */
-    if (type != KT_LATIN || KVAL(kbe.kb_value) >= 0x80)
-        return;
-    
-    *text = KVAL(kbe.kb_value);
-    SDL_SendKeyboardText(text);
-}
-#endif /* SDL_INPUT_LINUXKD */
-
 void 
 SDL_EVDEV_Poll(void)
 {
@@ -423,7 +250,7 @@ SDL_EVDEV_Poll(void)
                     events[i].type == EV_SYN && events[i].code != SYN_REPORT) {
                     break;
                 }
-                
+
                 switch (events[i].type) {
                 case EV_KEY:
                     if (events[i].code >= BTN_MOUSE && events[i].code < BTN_MOUSE + SDL_arraysize(EVDEV_MouseButtons)) {
@@ -443,11 +270,9 @@ SDL_EVDEV_Poll(void)
                             SDL_SendKeyboardKey(SDL_RELEASED, scan_code);
                         } else if (events[i].value == 1 || events[i].value == 2 /* key repeated */) {
                             SDL_SendKeyboardKey(SDL_PRESSED, scan_code);
-#ifdef SDL_INPUT_LINUXKD
-                            SDL_EVDEV_do_text_input(events[i].code);
-#endif /* SDL_INPUT_LINUXKD */
                         }
                     }
+                    SDL_EVDEV_kbd_keycode(_this->kbd, events[i].code, events[i].value);
                     break;
                 case EV_ABS:
                     switch(events[i].code) {
@@ -519,13 +344,13 @@ SDL_EVDEV_Poll(void)
                     case SYN_REPORT:
                         if (!item->is_touchscreen) /* FIXME: temp hack */
                             break;
-                            
+
                         for(j = 0; j < item->touchscreen_data->max_slots; j++) {
                             norm_x = (float)(item->touchscreen_data->slots[j].x - item->touchscreen_data->min_x) /
                                 (float)item->touchscreen_data->range_x;
                             norm_y = (float)(item->touchscreen_data->slots[j].y - item->touchscreen_data->min_y) /
                                 (float)item->touchscreen_data->range_y;
-                        
+
                             switch(item->touchscreen_data->slots[j].delta) {
                             case EVDEV_TOUCH_SLOTDELTA_DOWN:
                                 SDL_SendTouch(item->fd, item->touchscreen_data->slots[j].tracking_id, SDL_TRUE, norm_x, norm_y, 1.0f);
@@ -544,7 +369,7 @@ SDL_EVDEV_Poll(void)
                                 break;
                             }
                         }
-                        
+
                         if (item->out_of_sync)
                             item->out_of_sync = 0;
                         break;
@@ -573,8 +398,8 @@ SDL_EVDEV_translate_keycode(int keycode)
 
     if (scancode == SDL_SCANCODE_UNKNOWN) {
         SDL_Log("The key you just pressed is not recognized by SDL. To help "
-            "get this fixed, please report this to the SDL mailing list "
-            "<sdl at libsdl.org> EVDEV KeyCode %d\n", keycode);
+            "get this fixed, please report this to the SDL forums/mailing list "
+            "<https://discourse.libsdl.org/> EVDEV KeyCode %d", keycode);
     }
 
     return scancode;
@@ -587,26 +412,26 @@ SDL_EVDEV_init_touchscreen(SDL_evdevlist_item* item)
     int ret, i;
     char name[64];
     struct input_absinfo abs_info;
-    
+
     if (!item->is_touchscreen)
         return 0;
-    
+
     item->touchscreen_data = SDL_calloc(1, sizeof(*item->touchscreen_data));
     if (item->touchscreen_data == NULL)
         return SDL_OutOfMemory();
-    
+
     ret = ioctl(item->fd, EVIOCGNAME(sizeof(name)), name);
     if (ret < 0) {
         SDL_free(item->touchscreen_data);
         return SDL_SetError("Failed to get evdev touchscreen name");
     }
-    
+
     item->touchscreen_data->name = SDL_strdup(name);
     if (item->touchscreen_data->name == NULL) {
         SDL_free(item->touchscreen_data);
         return SDL_OutOfMemory();
     }
-    
+
     ret = ioctl(item->fd, EVIOCGABS(ABS_MT_POSITION_X), &abs_info);
     if (ret < 0) {
         SDL_free(item->touchscreen_data->name);
@@ -616,7 +441,7 @@ SDL_EVDEV_init_touchscreen(SDL_evdevlist_item* item)
     item->touchscreen_data->min_x = abs_info.minimum;
     item->touchscreen_data->max_x = abs_info.maximum;
     item->touchscreen_data->range_x = abs_info.maximum - abs_info.minimum;
-        
+
     ret = ioctl(item->fd, EVIOCGABS(ABS_MT_POSITION_Y), &abs_info);
     if (ret < 0) {
         SDL_free(item->touchscreen_data->name);
@@ -626,7 +451,7 @@ SDL_EVDEV_init_touchscreen(SDL_evdevlist_item* item)
     item->touchscreen_data->min_y = abs_info.minimum;
     item->touchscreen_data->max_y = abs_info.maximum;
     item->touchscreen_data->range_y = abs_info.maximum - abs_info.minimum;
-    
+
     ret = ioctl(item->fd, EVIOCGABS(ABS_MT_SLOT), &abs_info);
     if (ret < 0) {
         SDL_free(item->touchscreen_data->name);
@@ -634,7 +459,7 @@ SDL_EVDEV_init_touchscreen(SDL_evdevlist_item* item)
         return SDL_SetError("Failed to get evdev touchscreen limits");
     }
     item->touchscreen_data->max_slots = abs_info.maximum + 1;
-    
+
     item->touchscreen_data->slots = SDL_calloc(
         item->touchscreen_data->max_slots,
         sizeof(*item->touchscreen_data->slots));
@@ -643,11 +468,11 @@ SDL_EVDEV_init_touchscreen(SDL_evdevlist_item* item)
         SDL_free(item->touchscreen_data);
         return SDL_OutOfMemory();
     }
-    
+
     for(i = 0; i < item->touchscreen_data->max_slots; i++) {
         item->touchscreen_data->slots[i].tracking_id = -1;
     }
-    
+
     ret = SDL_AddTouch(item->fd, /* I guess our fd is unique enough */
         item->touchscreen_data->name);
     if (ret < 0) {
@@ -656,7 +481,7 @@ SDL_EVDEV_init_touchscreen(SDL_evdevlist_item* item)
         SDL_free(item->touchscreen_data);
         return ret;
     }
-    
+
     return 0;
 }
 #endif /* SDL_USE_LIBUDEV */
@@ -665,7 +490,7 @@ static void
 SDL_EVDEV_destroy_touchscreen(SDL_evdevlist_item* item) {
     if (!item->is_touchscreen)
         return;
-    
+
     SDL_DelTouch(item->fd);
     SDL_free(item->touchscreen_data->slots);
     SDL_free(item->touchscreen_data->name);
@@ -689,21 +514,21 @@ SDL_EVDEV_sync_device(SDL_evdevlist_item *item)
     __u32* mt_req_code;
     __s32* mt_req_values;
     size_t mt_req_size;
-    
+
     /* TODO: sync devices other than touchscreen */
     if (!item->is_touchscreen)
         return;
-    
+
     mt_req_size = sizeof(*mt_req_code) +
         sizeof(*mt_req_values) * item->touchscreen_data->max_slots;
-    
+
     mt_req_code = SDL_calloc(1, mt_req_size);
     if (mt_req_code == NULL) {
         return;
     }
-    
+
     mt_req_values = (__s32*)mt_req_code + 1;
-    
+
     *mt_req_code = ABS_MT_TRACKING_ID;
     ret = ioctl(item->fd, EVIOCGMTSLOTS(mt_req_size), mt_req_code);
     if (ret < 0) {
@@ -730,7 +555,7 @@ SDL_EVDEV_sync_device(SDL_evdevlist_item *item)
             item->touchscreen_data->slots[i].delta = EVDEV_TOUCH_SLOTDELTA_UP;
         }
     }
-    
+
     *mt_req_code = ABS_MT_POSITION_X;
     ret = ioctl(item->fd, EVIOCGMTSLOTS(mt_req_size), mt_req_code);
     if (ret < 0) {
@@ -748,7 +573,7 @@ SDL_EVDEV_sync_device(SDL_evdevlist_item *item)
             }
         }
     }
-    
+
     *mt_req_code = ABS_MT_POSITION_Y;
     ret = ioctl(item->fd, EVIOCGMTSLOTS(mt_req_size), mt_req_code);
     if (ret < 0) {
@@ -766,14 +591,14 @@ SDL_EVDEV_sync_device(SDL_evdevlist_item *item)
             }
         }
     }
-    
+
     ret = ioctl(item->fd, EVIOCGABS(ABS_MT_SLOT), &abs_info);
     if (ret < 0) {
         SDL_free(mt_req_code);
         return;
     }
     item->touchscreen_data->current_slot = abs_info.value;
-    
+
     SDL_free(mt_req_code);
 
 #endif /* EVIOCGMTSLOTS */
@@ -792,7 +617,7 @@ SDL_EVDEV_device_added(const char *dev_path, int udev_class)
             return -1;  /* already have this one */
         }
     }
-    
+
     item = (SDL_evdevlist_item *) SDL_calloc(1, sizeof (SDL_evdevlist_item));
     if (item == NULL) {
         return SDL_OutOfMemory();
@@ -803,33 +628,33 @@ SDL_EVDEV_device_added(const char *dev_path, int udev_class)
         SDL_free(item);
         return SDL_SetError("Unable to open %s", dev_path);
     }
-    
+
     item->path = SDL_strdup(dev_path);
     if (item->path == NULL) {
         close(item->fd);
         SDL_free(item);
         return SDL_OutOfMemory();
     }
-    
+
     if (udev_class & SDL_UDEV_DEVICE_TOUCHSCREEN) {
         item->is_touchscreen = 1;
-        
+
         if ((ret = SDL_EVDEV_init_touchscreen(item)) < 0) {
             close(item->fd);
             SDL_free(item);
             return ret;
         }
     }
-    
+
     if (_this->last == NULL) {
         _this->first = _this->last = item;
     } else {
         _this->last->next = item;
         _this->last = item;
     }
-    
+
     SDL_EVDEV_sync_device(item);
-    
+
     return _this->num_devices++;
 }
 #endif /* SDL_USE_LIBUDEV */
diff --git a/src/core/linux/SDL_evdev.h b/src/core/linux/SDL_evdev.h
index 85b1938..ba1b4fc 100644
--- a/src/core/linux/SDL_evdev.h
+++ b/src/core/linux/SDL_evdev.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_evdev_h
-#define _SDL_evdev_h
+#ifndef SDL_evdev_h_
+#define SDL_evdev_h_
 
 #ifdef SDL_INPUT_LINUXEV
 
@@ -34,6 +34,6 @@ extern void SDL_EVDEV_Poll(void);
 
 #endif /* SDL_INPUT_LINUXEV */
 
-#endif /* _SDL_evdev_h */
+#endif /* SDL_evdev_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_evdev_kbd.c b/src/core/linux/SDL_evdev_kbd.c
new file mode 100644
index 0000000..9c63ab7
--- /dev/null
+++ b/src/core/linux/SDL_evdev_kbd.c
@@ -0,0 +1,677 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "../../SDL_internal.h"
+
+#include "SDL_evdev_kbd.h"
+
+#ifdef SDL_INPUT_LINUXKD
+
+/* This logic is adapted from drivers/tty/vt/keyboard.c in the Linux kernel source */
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <linux/kd.h>
+#include <linux/keyboard.h>
+#include <linux/vt.h>
+#include <linux/tiocl.h> /* for TIOCL_GETSHIFTSTATE */
+
+#include "../../events/SDL_events_c.h"
+#include "SDL_evdev_kbd_default_accents.h"
+#include "SDL_evdev_kbd_default_keymap.h"
+
+/* These are not defined in older Linux kernel headers */
+#ifndef K_UNICODE
+#define K_UNICODE 0x03
+#endif
+#ifndef K_OFF
+#define K_OFF 0x04
+#endif
+
+/*
+ * Handler Tables.
+ */
+
+#define K_HANDLERS\
+    k_self,     k_fn,       k_spec,       k_pad,\
+    k_dead,     k_cons,     k_cur,        k_shift,\
+    k_meta,     k_ascii,    k_lock,       k_lowercase,\
+    k_slock,    k_dead2,    k_brl,        k_ignore
+
+typedef void (k_handler_fn)(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag);
+static k_handler_fn K_HANDLERS;
+static k_handler_fn *k_handler[16] = { K_HANDLERS };
+
+typedef void (fn_handler_fn)(SDL_EVDEV_keyboard_state *kbd);
+static void fn_enter(SDL_EVDEV_keyboard_state *kbd);
+static void fn_caps_toggle(SDL_EVDEV_keyboard_state *kbd);
+static void fn_caps_on(SDL_EVDEV_keyboard_state *kbd);
+static void fn_num(SDL_EVDEV_keyboard_state *kbd);
+static void fn_compose(SDL_EVDEV_keyboard_state *kbd);
+
+static fn_handler_fn *fn_handler[] =
+{
+    NULL,       fn_enter,   NULL,       NULL,
+    NULL,       NULL,       NULL,       fn_caps_toggle,
+    fn_num,     NULL,       NULL,       NULL,
+    NULL,       fn_caps_on, fn_compose, NULL,
+    NULL,       NULL,       NULL,       fn_num
+};
+
+
+/*
+ * Keyboard State
+ */
+
+struct SDL_EVDEV_keyboard_state
+{
+    int console_fd;
+    int old_kbd_mode;
+    unsigned short **key_maps;
+    unsigned char shift_down[NR_SHIFT];        /* shift state counters.. */
+    SDL_bool dead_key_next;
+    int npadch;                    /* -1 or number assembled on pad */
+    struct kbdiacrs *accents;
+    unsigned int diacr;
+    SDL_bool rep;                    /* flag telling character repeat */
+    unsigned char lockstate;
+    unsigned char slockstate;
+    unsigned char ledflagstate;
+    char shift_state;
+    char text[128];
+    unsigned int text_len;
+};
+
+#ifdef DUMP_ACCENTS
+static void SDL_EVDEV_dump_accents(SDL_EVDEV_keyboard_state *kbd)
+{
+    unsigned int i;
+
+    printf("static struct kbdiacrs default_accents = {\n");
+    printf("    %d,\n", kbd->accents->kb_cnt);
+    printf("    {\n");
+    for (i = 0; i < kbd->accents->kb_cnt; ++i) {
+        struct kbdiacr *diacr = &kbd->accents->kbdiacr[i];
+        printf("        { 0x%.2x, 0x%.2x, 0x%.2x },\n",
+            diacr->diacr, diacr->base, diacr->result);
+    }
+    while (i < 256) {
+        printf("        { 0x00, 0x00, 0x00 },\n");
+        ++i;
+    }
+    printf("    }\n");
+    printf("};\n");
+}
+#endif /* DUMP_ACCENTS */
+
+#ifdef DUMP_KEYMAP
+static void SDL_EVDEV_dump_keymap(SDL_EVDEV_keyboard_state *kbd)
+{
+    int i, j;
+
+    for (i = 0; i < MAX_NR_KEYMAPS; ++i) {
+        if (kbd->key_maps[i]) {
+            printf("static unsigned short default_key_map_%d[NR_KEYS] = {", i);
+            for (j = 0; j < NR_KEYS; ++j) {
+                if ((j%8) == 0) {
+                    printf("\n    ");
+                }
+                printf("0x%.4x, ", kbd->key_maps[i][j]);
+            }
+            printf("\n};\n");
+        }
+    }
+    printf("\n");
+    printf("static unsigned short *default_key_maps[MAX_NR_KEYMAPS] = {\n");
+    for (i = 0; i < MAX_NR_KEYMAPS; ++i) {
+        if (kbd->key_maps[i]) {
+            printf("    default_key_map_%d,\n", i);
+        } else {
+            printf("    NULL,\n");
+        }
+    }
+    printf("};\n");
+}
+#endif /* DUMP_KEYMAP */
+
+static int SDL_EVDEV_kbd_load_keymaps(SDL_EVDEV_keyboard_state *kbd)
+{
+    int i, j;
+
+    kbd->key_maps = (unsigned short **)SDL_calloc(MAX_NR_KEYMAPS, sizeof(unsigned short *));
+    if (!kbd->key_maps) {
+        return -1;
+    }
+
+    for (i = 0; i < MAX_NR_KEYMAPS; ++i) {
+        struct kbentry kbe;
+
+        kbe.kb_table = i;
+        kbe.kb_index = 0;
+        if (ioctl(kbd->console_fd, KDGKBENT, &kbe) < 0) {
+            return -1;
+        }
+
+        if (kbe.kb_value == K_NOSUCHMAP) {
+            continue;
+        }
+
+        kbd->key_maps[i] = (unsigned short *)SDL_malloc(NR_KEYS * sizeof(unsigned short));
+        if (!kbd->key_maps[i]) {
+            return -1;
+        }
+
+        for (j = 0; j < NR_KEYS; ++j) {
+            kbe.kb_table = i;
+            kbe.kb_index = j;
+            if (ioctl(kbd->console_fd, KDGKBENT, &kbe) < 0) {
+                return -1;
+            }
+            kbd->key_maps[i][j] = (kbe.kb_value ^ 0xf000);
+        }
+    }
+    return 0;
+}
+
+SDL_EVDEV_keyboard_state *
+SDL_EVDEV_kbd_init(void)
+{
+    SDL_EVDEV_keyboard_state *kbd;
+    int i;
+    char flag_state;
+    char shift_state[2] = {TIOCL_GETSHIFTSTATE, 0};
+
+    kbd = (SDL_EVDEV_keyboard_state *)SDL_calloc(1, sizeof(*kbd));
+    if (!kbd) {
+        return NULL;
+    }
+
+    kbd->npadch = -1;
+
+    /* This might fail if we're not connected to a tty (e.g. on the Steam Link) */
+    kbd->console_fd = open("/dev/tty", O_RDONLY);
+
+    if (ioctl(kbd->console_fd, TIOCLINUX, shift_state) == 0) {
+        kbd->shift_state = *shift_state;
+    }
+
+    if (ioctl(kbd->console_fd, KDGKBLED, &flag_state) == 0) {
+        kbd->ledflagstate = flag_state;
+    }
+
+    kbd->accents = &default_accents;
+    if (ioctl(kbd->console_fd, KDGKBDIACR, kbd->accents) < 0) {
+        /* No worries, we'll use the default accent table */
+    }
+
+    kbd->key_maps = default_key_maps;
+    if (ioctl(kbd->console_fd, KDGKBMODE, &kbd->old_kbd_mode) == 0) {
+        /* Set the keyboard in UNICODE mode and load the keymaps */
+        ioctl(kbd->console_fd, KDSKBMODE, K_UNICODE);
+
+        if (SDL_EVDEV_kbd_load_keymaps(kbd) < 0) {
+            for (i = 0; i < MAX_NR_KEYMAPS; ++i) {
+                if (kbd->key_maps[i]) {
+                    SDL_free(kbd->key_maps[i]);
+                }
+            }
+            SDL_free(kbd->key_maps);
+
+            kbd->key_maps = default_key_maps;
+        }
+
+        /* Mute the keyboard so keystrokes only generate evdev events
+         * and do not leak through to the console
+         */
+        ioctl(kbd->console_fd, KDSKBMODE, K_OFF);
+    }
+
+#ifdef DUMP_ACCENTS
+    SDL_EVDEV_dump_accents(kbd);
+#endif
+#ifdef DUMP_KEYMAP
+    SDL_EVDEV_dump_keymap(kbd);
+#endif
+    return kbd;
+}
+
+void
+SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *kbd)
+{
+    if (!kbd) {
+        return;
+    }
+
+    if (kbd->console_fd >= 0) {
+        /* Restore the original keyboard mode */
+        ioctl(kbd->console_fd, KDSKBMODE, kbd->old_kbd_mode);
+
+        close(kbd->console_fd);
+        kbd->console_fd = -1;
+    }
+
+    if (kbd->key_maps && kbd->key_maps != default_key_maps) {
+        int i;
+        for (i = 0; i < MAX_NR_KEYMAPS; ++i) {
+            if (kbd->key_maps[i]) {
+                SDL_free(kbd->key_maps[i]);
+            }
+        }
+        SDL_free(kbd->key_maps);
+    }
+
+    SDL_free(kbd);
+}
+
+/*
+ * Helper Functions.
+ */
+static void put_queue(SDL_EVDEV_keyboard_state *kbd, uint c)
+{
+    /* c is already part of a UTF-8 sequence and safe to add as a character */
+    if (kbd->text_len < (sizeof(kbd->text)-1)) {
+        kbd->text[kbd->text_len++] = (char)c;
+    }
+}
+
+static void put_utf8(SDL_EVDEV_keyboard_state *kbd, uint c)
+{
+    if (c < 0x80)
+        /*  0******* */
+        put_queue(kbd, c);
+    else if (c < 0x800) {
+        /* 110***** 10****** */
+        put_queue(kbd, 0xc0 | (c >> 6));
+        put_queue(kbd, 0x80 | (c & 0x3f));
+    } else if (c < 0x10000) {
+        if (c >= 0xD800 && c < 0xE000)
+            return;
+        if (c == 0xFFFF)
+            return;
+        /* 1110**** 10****** 10****** */
+        put_queue(kbd, 0xe0 | (c >> 12));
+        put_queue(kbd, 0x80 | ((c >> 6) & 0x3f));
+        put_queue(kbd, 0x80 | (c & 0x3f));
+    } else if (c < 0x110000) {
+        /* 11110*** 10****** 10****** 10****** */
+        put_queue(kbd, 0xf0 | (c >> 18));
+        put_queue(kbd, 0x80 | ((c >> 12) & 0x3f));
+        put_queue(kbd, 0x80 | ((c >> 6) & 0x3f));
+        put_queue(kbd, 0x80 | (c & 0x3f));
+    }
+}
+
+/*
+ * We have a combining character DIACR here, followed by the character CH.
+ * If the combination occurs in the table, return the corresponding value.
+ * Otherwise, if CH is a space or equals DIACR, return DIACR.
+ * Otherwise, conclude that DIACR was not combining after all,
+ * queue it and return CH.
+ */
+static unsigned int handle_diacr(SDL_EVDEV_keyboard_state *kbd, unsigned int ch)
+{
+    unsigned int d = kbd->diacr;
+    unsigned int i;
+
+    kbd->diacr = 0;
+
+    for (i = 0; i < kbd->accents->kb_cnt; i++) {
+        if (kbd->accents->kbdiacr[i].diacr == d &&
+            kbd->accents->kbdiacr[i].base == ch) {
+            return kbd->accents->kbdiacr[i].result;
+        }
+    }
+
+    if (ch == ' ' || ch == d)
+        return d;
+
+    put_utf8(kbd, d);
+
+    return ch;
+}
+
+static int vc_kbd_led(SDL_EVDEV_keyboard_state *kbd, int flag)
+{
+    return ((kbd->ledflagstate >> flag) & 1);
+}
+
+static void set_vc_kbd_led(SDL_EVDEV_keyboard_state *kbd, int flag)
+{
+    kbd->ledflagstate |= 1 << flag;
+}
+
+static void clr_vc_kbd_led(SDL_EVDEV_keyboard_state *kbd, int flag)
+{
+    kbd->ledflagstate &= ~(1 << flag);
+}
+
+static void chg_vc_kbd_lock(SDL_EVDEV_keyboard_state *kbd, int flag)
+{
+    kbd->lockstate ^= 1 << flag;
+}
+
+static void chg_vc_kbd_slock(SDL_EVDEV_keyboard_state *kbd, int flag)
+{
+    kbd->slockstate ^= 1 << flag;
+}
+
+static void chg_vc_kbd_led(SDL_EVDEV_keyboard_state *kbd, int flag)
+{
+    kbd->ledflagstate ^= 1 << flag;
+}
+
+/*
+ * Special function handlers
+ */
+
+static void fn_enter(SDL_EVDEV_keyboard_state *kbd)
+{
+    if (kbd->diacr) {
+        put_utf8(kbd, kbd->diacr);
+        kbd->diacr = 0;
+    }
+}
+
+static void fn_caps_toggle(SDL_EVDEV_keyboard_state *kbd)
+{
+    if (kbd->rep)
+        return;
+
+    chg_vc_kbd_led(kbd, K_CAPSLOCK);
+}
+
+static void fn_caps_on(SDL_EVDEV_keyboard_state *kbd)
+{
+    if (kbd->rep)
+        return;
+
+    set_vc_kbd_led(kbd, K_CAPSLOCK);
+}
+
+static void fn_num(SDL_EVDEV_keyboard_state *kbd)
+{
+    if (!kbd->rep)
+        chg_vc_kbd_led(kbd, K_NUMLOCK);
+}
+
+static void fn_compose(SDL_EVDEV_keyboard_state *kbd)
+{
+    kbd->dead_key_next = SDL_TRUE;
+}
+
+/*
+ * Special key handlers
+ */
+
+static void k_ignore(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+}
+
+static void k_spec(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+    if (up_flag)
+        return;
+    if (value >= SDL_arraysize(fn_handler))
+        return;
+    if (fn_handler[value])
+        fn_handler[value](kbd);
+}
+
+static void k_lowercase(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+}
+
+static void k_self(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+    if (up_flag)
+        return;        /* no action, if this is a key release */
+
+    if (kbd->diacr)
+        value = handle_diacr(kbd, value);
+
+    if (kbd->dead_key_next) {
+        kbd->dead_key_next = SDL_FALSE;
+        kbd->diacr = value;
+        return;
+    }
+    put_utf8(kbd, value);
+}
+
+static void k_deadunicode(SDL_EVDEV_keyboard_state *kbd, unsigned int value, char up_flag)
+{
+    if (up_flag)
+        return;
+
+    kbd->diacr = (kbd->diacr ? handle_diacr(kbd, value) : value);
+}
+
+static void k_dead(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+    const unsigned char ret_diacr[NR_DEAD] = {'`', '\'', '^', '~', '"', ',' };
+
+    k_deadunicode(kbd, ret_diacr[value], up_flag);
+}
+
+static void k_dead2(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+    k_deadunicode(kbd, value, up_flag);
+}
+
+static void k_cons(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+}
+
+static void k_fn(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+}
+
+static void k_cur(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+}
+
+static void k_pad(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+    static const char pad_chars[] = "0123456789+-*/\015,.?()#";
+
+    if (up_flag)
+        return;        /* no action, if this is a key release */
+
+    if (!vc_kbd_led(kbd, K_NUMLOCK)) {
+        /* unprintable action */
+        return;
+    }
+
+    put_queue(kbd, pad_chars[value]);
+}
+
+static void k_shift(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+    int old_state = kbd->shift_state;
+
+    if (kbd->rep)
+        return;
+    /*
+     * Mimic typewriter:
+     * a CapsShift key acts like Shift but undoes CapsLock
+     */
+    if (value == KVAL(K_CAPSSHIFT)) {
+        value = KVAL(K_SHIFT);
+        if (!up_flag)
+            clr_vc_kbd_led(kbd, K_CAPSLOCK);
+    }
+
+    if (up_flag) {
+        /*
+         * handle the case that two shift or control
+         * keys are depressed simultaneously
+         */
+        if (kbd->shift_down[value])
+            kbd->shift_down[value]--;
+    } else
+        kbd->shift_down[value]++;
+
+    if (kbd->shift_down[value])
+        kbd->shift_state |= (1 << value);
+    else
+        kbd->shift_state &= ~(1 << value);
+
+    /* kludge */
+    if (up_flag && kbd->shift_state != old_state && kbd->npadch != -1) {
+        put_utf8(kbd, kbd->npadch);
+        kbd->npadch = -1;
+    }
+}
+
+static void k_meta(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+}
+
+static void k_ascii(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+    int base;
+
+    if (up_flag)
+        return;
+
+    if (value < 10) {
+        /* decimal input of code, while Alt depressed */
+        base = 10;
+    } else {
+        /* hexadecimal input of code, while AltGr depressed */
+        value -= 10;
+        base = 16;
+    }
+
+    if (kbd->npadch == -1)
+        kbd->npadch = value;
+    else
+        kbd->npadch = kbd->npadch * base + value;
+}
+
+static void k_lock(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+    if (up_flag || kbd->rep)
+        return;
+
+    chg_vc_kbd_lock(kbd, value);
+}
+
+static void k_slock(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+    k_shift(kbd, value, up_flag);
+    if (up_flag || kbd->rep)
+        return;
+
+    chg_vc_kbd_slock(kbd, value);
+    /* try to make Alt, oops, AltGr and such work */
+    if (!kbd->key_maps[kbd->lockstate ^ kbd->slockstate]) {
+        kbd->slockstate = 0;
+        chg_vc_kbd_slock(kbd, value);
+    }
+}
+
+static void k_brl(SDL_EVDEV_keyboard_state *kbd, unsigned char value, char up_flag)
+{
+}
+
+void
+SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *kbd, unsigned int keycode, int down)
+{
+    unsigned char shift_final;
+    unsigned char type;
+    unsigned short *key_map;
+    unsigned short keysym;
+
+    if (!kbd) {
+        return;
+    }
+
+    kbd->rep = (down == 2);
+
+    shift_final = (kbd->shift_state | kbd->slockstate) ^ kbd->lockstate;
+    key_map = kbd->key_maps[shift_final];
+    if (!key_map) {
+        kbd->slockstate = 0;
+        return;
+    }
+
+    if (keycode < NR_KEYS) {
+        keysym = key_map[keycode];
+    } else {
+        return;
+    }
+
+    type = KTYP(keysym);
+
+    if (type < 0xf0) {
+        if (down) {
+            put_utf8(kbd, keysym);
+        }
+    } else {
+        type -= 0xf0;
+
+        /* if type is KT_LETTER then it can be affected by Caps Lock */
+        if (type == KT_LETTER) {
+            type = KT_LATIN;
+
+            if (vc_kbd_led(kbd, K_CAPSLOCK)) {
+                key_map = kbd->key_maps[shift_final ^ (1 << KG_SHIFT)];
+                if (key_map) {
+                    keysym = key_map[keycode];
+                }
+            }
+        }
+
+        (*k_handler[type])(kbd, keysym & 0xff, !down);
+
+        if (type != KT_SLOCK) {
+            kbd->slockstate = 0;
+        }
+    }
+
+    if (kbd->text_len > 0) {
+        kbd->text[kbd->text_len] = '\0';
+        SDL_SendKeyboardText(kbd->text);
+        kbd->text_len = 0;
+    }
+}
+
+#else /* !SDL_INPUT_LINUXKD */
+
+SDL_EVDEV_keyboard_state *
+SDL_EVDEV_kbd_init(void)
+{
+    return NULL;
+}
+
+void
+SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *state, unsigned int keycode, int down)
+{
+}
+
+void
+SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *state)
+{
+}
+
+#endif /* SDL_INPUT_LINUXKD */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/events/SDL_clipboardevents_c.h b/src/core/linux/SDL_evdev_kbd.h
similarity index 70%
copy from src/events/SDL_clipboardevents_c.h
copy to src/core/linux/SDL_evdev_kbd.h
index 98e6a38..990c99a 100644
--- a/src/events/SDL_clipboardevents_c.h
+++ b/src/core/linux/SDL_evdev_kbd.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,13 +18,12 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../SDL_internal.h"
 
-#ifndef _SDL_clipboardevents_c_h
-#define _SDL_clipboardevents_c_h
+struct SDL_EVDEV_keyboard_state;
+typedef struct SDL_EVDEV_keyboard_state SDL_EVDEV_keyboard_state;
 
-extern int SDL_SendClipboardUpdate(void);
-
-#endif /* _SDL_clipboardevents_c_h */
+extern SDL_EVDEV_keyboard_state *SDL_EVDEV_kbd_init(void);
+extern void SDL_EVDEV_kbd_keycode(SDL_EVDEV_keyboard_state *state, unsigned int keycode, int down);
+extern void SDL_EVDEV_kbd_quit(SDL_EVDEV_keyboard_state *state);
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_evdev_kbd_default_accents.h b/src/core/linux/SDL_evdev_kbd_default_accents.h
new file mode 100644
index 0000000..e01eb59
--- /dev/null
+++ b/src/core/linux/SDL_evdev_kbd_default_accents.h
@@ -0,0 +1,284 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+static struct kbdiacrs default_accents = {
+    68,
+    {
+        { 0x60, 0x41, 0xc0 },
+        { 0x60, 0x61, 0xe0 },
+        { 0x27, 0x41, 0xc1 },
+        { 0x27, 0x61, 0xe1 },
+        { 0x5e, 0x41, 0xc2 },
+        { 0x5e, 0x61, 0xe2 },
+        { 0x7e, 0x41, 0xc3 },
+        { 0x7e, 0x61, 0xe3 },
+        { 0x22, 0x41, 0xc4 },
+        { 0x22, 0x61, 0xe4 },
+        { 0x4f, 0x41, 0xc5 },
+        { 0x6f, 0x61, 0xe5 },
+        { 0x30, 0x41, 0xc5 },
+        { 0x30, 0x61, 0xe5 },
+        { 0x41, 0x41, 0xc5 },
+        { 0x61, 0x61, 0xe5 },
+        { 0x41, 0x45, 0xc6 },
+        { 0x61, 0x65, 0xe6 },
+        { 0x2c, 0x43, 0xc7 },
+        { 0x2c, 0x63, 0xe7 },
+        { 0x60, 0x45, 0xc8 },
+        { 0x60, 0x65, 0xe8 },
+        { 0x27, 0x45, 0xc9 },
+        { 0x27, 0x65, 0xe9 },
+        { 0x5e, 0x45, 0xca },
+        { 0x5e, 0x65, 0xea },
+        { 0x22, 0x45, 0xcb },
+        { 0x22, 0x65, 0xeb },
+        { 0x60, 0x49, 0xcc },
+        { 0x60, 0x69, 0xec },
+        { 0x27, 0x49, 0xcd },
+        { 0x27, 0x69, 0xed },
+        { 0x5e, 0x49, 0xce },
+        { 0x5e, 0x69, 0xee },
+        { 0x22, 0x49, 0xcf },
+        { 0x22, 0x69, 0xef },
+        { 0x2d, 0x44, 0xd0 },
+        { 0x2d, 0x64, 0xf0 },
+        { 0x7e, 0x4e, 0xd1 },
+        { 0x7e, 0x6e, 0xf1 },
+        { 0x60, 0x4f, 0xd2 },
+        { 0x60, 0x6f, 0xf2 },
+        { 0x27, 0x4f, 0xd3 },
+        { 0x27, 0x6f, 0xf3 },
+        { 0x5e, 0x4f, 0xd4 },
+        { 0x5e, 0x6f, 0xf4 },
+        { 0x7e, 0x4f, 0xd5 },
+        { 0x7e, 0x6f, 0xf5 },
+        { 0x22, 0x4f, 0xd6 },
+        { 0x22, 0x6f, 0xf6 },
+        { 0x2f, 0x4f, 0xd8 },
+        { 0x2f, 0x6f, 0xf8 },
+        { 0x60, 0x55, 0xd9 },
+        { 0x60, 0x75, 0xf9 },
+        { 0x27, 0x55, 0xda },
+        { 0x27, 0x75, 0xfa },
+        { 0x5e, 0x55, 0xdb },
+        { 0x5e, 0x75, 0xfb },
+        { 0x22, 0x55, 0xdc },
+        { 0x22, 0x75, 0xfc },
+        { 0x27, 0x59, 0xdd },
+        { 0x27, 0x79, 0xfd },
+        { 0x54, 0x48, 0xde },
+        { 0x74, 0x68, 0xfe },
+        { 0x73, 0x73, 0xdf },
+        { 0x22, 0x79, 0xff },
+        { 0x73, 0x7a, 0xdf },
+        { 0x69, 0x6a, 0xff },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+        { 0x00, 0x00, 0x00 },
+    }
+};
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_evdev_kbd_default_keymap.h b/src/core/linux/SDL_evdev_kbd_default_keymap.h
new file mode 100644
index 0000000..220e750
--- /dev/null
+++ b/src/core/linux/SDL_evdev_kbd_default_keymap.h
@@ -0,0 +1,4763 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+static unsigned short default_key_map_0[NR_KEYS] = {
+    0xf200, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+};
+static unsigned short default_key_map_1[NR_KEYS] = {
+    0xf200, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, 
+    0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, 
+    0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, 
+    0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+};
+static unsigned short default_key_map_2[NR_KEYS] = {
+    0xf200, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, 
+    0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+};
+static unsigned short default_key_map_3[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+#ifdef INCLUDE_EXTENDED_KEYMAP
+static unsigned short default_key_map_4[NR_KEYS] = {
+    0xf200, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, 
+    0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, 
+    0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+};
+static unsigned short default_key_map_5[NR_KEYS] = {
+    0xf200, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, 
+    0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, 
+    0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+};
+static unsigned short default_key_map_6[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_7[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_8[NR_KEYS] = {
+    0xf200, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, 
+    0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, 
+    0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, 
+    0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+};
+static unsigned short default_key_map_9[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, 
+    0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_10[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_11[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_12[NR_KEYS] = {
+    0xf200, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf11a, 0xf10c, 0xf10d, 0xf11b, 0xf11c, 0xf110, 0xf311, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+    0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 
+};
+static unsigned short default_key_map_13[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_14[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_15[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_16[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_17[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, 
+    0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, 
+    0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_18[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, 
+    0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_19[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_20[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, 
+    0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, 
+    0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_21[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, 
+    0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, 
+    0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_22[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_23[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_24[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, 
+    0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, 
+    0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, 
+    0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_25[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, 
+    0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_26[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_27[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_28[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_29[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_30[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_31[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_32[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_33[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, 
+    0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, 
+    0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_34[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, 
+    0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_35[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_36[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, 
+    0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, 
+    0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_37[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, 
+    0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, 
+    0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_38[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_39[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_40[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, 
+    0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, 
+    0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, 
+    0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_41[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, 
+    0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_42[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_43[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_44[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_45[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_46[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_47[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_48[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_49[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, 
+    0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, 
+    0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_50[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, 
+    0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_51[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_52[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, 
+    0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, 
+    0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_53[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, 
+    0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, 
+    0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_54[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_55[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_56[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, 
+    0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, 
+    0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, 
+    0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_57[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, 
+    0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_58[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_59[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_60[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_61[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_62[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_63[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_64[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_65[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, 
+    0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, 
+    0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_66[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, 
+    0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_67[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_68[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, 
+    0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, 
+    0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_69[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, 
+    0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, 
+    0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_70[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_71[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_72[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, 
+    0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, 
+    0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, 
+    0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_73[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, 
+    0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_74[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_75[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_76[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_77[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_78[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_79[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_80[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_81[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, 
+    0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, 
+    0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_82[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, 
+    0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_83[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_84[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, 
+    0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, 
+    0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_85[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, 
+    0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, 
+    0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_86[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_87[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_88[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, 
+    0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, 
+    0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, 
+    0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_89[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, 
+    0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_90[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_91[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_92[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_93[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_94[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_95[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_96[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_97[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, 
+    0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, 
+    0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_98[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, 
+    0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_99[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_100[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, 
+    0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, 
+    0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_101[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, 
+    0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, 
+    0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_102[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_103[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_104[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, 
+    0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, 
+    0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, 
+    0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_105[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, 
+    0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_106[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_107[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_108[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_109[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_110[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_111[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_112[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_113[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf10c, 0xf10d, 0xf10e, 0xf10f, 0xf110, 
+    0xf111, 0xf112, 0xf113, 0xf11e, 0xf11f, 0xf208, 0xf203, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf03e, 0xf120, 
+    0xf121, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf200, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf20b, 0xf601, 0xf602, 0xf117, 0xf600, 0xf20a, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_114[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf031, 0xf032, 0xf033, 0xf034, 0xf035, 0xf036, 
+    0xf037, 0xf038, 0xf039, 0xf030, 0xf02d, 0xf03d, 0xf07f, 0xf009, 
+    0xfb51, 0xfb57, 0xfb45, 0xfb52, 0xfb54, 0xfb59, 0xfb55, 0xfb49, 
+    0xfb4f, 0xfb50, 0xf05b, 0xf05d, 0xf201, 0xf702, 0xfb41, 0xfb53, 
+    0xfb44, 0xfb46, 0xfb47, 0xfb48, 0xfb4a, 0xfb4b, 0xfb4c, 0xf03b, 
+    0xf027, 0xf060, 0xf700, 0xf05c, 0xfb5a, 0xfb58, 0xfb43, 0xfb56, 
+    0xfb42, 0xfb4e, 0xfb4d, 0xf02c, 0xf02e, 0xf02f, 0xf700, 0xf916, 
+    0xf703, 0xf020, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf202, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf07c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_115[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf021, 0xf040, 0xf023, 0xf024, 0xf025, 0xf05e, 
+    0xf026, 0xf02a, 0xf028, 0xf029, 0xf05f, 0xf02b, 0xf07f, 0xf009, 
+    0xfb71, 0xfb77, 0xfb65, 0xfb72, 0xfb74, 0xfb79, 0xfb75, 0xfb69, 
+    0xfb6f, 0xfb70, 0xf07b, 0xf07d, 0xf201, 0xf702, 0xfb61, 0xfb73, 
+    0xfb64, 0xfb66, 0xfb67, 0xfb68, 0xfb6a, 0xfb6b, 0xfb6c, 0xf03a, 
+    0xf022, 0xf07e, 0xf700, 0xf07c, 0xfb7a, 0xfb78, 0xfb63, 0xfb76, 
+    0xfb62, 0xfb6e, 0xfb6d, 0xf03c, 0xf03e, 0xf03f, 0xf700, 0xf30c, 
+    0xf703, 0xf020, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0x00a6, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_116[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf122, 0xf123, 0xf124, 0xf125, 0xf126, 
+    0xf127, 0xf128, 0xf129, 0xf12a, 0xf12b, 0xf208, 0xf204, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf12c, 
+    0xf12d, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_117[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf12e, 0xf12f, 0xf130, 0xf131, 0xf132, 
+    0xf133, 0xf134, 0xf135, 0xf136, 0xf137, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf138, 
+    0xf139, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_118[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf000, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf01c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_119[NR_KEYS] = {
+    0xf27e, 0xf01b, 0xf200, 0xf000, 0xf200, 0xf200, 0xf200, 0xf01e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf01f, 0xf200, 0xf008, 0xf009, 
+    0xf011, 0xf017, 0xf005, 0xf012, 0xf014, 0xf019, 0xf015, 0xf009, 
+    0xf00f, 0xf010, 0xf01b, 0xf01d, 0xf00d, 0xf702, 0xf001, 0xf013, 
+    0xf004, 0xf006, 0xf007, 0xf008, 0xf00a, 0xf00b, 0xf00c, 0xf200, 
+    0xf200, 0xf01e, 0xf700, 0xf01c, 0xf01a, 0xf018, 0xf003, 0xf016, 
+    0xf002, 0xf00e, 0xf201, 0xf200, 0xf20e, 0xf07f, 0xf700, 0xf30c, 
+    0xf703, 0xf000, 0xfa06, 0xf518, 0xf519, 0xf51a, 0xf51b, 0xf51c, 
+    0xf51d, 0xf51e, 0xf51f, 0xf520, 0xf521, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf01c, 0xf522, 
+    0xf523, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf01c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf205, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_120[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf202, 0xf907, 
+    0xf908, 0xf909, 0xf30b, 0xf904, 0xf905, 0xf906, 0xf30a, 0xf901, 
+    0xf902, 0xf903, 0xf900, 0xf310, 0xf206, 0xf200, 0xf83c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf212, 
+    0xf118, 0xf210, 0xf211, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_121[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf916, 
+    0xf703, 0xf820, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf914, 0xf209, 0xf911, 
+    0xf912, 0xf913, 0xf917, 0xf90e, 0xf90f, 0xf910, 0xf918, 0xf90b, 
+    0xf90c, 0xf90d, 0xf90a, 0xf310, 0xf206, 0xf200, 0xf83e, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf919, 0xf702, 0xf915, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_122[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf831, 0xf832, 0xf833, 0xf834, 0xf835, 0xf836, 
+    0xf837, 0xf838, 0xf839, 0xf830, 0xf82d, 0xf83d, 0xf87f, 0xf809, 
+    0xf871, 0xf877, 0xf865, 0xf872, 0xf874, 0xf879, 0xf875, 0xf869, 
+    0xf86f, 0xf870, 0xf85b, 0xf85d, 0xf80d, 0xf702, 0xf861, 0xf873, 
+    0xf864, 0xf866, 0xf867, 0xf868, 0xf86a, 0xf86b, 0xf86c, 0xf83b, 
+    0xf827, 0xf860, 0xf700, 0xf85c, 0xf87a, 0xf878, 0xf863, 0xf876, 
+    0xf862, 0xf86e, 0xf86d, 0xf82c, 0xf82e, 0xf82f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_123[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf821, 0xf840, 0xf823, 0xf824, 0xf825, 0xf85e, 
+    0xf826, 0xf82a, 0xf828, 0xf829, 0xf85f, 0xf82b, 0xf87f, 0xf809, 
+    0xf851, 0xf857, 0xf845, 0xf852, 0xf854, 0xf859, 0xf855, 0xf849, 
+    0xf84f, 0xf850, 0xf87b, 0xf87d, 0xf80d, 0xf702, 0xf841, 0xf853, 
+    0xf844, 0xf846, 0xf847, 0xf848, 0xf84a, 0xf84b, 0xf84c, 0xf83a, 
+    0xf822, 0xf87e, 0xf700, 0xf87c, 0xf85a, 0xf858, 0xf843, 0xf856, 
+    0xf842, 0xf84e, 0xf84d, 0xf83c, 0xf83e, 0xf83f, 0xf700, 0xf30c, 
+    0xf703, 0xf820, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf87c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf206, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_124[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf500, 0xf501, 0xf502, 0xf503, 0xf504, 
+    0xf505, 0xf506, 0xf507, 0xf508, 0xf509, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf50a, 
+    0xf50b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_125[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf50c, 0xf50d, 0xf50e, 0xf50f, 0xf510, 
+    0xf511, 0xf512, 0xf513, 0xf514, 0xf515, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf516, 
+    0xf517, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_126[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf800, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf20c, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf20c, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+static unsigned short default_key_map_127[NR_KEYS] = {
+    0xf27e, 0xf81b, 0xf200, 0xf800, 0xf200, 0xf200, 0xf200, 0xf81e, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf81f, 0xf200, 0xf808, 0xf809, 
+    0xf811, 0xf817, 0xf805, 0xf812, 0xf814, 0xf819, 0xf815, 0xf809, 
+    0xf80f, 0xf810, 0xf81b, 0xf81d, 0xf80d, 0xf702, 0xf801, 0xf813, 
+    0xf804, 0xf806, 0xf807, 0xf808, 0xf80a, 0xf80b, 0xf80c, 0xf200, 
+    0xf200, 0xf81e, 0xf700, 0xf81c, 0xf81a, 0xf818, 0xf803, 0xf816, 
+    0xf802, 0xf80e, 0xf80d, 0xf200, 0xf20e, 0xf87f, 0xf700, 0xf30c, 
+    0xf703, 0xf800, 0xfa06, 0xf100, 0xf101, 0xf102, 0xf103, 0xf104, 
+    0xf105, 0xf106, 0xf107, 0xf108, 0xf109, 0xf208, 0xf209, 0xf307, 
+    0xf308, 0xf309, 0xf30b, 0xf304, 0xf305, 0xf306, 0xf30a, 0xf301, 
+    0xf302, 0xf303, 0xf300, 0xf310, 0xf206, 0xf200, 0xf81c, 0xf10a, 
+    0xf10b, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf30e, 0xf702, 0xf30d, 0xf81c, 0xf703, 0xf205, 0xf114, 0xf603, 
+    0xf118, 0xf601, 0xf602, 0xf117, 0xf600, 0xf119, 0xf115, 0xf116, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf11d, 
+    0xf200, 0xf310, 0xf200, 0xf200, 0xf200, 0xf703, 0xf703, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+    0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 0xf200, 
+};
+#endif /* INCLUDE_EXTENDED_KEYMAP */
+
+static unsigned short *default_key_maps[MAX_NR_KEYMAPS] = {
+    default_key_map_0,
+    default_key_map_1,
+    default_key_map_2,
+    default_key_map_3,
+#ifdef INCLUDE_EXTENDED_KEYMAP
+    default_key_map_4,
+    default_key_map_5,
+    default_key_map_6,
+    default_key_map_7,
+    default_key_map_8,
+    default_key_map_9,
+    default_key_map_10,
+    default_key_map_11,
+    default_key_map_12,
+    default_key_map_13,
+    default_key_map_14,
+    default_key_map_15,
+    default_key_map_16,
+    default_key_map_17,
+    default_key_map_18,
+    default_key_map_19,
+    default_key_map_20,
+    default_key_map_21,
+    default_key_map_22,
+    default_key_map_23,
+    default_key_map_24,
+    default_key_map_25,
+    default_key_map_26,
+    default_key_map_27,
+    default_key_map_28,
+    default_key_map_29,
+    default_key_map_30,
+    default_key_map_31,
+    default_key_map_32,
+    default_key_map_33,
+    default_key_map_34,
+    default_key_map_35,
+    default_key_map_36,
+    default_key_map_37,
+    default_key_map_38,
+    default_key_map_39,
+    default_key_map_40,
+    default_key_map_41,
+    default_key_map_42,
+    default_key_map_43,
+    default_key_map_44,
+    default_key_map_45,
+    default_key_map_46,
+    default_key_map_47,
+    default_key_map_48,
+    default_key_map_49,
+    default_key_map_50,
+    default_key_map_51,
+    default_key_map_52,
+    default_key_map_53,
+    default_key_map_54,
+    default_key_map_55,
+    default_key_map_56,
+    default_key_map_57,
+    default_key_map_58,
+    default_key_map_59,
+    default_key_map_60,
+    default_key_map_61,
+    default_key_map_62,
+    default_key_map_63,
+    default_key_map_64,
+    default_key_map_65,
+    default_key_map_66,
+    default_key_map_67,
+    default_key_map_68,
+    default_key_map_69,
+    default_key_map_70,
+    default_key_map_71,
+    default_key_map_72,
+    default_key_map_73,
+    default_key_map_74,
+    default_key_map_75,
+    default_key_map_76,
+    default_key_map_77,
+    default_key_map_78,
+    default_key_map_79,
+    default_key_map_80,
+    default_key_map_81,
+    default_key_map_82,
+    default_key_map_83,
+    default_key_map_84,
+    default_key_map_85,
+    default_key_map_86,
+    default_key_map_87,
+    default_key_map_88,
+    default_key_map_89,
+    default_key_map_90,
+    default_key_map_91,
+    default_key_map_92,
+    default_key_map_93,
+    default_key_map_94,
+    default_key_map_95,
+    default_key_map_96,
+    default_key_map_97,
+    default_key_map_98,
+    default_key_map_99,
+    default_key_map_100,
+    default_key_map_101,
+    default_key_map_102,
+    default_key_map_103,
+    default_key_map_104,
+    default_key_map_105,
+    default_key_map_106,
+    default_key_map_107,
+    default_key_map_108,
+    default_key_map_109,
+    default_key_map_110,
+    default_key_map_111,
+    default_key_map_112,
+    default_key_map_113,
+    default_key_map_114,
+    default_key_map_115,
+    default_key_map_116,
+    default_key_map_117,
+    default_key_map_118,
+    default_key_map_119,
+    default_key_map_120,
+    default_key_map_121,
+    default_key_map_122,
+    default_key_map_123,
+    default_key_map_124,
+    default_key_map_125,
+    default_key_map_126,
+    default_key_map_127,
+#else /* !INCLUDE_EXTENDED_KEYMAP */
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+#endif /* INCLUDE_EXTENDED_KEYMAP */
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+};
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_fcitx.c b/src/core/linux/SDL_fcitx.c
index 83d19e6..e59a99d 100644
--- a/src/core/linux/SDL_fcitx.c
+++ b/src/core/linux/SDL_fcitx.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -118,71 +118,6 @@ GetAppName()
     return SDL_strdup("SDL_App");
 }
 
-/*
- * Copied from fcitx source
- */
-#define CONT(i)   ISUTF8_CB(in[i])
-#define VAL(i, s) ((in[i]&0x3f) << s)
-
-static char *
-_fcitx_utf8_get_char(const char *i, uint32_t *chr)
-{
-    const unsigned char* in = (const unsigned char *)i;
-    if (!(in[0] & 0x80)) {
-        *(chr) = *(in);
-        return (char *)in + 1;
-    }
-
-    /* 2-byte, 0x80-0x7ff */
-    if ((in[0] & 0xe0) == 0xc0 && CONT(1)) {
-        *chr = ((in[0] & 0x1f) << 6) | VAL(1, 0);
-        return (char *)in + 2;
-    }
-
-    /* 3-byte, 0x800-0xffff */
-    if ((in[0] & 0xf0) == 0xe0 && CONT(1) && CONT(2)) {
-        *chr = ((in[0] & 0xf) << 12) | VAL(1, 6) | VAL(2, 0);
-        return (char *)in + 3;
-    }
-
-    /* 4-byte, 0x10000-0x1FFFFF */
-    if ((in[0] & 0xf8) == 0xf0 && CONT(1) && CONT(2) && CONT(3)) {
-        *chr = ((in[0] & 0x7) << 18) | VAL(1, 12) | VAL(2, 6) | VAL(3, 0);
-        return (char *)in + 4;
-    }
-
-    /* 5-byte, 0x200000-0x3FFFFFF */
-    if ((in[0] & 0xfc) == 0xf8 && CONT(1) && CONT(2) && CONT(3) && CONT(4)) {
-        *chr = ((in[0] & 0x3) << 24) | VAL(1, 18) | VAL(2, 12) | VAL(3, 6) | VAL(4, 0);
-        return (char *)in + 5;
-    }
-
-    /* 6-byte, 0x400000-0x7FFFFFF */
-    if ((in[0] & 0xfe) == 0xfc && CONT(1) && CONT(2) && CONT(3) && CONT(4) && CONT(5)) {
-        *chr = ((in[0] & 0x1) << 30) | VAL(1, 24) | VAL(2, 18) | VAL(3, 12) | VAL(4, 6) | VAL(5, 0);
-        return (char *)in + 6;
-    }
-
-    *chr = *in;
-
-    return (char *)in + 1;
-}
-
-static size_t
-_fcitx_utf8_strlen(const char *s)
-{
-    unsigned int l = 0;
-
-    while (*s) {
-        uint32_t chr;
-
-        s = _fcitx_utf8_get_char(s, &chr);
-        l++;
-    }
-
-    return l;
-}
-
 static DBusHandlerResult
 DBus_MessageFilter(DBusConnection *conn, DBusMessage *msg, void *data)
 {
@@ -214,8 +149,8 @@ DBus_MessageFilter(DBusConnection *conn, DBusMessage *msg, void *data)
             size_t cursor = 0;
 
             while (i < text_bytes) {
-                size_t sz = SDL_utf8strlcpy(buf, text + i, sizeof(buf));
-                size_t chars = _fcitx_utf8_strlen(buf);
+                const size_t sz = SDL_utf8strlcpy(buf, text + i, sizeof(buf));
+                const size_t chars = SDL_utf8strlen(buf);
 
                 SDL_SendEditingText(buf, cursor, chars);
 
@@ -231,116 +166,50 @@ DBus_MessageFilter(DBusConnection *conn, DBusMessage *msg, void *data)
     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
 }
 
-static DBusMessage*
-FcitxClientICNewMethod(FcitxClient *client,
-        const char *method)
-{
-    SDL_DBusContext *dbus = client->dbus;
-    return dbus->message_new_method_call(
-            client->servicename,
-            client->icname,
-            FCITX_IC_DBUS_INTERFACE,
-            method);
-}
-
 static void
-FcitxClientICCallMethod(FcitxClient *client,
-        const char *method)
+FcitxClientICCallMethod(FcitxClient *client, const char *method)
 {
-    SDL_DBusContext *dbus = client->dbus;
-    DBusMessage *msg = FcitxClientICNewMethod(client, method);
-
-    if (msg == NULL)
-        return ;
-
-    if (dbus->connection_send(dbus->session_conn, msg, NULL)) {
-        dbus->connection_flush(dbus->session_conn);
-    }
-
-    dbus->message_unref(msg);
+    SDL_DBus_CallVoidMethod(client->servicename, client->icname, FCITX_IC_DBUS_INTERFACE, method, DBUS_TYPE_INVALID);
 }
 
-static void
+static void SDLCALL
 Fcitx_SetCapabilities(void *data,
         const char *name,
         const char *old_val,
         const char *internal_editing)
 {
     FcitxClient *client = (FcitxClient *)data;
-    SDL_DBusContext *dbus = client->dbus;
     Uint32 caps = CAPACITY_NONE;
 
-    DBusMessage *msg = FcitxClientICNewMethod(client, "SetCapacity");
-    if (msg == NULL)
-        return ;
-
     if (!(internal_editing && *internal_editing == '1')) {
         caps |= CAPACITY_PREEDIT;
     }
 
-    dbus->message_append_args(msg,
-            DBUS_TYPE_UINT32, &caps,
-            DBUS_TYPE_INVALID);
-    if (dbus->connection_send(dbus->session_conn, msg, NULL)) {
-        dbus->connection_flush(dbus->session_conn);
-    }
-
-    dbus->message_unref(msg);
+    SDL_DBus_CallVoidMethod(client->servicename, client->icname, FCITX_IC_DBUS_INTERFACE, "SetCapacity", DBUS_TYPE_UINT32, &caps, DBUS_TYPE_INVALID);
 }
 
-static void
+static SDL_bool
 FcitxClientCreateIC(FcitxClient *client)
 {
-    char *appname = NULL;
-    pid_t pid = 0;
-    int id = 0;
-    SDL_bool enable;
-    Uint32 arg1, arg2, arg3, arg4;
-
-    SDL_DBusContext *dbus = client->dbus;
-    DBusMessage *reply = NULL;
-    DBusMessage *msg = dbus->message_new_method_call(
-            client->servicename,
-            FCITX_IM_DBUS_PATH,
-            FCITX_IM_DBUS_INTERFACE,
-            "CreateICv3"
-            );
-
-    if (msg == NULL)
-        return ;
+    char *appname = GetAppName();
+    pid_t pid = getpid();
+    int id = -1;
+    Uint32 enable, arg1, arg2, arg3, arg4;
+
+    if (!SDL_DBus_CallMethod(client->servicename, FCITX_IM_DBUS_PATH, FCITX_IM_DBUS_INTERFACE, "CreateICv3",
+            DBUS_TYPE_STRING, &appname, DBUS_TYPE_INT32, &pid, DBUS_TYPE_INVALID,
+            DBUS_TYPE_INT32, &id, DBUS_TYPE_BOOLEAN, &enable, DBUS_TYPE_UINT32, &arg1, DBUS_TYPE_UINT32, &arg2, DBUS_TYPE_UINT32, &arg3, DBUS_TYPE_UINT32, &arg4, DBUS_TYPE_INVALID)) {
+        id = -1;  /* just in case. */
+    }
 
-    appname = GetAppName();
-    pid = getpid();
-    dbus->message_append_args(msg,
-            DBUS_TYPE_STRING, &appname,
-            DBUS_TYPE_INT32, &pid,
-            DBUS_TYPE_INVALID);
-
-    do {
-        reply = dbus->connection_send_with_reply_and_block(
-                dbus->session_conn,
-                msg,
-                DBUS_TIMEOUT,
-                NULL);
+    SDL_free(appname);
+
+    if (id >= 0) {
+        SDL_DBusContext *dbus = client->dbus;
 
-        if (!reply)
-            break;
-        if (!dbus->message_get_args(reply, NULL,
-                DBUS_TYPE_INT32, &id,
-                DBUS_TYPE_BOOLEAN, &enable,
-                DBUS_TYPE_UINT32, &arg1,
-                DBUS_TYPE_UINT32, &arg2,
-                DBUS_TYPE_UINT32, &arg3,
-                DBUS_TYPE_UINT32, &arg4,
-                DBUS_TYPE_INVALID))
-            break;
-
-        if (id < 0)
-            break;
         client->id = id;
 
-        SDL_snprintf(client->icname, IC_NAME_MAX,
-                FCITX_IC_DBUS_PATH, client->id);
+        SDL_snprintf(client->icname, IC_NAME_MAX, FCITX_IC_DBUS_PATH, client->id);
 
         dbus->bus_add_match(dbus->session_conn,
                 "type='signal', interface='org.fcitx.Fcitx.InputContext'",
@@ -350,14 +219,11 @@ FcitxClientCreateIC(FcitxClient *client)
                 NULL);
         dbus->connection_flush(dbus->session_conn);
 
-        SDL_AddHintCallback(SDL_HINT_IME_INTERNAL_EDITING, &Fcitx_SetCapabilities, client);
+        SDL_AddHintCallback(SDL_HINT_IME_INTERNAL_EDITING, Fcitx_SetCapabilities, client);
+        return SDL_TRUE;
     }
-    while (0);
 
-    if (reply)
-        dbus->message_unref(reply);
-    dbus->message_unref(msg);
-    SDL_free(appname);
+    return SDL_FALSE;
 }
 
 static Uint32
@@ -391,9 +257,7 @@ SDL_Fcitx_Init()
             "%s-%d",
             FCITX_DBUS_SERVICE, GetDisplayNumber());
 
-    FcitxClientCreateIC(&fcitx_client);
-
-    return SDL_TRUE;
+    return FcitxClientCreateIC(&fcitx_client);
 }
 
 void
@@ -422,47 +286,21 @@ SDL_Fcitx_Reset(void)
 SDL_bool
 SDL_Fcitx_ProcessKeyEvent(Uint32 keysym, Uint32 keycode)
 {
-    DBusMessage *msg = NULL;
-    DBusMessage *reply = NULL;
-    SDL_DBusContext *dbus = fcitx_client.dbus;
-
-    Uint32 state = 0;
-    SDL_bool handled = SDL_FALSE;
+    Uint32 state = Fcitx_ModState();
+    Uint32 handled = SDL_FALSE;
     int type = FCITX_PRESS_KEY;
     Uint32 event_time = 0;
 
-    msg = FcitxClientICNewMethod(&fcitx_client, "ProcessKeyEvent");
-    if (msg == NULL)
-        return SDL_FALSE;
-
-    state = Fcitx_ModState();
-    dbus->message_append_args(msg,
-            DBUS_TYPE_UINT32, &keysym,
-            DBUS_TYPE_UINT32, &keycode,
-            DBUS_TYPE_UINT32, &state,
-            DBUS_TYPE_INT32, &type,
-            DBUS_TYPE_UINT32, &event_time,
-            DBUS_TYPE_INVALID);
-
-    reply = dbus->connection_send_with_reply_and_block(dbus->session_conn,
-            msg,
-            -1,
-            NULL);
-
-    if (reply) {
-        dbus->message_get_args(reply,
-                NULL,
-                DBUS_TYPE_INT32, &handled,
-                DBUS_TYPE_INVALID);
-
-        dbus->message_unref(reply);
-    }
-
-    if (handled) {
-        SDL_Fcitx_UpdateTextRect(NULL);
+    if (SDL_DBus_CallMethod(fcitx_client.servicename, fcitx_client.icname, FCITX_IC_DBUS_INTERFACE, "ProcessKeyEvent",
+            DBUS_TYPE_UINT32, &keysym, DBUS_TYPE_UINT32, &keycode, DBUS_TYPE_UINT32, &state, DBUS_TYPE_INT32, &type, DBUS_TYPE_UINT32, &event_time, DBUS_TYPE_INVALID,
+            DBUS_TYPE_INT32, &handled, DBUS_TYPE_INVALID)) {
+        if (handled) {
+            SDL_Fcitx_UpdateTextRect(NULL);
+            return SDL_TRUE;
+        }
     }
 
-    return handled;
+    return SDL_FALSE;
 }
 
 void
@@ -473,10 +311,6 @@ SDL_Fcitx_UpdateTextRect(SDL_Rect *rect)
     int x = 0, y = 0;
     SDL_Rect *cursor = &fcitx_client.cursor_rect;
 
-    SDL_DBusContext *dbus = fcitx_client.dbus;
-    DBusMessage *msg = NULL;
-    DBusConnection *conn;
-
     if (rect) {
         SDL_memcpy(cursor, rect, sizeof(SDL_Rect));
     }
@@ -506,7 +340,7 @@ SDL_Fcitx_UpdateTextRect(SDL_Rect *rect)
 #endif
 
     if (cursor->x == -1 && cursor->y == -1 && cursor->w == 0 && cursor->h == 0) {
-        // move to bottom left
+        /* move to bottom left */
         int w = 0, h = 0;
         SDL_GetWindowSize(focused_win, &w, &h);
         cursor->x = 0;
@@ -516,26 +350,12 @@ SDL_Fcitx_UpdateTextRect(SDL_Rect *rect)
     x += cursor->x;
     y += cursor->y;
 
-    msg = FcitxClientICNewMethod(&fcitx_client, "SetCursorRect");
-    if (msg == NULL)
-        return ;
-
-    dbus->message_append_args(msg,
-            DBUS_TYPE_INT32, &x,
-            DBUS_TYPE_INT32, &y,
-            DBUS_TYPE_INT32, &cursor->w,
-            DBUS_TYPE_INT32, &cursor->h,
-            DBUS_TYPE_INVALID);
-
-    conn = dbus->session_conn;
-    if (dbus->connection_send(conn, msg, NULL))
-        dbus->connection_flush(conn);
-
-    dbus->message_unref(msg);
+    SDL_DBus_CallVoidMethod(fcitx_client.servicename, fcitx_client.icname, FCITX_IC_DBUS_INTERFACE, "SetCursorRect",
+        DBUS_TYPE_INT32, &x, DBUS_TYPE_INT32, &y, DBUS_TYPE_INT32, &cursor->w, DBUS_TYPE_INT32, &cursor->h, DBUS_TYPE_INVALID);
 }
 
 void
-SDL_Fcitx_PumpEvents()
+SDL_Fcitx_PumpEvents(void)
 {
     SDL_DBusContext *dbus = fcitx_client.dbus;
     DBusConnection *conn = dbus->session_conn;
diff --git a/src/core/linux/SDL_fcitx.h b/src/core/linux/SDL_fcitx.h
index 6402047..4cefcf2 100644
--- a/src/core/linux/SDL_fcitx.h
+++ b/src/core/linux/SDL_fcitx.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_fcitx_h
-#define _SDL_fcitx_h
+#ifndef SDL_fcitx_h_
+#define SDL_fcitx_h_
 
 #include "../../SDL_internal.h"
 
@@ -33,8 +33,8 @@ extern void SDL_Fcitx_SetFocus(SDL_bool focused);
 extern void SDL_Fcitx_Reset(void);
 extern SDL_bool SDL_Fcitx_ProcessKeyEvent(Uint32 keysym, Uint32 keycode);
 extern void SDL_Fcitx_UpdateTextRect(SDL_Rect *rect);
-extern void SDL_Fcitx_PumpEvents();
+extern void SDL_Fcitx_PumpEvents(void);
 
-#endif /* _SDL_fcitx_h */
+#endif /* SDL_fcitx_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_ibus.c b/src/core/linux/SDL_ibus.c
index 3d63b8b..0fcec87 100644
--- a/src/core/linux/SDL_ibus.c
+++ b/src/core/linux/SDL_ibus.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -45,7 +45,7 @@ static char *input_ctx_path = NULL;
 static SDL_Rect ibus_cursor_rect = { 0, 0, 0, 0 };
 static DBusConnection *ibus_conn = NULL;
 static char *ibus_addr_file = NULL;
-int inotify_fd = -1, inotify_wd = -1;
+static int inotify_fd = -1, inotify_wd = -1;
 
 static Uint32
 IBus_ModState(void)
@@ -107,21 +107,6 @@ IBus_GetVariantText(DBusConnection *conn, DBusMessageIter *iter, SDL_DBusContext
     return text;
 }
 
-static size_t 
-IBus_utf8_strlen(const char *str)
-{
-    size_t utf8_len = 0;
-    const char *p;
-    
-    for (p = str; *p; ++p) {
-        if (!((*p & 0x80) && !(*p & 0x40))) {
-            ++utf8_len;
-        }
-    }
-    
-    return utf8_len;
-}
-
 static DBusHandlerResult
 IBus_MessageHandler(DBusConnection *conn, DBusMessage *msg, void *user_data)
 {
@@ -135,7 +120,7 @@ IBus_MessageHandler(DBusConnection *conn, DBusMessage *msg, void *user_data)
         
         text = IBus_GetVariantText(conn, &iter, dbus);
         if (text && *text) {
-            char buf[SDL_TEXTEDITINGEVENT_TEXT_SIZE];
+            char buf[SDL_TEXTINPUTEVENT_TEXT_SIZE];
             size_t text_bytes = SDL_strlen(text), i = 0;
             
             while (i < text_bytes) {
@@ -162,8 +147,8 @@ IBus_MessageHandler(DBusConnection *conn, DBusMessage *msg, void *user_data)
             size_t cursor = 0;
             
             do {
-                size_t sz = SDL_utf8strlcpy(buf, text+i, sizeof(buf));
-                size_t chars = IBus_utf8_strlen(buf);
+                const size_t sz = SDL_utf8strlcpy(buf, text+i, sizeof(buf));
+                const size_t chars = SDL_utf8strlen(buf);
                 
                 SDL_SendEditingText(buf, cursor, chars);
 
@@ -302,35 +287,20 @@ IBus_GetDBusAddressFilename(void)
 
 static SDL_bool IBus_CheckConnection(SDL_DBusContext *dbus);
 
-static void
+static void SDLCALL
 IBus_SetCapabilities(void *data, const char *name, const char *old_val,
                                                    const char *internal_editing)
 {
     SDL_DBusContext *dbus = SDL_DBus_GetContext();
     
     if (IBus_CheckConnection(dbus)) {
-
-        DBusMessage *msg = dbus->message_new_method_call(IBUS_SERVICE,
-                                                         input_ctx_path,
-                                                         IBUS_INPUT_INTERFACE,
-                                                         "SetCapabilities");
-        if (msg) {
-            Uint32 caps = IBUS_CAP_FOCUS;
-            if (!(internal_editing && *internal_editing == '1')) {
-                caps |= IBUS_CAP_PREEDIT_TEXT;
-            }
-            
-            dbus->message_append_args(msg,
-                                      DBUS_TYPE_UINT32, &caps,
-                                      DBUS_TYPE_INVALID);
-        }
-        
-        if (msg) {
-            if (dbus->connection_send(ibus_conn, msg, NULL)) {
-                dbus->connection_flush(ibus_conn);
-            }
-            dbus->message_unref(msg);
+        Uint32 caps = IBUS_CAP_FOCUS;
+        if (!(internal_editing && *internal_editing == '1')) {
+            caps |= IBUS_CAP_PREEDIT_TEXT;
         }
+
+        SDL_DBus_CallVoidMethod(IBUS_SERVICE, input_ctx_path, IBUS_INPUT_INTERFACE, "SetCapabilities",
+                                DBUS_TYPE_UINT32, &caps, DBUS_TYPE_INVALID);
     }
 }
 
@@ -338,9 +308,9 @@ IBus_SetCapabilities(void *data, const char *name, const char *old_val,
 static SDL_bool
 IBus_SetupConnection(SDL_DBusContext *dbus, const char* addr)
 {
+    const char *client_name = "SDL2_Application";
     const char *path = NULL;
     SDL_bool result = SDL_FALSE;
-    DBusMessage *msg;
     DBusObjectPathVTable ibus_vtable;
 
     SDL_zero(ibus_vtable);
@@ -361,35 +331,12 @@ IBus_SetupConnection(SDL_DBusContext *dbus, const char* addr)
     
     dbus->connection_flush(ibus_conn);
 
-    msg = dbus->message_new_method_call(IBUS_SERVICE, IBUS_PATH, IBUS_INTERFACE, "CreateInputContext");
-    if (msg) {
-        const char *client_name = "SDL2_Application";
-        dbus->message_append_args(msg,
-                                  DBUS_TYPE_STRING, &client_name,
-                                  DBUS_TYPE_INVALID);
-    }
-    
-    if (msg) {
-        DBusMessage *reply;
-        
-        reply = dbus->connection_send_with_reply_and_block(ibus_conn, msg, 1000, NULL);
-        if (reply) {
-            if (dbus->message_get_args(reply, NULL,
-                                       DBUS_TYPE_OBJECT_PATH, &path,
-                                       DBUS_TYPE_INVALID)) {
-                if (input_ctx_path) {
-                    SDL_free(input_ctx_path);
-                }
-                input_ctx_path = SDL_strdup(path);
-                result = SDL_TRUE;                          
-            }
-            dbus->message_unref(reply);
-        }
-        dbus->message_unref(msg);
-    }
-
-    if (result) {
-        SDL_AddHintCallback(SDL_HINT_IME_INTERNAL_EDITING, &IBus_SetCapabilities, NULL);
+    if (SDL_DBus_CallMethodOnConnection(ibus_conn, IBUS_SERVICE, IBUS_PATH, IBUS_INTERFACE, "CreateInputContext",
+            DBUS_TYPE_STRING, &client_name, DBUS_TYPE_INVALID,
+            DBUS_TYPE_OBJECT_PATH, &path, DBUS_TYPE_INVALID)) {
+        SDL_free(input_ctx_path);
+        input_ctx_path = SDL_strdup(path);
+        SDL_AddHintCallback(SDL_HINT_IME_INTERNAL_EDITING, IBus_SetCapabilities, NULL);
         
         dbus->bus_add_match(ibus_conn, "type='signal',interface='org.freedesktop.IBus.InputContext'", NULL);
         dbus->connection_try_register_object_path(ibus_conn, input_ctx_path, &ibus_vtable, dbus, NULL);
@@ -521,7 +468,7 @@ SDL_IBus_Quit(void)
         inotify_wd = -1;
     }
     
-    SDL_DelHintCallback(SDL_HINT_IME_INTERNAL_EDITING, &IBus_SetCapabilities, NULL);
+    SDL_DelHintCallback(SDL_HINT_IME_INTERNAL_EDITING, IBus_SetCapabilities, NULL);
     
     SDL_memset(&ibus_cursor_rect, 0, sizeof(ibus_cursor_rect));
 }
@@ -532,16 +479,7 @@ IBus_SimpleMessage(const char *method)
     SDL_DBusContext *dbus = SDL_DBus_GetContext();
     
     if (IBus_CheckConnection(dbus)) {
-        DBusMessage *msg = dbus->message_new_method_call(IBUS_SERVICE,
-                                                         input_ctx_path,
-                                                         IBUS_INPUT_INTERFACE,
-                                                         method);
-        if (msg) {
-            if (dbus->connection_send(ibus_conn, msg, NULL)) {
-                dbus->connection_flush(ibus_conn);
-            }
-            dbus->message_unref(msg);
-        }
+        SDL_DBus_CallVoidMethodOnConnection(ibus_conn, IBUS_SERVICE, input_ctx_path, IBUS_INPUT_INTERFACE, method);
     }
 }
 
@@ -561,43 +499,21 @@ SDL_IBus_Reset(void)
 SDL_bool
 SDL_IBus_ProcessKeyEvent(Uint32 keysym, Uint32 keycode)
 { 
-    SDL_bool result = SDL_FALSE;   
+    Uint32 result = 0;
     SDL_DBusContext *dbus = SDL_DBus_GetContext();
     
     if (IBus_CheckConnection(dbus)) {
-        DBusMessage *msg = dbus->message_new_method_call(IBUS_SERVICE,
-                                                         input_ctx_path,
-                                                         IBUS_INPUT_INTERFACE,
-                                                         "ProcessKeyEvent");
-        if (msg) {
-            Uint32 mods = IBus_ModState();
-            dbus->message_append_args(msg,
-                                      DBUS_TYPE_UINT32, &keysym,
-                                      DBUS_TYPE_UINT32, &keycode,
-                                      DBUS_TYPE_UINT32, &mods,
-                                      DBUS_TYPE_INVALID);
-        }
-        
-        if (msg) {
-            DBusMessage *reply;
-            
-            reply = dbus->connection_send_with_reply_and_block(ibus_conn, msg, 300, NULL);
-            if (reply) {
-                if (!dbus->message_get_args(reply, NULL,
-                                           DBUS_TYPE_BOOLEAN, &result,
-                                           DBUS_TYPE_INVALID)) {
-                    result = SDL_FALSE;                         
-                }
-                dbus->message_unref(reply);
-            }
-            dbus->message_unref(msg);
+        Uint32 mods = IBus_ModState();
+        if (!SDL_DBus_CallMethodOnConnection(ibus_conn, IBUS_SERVICE, input_ctx_path, IBUS_INPUT_INTERFACE, "ProcessKeyEvent",
+                DBUS_TYPE_UINT32, &keysym, DBUS_TYPE_UINT32, &keycode, DBUS_TYPE_UINT32, &mods, DBUS_TYPE_INVALID,
+                DBUS_TYPE_BOOLEAN, &result, DBUS_TYPE_INVALID)) {
+            result = 0;
         }
-        
     }
     
     SDL_IBus_UpdateTextRect(NULL);
 
-    return result;
+    return result ? SDL_TRUE : SDL_FALSE;
 }
 
 void
@@ -643,25 +559,8 @@ SDL_IBus_UpdateTextRect(SDL_Rect *rect)
     dbus = SDL_DBus_GetContext();
     
     if (IBus_CheckConnection(dbus)) {
-        DBusMessage *msg = dbus->message_new_method_call(IBUS_SERVICE,
-                                                         input_ctx_path,
-                                                         IBUS_INPUT_INTERFACE,
-                                                         "SetCursorLocation");
-        if (msg) {
-            dbus->message_append_args(msg,
-                                      DBUS_TYPE_INT32, &x,
-                                      DBUS_TYPE_INT32, &y,
-                                      DBUS_TYPE_INT32, &ibus_cursor_rect.w,
-                                      DBUS_TYPE_INT32, &ibus_cursor_rect.h,
-                                      DBUS_TYPE_INVALID);
-        }
-        
-        if (msg) {
-            if (dbus->connection_send(ibus_conn, msg, NULL)) {
-                dbus->connection_flush(ibus_conn);
-            }
-            dbus->message_unref(msg);
-        }
+        SDL_DBus_CallVoidMethodOnConnection(ibus_conn, IBUS_SERVICE, input_ctx_path, IBUS_INPUT_INTERFACE, "SetCursorLocation",
+                DBUS_TYPE_INT32, &x, DBUS_TYPE_INT32, &y, DBUS_TYPE_INT32, &ibus_cursor_rect.w, DBUS_TYPE_INT32, &ibus_cursor_rect.h, DBUS_TYPE_INVALID);
     }
 }
 
@@ -680,3 +579,5 @@ SDL_IBus_PumpEvents(void)
 }
 
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_ibus.h b/src/core/linux/SDL_ibus.h
index 5ee7a8e..7646bdd 100644
--- a/src/core/linux/SDL_ibus.h
+++ b/src/core/linux/SDL_ibus.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_ibus_h
-#define _SDL_ibus_h
+#ifndef SDL_ibus_h_
+#define SDL_ibus_h_
 
 #ifdef HAVE_IBUS_IBUS_H
 #define SDL_USE_IBUS 1
@@ -49,10 +49,10 @@ extern void SDL_IBus_UpdateTextRect(SDL_Rect *window_relative_rect);
 
 /* Checks DBus for new IBus events, and calls SDL_SendKeyboardText / 
    SDL_SendEditingText for each event it finds */
-extern void SDL_IBus_PumpEvents();
+extern void SDL_IBus_PumpEvents(void);
 
 #endif /* HAVE_IBUS_IBUS_H */
 
-#endif /* _SDL_ibus_h */
+#endif /* SDL_ibus_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_ime.c b/src/core/linux/SDL_ime.c
index 049bd6e..eb9cb57 100644
--- a/src/core/linux/SDL_ime.c
+++ b/src/core/linux/SDL_ime.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -87,8 +87,20 @@ SDL_IME_Init(void)
 {
     InitIME();
 
-    if (SDL_IME_Init_Real)
-        return SDL_IME_Init_Real();
+    if (SDL_IME_Init_Real) {
+        if (SDL_IME_Init_Real()) {
+            return SDL_TRUE;
+        }
+
+        /* uhoh, the IME implementation's init failed! Disable IME support. */
+        SDL_IME_Init_Real = NULL;
+        SDL_IME_Quit_Real = NULL;
+        SDL_IME_SetFocus_Real = NULL;
+        SDL_IME_Reset_Real = NULL;
+        SDL_IME_ProcessKeyEvent_Real = NULL;
+        SDL_IME_UpdateTextRect_Real = NULL;
+        SDL_IME_PumpEvents_Real = NULL;
+    }
 
     return SDL_FALSE;
 }
@@ -136,3 +148,5 @@ SDL_IME_PumpEvents()
     if (SDL_IME_PumpEvents_Real)
         SDL_IME_PumpEvents_Real();
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_ime.h b/src/core/linux/SDL_ime.h
index 22b31de..8672188 100644
--- a/src/core/linux/SDL_ime.h
+++ b/src/core/linux/SDL_ime.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,20 +19,22 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_ime_h
-#define _SDL_ime_h
+#ifndef SDL_ime_h_
+#define SDL_ime_h_
 
 #include "../../SDL_internal.h"
 
 #include "SDL_stdinc.h"
 #include "SDL_rect.h"
 
-extern SDL_bool SDL_IME_Init();
-extern void SDL_IME_Quit();
+extern SDL_bool SDL_IME_Init(void);
+extern void SDL_IME_Quit(void);
 extern void SDL_IME_SetFocus(SDL_bool focused);
-extern void SDL_IME_Reset();
+extern void SDL_IME_Reset(void);
 extern SDL_bool SDL_IME_ProcessKeyEvent(Uint32 keysym, Uint32 keycode);
 extern void SDL_IME_UpdateTextRect(SDL_Rect *rect);
-extern void SDL_IME_PumpEvents();
+extern void SDL_IME_PumpEvents(void);
 
-#endif /* _SDL_ime_h */
+#endif /* SDL_ime_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_udev.c b/src/core/linux/SDL_udev.c
index ae78ddd..502490b 100644
--- a/src/core/linux/SDL_udev.c
+++ b/src/core/linux/SDL_udev.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -31,9 +31,19 @@
 
 #include <linux/input.h>
 
-#include "SDL.h"
+#include "SDL_assert.h"
+#include "SDL_loadso.h"
+#include "SDL_timer.h"
+#include "../unix/SDL_poll.h"
 
-static const char* SDL_UDEV_LIBS[] = { "libudev.so.1", "libudev.so.0" };
+static const char *SDL_UDEV_LIBS[] = {
+#ifdef SDL_UDEV_DYNAMIC
+	SDL_UDEV_DYNAMIC
+#else
+	"libudev.so.1",
+	"libudev.so.0"
+#endif
+};
 
 #define _THIS SDL_UDEV_PrivateData *_this
 static _THIS = NULL;
@@ -98,14 +108,7 @@ SDL_UDEV_hotplug_update_available(void)
 {
     if (_this->udev_mon != NULL) {
         const int fd = _this->udev_monitor_get_fd(_this->udev_mon);
-        fd_set fds;
-        struct timeval tv;
-
-        FD_ZERO(&fds);
-        FD_SET(fd, &fds);
-        tv.tv_sec = 0;
-        tv.tv_usec = 0;
-        if ((select(fd+1, &fds, NULL, NULL, &tv) > 0) && (FD_ISSET(fd, &fds))) {
+        if (SDL_IOReady(fd, SDL_FALSE, 0)) {
             return SDL_TRUE;
         }
     }
@@ -209,7 +212,7 @@ SDL_UDEV_Scan(void)
     enumerate = _this->udev_enumerate_new(_this->udev);
     if (enumerate == NULL) {
         SDL_UDEV_Quit();
-        SDL_SetError("udev_monitor_new_from_netlink() failed");
+        SDL_SetError("udev_enumerate_new() failed");
         return;
     }
     
@@ -252,8 +255,12 @@ SDL_UDEV_LoadLibrary(void)
     if (_this == NULL) {
         return SDL_SetError("UDEV not initialized");
     }
-    
-   
+ 
+    /* See if there is a udev library already loaded */
+    if (SDL_UDEV_load_syms() == 0) {
+        return 0;
+    }
+
     if (_this->udev_handle == NULL) {
         for( i = 0 ; i < SDL_arraysize(SDL_UDEV_LIBS); i++) {
             _this->udev_handle = SDL_LoadObject(SDL_UDEV_LIBS[i]);
@@ -280,7 +287,6 @@ SDL_UDEV_LoadLibrary(void)
 #define BITS_PER_LONG           (sizeof(unsigned long) * 8)
 #define NBITS(x)                ((((x)-1)/BITS_PER_LONG)+1)
 #define OFF(x)                  ((x)%BITS_PER_LONG)
-#define BIT(x)                  (1UL<<OFF(x))
 #define LONG(x)                 ((x)/BITS_PER_LONG)
 #define test_bit(bit, array)    ((array[LONG(bit)] >> OFF(bit)) & 1)
 
@@ -537,3 +543,5 @@ SDL_UDEV_DelCallback(SDL_UDEV_Callback cb)
 
 
 #endif /* SDL_USE_LIBUDEV */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/linux/SDL_udev.h b/src/core/linux/SDL_udev.h
index 9ffbb32..5a9b6e0 100644
--- a/src/core/linux/SDL_udev.h
+++ b/src/core/linux/SDL_udev.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_udev_h
-#define _SDL_udev_h
+#ifndef SDL_udev_h_
+#define SDL_udev_h_
 
 #if HAVE_LIBUDEV_H
 
@@ -116,4 +116,6 @@ extern void SDL_UDEV_DelCallback(SDL_UDEV_Callback cb);
 
 #endif /* HAVE_LIBUDEV_H */
 
-#endif /* _SDL_udev_h */
+#endif /* SDL_udev_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/unix/SDL_poll.c b/src/core/unix/SDL_poll.c
new file mode 100644
index 0000000..b970a7a
--- /dev/null
+++ b/src/core/unix/SDL_poll.c
@@ -0,0 +1,88 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+
+#include "SDL_assert.h"
+#include "SDL_poll.h"
+
+#undef HAVE_POLL
+#ifdef HAVE_POLL
+#include <poll.h>
+#else
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+#endif
+#include <errno.h>
+
+
+int
+SDL_IOReady(int fd, SDL_bool forWrite, int timeoutMS)
+{
+    int result;
+
+    /* Note: We don't bother to account for elapsed time if we get EINTR */
+    do
+    {
+#ifdef HAVE_POLL
+        struct pollfd info;
+
+        info.fd = fd;
+        if (forWrite) {
+            info.events = POLLOUT;
+        } else {
+            info.events = POLLIN | POLLPRI;
+        }
+        result = poll(&info, 1, timeoutMS);
+#else
+        fd_set rfdset, *rfdp = NULL;
+        fd_set wfdset, *wfdp = NULL;
+        struct timeval tv, *tvp = NULL;
+
+        /* If this assert triggers we'll corrupt memory here */
+        SDL_assert(fd >= 0 && fd < FD_SETSIZE);
+
+        if (forWrite) {
+            FD_ZERO(&wfdset);
+            FD_SET(fd, &wfdset);
+            wfdp = &wfdset;
+        } else {
+            FD_ZERO(&rfdset);
+            FD_SET(fd, &rfdset);
+            rfdp = &rfdset;
+        }
+
+        if (timeoutMS >= 0) {
+            tv.tv_sec = timeoutMS / 1000;
+            tv.tv_usec = (timeoutMS % 1000) * 1000;
+            tvp = &tv;
+        }
+
+        result = select(fd + 1, rfdp, wfdp, NULL, tvp);
+#endif /* HAVE_POLL */
+
+    } while ( result < 0 && errno == EINTR );
+
+    return result;
+}
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/winrt/SDL_winrtmessagebox.h b/src/core/unix/SDL_poll.h
similarity index 81%
copy from src/video/winrt/SDL_winrtmessagebox.h
copy to src/core/unix/SDL_poll.h
index 4184aa5..9a23b84 100644
--- a/src/video/winrt/SDL_winrtmessagebox.h
+++ b/src/core/unix/SDL_poll.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,12 +18,17 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
+
 #include "../../SDL_internal.h"
 
-#if SDL_VIDEO_DRIVER_WINRT
+#ifndef SDL_poll_h_
+#define SDL_poll_h_
+
+#include "SDL_stdinc.h"
+
 
-extern int WINRT_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid);
+extern int SDL_IOReady(int fd, SDL_bool forWrite, int timeoutMS);
 
-#endif /* SDL_VIDEO_DRIVER_WINRT */
+#endif /* SDL_poll_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/windows/SDL_directx.h b/src/core/windows/SDL_directx.h
index 0533f61..4226c6e 100644
--- a/src/core/windows/SDL_directx.h
+++ b/src/core/windows/SDL_directx.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_directx_h
-#define _SDL_directx_h
+#ifndef SDL_directx_h_
+#define SDL_directx_h_
 
 /* Include all of the DirectX 8.0 headers and adds any necessary tweaks */
 
@@ -106,6 +106,6 @@
 typedef struct { int unused; } DIDEVICEINSTANCE;
 #endif
 
-#endif /* _SDL_directx_h */
+#endif /* SDL_directx_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/windows/SDL_windows.c b/src/core/windows/SDL_windows.c
index 6433fe2..117fb15 100644
--- a/src/core/windows/SDL_windows.c
+++ b/src/core/windows/SDL_windows.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -115,7 +115,7 @@ IsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WORD wServiceP
 }
 #endif
 
-BOOL WIN_IsWindowsVistaOrGreater()
+BOOL WIN_IsWindowsVistaOrGreater(void)
 {
 #ifdef __WINRT__
     return TRUE;
@@ -142,6 +142,8 @@ Registry, and a unhelpful "Microphone(Yeti Stereo Microph" in winmm. Sigh.
 
 (Also, DirectSound shouldn't be limited to 32 chars, but its device enum
 has the same problem.)
+
+WASAPI doesn't need this. This is just for DirectSound/WinMM.
 */
 char *
 WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid)
@@ -158,7 +160,7 @@ WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid)
     DWORD len = 0;
     char *retval = NULL;
 
-    if (SDL_memcmp(guid, &nullguid, sizeof (*guid)) == 0) {
+    if (WIN_IsEqualGUID(guid, &nullguid)) {
         return WIN_StringToUTF8(name);  /* No GUID, go with what we've got. */
     }
 
@@ -202,6 +204,18 @@ WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid)
 #endif /* if __WINRT__ / else */
 }
 
+BOOL
+WIN_IsEqualGUID(const GUID * a, const GUID * b)
+{
+    return (SDL_memcmp(a, b, sizeof (*a)) == 0);
+}
+
+BOOL
+WIN_IsEqualIID(REFIID a, REFIID b)
+{
+    return (SDL_memcmp(a, b, sizeof (*a)) == 0);
+}
+
 #endif /* __WIN32__ || __WINRT__ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/windows/SDL_windows.h b/src/core/windows/SDL_windows.h
index 0f67e4b..2a00dd4 100644
--- a/src/core/windows/SDL_windows.h
+++ b/src/core/windows/SDL_windows.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -35,6 +35,7 @@
 #endif
 
 #include <windows.h>
+#include <basetyps.h>   /* for REFIID with broken mingw.org headers */
 
 /* Routines to convert from UTF8 to native Windows text */
 #if UNICODE
@@ -57,11 +58,15 @@ extern HRESULT WIN_CoInitialize(void);
 extern void WIN_CoUninitialize(void);
 
 /* Returns SDL_TRUE if we're running on Windows Vista and newer */
-extern BOOL WIN_IsWindowsVistaOrGreater();
+extern BOOL WIN_IsWindowsVistaOrGreater(void);
 
 /* You need to SDL_free() the result of this call. */
 extern char *WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid);
 
+/* Checks to see if two GUID are the same. */
+extern BOOL WIN_IsEqualGUID(const GUID * a, const GUID * b);
+extern BOOL WIN_IsEqualIID(REFIID a, REFIID b);
+
 #endif /* _INCLUDED_WINDOWS_H */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/windows/SDL_xinput.c b/src/core/windows/SDL_xinput.c
index 355cd83..dcdbba3 100644
--- a/src/core/windows/SDL_xinput.c
+++ b/src/core/windows/SDL_xinput.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/core/windows/SDL_xinput.h b/src/core/windows/SDL_xinput.h
index 67f8fdc..de18380 100644
--- a/src/core/windows/SDL_xinput.h
+++ b/src/core/windows/SDL_xinput.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_xinput_h
-#define _SDL_xinput_h
+#ifndef SDL_xinput_h_
+#define SDL_xinput_h_
 
 #ifdef HAVE_XINPUT_H
 
@@ -100,6 +100,8 @@
 #endif
 
 /* typedef's for XInput structs we use */
+
+#ifndef HAVE_XINPUT_GAMEPAD_EX
 typedef struct
 {
     WORD wButtons;
@@ -111,12 +113,15 @@ typedef struct
     SHORT sThumbRY;
     DWORD dwPaddingReserved;
 } XINPUT_GAMEPAD_EX;
+#endif
 
+#ifndef HAVE_XINPUT_STATE_EX
 typedef struct
 {
     DWORD dwPacketNumber;
     XINPUT_GAMEPAD_EX Gamepad;
 } XINPUT_STATE_EX;
+#endif
 
 typedef struct
 {
@@ -167,6 +172,6 @@ extern DWORD SDL_XInputVersion;  /* ((major << 16) & 0xFF00) | (minor & 0xFF) */
 
 #endif /* HAVE_XINPUT_H */
 
-#endif /* _SDL_xinput_h */
+#endif /* SDL_xinput_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/core/winrt/SDL_winrtapp_common.cpp b/src/core/winrt/SDL_winrtapp_common.cpp
index 265aa94..408f98d 100644
--- a/src/core/winrt/SDL_winrtapp_common.cpp
+++ b/src/core/winrt/SDL_winrtapp_common.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/core/winrt/SDL_winrtapp_common.h b/src/core/winrt/SDL_winrtapp_common.h
index e87a0b6..2e6c81f 100644
--- a/src/core/winrt/SDL_winrtapp_common.h
+++ b/src/core/winrt/SDL_winrtapp_common.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,12 +20,12 @@
 */
 #include "SDL_config.h"
 
-#ifndef _SDL_winrtapp_common_h
-#define _SDL_winrtapp_common_h
+#ifndef SDL_winrtapp_common_h_
+#define SDL_winrtapp_common_h_
 
 /* A pointer to the app's C-style main() function (which is a different
    function than the WinRT app's actual entry point).
  */
 extern int (*WINRT_SDLAppEntryPoint)(int, char **);
 
-#endif // ifndef _SDL_winrtapp_common_h
+#endif // SDL_winrtapp_common_h_
diff --git a/src/core/winrt/SDL_winrtapp_direct3d.cpp b/src/core/winrt/SDL_winrtapp_direct3d.cpp
index e4ffada..7084f93 100644
--- a/src/core/winrt/SDL_winrtapp_direct3d.cpp
+++ b/src/core/winrt/SDL_winrtapp_direct3d.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -47,7 +47,6 @@ using namespace Windows::Phone::UI::Input;
 
 /* SDL includes */
 extern "C" {
-#include "../../SDL_internal.h"
 #include "SDL_assert.h"
 #include "SDL_events.h"
 #include "SDL_hints.h"
@@ -122,7 +121,8 @@ int SDL_WinRTInitNonXAMLApp(int (*mainFunction)(int, char **))
     return 0;
 }
 
-static void WINRT_SetDisplayOrientationsPreference(void *userdata, const char *name, const char *oldValue, const char *newValue)
+static void SDLCALL
+WINRT_SetDisplayOrientationsPreference(void *userdata, const char *name, const char *oldValue, const char *newValue)
 {
     SDL_assert(SDL_strcmp(name, SDL_HINT_ORIENTATIONS) == 0);
 
@@ -827,7 +827,7 @@ static void WINRT_OnBackButtonPressed(BackButtonEventArgs ^ args)
     }
 }
 
-#if NTDDI_VERSION == NTDDI_WIN10
+#if NTDDI_VERSION >= NTDDI_WIN10
 void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::UI::Core::BackRequestedEventArgs^ args)
 
 {
diff --git a/src/core/winrt/SDL_winrtapp_direct3d.h b/src/core/winrt/SDL_winrtapp_direct3d.h
index 4b48115..5b31861 100644
--- a/src/core/winrt/SDL_winrtapp_direct3d.h
+++ b/src/core/winrt/SDL_winrtapp_direct3d.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/core/winrt/SDL_winrtapp_xaml.cpp b/src/core/winrt/SDL_winrtapp_xaml.cpp
index 201e3b6..8a76bf9 100644
--- a/src/core/winrt/SDL_winrtapp_xaml.cpp
+++ b/src/core/winrt/SDL_winrtapp_xaml.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/core/winrt/SDL_winrtapp_xaml.h b/src/core/winrt/SDL_winrtapp_xaml.h
index a08b67c..cd827a6 100644
--- a/src/core/winrt/SDL_winrtapp_xaml.h
+++ b/src/core/winrt/SDL_winrtapp_xaml.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "SDL_config.h"
 
-#ifndef _SDL_winrtapp_xaml_h
-#define _SDL_winrtapp_xaml_h
+#ifndef SDL_winrtapp_xaml_h_
+#define SDL_winrtapp_xaml_h_
 
 #include "SDL_stdinc.h"
 
@@ -30,4 +30,4 @@ extern SDL_bool WINRT_XAMLWasEnabled;
 extern int SDL_WinRTInitXAMLApp(int (*mainFunction)(int, char **), void * backgroundPanelAsIInspectable);
 #endif // ifdef __cplusplus
 
-#endif // ifndef _SDL_winrtapp_xaml_h
+#endif // SDL_winrtapp_xaml_h_
diff --git a/src/cpuinfo/SDL_cpuinfo.c b/src/cpuinfo/SDL_cpuinfo.c
index c4c55be..968d73e 100644
--- a/src/cpuinfo/SDL_cpuinfo.c
+++ b/src/cpuinfo/SDL_cpuinfo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,6 +27,13 @@
 #if defined(__WIN32__)
 #include "../core/windows/SDL_windows.h"
 #endif
+#if defined(__OS2__)
+#define INCL_DOS
+#include <os2.h>
+#ifndef QSV_NUMPROCESSORS
+#define QSV_NUMPROCESSORS 26
+#endif
+#endif
 
 /* CPU feature detection for SDL */
 
@@ -50,6 +57,25 @@
 #include <setjmp.h>
 #endif
 
+#if defined(__QNXNTO__)
+#include <sys/syspage.h>
+#endif
+
+#if (defined(__LINUX__) || defined(__ANDROID__)) && defined(__ARM_ARCH)
+/*#include <asm/hwcap.h>*/
+#ifndef AT_HWCAP
+#define AT_HWCAP 16
+#endif
+#ifndef HWCAP_NEON
+#define HWCAP_NEON (1 << 12)
+#endif
+#if defined HAVE_GETAUXVAL
+#include <sys/auxv.h>
+#else
+#include <fcntl.h>
+#endif
+#endif
+
 #define CPU_HAS_RDTSC   0x00000001
 #define CPU_HAS_ALTIVEC 0x00000002
 #define CPU_HAS_MMX     0x00000004
@@ -61,6 +87,7 @@
 #define CPU_HAS_SSE42   0x00000200
 #define CPU_HAS_AVX     0x00000400
 #define CPU_HAS_AVX2    0x00000800
+#define CPU_HAS_NEON    0x00001000
 
 #if SDL_ALTIVEC_BLITTERS && HAVE_SETJMP && !__MACOSX__ && !__OpenBSD__
 /* This is the brute force way of detecting instruction sets...
@@ -78,6 +105,7 @@ static int
 CPU_haveCPUID(void)
 {
     int has_CPUID = 0;
+
 /* *INDENT-OFF* */
 #ifndef SDL_CPUINFO_DISABLED
 #if defined(__GNUC__) && defined(i386)
@@ -212,62 +240,50 @@ done:
 }
 #else
 #define cpuid(func, a, b, c, d) \
-    a = b = c = d = 0
+    do { a = b = c = d = 0; (void) a; (void) b; (void) c; (void) d; } while (0)
 #endif
 
-static int
-CPU_getCPUIDFeatures(void)
-{
-    int features = 0;
-    int a, b, c, d;
-
-    cpuid(0, a, b, c, d);
-    if (a >= 1) {
-        cpuid(1, a, b, c, d);
-        features = d;
-    }
-    return features;
-}
+static int CPU_CPUIDFeatures[4];
+static int CPU_CPUIDMaxFunction = 0;
+static SDL_bool CPU_OSSavesYMM = SDL_FALSE;
 
-static SDL_bool
-CPU_OSSavesYMM(void)
+static void
+CPU_calcCPUIDFeatures(void)
 {
-    int a, b, c, d;
-
-    /* Check to make sure we can call xgetbv */
-    cpuid(0, a, b, c, d);
-    if (a < 1) {
-        return SDL_FALSE;
-    }
-    cpuid(1, a, b, c, d);
-    if (!(c & 0x08000000)) {
-        return SDL_FALSE;
-    }
-
-    /* Call xgetbv to see if YMM register state is saved */
-    a = 0;
+    static SDL_bool checked = SDL_FALSE;
+    if (!checked) {
+        checked = SDL_TRUE;
+        if (CPU_haveCPUID()) {
+            int a, b, c, d;
+            cpuid(0, a, b, c, d);
+            CPU_CPUIDMaxFunction = a;
+            if (CPU_CPUIDMaxFunction >= 1) {
+                cpuid(1, a, b, c, d);
+                CPU_CPUIDFeatures[0] = a;
+                CPU_CPUIDFeatures[1] = b;
+                CPU_CPUIDFeatures[2] = c;
+                CPU_CPUIDFeatures[3] = d;
+
+                /* Check to make sure we can call xgetbv */
+                if (c & 0x08000000) {
+                    /* Call xgetbv to see if YMM register state is saved */
 #if defined(__GNUC__) && (defined(i386) || defined(__x86_64__))
-    asm(".byte 0x0f, 0x01, 0xd0" : "=a" (a) : "c" (0) : "%edx");
+                    __asm__(".byte 0x0f, 0x01, 0xd0" : "=a" (a) : "c" (0) : "%edx");
 #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) && (_MSC_FULL_VER >= 160040219) /* VS2010 SP1 */
-    a = (int)_xgetbv(0);
+                    a = (int)_xgetbv(0);
 #elif (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
-    __asm
-    {
-        xor ecx, ecx
-        _asm _emit 0x0f _asm _emit 0x01 _asm _emit 0xd0
-        mov a, eax
-    }
+                    __asm
+                    {
+                        xor ecx, ecx
+                        _asm _emit 0x0f _asm _emit 0x01 _asm _emit 0xd0
+                        mov a, eax
+                    }
 #endif
-    return ((a & 6) == 6) ? SDL_TRUE : SDL_FALSE;
-}
-
-static int
-CPU_haveRDTSC(void)
-{
-    if (CPU_haveCPUID()) {
-        return (CPU_getCPUIDFeatures() & 0x00000010);
+                    CPU_OSSavesYMM = ((a & 6) == 6) ? SDL_TRUE : SDL_FALSE;
+                }
+            }
+        }
     }
-    return 0;
 }
 
 static int
@@ -299,119 +315,87 @@ CPU_haveAltiVec(void)
     return altivec;
 }
 
+#if (defined(__LINUX__) || defined(__ANDROID__)) && defined(__ARM_ARCH) && !defined(HAVE_GETAUXVAL)
 static int
-CPU_haveMMX(void)
-{
-    if (CPU_haveCPUID()) {
-        return (CPU_getCPUIDFeatures() & 0x00800000);
-    }
-    return 0;
-}
-
-static int
-CPU_have3DNow(void)
-{
-    if (CPU_haveCPUID()) {
-        int a, b, c, d;
-
-        cpuid(0x80000000, a, b, c, d);
-        if (a >= 0x80000001) {
-            cpuid(0x80000001, a, b, c, d);
-            return (d & 0x80000000);
+readProcAuxvForNeon(void)
+{
+    int neon = 0;
+    int kv[2];
+    const int fd = open("/proc/self/auxv", O_RDONLY);
+    if (fd != -1) {
+        while (read(fd, kv, sizeof (kv)) == sizeof (kv)) {
+            if (kv[0] == AT_HWCAP) {
+                neon = ((kv[1] & HWCAP_NEON) == HWCAP_NEON);
+                break;
+            }
         }
+        close(fd);
     }
-    return 0;
-}
-
-static int
-CPU_haveSSE(void)
-{
-    if (CPU_haveCPUID()) {
-        return (CPU_getCPUIDFeatures() & 0x02000000);
-    }
-    return 0;
-}
-
-static int
-CPU_haveSSE2(void)
-{
-    if (CPU_haveCPUID()) {
-        return (CPU_getCPUIDFeatures() & 0x04000000);
-    }
-    return 0;
+    return neon;
 }
+#endif
 
-static int
-CPU_haveSSE3(void)
-{
-    if (CPU_haveCPUID()) {
-        int a, b, c, d;
-
-        cpuid(0, a, b, c, d);
-        if (a >= 1) {
-            cpuid(1, a, b, c, d);
-            return (c & 0x00000001);
-        }
-    }
-    return 0;
-}
 
 static int
-CPU_haveSSE41(void)
-{
-    if (CPU_haveCPUID()) {
-        int a, b, c, d;
-
-        cpuid(0, a, b, c, d);
-        if (a >= 1) {
-            cpuid(1, a, b, c, d);
-            return (c & 0x00080000);
-        }
-    }
+CPU_haveNEON(void)
+{
+/* The way you detect NEON is a privileged instruction on ARM, so you have
+   query the OS kernel in a platform-specific way. :/ */
+#if defined(SDL_CPUINFO_DISABLED) || !defined(__ARM_ARCH)
+    return 0;  /* disabled or not an ARM CPU at all. */
+#elif __ARM_ARCH >= 8
+    return 1;  /* ARMv8 always has non-optional NEON support. */
+#elif defined(__APPLE__) && (__ARM_ARCH >= 7)
+    /* (note that sysctlbyname("hw.optional.neon") doesn't work!) */
+    return 1;  /* all Apple ARMv7 chips and later have NEON. */
+#elif defined(__APPLE__)
+    return 0;  /* assune anything else from Apple doesn't have NEON. */
+#elif defined(__QNXNTO__)
+    return SYSPAGE_ENTRY(cpuinfo)->flags & ARM_CPU_FLAG_NEON;
+#elif (defined(__LINUX__) || defined(__ANDROID__)) && defined(HAVE_GETAUXVAL)
+    return ((getauxval(AT_HWCAP) & HWCAP_NEON) == HWCAP_NEON);
+#elif (defined(__LINUX__) || defined(__ANDROID__))
+    return readProcAuxvForNeon();   /* Android offers a static library for this, but it just parses /proc/self/auxv */
+#elif (defined(__WINDOWS__) || defined(__WINRT__)) && defined(_M_ARM)
+    /* All WinRT ARM devices are required to support NEON, but just in case. */
+    return IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE) != 0;
+#else
+#warning SDL_HasNEON is not implemented for this ARM platform. Write me.
     return 0;
+#endif
 }
 
 static int
-CPU_haveSSE42(void)
+CPU_have3DNow(void)
 {
-    if (CPU_haveCPUID()) {
+    if (CPU_CPUIDMaxFunction > 0) {  /* that is, do we have CPUID at all? */
         int a, b, c, d;
-
-        cpuid(0, a, b, c, d);
-        if (a >= 1) {
-            cpuid(1, a, b, c, d);
-            return (c & 0x00100000);
+        cpuid(0x80000000, a, b, c, d);
+        if (a >= 0x80000001) {
+            cpuid(0x80000001, a, b, c, d);
+            return (d & 0x80000000);
         }
     }
     return 0;
 }
 
-static int
-CPU_haveAVX(void)
-{
-    if (CPU_haveCPUID() && CPU_OSSavesYMM()) {
-        int a, b, c, d;
-
-        cpuid(0, a, b, c, d);
-        if (a >= 1) {
-            cpuid(1, a, b, c, d);
-            return (c & 0x10000000);
-        }
-    }
-    return 0;
-}
+#define CPU_haveRDTSC() (CPU_CPUIDFeatures[3] & 0x00000010)
+#define CPU_haveMMX() (CPU_CPUIDFeatures[3] & 0x00800000)
+#define CPU_haveSSE() (CPU_CPUIDFeatures[3] & 0x02000000)
+#define CPU_haveSSE2() (CPU_CPUIDFeatures[3] & 0x04000000)
+#define CPU_haveSSE3() (CPU_CPUIDFeatures[2] & 0x00000001)
+#define CPU_haveSSE41() (CPU_CPUIDFeatures[2] & 0x00080000)
+#define CPU_haveSSE42() (CPU_CPUIDFeatures[2] & 0x00100000)
+#define CPU_haveAVX() (CPU_OSSavesYMM && (CPU_CPUIDFeatures[2] & 0x10000000))
 
 static int
 CPU_haveAVX2(void)
 {
-    if (CPU_haveCPUID() && CPU_OSSavesYMM()) {
+    if (CPU_OSSavesYMM && (CPU_CPUIDMaxFunction >= 7)) {
         int a, b, c, d;
-
-        cpuid(0, a, b, c, d);
-        if (a >= 7) {
-            cpuid(7, a, b, c, d);
-            return (b & 0x00000020);
-        }
+        (void) a; (void) b; (void) c; (void) d;  /* compiler warnings... */
+        cpuid(7, a, b, c, d);
+        return (b & 0x00000020);
     }
     return 0;
 }
@@ -441,6 +425,12 @@ SDL_GetCPUCount(void)
             SDL_CPUCount = info.dwNumberOfProcessors;
         }
 #endif
+#ifdef __OS2__
+        if (SDL_CPUCount <= 0) {
+            DosQuerySysInfo(QSV_NUMPROCESSORS, QSV_NUMPROCESSORS,
+                            &SDL_CPUCount, sizeof(SDL_CPUCount) );
+        }
+#endif
 #endif
         /* There has to be at least 1, right? :) */
         if (SDL_CPUCount <= 0) {
@@ -459,7 +449,8 @@ SDL_GetCPUType(void)
     if (!SDL_CPUType[0]) {
         int i = 0;
 
-        if (CPU_haveCPUID()) {
+        CPU_calcCPUIDFeatures();
+        if (CPU_CPUIDMaxFunction > 0) {  /* do we have CPUID at all? */
             int a, b, c, d;
             cpuid(0x00000000, a, b, c, d);
             (void) a;
@@ -496,7 +487,8 @@ SDL_GetCPUName(void)
         int i = 0;
         int a, b, c, d;
 
-        if (CPU_haveCPUID()) {
+        CPU_calcCPUIDFeatures();
+        if (CPU_CPUIDMaxFunction > 0) {  /* do we have CPUID at all? */
             cpuid(0x80000000, a, b, c, d);
             if (a >= 0x80000004) {
                 cpuid(0x80000002, a, b, c, d);
@@ -584,6 +576,7 @@ static Uint32
 SDL_GetCPUFeatures(void)
 {
     if (SDL_CPUFeatures == 0xFFFFFFFF) {
+        CPU_calcCPUIDFeatures();
         SDL_CPUFeatures = 0;
         if (CPU_haveRDTSC()) {
             SDL_CPUFeatures |= CPU_HAS_RDTSC;
@@ -618,107 +611,84 @@ SDL_GetCPUFeatures(void)
         if (CPU_haveAVX2()) {
             SDL_CPUFeatures |= CPU_HAS_AVX2;
         }
+        if (CPU_haveNEON()) {
+            SDL_CPUFeatures |= CPU_HAS_NEON;
+        }
     }
     return SDL_CPUFeatures;
 }
 
-SDL_bool
-SDL_HasRDTSC(void)
+#define CPU_FEATURE_AVAILABLE(f) ((SDL_GetCPUFeatures() & f) ? SDL_TRUE : SDL_FALSE)
+
+SDL_bool SDL_HasRDTSC(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_RDTSC) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_RDTSC);
 }
 
 SDL_bool
 SDL_HasAltiVec(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_ALTIVEC) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_ALTIVEC);
 }
 
 SDL_bool
 SDL_HasMMX(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_MMX) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_MMX);
 }
 
 SDL_bool
 SDL_Has3DNow(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_3DNOW) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_3DNOW);
 }
 
 SDL_bool
 SDL_HasSSE(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_SSE) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_SSE);
 }
 
 SDL_bool
 SDL_HasSSE2(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_SSE2) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_SSE2);
 }
 
 SDL_bool
 SDL_HasSSE3(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_SSE3) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_SSE3);
 }
 
 SDL_bool
 SDL_HasSSE41(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_SSE41) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_SSE41);
 }
 
 SDL_bool
 SDL_HasSSE42(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_SSE42) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_SSE42);
 }
 
 SDL_bool
 SDL_HasAVX(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_AVX) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_AVX);
 }
 
 SDL_bool
 SDL_HasAVX2(void)
 {
-    if (SDL_GetCPUFeatures() & CPU_HAS_AVX2) {
-        return SDL_TRUE;
-    }
-    return SDL_FALSE;
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_AVX2);
+}
+
+SDL_bool
+SDL_HasNEON(void)
+{
+    return CPU_FEATURE_AVAILABLE(CPU_HAS_NEON);
 }
 
 static int SDL_SystemRAM = 0;
@@ -762,6 +732,13 @@ SDL_GetSystemRAM(void)
             }
         }
 #endif
+#ifdef __OS2__
+        if (SDL_SystemRAM <= 0) {
+            Uint32 sysram = 0;
+            DosQuerySysInfo(QSV_TOTPHYSMEM, QSV_TOTPHYSMEM, &sysram, 4);
+            SDL_SystemRAM = (int) (sysram / 0x100000U);
+        }
+#endif
 #endif
     }
     return SDL_SystemRAM;
@@ -790,6 +767,7 @@ main()
     printf("SSE4.2: %d\n", SDL_HasSSE42());
     printf("AVX: %d\n", SDL_HasAVX());
     printf("AVX2: %d\n", SDL_HasAVX2());
+    printf("NEON: %d\n", SDL_HasNEON());
     printf("RAM: %d MB\n", SDL_GetSystemRAM());
     return 0;
 }
diff --git a/src/dynapi/SDL_dynapi.c b/src/dynapi/SDL_dynapi.c
index c26baf3..1d09220 100644
--- a/src/dynapi/SDL_dynapi.c
+++ b/src/dynapi/SDL_dynapi.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,11 +24,17 @@
 
 #if SDL_DYNAMIC_API
 
+#if defined(__OS2__)
+#define INCL_DOS
+#define INCL_DOSERRORS
+#include <dos.h>
+#endif
+
 #include "SDL.h"
 
-/* !!! FIXME: Shouldn't these be included in SDL.h? */
-#include "SDL_shape.h"
+/* These headers have system specific definitions, so aren't included above */
 #include "SDL_syswm.h"
+#include "SDL_vulkan.h"
 
 /* This is the version of the dynamic API. This doesn't match the SDL version
    and should not change until there's been a major revamp in API/ABI.
@@ -56,38 +62,38 @@ static void SDL_InitDynamicAPI(void);
 #if DISABLE_JUMP_MAGIC
 /* Can't use the macro for varargs nonsense. This is atrocious. */
 #define SDL_DYNAPI_VARARGS_LOGFN(_static, name, initcall, logname, prio) \
-    _static void SDL_Log##logname##name(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \
+    _static void SDLCALL SDL_Log##logname##name(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \
         va_list ap; initcall; va_start(ap, fmt); \
         jump_table.SDL_LogMessageV(category, SDL_LOG_PRIORITY_##prio, fmt, ap); \
         va_end(ap); \
     }
 
 #define SDL_DYNAPI_VARARGS(_static, name, initcall) \
-    _static int SDL_SetError##name(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \
+    _static int SDLCALL SDL_SetError##name(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \
         char buf[512]; /* !!! FIXME: dynamic allocation */ \
         va_list ap; initcall; va_start(ap, fmt); \
         jump_table.SDL_vsnprintf(buf, sizeof (buf), fmt, ap); \
         va_end(ap); \
         return jump_table.SDL_SetError("%s", buf); \
     } \
-    _static int SDL_sscanf##name(const char *buf, SDL_SCANF_FORMAT_STRING const char *fmt, ...) { \
+    _static int SDLCALL SDL_sscanf##name(const char *buf, SDL_SCANF_FORMAT_STRING const char *fmt, ...) { \
         int retval; va_list ap; initcall; va_start(ap, fmt); \
         retval = jump_table.SDL_vsscanf(buf, fmt, ap); \
         va_end(ap); \
         return retval; \
     } \
-    _static int SDL_snprintf##name(SDL_OUT_Z_CAP(maxlen) char *buf, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \
+    _static int SDLCALL SDL_snprintf##name(SDL_OUT_Z_CAP(maxlen) char *buf, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \
         int retval; va_list ap; initcall; va_start(ap, fmt); \
         retval = jump_table.SDL_vsnprintf(buf, maxlen, fmt, ap); \
         va_end(ap); \
         return retval; \
     } \
-    _static void SDL_Log##name(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \
+    _static void SDLCALL SDL_Log##name(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \
         va_list ap; initcall; va_start(ap, fmt); \
         jump_table.SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap); \
         va_end(ap); \
     } \
-    _static void SDL_LogMessage##name(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \
+    _static void SDLCALL SDL_LogMessage##name(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { \
         va_list ap; initcall; va_start(ap, fmt); \
         jump_table.SDL_LogMessageV(category, priority, fmt, ap); \
         va_end(ap); \
@@ -105,9 +111,9 @@ static void SDL_InitDynamicAPI(void);
 /* The DEFAULT funcs will init jump table and then call real function. */
 /* The REAL funcs are the actual functions, name-mangled to not clash. */
 #define SDL_DYNAPI_PROC(rc,fn,params,args,ret) \
-    typedef rc (*SDL_DYNAPIFN_##fn) params; \
-    static rc fn##_DEFAULT params; \
-    extern rc fn##_REAL params;
+    typedef rc (SDLCALL *SDL_DYNAPIFN_##fn) params; \
+    static rc SDLCALL fn##_DEFAULT params; \
+    extern rc SDLCALL fn##_REAL params;
 #include "SDL_dynapi_procs.h"
 #undef SDL_DYNAPI_PROC
 
@@ -119,7 +125,7 @@ typedef struct {
 } SDL_DYNAPI_jump_table;
 
 /* Predeclare the default functions for initializing the jump table. */
-#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) static rc fn##_DEFAULT params;
+#define SDL_DYNAPI_PROC(rc,fn,params,args,ret) static rc SDLCALL fn##_DEFAULT params;
 #include "SDL_dynapi_procs.h"
 #undef SDL_DYNAPI_PROC
 
@@ -133,7 +139,7 @@ static SDL_DYNAPI_jump_table jump_table = {
 /* Default functions init the function table then call right thing. */
 #if DISABLE_JUMP_MAGIC
 #define SDL_DYNAPI_PROC(rc,fn,params,args,ret) \
-    static rc fn##_DEFAULT params { \
+    static rc SDLCALL fn##_DEFAULT params { \
         SDL_InitDynamicAPI(); \
         ret jump_table.fn args; \
     }
@@ -150,7 +156,7 @@ SDL_DYNAPI_VARARGS(static, _DEFAULT, SDL_InitDynamicAPI())
 /* Public API functions to jump into the jump table. */
 #if DISABLE_JUMP_MAGIC
 #define SDL_DYNAPI_PROC(rc,fn,params,args,ret) \
-    rc fn params { ret jump_table.fn args; }
+    rc SDLCALL fn params { ret jump_table.fn args; }
 #define SDL_DYNAPI_PROC_NO_VARARGS 1
 #include "SDL_dynapi_procs.h"
 #undef SDL_DYNAPI_PROC
@@ -216,21 +222,7 @@ static SDL_INLINE void *get_sdlapi_entry(const char *fname, const char *sym)
     return retval;
 }
 
-#elif defined(__HAIKU__)
-#include <os/kernel/image.h>
-static SDL_INLINE void *get_sdlapi_entry(const char *fname, const char *sym)
-{
-    image_id lib = load_add_on(fname);
-    void *retval = NULL;
-    if (lib >= 0) {
-        if (get_image_symbol(lib, sym, B_SYMBOL_TYPE_TEXT, &retval) != B_NO_ERROR) {
-            unload_add_on(lib);
-            retval = NULL;
-        }
-    }
-    return retval;
-}
-#elif defined(unix) || defined(__unix__) || defined(__APPLE__)
+#elif defined(unix) || defined(__unix__) || defined(__APPLE__) || defined(__HAIKU__) || defined(__QNX__)
 #include <dlfcn.h>
 static SDL_INLINE void *get_sdlapi_entry(const char *fname, const char *sym)
 {
@@ -244,6 +236,21 @@ static SDL_INLINE void *get_sdlapi_entry(const char *fname, const char *sym)
     }
     return retval;
 }
+
+#elif defined(__OS2__)
+static SDL_INLINE void *get_sdlapi_entry(const char *fname, const char *sym)
+{
+    HMODULE hmodule;
+    PFN retval = NULL;
+    char error[256];
+    if (DosLoadModule(&error, sizeof(error), fname, &hmodule) == NO_ERROR) {
+        if (DosQueryProcAddr(hmodule, 0, sym, &retval) != NO_ERROR) {
+            DosFreeModule(hmodule);
+        }
+    }
+    return (void *) retval;
+}
+
 #else
 #error Please define your platform.
 #endif
@@ -316,4 +323,3 @@ SDL_InitDynamicAPI(void)
 #endif  /* SDL_DYNAMIC_API */
 
 /* vi: set ts=4 sw=4 expandtab: */
-
diff --git a/src/dynapi/SDL_dynapi.h b/src/dynapi/SDL_dynapi.h
index 5e78338..adb2c36 100644
--- a/src/dynapi/SDL_dynapi.h
+++ b/src/dynapi/SDL_dynapi.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_dynapi_h
-#define _SDL_dynapi_h
+#ifndef SDL_dynapi_h_
+#define SDL_dynapi_h_
 
 /* IMPORTANT:
    This is the master switch to disabling the dynamic API. We made it so you
diff --git a/src/dynapi/SDL_dynapi_overrides.h b/src/dynapi/SDL_dynapi_overrides.h
index 9541611..95943bc 100644
--- a/src/dynapi/SDL_dynapi_overrides.h
+++ b/src/dynapi/SDL_dynapi_overrides.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,12 +27,6 @@
 #error You should not be here.
 #endif
 
-/* so annoying. */
-#if defined(__thumb__) && (defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__))
-#define SDL_MemoryBarrierRelease SDL_MemoryBarrierRelease_REAL
-#define SDL_MemoryBarrierAcquire SDL_MemoryBarrierAcquire_REAL
-#endif
-
 #define SDL_SetError SDL_SetError_REAL
 #define SDL_Log SDL_Log_REAL
 #define SDL_LogVerbose SDL_LogVerbose_REAL
@@ -612,3 +606,32 @@
 #define SDL_CreateRGBSurfaceWithFormat SDL_CreateRGBSurfaceWithFormat_REAL
 #define SDL_CreateRGBSurfaceWithFormatFrom SDL_CreateRGBSurfaceWithFormatFrom_REAL
 #define SDL_GetHintBoolean SDL_GetHintBoolean_REAL
+#define SDL_JoystickGetDeviceVendor SDL_JoystickGetDeviceVendor_REAL
+#define SDL_JoystickGetDeviceProduct SDL_JoystickGetDeviceProduct_REAL
+#define SDL_JoystickGetDeviceProductVersion SDL_JoystickGetDeviceProductVersion_REAL
+#define SDL_JoystickGetVendor SDL_JoystickGetVendor_REAL
+#define SDL_JoystickGetProduct SDL_JoystickGetProduct_REAL
+#define SDL_JoystickGetProductVersion SDL_JoystickGetProductVersion_REAL
+#define SDL_GameControllerGetVendor SDL_GameControllerGetVendor_REAL
+#define SDL_GameControllerGetProduct SDL_GameControllerGetProduct_REAL
+#define SDL_GameControllerGetProductVersion SDL_GameControllerGetProductVersion_REAL
+#define SDL_HasNEON SDL_HasNEON_REAL
+#define SDL_GameControllerNumMappings SDL_GameControllerNumMappings_REAL
+#define SDL_GameControllerMappingForIndex SDL_GameControllerMappingForIndex_REAL
+#define SDL_JoystickGetAxisInitialState SDL_JoystickGetAxisInitialState_REAL
+#define SDL_JoystickGetDeviceType SDL_JoystickGetDeviceType_REAL
+#define SDL_JoystickGetType SDL_JoystickGetType_REAL
+#define SDL_MemoryBarrierReleaseFunction SDL_MemoryBarrierReleaseFunction_REAL
+#define SDL_MemoryBarrierAcquireFunction SDL_MemoryBarrierAcquireFunction_REAL
+#define SDL_JoystickGetDeviceInstanceID SDL_JoystickGetDeviceInstanceID_REAL
+#define SDL_utf8strlen SDL_utf8strlen_REAL
+#define SDL_LoadFile_RW SDL_LoadFile_RW_REAL
+#define SDL_wcscmp SDL_wcscmp_REAL
+#define SDL_ComposeCustomBlendMode SDL_ComposeCustomBlendMode_REAL
+#define SDL_DuplicateSurface SDL_DuplicateSurface_REAL
+#define SDL_Vulkan_LoadLibrary SDL_Vulkan_LoadLibrary_REAL
+#define SDL_Vulkan_GetVkGetInstanceProcAddr SDL_Vulkan_GetVkGetInstanceProcAddr_REAL
+#define SDL_Vulkan_UnloadLibrary SDL_Vulkan_UnloadLibrary_REAL
+#define SDL_Vulkan_GetInstanceExtensions SDL_Vulkan_GetInstanceExtensions_REAL
+#define SDL_Vulkan_CreateSurface SDL_Vulkan_CreateSurface_REAL
+#define SDL_Vulkan_GetDrawableSize SDL_Vulkan_GetDrawableSize_REAL
diff --git a/src/dynapi/SDL_dynapi_procs.h b/src/dynapi/SDL_dynapi_procs.h
index a08835b..b7466fd 100644
--- a/src/dynapi/SDL_dynapi_procs.h
+++ b/src/dynapi/SDL_dynapi_procs.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -50,6 +50,8 @@ SDL_DYNAPI_PROC(int,SDL_snprintf,(SDL_OUT_Z_CAP(b) char *a, size_t b, SDL_PRINTF
 
 #if defined(__WIN32__) && !defined(HAVE_LIBC)
 SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThread,(SDL_ThreadFunction a, const char *b, void *c, pfnSDL_CurrentBeginThread d, pfnSDL_CurrentEndThread e),(a,b,c,d,e),return)
+#elif defined(__OS2__)
+SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThread,(SDL_ThreadFunction a, const char *b, void *c, pfnSDL_CurrentBeginThread d, pfnSDL_CurrentEndThread e),(a,b,c,d,e),return)
 #else
 SDL_DYNAPI_PROC(SDL_Thread*,SDL_CreateThread,(SDL_ThreadFunction a, const char *b, void *c),(a,b,c),return)
 #endif
@@ -60,12 +62,6 @@ SDL_DYNAPI_PROC(SDL_RWops*,SDL_RWFromFP,(FILE *a, SDL_bool b),(a,b),return)
 SDL_DYNAPI_PROC(SDL_RWops*,SDL_RWFromFP,(void *a, SDL_bool b),(a,b),return)
 #endif
 
-/* so annoying. */
-#if defined(__thumb__) && (defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__))
-SDL_DYNAPI_PROC(void,SDL_MemoryBarrierRelease,(void),(),)
-SDL_DYNAPI_PROC(void,SDL_MemoryBarrierAcquire,(void),(),)
-#endif
-
 #ifdef __WIN32__
 SDL_DYNAPI_PROC(int,SDL_RegisterApp,(char *a, Uint32 b, void *c),(a,b,c),return)
 SDL_DYNAPI_PROC(void,SDL_UnregisterApp,(void),(),)
@@ -644,3 +640,32 @@ SDL_DYNAPI_PROC(void,SDL_SetWindowResizable,(SDL_Window *a, SDL_bool b),(a,b),)
 SDL_DYNAPI_PROC(SDL_Surface*,SDL_CreateRGBSurfaceWithFormat,(Uint32 a, int b, int c, int d, Uint32 e),(a,b,c,d,e),return)
 SDL_DYNAPI_PROC(SDL_Surface*,SDL_CreateRGBSurfaceWithFormatFrom,(void *a, int b, int c, int d, int e, Uint32 f),(a,b,c,d,e,f),return)
 SDL_DYNAPI_PROC(SDL_bool,SDL_GetHintBoolean,(const char *a, SDL_bool b),(a,b),return)
+SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetDeviceVendor,(int a),(a),return)
+SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetDeviceProduct,(int a),(a),return)
+SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetDeviceProductVersion,(int a),(a),return)
+SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetVendor,(SDL_Joystick *a),(a),return)
+SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetProduct,(SDL_Joystick *a),(a),return)
+SDL_DYNAPI_PROC(Uint16,SDL_JoystickGetProductVersion,(SDL_Joystick *a),(a),return)
+SDL_DYNAPI_PROC(Uint16,SDL_GameControllerGetVendor,(SDL_GameController *a),(a),return)
+SDL_DYNAPI_PROC(Uint16,SDL_GameControllerGetProduct,(SDL_GameController *a),(a),return)
+SDL_DYNAPI_PROC(Uint16,SDL_GameControllerGetProductVersion,(SDL_GameController *a),(a),return)
+SDL_DYNAPI_PROC(SDL_bool,SDL_HasNEON,(void),(),return)
+SDL_DYNAPI_PROC(int,SDL_GameControllerNumMappings,(void),(),return)
+SDL_DYNAPI_PROC(char*,SDL_GameControllerMappingForIndex,(int a),(a),return)
+SDL_DYNAPI_PROC(SDL_bool,SDL_JoystickGetAxisInitialState,(SDL_Joystick *a, int b, Sint16 *c),(a,b,c),return)
+SDL_DYNAPI_PROC(SDL_JoystickType,SDL_JoystickGetDeviceType,(int a),(a),return)
+SDL_DYNAPI_PROC(SDL_JoystickType,SDL_JoystickGetType,(SDL_Joystick *a),(a),return)
+SDL_DYNAPI_PROC(void,SDL_MemoryBarrierReleaseFunction,(void),(),)
+SDL_DYNAPI_PROC(void,SDL_MemoryBarrierAcquireFunction,(void),(),)
+SDL_DYNAPI_PROC(SDL_JoystickID,SDL_JoystickGetDeviceInstanceID,(int a),(a),return)
+SDL_DYNAPI_PROC(size_t,SDL_utf8strlen,(const char *a),(a),return)
+SDL_DYNAPI_PROC(void*,SDL_LoadFile_RW,(SDL_RWops *a, size_t *b, int c),(a,b,c),return)
+SDL_DYNAPI_PROC(int,SDL_wcscmp,(const wchar_t *a, const wchar_t *b),(a,b),return)
+SDL_DYNAPI_PROC(SDL_BlendMode,SDL_ComposeCustomBlendMode,(SDL_BlendFactor a, SDL_BlendFactor b, SDL_BlendOperation c, SDL_BlendFactor d, SDL_BlendFactor e, SDL_BlendOperation f),(a,b,c,d,e,f),return)
+SDL_DYNAPI_PROC(SDL_Surface*,SDL_DuplicateSurface,(SDL_Surface *a),(a),return)
+SDL_DYNAPI_PROC(int,SDL_Vulkan_LoadLibrary,(const char *a),(a),return)
+SDL_DYNAPI_PROC(void*,SDL_Vulkan_GetVkGetInstanceProcAddr,(void),(),return)
+SDL_DYNAPI_PROC(void,SDL_Vulkan_UnloadLibrary,(void),(),)
+SDL_DYNAPI_PROC(SDL_bool,SDL_Vulkan_GetInstanceExtensions,(SDL_Window *a, unsigned int *b, const char **c),(a,b,c),return)
+SDL_DYNAPI_PROC(SDL_bool,SDL_Vulkan_CreateSurface,(SDL_Window *a, VkInstance b, VkSurfaceKHR *c),(a,b,c),return)
+SDL_DYNAPI_PROC(void,SDL_Vulkan_GetDrawableSize,(SDL_Window *a, int *b, int *c),(a,b,c),)
diff --git a/src/dynapi/gendynapi.pl b/src/dynapi/gendynapi.pl
index 5c3d796..0e88433 100755
--- a/src/dynapi/gendynapi.pl
+++ b/src/dynapi/gendynapi.pl
@@ -1,7 +1,7 @@
 #!/usr/bin/perl -w
 
 #  Simple DirectMedia Layer
-#  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+#  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 #
 #  This software is provided 'as-is', without any express or implied
 #  warranty.  In no event will the authors be held liable for any damages
diff --git a/src/events/SDL_clipboardevents.c b/src/events/SDL_clipboardevents.c
index 9b2209b..4ecd695 100644
--- a/src/events/SDL_clipboardevents.c
+++ b/src/events/SDL_clipboardevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/events/SDL_clipboardevents_c.h b/src/events/SDL_clipboardevents_c.h
index 98e6a38..538195b 100644
--- a/src/events/SDL_clipboardevents_c.h
+++ b/src/events/SDL_clipboardevents_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,11 +20,11 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_clipboardevents_c_h
-#define _SDL_clipboardevents_c_h
+#ifndef SDL_clipboardevents_c_h_
+#define SDL_clipboardevents_c_h_
 
 extern int SDL_SendClipboardUpdate(void);
 
-#endif /* _SDL_clipboardevents_c_h */
+#endif /* SDL_clipboardevents_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/events/SDL_dropevents.c b/src/events/SDL_dropevents.c
index 49b07d9..f783d68 100644
--- a/src/events/SDL_dropevents.c
+++ b/src/events/SDL_dropevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/events/SDL_dropevents_c.h b/src/events/SDL_dropevents_c.h
index a7adb85..7016820 100644
--- a/src/events/SDL_dropevents_c.h
+++ b/src/events/SDL_dropevents_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,13 +20,13 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_dropevents_c_h
-#define _SDL_dropevents_c_h
+#ifndef SDL_dropevents_c_h_
+#define SDL_dropevents_c_h_
 
 extern int SDL_SendDropFile(SDL_Window *window, const char *file);
 extern int SDL_SendDropText(SDL_Window *window, const char *text);
 extern int SDL_SendDropComplete(SDL_Window *window);
 
-#endif /* _SDL_dropevents_c_h */
+#endif /* SDL_dropevents_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/events/SDL_events.c b/src/events/SDL_events.c
index 2f5b0af..c87dc99 100644
--- a/src/events/SDL_events.c
+++ b/src/events/SDL_events.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,7 +24,6 @@
 
 #include "SDL.h"
 #include "SDL_events.h"
-#include "SDL_syswm.h"
 #include "SDL_thread.h"
 #include "SDL_events_c.h"
 #include "../timer/SDL_timer_c.h"
@@ -32,6 +31,9 @@
 #include "../joystick/SDL_joystick_c.h"
 #endif
 #include "../video/SDL_sysvideo.h"
+#include "SDL_syswm.h"
+
+/*#define SDL_DEBUG_EVENTS 1*/
 
 /* An arbitrary limit so we don't have unbounded growth */
 #define SDL_MAX_QUEUED_EVENTS   65535
@@ -84,6 +86,230 @@ static struct
 } SDL_EventQ = { NULL, { 1 }, { 0 }, 0, NULL, NULL, NULL, NULL, NULL };
 
 
+#ifdef SDL_DEBUG_EVENTS
+
+/* this is to make printf() calls cleaner. */
+#define uint unsigned int
+
+static void
+SDL_DebugPrintEvent(const SDL_Event *event)
+{
+    /* !!! FIXME: This code is kinda ugly, sorry. */
+    printf("SDL EVENT: ");
+
+    if ((event->type >= SDL_USEREVENT) && (event->type <= SDL_LASTEVENT)) {
+        printf("SDL_USEREVENT");
+        if (event->type > SDL_USEREVENT) {
+            printf("+%u", ((uint) event->type) - SDL_USEREVENT);
+        }
+        printf(" (timestamp=%u windowid=%u code=%d data1=%p data2=%p)",
+                (uint) event->user.timestamp, (uint) event->user.windowID,
+                (int) event->user.code, event->user.data1, event->user.data2);
+        return;
+    }
+
+    switch (event->type) {
+        #define SDL_EVENT_CASE(x) case x: printf("%s", #x);
+        SDL_EVENT_CASE(SDL_FIRSTEVENT) printf("(THIS IS PROBABLY A BUG!)"); break;
+        SDL_EVENT_CASE(SDL_QUIT) printf("(timestamp=%u)", (uint) event->quit.timestamp); break;
+        SDL_EVENT_CASE(SDL_APP_TERMINATING) break;
+        SDL_EVENT_CASE(SDL_APP_LOWMEMORY) break;
+        SDL_EVENT_CASE(SDL_APP_WILLENTERBACKGROUND) break;
+        SDL_EVENT_CASE(SDL_APP_DIDENTERBACKGROUND) break;
+        SDL_EVENT_CASE(SDL_APP_WILLENTERFOREGROUND) break;
+        SDL_EVENT_CASE(SDL_APP_DIDENTERFOREGROUND) break;
+        SDL_EVENT_CASE(SDL_KEYMAPCHANGED) break;
+        SDL_EVENT_CASE(SDL_CLIPBOARDUPDATE) break;
+        SDL_EVENT_CASE(SDL_RENDER_TARGETS_RESET) break;
+        SDL_EVENT_CASE(SDL_RENDER_DEVICE_RESET) break;
+        #undef SDL_EVENT_CASE
+
+        #define SDL_EVENT_CASE(x) case x: printf("%s ", #x);
+
+        SDL_EVENT_CASE(SDL_WINDOWEVENT)
+            printf("(timestamp=%u windowid=%u event=", (uint) event->window.timestamp, (uint) event->window.windowID);
+            switch(event->window.event) {
+                case SDL_WINDOWEVENT_NONE: printf("none(THIS IS PROBABLY A BUG!)"); break;
+                #define SDL_WINDOWEVENT_CASE(x) case x: printf("%s", #x); break
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_SHOWN);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_HIDDEN);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_EXPOSED);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_MOVED);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_RESIZED);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_SIZE_CHANGED);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_MINIMIZED);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_MAXIMIZED);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_RESTORED);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_ENTER);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_LEAVE);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_FOCUS_GAINED);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_FOCUS_LOST);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_CLOSE);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_TAKE_FOCUS);
+                SDL_WINDOWEVENT_CASE(SDL_WINDOWEVENT_HIT_TEST);
+                #undef SDL_WINDOWEVENT_CASE
+                default: printf("UNKNOWN(bug? fixme?)"); break;
+            }
+            printf(" data1=%d data2=%d)", (int) event->window.data1, (int) event->window.data2);
+            break;
+
+        SDL_EVENT_CASE(SDL_SYSWMEVENT)
+            printf("(timestamp=%u)", (uint) event->syswm.timestamp);
+            /* !!! FIXME: we don't delve further at the moment. */
+            break;
+
+        #define PRINT_KEY_EVENT(event) \
+            printf("(timestamp=%u windowid=%u state=%s repeat=%s scancode=%u keycode=%u mod=%u)", \
+                (uint) event->key.timestamp, (uint) event->key.windowID, \
+                event->key.state == SDL_PRESSED ? "pressed" : "released", \
+                event->key.repeat ? "true" : "false", \
+                (uint) event->key.keysym.scancode, \
+                (uint) event->key.keysym.sym, \
+                (uint) event->key.keysym.mod)
+        SDL_EVENT_CASE(SDL_KEYDOWN) PRINT_KEY_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_KEYUP) PRINT_KEY_EVENT(event); break;
+        #undef PRINT_KEY_EVENT
+
+        SDL_EVENT_CASE(SDL_TEXTEDITING)
+            printf("(timestamp=%u windowid=%u text='%s' start=%d length=%d)",
+                (uint) event->edit.timestamp, (uint) event->edit.windowID,
+                event->edit.text, (int) event->edit.start, (int) event->edit.length);
+            break;
+
+        SDL_EVENT_CASE(SDL_TEXTINPUT)
+            printf("(timestamp=%u windowid=%u text='%s')", (uint) event->text.timestamp, (uint) event->text.windowID, event->text.text);
+            break;
+
+
+        SDL_EVENT_CASE(SDL_MOUSEMOTION)
+            printf("(timestamp=%u windowid=%u which=%u state=%u x=%d y=%d xrel=%d yrel=%d)",
+                    (uint) event->motion.timestamp, (uint) event->motion.windowID,
+                    (uint) event->motion.which, (uint) event->motion.state,
+                    (int) event->motion.x, (int) event->motion.y,
+                    (int) event->motion.xrel, (int) event->motion.yrel);
+            break;
+
+        #define PRINT_MBUTTON_EVENT(event) \
+            printf("(timestamp=%u windowid=%u which=%u button=%u state=%s clicks=%u x=%d y=%d)", \
+                    (uint) event->button.timestamp, (uint) event->button.windowID, \
+                    (uint) event->button.which, (uint) event->button.button, \
+                    event->button.state == SDL_PRESSED ? "pressed" : "released", \
+                    (uint) event->button.clicks, (int) event->button.x, (int) event->button.y)
+        SDL_EVENT_CASE(SDL_MOUSEBUTTONDOWN) PRINT_MBUTTON_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_MOUSEBUTTONUP) PRINT_MBUTTON_EVENT(event); break;
+        #undef PRINT_MBUTTON_EVENT
+
+
+        SDL_EVENT_CASE(SDL_MOUSEWHEEL)
+            printf("(timestamp=%u windowid=%u which=%u x=%d y=%d direction=%s)",
+                    (uint) event->wheel.timestamp, (uint) event->wheel.windowID,
+                    (uint) event->wheel.which, (int) event->wheel.x, (int) event->wheel.y,
+                    event->wheel.direction == SDL_MOUSEWHEEL_NORMAL ? "normal" : "flipped");
+            break;
+
+        SDL_EVENT_CASE(SDL_JOYAXISMOTION)
+            printf("(timestamp=%u which=%d axis=%u value=%d)",
+                (uint) event->jaxis.timestamp, (int) event->jaxis.which,
+                (uint) event->jaxis.axis, (int) event->jaxis.value);
+            break;
+
+        SDL_EVENT_CASE(SDL_JOYBALLMOTION)
+            printf("(timestamp=%u which=%d ball=%u xrel=%d yrel=%d)",
+                (uint) event->jball.timestamp, (int) event->jball.which,
+                (uint) event->jball.ball, (int) event->jball.xrel, (int) event->jball.yrel);
+            break;
+
+        SDL_EVENT_CASE(SDL_JOYHATMOTION)
+            printf("(timestamp=%u which=%d hat=%u value=%u)",
+                (uint) event->jhat.timestamp, (int) event->jhat.which,
+                (uint) event->jhat.hat, (uint) event->jhat.value);
+            break;
+
+        #define PRINT_JBUTTON_EVENT(event) \
+            printf("(timestamp=%u which=%d button=%u state=%s)", \
+                (uint) event->jbutton.timestamp, (int) event->jbutton.which, \
+                (uint) event->jbutton.button, event->jbutton.state == SDL_PRESSED ? "pressed" : "released")
+        SDL_EVENT_CASE(SDL_JOYBUTTONDOWN) PRINT_JBUTTON_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_JOYBUTTONUP) PRINT_JBUTTON_EVENT(event); break;
+        #undef PRINT_JBUTTON_EVENT
+
+        #define PRINT_JOYDEV_EVENT(event) printf("(timestamp=%u which=%d)", (uint) event->jdevice.timestamp, (int) event->jdevice.which)
+        SDL_EVENT_CASE(SDL_JOYDEVICEADDED) PRINT_JOYDEV_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_JOYDEVICEREMOVED) PRINT_JOYDEV_EVENT(event); break;
+        #undef PRINT_JOYDEV_EVENT
+
+        SDL_EVENT_CASE(SDL_CONTROLLERAXISMOTION)
+            printf("(timestamp=%u which=%d axis=%u value=%d)",
+                (uint) event->caxis.timestamp, (int) event->caxis.which,
+                (uint) event->caxis.axis, (int) event->caxis.value);
+            break;
+
+        #define PRINT_CBUTTON_EVENT(event) \
+            printf("(timestamp=%u which=%d button=%u state=%s)", \
+                (uint) event->cbutton.timestamp, (int) event->cbutton.which, \
+                (uint) event->cbutton.button, event->cbutton.state == SDL_PRESSED ? "pressed" : "released")
+        SDL_EVENT_CASE(SDL_CONTROLLERBUTTONDOWN) PRINT_CBUTTON_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_CONTROLLERBUTTONUP) PRINT_CBUTTON_EVENT(event); break;
+        #undef PRINT_CBUTTON_EVENT
+
+        #define PRINT_CONTROLLERDEV_EVENT(event) printf("(timestamp=%u which=%d)", (uint) event->cdevice.timestamp, (int) event->cdevice.which)
+        SDL_EVENT_CASE(SDL_CONTROLLERDEVICEADDED) PRINT_CONTROLLERDEV_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_CONTROLLERDEVICEREMOVED) PRINT_CONTROLLERDEV_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_CONTROLLERDEVICEREMAPPED) PRINT_CONTROLLERDEV_EVENT(event); break;
+        #undef PRINT_CONTROLLERDEV_EVENT
+
+        #define PRINT_FINGER_EVENT(event) \
+            printf("(timestamp=%u touchid=%lld fingerid=%lld x=%f y=%f dx=%f dy=%f pressure=%f)", \
+                (uint) event->tfinger.timestamp, (long long) event->tfinger.touchId, \
+                (long long) event->tfinger.fingerId, event->tfinger.x, event->tfinger.y, \
+                event->tfinger.dx, event->tfinger.dy, event->tfinger.pressure)
+        SDL_EVENT_CASE(SDL_FINGERDOWN) PRINT_FINGER_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_FINGERUP) PRINT_FINGER_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_FINGERMOTION) PRINT_FINGER_EVENT(event); break;
+        #undef PRINT_FINGER_EVENT
+
+        #define PRINT_DOLLAR_EVENT(event) \
+            printf("(timestamp=%u touchid=%lld gestureid=%lld numfingers=%u error=%f x=%f y=%f)", \
+                (uint) event->dgesture.timestamp, (long long) event->dgesture.touchId, \
+                (long long) event->dgesture.gestureId, (uint) event->dgesture.numFingers, \
+                event->dgesture.error, event->dgesture.x, event->dgesture.y);
+        SDL_EVENT_CASE(SDL_DOLLARGESTURE) PRINT_DOLLAR_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_DOLLARRECORD) PRINT_DOLLAR_EVENT(event); break;
+        #undef PRINT_DOLLAR_EVENT
+
+        SDL_EVENT_CASE(SDL_MULTIGESTURE)
+            printf("(timestamp=%u touchid=%lld dtheta=%f ddist=%f x=%f y=%f numfingers=%u)",
+                (uint) event->mgesture.timestamp, (long long) event->mgesture.touchId,
+                event->mgesture.dTheta, event->mgesture.dDist,
+                event->mgesture.x, event->mgesture.y, (uint) event->mgesture.numFingers);
+            break;
+
+        #define PRINT_DROP_EVENT(event) printf("(file='%s' timestamp=%u windowid=%u)", event->drop.file, (uint) event->drop.timestamp, (uint) event->drop.windowID)
+        SDL_EVENT_CASE(SDL_DROPFILE) PRINT_DROP_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_DROPTEXT) PRINT_DROP_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_DROPBEGIN) PRINT_DROP_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_DROPCOMPLETE) PRINT_DROP_EVENT(event); break;
+        #undef PRINT_DROP_EVENT
+
+        #define PRINT_AUDIODEV_EVENT(event) printf("(timestamp=%u which=%u iscapture=%s)", (uint) event->adevice.timestamp, (uint) event->adevice.which, event->adevice.iscapture ? "true" : "false");
+        SDL_EVENT_CASE(SDL_AUDIODEVICEADDED) PRINT_AUDIODEV_EVENT(event); break;
+        SDL_EVENT_CASE(SDL_AUDIODEVICEREMOVED) PRINT_AUDIODEV_EVENT(event); break;
+        #undef PRINT_AUDIODEV_EVENT
+
+        #undef SDL_EVENT_CASE
+
+        default:
+            printf("UNKNOWN SDL EVENT #%u! (Bug? FIXME?)", (uint) event->type);
+            break;
+    }
+
+    printf("\n");
+}
+#undef uint
+#endif
+
+
+
 /* Public functions */
 
 void
@@ -209,6 +435,10 @@ SDL_AddEvent(SDL_Event * event)
         SDL_EventQ.free = entry->next;
     }
 
+    #ifdef SDL_DEBUG_EVENTS
+    SDL_DebugPrintEvent(event);
+    #endif
+
     entry->event = *event;
     if (event->type == SDL_SYSWMEVENT) {
         entry->msg = *event->syswm.msg;
diff --git a/src/events/SDL_events_c.h b/src/events/SDL_events_c.h
index 2e33190..83b0e14 100644
--- a/src/events/SDL_events_c.h
+++ b/src/events/SDL_events_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/events/SDL_gesture.c b/src/events/SDL_gesture.c
index 4391420..4193b9d 100644
--- a/src/events/SDL_gesture.c
+++ b/src/events/SDL_gesture.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -71,9 +71,9 @@ typedef struct {
     SDL_bool recording;
 } SDL_GestureTouch;
 
-SDL_GestureTouch *SDL_gestureTouch;
-int SDL_numGestureTouches = 0;
-SDL_bool recordAll;
+static SDL_GestureTouch *SDL_gestureTouch;
+static int SDL_numGestureTouches = 0;
+static SDL_bool recordAll;
 
 #if 0
 static void PrintPath(SDL_FloatPoint *path)
@@ -101,6 +101,12 @@ int SDL_RecordGesture(SDL_TouchID touchId)
     return (touchId < 0);
 }
 
+void SDL_GestureQuit()
+{
+    SDL_free(SDL_gestureTouch);
+    SDL_gestureTouch = NULL;
+}
+
 static unsigned long SDL_HashDollar(SDL_FloatPoint* points)
 {
     unsigned long hash = 5381;
@@ -374,7 +380,7 @@ static int dollarNormalize(const SDL_DollarPath *path,SDL_FloatPoint *points)
         dist += d;
     }
     if (numPoints < DOLLARNPOINTS-1) {
-        SDL_SetError("ERROR: NumPoints = %i\n",numPoints);
+        SDL_SetError("ERROR: NumPoints = %i", numPoints);
         return 0;
     }
     /* copy the last point */
@@ -457,6 +463,28 @@ int SDL_GestureAddTouch(SDL_TouchID touchId)
     return 0;
 }
 
+int SDL_GestureDelTouch(SDL_TouchID touchId)
+{
+    int i;
+    for (i = 0; i < SDL_numGestureTouches; i++) {
+        if (SDL_gestureTouch[i].id == touchId) {
+            break;
+        }
+    }
+
+    if (i == SDL_numGestureTouches) {
+        /* not found */
+        return -1;
+    }
+
+    SDL_free(SDL_gestureTouch[i].dollarTemplate);
+    SDL_zero(SDL_gestureTouch[i]);
+
+    SDL_numGestureTouches--;
+    SDL_memcpy(&SDL_gestureTouch[i], &SDL_gestureTouch[SDL_numGestureTouches], sizeof(SDL_gestureTouch[i]));
+    return 0;
+}
+
 static SDL_GestureTouch * SDL_GetGestureTouch(SDL_TouchID id)
 {
     int i;
@@ -468,7 +496,7 @@ static SDL_GestureTouch * SDL_GetGestureTouch(SDL_TouchID id)
     return NULL;
 }
 
-int SDL_SendGestureMulti(SDL_GestureTouch* touch,float dTheta,float dDist)
+static int SDL_SendGestureMulti(SDL_GestureTouch* touch,float dTheta,float dDist)
 {
     SDL_Event event;
     event.mgesture.type = SDL_MULTIGESTURE;
diff --git a/src/events/SDL_gesture_c.h b/src/events/SDL_gesture_c.h
index 3ff542c..ab588b0 100644
--- a/src/events/SDL_gesture_c.h
+++ b/src/events/SDL_gesture_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,15 +20,16 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_gesture_c_h
-#define _SDL_gesture_c_h
+#ifndef SDL_gesture_c_h_
+#define SDL_gesture_c_h_
 
 extern int SDL_GestureAddTouch(SDL_TouchID touchId);
+extern int SDL_GestureDelTouch(SDL_TouchID touchId);
 
 extern void SDL_GestureProcessEvent(SDL_Event* event);
 
-extern int SDL_RecordGesture(SDL_TouchID touchId);
+extern void SDL_GestureQuit(void);
 
-#endif /* _SDL_gesture_c_h */
+#endif /* SDL_gesture_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/events/SDL_keyboard.c b/src/events/SDL_keyboard.c
index 1572654..d84b2fd 100644
--- a/src/events/SDL_keyboard.c
+++ b/src/events/SDL_keyboard.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -273,6 +273,10 @@ static const SDL_Keycode SDL_default_keymap[SDL_NUM_SCANCODES] = {
     SDLK_KBDILLUMUP,
     SDLK_EJECT,
     SDLK_SLEEP,
+    SDLK_APP1,
+    SDLK_APP2,
+    SDLK_AUDIOREWIND,
+    SDLK_AUDIOFASTFORWARD,
 };
 
 static const char *SDL_scancode_names[SDL_NUM_SCANCODES] = {
@@ -505,6 +509,10 @@ static const char *SDL_scancode_names[SDL_NUM_SCANCODES] = {
     "KBDIllumUp",
     "Eject",
     "Sleep",
+    "App1",
+    "App2",
+    "AudioRewind",
+    "AudioFastForward",
 };
 
 /* Taken from SDL_iconv() */
@@ -569,7 +577,7 @@ SDL_ResetKeyboard(void)
 #ifdef DEBUG_KEYBOARD
     printf("Resetting keyboard\n");
 #endif
-    for (scancode = 0; scancode < SDL_NUM_SCANCODES; ++scancode) {
+    for (scancode = (SDL_Scancode) 0; scancode < SDL_NUM_SCANCODES; ++scancode) {
         if (keyboard->keystate[scancode] == SDL_PRESSED) {
             SDL_SendKeyboardKey(SDL_RELEASED, scancode);
         }
@@ -586,12 +594,22 @@ void
 SDL_SetKeymap(int start, SDL_Keycode * keys, int length)
 {
     SDL_Keyboard *keyboard = &SDL_keyboard;
+    SDL_Scancode scancode;
 
     if (start < 0 || start + length > SDL_NUM_SCANCODES) {
         return;
     }
 
     SDL_memcpy(&keyboard->keymap[start], keys, sizeof(*keys) * length);
+
+    /* The number key scancodes always map to the number key keycodes.
+     * On AZERTY layouts these technically are symbols, but users (and games)
+     * always think of them and view them in UI as number keys.
+     */
+    keyboard->keymap[SDL_SCANCODE_0] = SDLK_0;
+    for (scancode = SDL_SCANCODE_1; scancode <= SDL_SCANCODE_9; ++scancode) {
+        keyboard->keymap[scancode] = SDLK_1 + (scancode - SDL_SCANCODE_1);
+    }
 }
 
 void
@@ -664,7 +682,6 @@ SDL_SendKeyboardKey(Uint8 state, SDL_Scancode scancode)
     int posted;
     SDL_Keymod modifier;
     SDL_Keycode keycode;
-    Uint16 modstate;
     Uint32 type;
     Uint8 repeat;
 
@@ -737,7 +754,6 @@ SDL_SendKeyboardKey(Uint8 state, SDL_Scancode scancode)
         break;
     }
     if (SDL_KEYDOWN == type) {
-        modstate = keyboard->modstate;
         switch (keycode) {
         case SDLK_NUMLOCKCLEAR:
             keyboard->modstate ^= KMOD_NUM;
@@ -751,7 +767,6 @@ SDL_SendKeyboardKey(Uint8 state, SDL_Scancode scancode)
         }
     } else {
         keyboard->modstate &= ~modifier;
-        modstate = keyboard->modstate;
     }
 
     /* Post the event, if desired */
@@ -763,7 +778,7 @@ SDL_SendKeyboardKey(Uint8 state, SDL_Scancode scancode)
         event.key.repeat = repeat;
         event.key.keysym.scancode = scancode;
         event.key.keysym.sym = keycode;
-        event.key.keysym.mod = modstate;
+        event.key.keysym.mod = keyboard->modstate;
         event.key.windowID = keyboard->focus ? keyboard->focus->id : 0;
         posted = (SDL_PushEvent(&event) > 0);
     }
@@ -834,7 +849,7 @@ SDL_GetModState(void)
 {
     SDL_Keyboard *keyboard = &SDL_keyboard;
 
-    return keyboard->modstate;
+    return (SDL_Keymod) keyboard->modstate;
 }
 
 void
@@ -863,7 +878,7 @@ SDL_GetKeyFromScancode(SDL_Scancode scancode)
 {
     SDL_Keyboard *keyboard = &SDL_keyboard;
 
-    if (scancode < SDL_SCANCODE_UNKNOWN || scancode >= SDL_NUM_SCANCODES) {
+    if (((int)scancode) < ((int)SDL_SCANCODE_UNKNOWN) || scancode >= SDL_NUM_SCANCODES) {
           SDL_InvalidParamError("scancode");
           return 0;
     }
@@ -890,7 +905,7 @@ const char *
 SDL_GetScancodeName(SDL_Scancode scancode)
 {
     const char *name;
-    if (scancode < SDL_SCANCODE_UNKNOWN || scancode >= SDL_NUM_SCANCODES) {
+    if (((int)scancode) < ((int)SDL_SCANCODE_UNKNOWN) || scancode >= SDL_NUM_SCANCODES) {
           SDL_InvalidParamError("scancode");
           return "";
     }
@@ -968,8 +983,10 @@ SDL_GetKeyFromName(const char *name)
 {
     SDL_Keycode key;
 
-        /* Check input */
-        if (name == NULL) return SDLK_UNKNOWN;
+    /* Check input */
+    if (name == NULL) {
+        return SDLK_UNKNOWN;
+    }
 
     /* If it's a single UTF-8 character, then that's the keycode itself */
     key = *(const unsigned char *)name;
diff --git a/src/events/SDL_keyboard_c.h b/src/events/SDL_keyboard_c.h
index b4d1c07..7103278 100644
--- a/src/events/SDL_keyboard_c.h
+++ b/src/events/SDL_keyboard_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_keyboard_c_h
-#define _SDL_keyboard_c_h
+#ifndef SDL_keyboard_c_h_
+#define SDL_keyboard_c_h_
 
 #include "SDL_keycode.h"
 #include "SDL_events.h"
@@ -65,6 +65,6 @@ extern char *SDL_UCS4ToUTF8(Uint32 ch, char *dst);
 /* Toggle on or off pieces of the keyboard mod state. */
 extern void SDL_ToggleModState(const SDL_Keymod modstate, const SDL_bool toggle);
 
-#endif /* _SDL_keyboard_c_h */
+#endif /* SDL_keyboard_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/events/SDL_mouse.c b/src/events/SDL_mouse.c
index 4236a99..7a7bb2e 100644
--- a/src/events/SDL_mouse.c
+++ b/src/events/SDL_mouse.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,7 +27,6 @@
 #include "SDL_timer.h"
 #include "SDL_events.h"
 #include "SDL_events_c.h"
-#include "default_cursor.h"
 #include "../video/SDL_sysvideo.h"
 
 /* #define DEBUG_MOUSE */
@@ -40,12 +39,57 @@ static int SDL_double_click_radius = 1;
 static int
 SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int x, int y);
 
+static void SDLCALL
+SDL_MouseNormalSpeedScaleChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
+{
+    SDL_Mouse *mouse = (SDL_Mouse *)userdata;
+
+    if (hint && *hint) {
+        mouse->normal_speed_scale = (float)SDL_atof(hint);
+    } else {
+        mouse->normal_speed_scale = 1.0f;
+    }
+}
+
+static void SDLCALL
+SDL_MouseRelativeSpeedScaleChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
+{
+    SDL_Mouse *mouse = (SDL_Mouse *)userdata;
+
+    if (hint && *hint) {
+        mouse->relative_speed_scale = (float)SDL_atof(hint);
+    } else {
+        mouse->relative_speed_scale = 1.0f;
+    }
+}
+
+static void SDLCALL
+SDL_TouchMouseEventsChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
+{
+    SDL_Mouse *mouse = (SDL_Mouse *)userdata;
+
+    if (hint && (*hint == '0' || SDL_strcasecmp(hint, "false") == 0)) {
+        mouse->touch_mouse_events = SDL_FALSE;
+    } else {
+        mouse->touch_mouse_events = SDL_TRUE;
+    }
+}
+
 /* Public functions */
 int
 SDL_MouseInit(void)
 {
     SDL_Mouse *mouse = SDL_GetMouse();
 
+    SDL_AddHintCallback(SDL_HINT_MOUSE_NORMAL_SPEED_SCALE,
+                        SDL_MouseNormalSpeedScaleChanged, mouse);
+
+    SDL_AddHintCallback(SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE,
+                        SDL_MouseRelativeSpeedScaleChanged, mouse);
+
+    SDL_AddHintCallback(SDL_HINT_TOUCH_MOUSE_EVENTS,
+                        SDL_TouchMouseEventsChanged, mouse);
+
     mouse->cursor_shown = SDL_TRUE;
 
     return (0);
@@ -82,6 +126,7 @@ SDL_GetMouseFocus(void)
     return mouse->focus;
 }
 
+#if 0
 void
 SDL_ResetMouse(void)
 {
@@ -98,6 +143,7 @@ SDL_ResetMouse(void)
     }
     SDL_assert(mouse->buttonstate == 0);
 }
+#endif
 
 void
 SDL_SetMouseFocus(SDL_Window * window)
@@ -126,6 +172,7 @@ SDL_SetMouseFocus(SDL_Window * window)
     }
 
     mouse->focus = window;
+    mouse->has_position = SDL_FALSE;
 
     if (mouse->focus) {
         SDL_SendWindowEvent(mouse->focus, SDL_WINDOWEVENT_ENTER, 0, 0);
@@ -176,10 +223,10 @@ SDL_UpdateMouseFocus(SDL_Window * window, int x, int y, Uint32 buttonstate)
 
     if (window != mouse->focus) {
 #ifdef DEBUG_MOUSE
-         printf("Mouse entered window, synthesizing focus gain & move event\n");
+        printf("Mouse entered window, synthesizing focus gain & move event\n");
 #endif
-         SDL_SetMouseFocus(window);
-         SDL_PrivateSendMouseMotion(window, mouse->mouseID, 0, x, y);
+        SDL_SetMouseFocus(window);
+        SDL_PrivateSendMouseMotion(window, mouse->mouseID, 0, x, y);
     }
     return SDL_TRUE;
 }
@@ -198,6 +245,21 @@ SDL_SendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int
 }
 
 static int
+GetScaledMouseDelta(float scale, int value, float *accum)
+{
+    if (scale != 1.0f) {
+        *accum += scale * value;
+        if (*accum >= 0.0f) {
+            value = (int)SDL_floor(*accum);
+        } else {
+            value = (int)SDL_ceil(*accum);
+        }
+        *accum -= value;
+    }
+    return value;
+}
+
+static int
 SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int x, int y)
 {
     SDL_Mouse *mouse = SDL_GetMouse();
@@ -205,7 +267,11 @@ SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relativ
     int xrel;
     int yrel;
 
-    if (mouse->relative_mode_warp) {
+    if (mouseID == SDL_TOUCH_MOUSEID && !mouse->touch_mouse_events) {
+        return 0;
+    }
+
+    if (mouseID != SDL_TOUCH_MOUSEID && mouse->relative_mode_warp) {
         int center_x = 0, center_y = 0;
         SDL_GetWindowSize(window, &center_x, &center_y);
         center_x /= 2;
@@ -219,6 +285,13 @@ SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relativ
     }
 
     if (relative) {
+        if (mouse->relative_mode) {
+            x = GetScaledMouseDelta(mouse->relative_speed_scale, x, &mouse->scale_accum_x);
+            y = GetScaledMouseDelta(mouse->relative_speed_scale, y, &mouse->scale_accum_y);
+        } else {
+            x = GetScaledMouseDelta(mouse->normal_speed_scale, x, &mouse->scale_accum_x);
+            y = GetScaledMouseDelta(mouse->normal_speed_scale, y, &mouse->scale_accum_y);
+        }
         xrel = x;
         yrel = y;
         x = (mouse->last_x + xrel);
@@ -236,6 +309,19 @@ SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relativ
         return 0;
     }
 
+    /* Ignore relative motion when first positioning the mouse */
+    if (!mouse->has_position) {
+        xrel = 0;
+        yrel = 0;
+        mouse->has_position = SDL_TRUE;
+    }
+
+    /* Ignore relative motion positioning the first touch */
+    if (mouseID == SDL_TOUCH_MOUSEID && !mouse->buttonstate) {
+        xrel = 0;
+        yrel = 0;
+    }
+
     /* Update internal mouse coordinates */
     if (!mouse->relative_mode) {
         mouse->x = x;
@@ -250,7 +336,7 @@ SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relativ
     if (window && ((window->flags & SDL_WINDOW_MOUSE_CAPTURE) == 0)) {
         int x_max = 0, y_max = 0;
 
-        // !!! FIXME: shouldn't this be (window) instead of (mouse->focus)?
+        /* !!! FIXME: shouldn't this be (window) instead of (mouse->focus)? */
         SDL_GetWindowSize(mouse->focus, &x_max, &y_max);
         --x_max;
         --y_max;
@@ -330,6 +416,10 @@ SDL_PrivateSendMouseButton(SDL_Window * window, SDL_MouseID mouseID, Uint8 state
     Uint32 type;
     Uint32 buttonstate = mouse->buttonstate;
 
+    if (mouseID == SDL_TOUCH_MOUSEID && !mouse->touch_mouse_events) {
+        return 0;
+    }
+
     /* Figure out which event to perform */
     switch (state) {
     case SDL_PRESSED:
@@ -417,10 +507,11 @@ SDL_SendMouseButton(SDL_Window * window, SDL_MouseID mouseID, Uint8 state, Uint8
 }
 
 int
-SDL_SendMouseWheel(SDL_Window * window, SDL_MouseID mouseID, int x, int y, SDL_MouseWheelDirection direction)
+SDL_SendMouseWheel(SDL_Window * window, SDL_MouseID mouseID, float x, float y, SDL_MouseWheelDirection direction)
 {
     SDL_Mouse *mouse = SDL_GetMouse();
     int posted;
+    int integral_x, integral_y;
 
     if (window) {
         SDL_SetMouseFocus(window);
@@ -430,6 +521,26 @@ SDL_SendMouseWheel(SDL_Window * window, SDL_MouseID mouseID, int x, int y, SDL_M
         return 0;
     }
 
+    mouse->accumulated_wheel_x += x;
+    if (mouse->accumulated_wheel_x > 0) {
+        integral_x = (int)SDL_floor(mouse->accumulated_wheel_x);
+    } else if (mouse->accumulated_wheel_x < 0) {
+        integral_x = (int)SDL_ceil(mouse->accumulated_wheel_x);
+    } else {
+        integral_x = 0;
+    }
+    mouse->accumulated_wheel_x -= integral_x;
+
+    mouse->accumulated_wheel_y += y;
+    if (mouse->accumulated_wheel_y > 0) {
+        integral_y = (int)SDL_floor(mouse->accumulated_wheel_y);
+    } else if (mouse->accumulated_wheel_y < 0) {
+        integral_y = (int)SDL_ceil(mouse->accumulated_wheel_y);
+    } else {
+        integral_y = 0;
+    }
+    mouse->accumulated_wheel_y -= integral_y;
+
     /* Post the event, if desired */
     posted = 0;
     if (SDL_GetEventState(SDL_MOUSEWHEEL) == SDL_ENABLE) {
@@ -437,8 +548,12 @@ SDL_SendMouseWheel(SDL_Window * window, SDL_MouseID mouseID, int x, int y, SDL_M
         event.type = SDL_MOUSEWHEEL;
         event.wheel.windowID = mouse->focus ? mouse->focus->id : 0;
         event.wheel.which = mouseID;
-        event.wheel.x = x;
-        event.wheel.y = y;
+#if 0 /* Uncomment this when it goes in for SDL 2.1 */
+        event.wheel.preciseX = x;
+        event.wheel.preciseY = y;
+#endif
+        event.wheel.x = integral_x;
+        event.wheel.y = integral_y;
         event.wheel.direction = (Uint32)direction;
         posted = (SDL_PushEvent(&event) > 0);
     }
@@ -473,6 +588,12 @@ SDL_MouseQuit(void)
     }
 
     SDL_zerop(mouse);
+
+    SDL_DelHintCallback(SDL_HINT_MOUSE_NORMAL_SPEED_SCALE,
+                        SDL_MouseNormalSpeedScaleChanged, mouse);
+
+    SDL_DelHintCallback(SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE,
+                        SDL_MouseRelativeSpeedScaleChanged, mouse);
 }
 
 Uint32
@@ -601,6 +722,8 @@ SDL_SetRelativeMouseMode(SDL_bool enabled)
         }
     }
     mouse->relative_mode = enabled;
+    mouse->scale_accum_x = 0.0f;
+    mouse->scale_accum_y = 0.0f;
 
     if (mouse->focus) {
         SDL_UpdateWindowGrab(mouse->focus);
diff --git a/src/events/SDL_mouse_c.h b/src/events/SDL_mouse_c.h
index 06dc887..52a41b3 100644
--- a/src/events/SDL_mouse_c.h
+++ b/src/events/SDL_mouse_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_mouse_c_h
-#define _SDL_mouse_c_h
+#ifndef SDL_mouse_c_h_
+#define SDL_mouse_c_h_
 
 #include "SDL_mouse.h"
 
@@ -80,9 +80,17 @@ typedef struct
     int xdelta;
     int ydelta;
     int last_x, last_y;         /* the last reported x and y coordinates */
+    float accumulated_wheel_x;
+    float accumulated_wheel_y;
     Uint32 buttonstate;
+    SDL_bool has_position;
     SDL_bool relative_mode;
     SDL_bool relative_mode_warp;
+    float normal_speed_scale;
+    float relative_speed_scale;
+    float scale_accum_x;
+    float scale_accum_y;
+    SDL_bool touch_mouse_events;
 
     /* Data for double-click tracking */
     int num_clickstates;
@@ -123,11 +131,11 @@ extern int SDL_SendMouseButton(SDL_Window * window, SDL_MouseID mouseID, Uint8 s
 extern int SDL_SendMouseButtonClicks(SDL_Window * window, SDL_MouseID mouseID, Uint8 state, Uint8 button, int clicks);
 
 /* Send a mouse wheel event */
-extern int SDL_SendMouseWheel(SDL_Window * window, SDL_MouseID mouseID, int x, int y, SDL_MouseWheelDirection direction);
+extern int SDL_SendMouseWheel(SDL_Window * window, SDL_MouseID mouseID, float x, float y, SDL_MouseWheelDirection direction);
 
 /* Shutdown the mouse subsystem */
 extern void SDL_MouseQuit(void);
 
-#endif /* _SDL_mouse_c_h */
+#endif /* SDL_mouse_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/events/SDL_quit.c b/src/events/SDL_quit.c
index 3cb6b3d..43007b3 100644
--- a/src/events/SDL_quit.c
+++ b/src/events/SDL_quit.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/events/SDL_sysevents.h b/src/events/SDL_sysevents.h
index c4ce087..3ab4a9d 100644
--- a/src/events/SDL_sysevents.h
+++ b/src/events/SDL_sysevents.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/events/SDL_touch.c b/src/events/SDL_touch.c
index c73827c..39a765a 100644
--- a/src/events/SDL_touch.c
+++ b/src/events/SDL_touch.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,6 +25,7 @@
 #include "SDL_assert.h"
 #include "SDL_events.h"
 #include "SDL_events_c.h"
+#include "../video/SDL_sysvideo.h"
 
 
 static int SDL_num_touch = 0;
@@ -48,7 +49,7 @@ SDL_TouchID
 SDL_GetTouchDevice(int index)
 {
     if (index < 0 || index >= SDL_num_touch) {
-        SDL_SetError("Unknown touch device");
+        SDL_SetError("Unknown touch device index %d", index);
         return 0;
     }
     return SDL_touchDevices[index]->id;
@@ -74,7 +75,12 @@ SDL_GetTouch(SDL_TouchID id)
 {
     int index = SDL_GetTouchIndex(id);
     if (index < 0 || index >= SDL_num_touch) {
-        SDL_SetError("Unknown touch device");
+        if (SDL_GetVideoDevice()->ResetTouch != NULL) {
+            SDL_SetError("Unknown touch id %d, resetting", (int) id);
+            (SDL_GetVideoDevice()->ResetTouch)(SDL_GetVideoDevice());
+        } else {
+            SDL_SetError("Unknown touch device id %d, cannot reset", (int) id);
+        }
         return NULL;
     }
     return SDL_touchDevices[index];
@@ -92,7 +98,7 @@ SDL_GetFingerIndex(const SDL_Touch * touch, SDL_FingerID fingerid)
     return -1;
 }
 
-SDL_Finger *
+static SDL_Finger *
 SDL_GetFinger(const SDL_Touch * touch, SDL_FingerID id)
 {
     int index = SDL_GetFingerIndex(touch, id);
@@ -346,6 +352,9 @@ SDL_DelTouch(SDL_TouchID id)
 
     SDL_num_touch--;
     SDL_touchDevices[index] = SDL_touchDevices[SDL_num_touch];
+
+    /* Delete this touch device for gestures */
+    SDL_GestureDelTouch(id);
 }
 
 void
@@ -360,6 +369,7 @@ SDL_TouchQuit(void)
 
     SDL_free(SDL_touchDevices);
     SDL_touchDevices = NULL;
+    SDL_GestureQuit();
 }
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/events/SDL_touch_c.h b/src/events/SDL_touch_c.h
index d025df6..cfaed08 100644
--- a/src/events/SDL_touch_c.h
+++ b/src/events/SDL_touch_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 #include "../SDL_internal.h"
 #include "../../include/SDL_touch.h"
 
-#ifndef _SDL_touch_c_h
-#define _SDL_touch_c_h
+#ifndef SDL_touch_c_h_
+#define SDL_touch_c_h_
 
 typedef struct SDL_Touch
 {
@@ -56,6 +56,6 @@ extern void SDL_DelTouch(SDL_TouchID id);
 /* Shutdown the touch subsystem */
 extern void SDL_TouchQuit(void);
 
-#endif /* _SDL_touch_c_h */
+#endif /* SDL_touch_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/events/SDL_windowevents.c b/src/events/SDL_windowevents.c
index b45015b..b12dfbf 100644
--- a/src/events/SDL_windowevents.c
+++ b/src/events/SDL_windowevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -28,7 +28,7 @@
 #include "../video/SDL_sysvideo.h"
 
 
-static int
+static int SDLCALL
 RemovePendingResizedEvents(void * userdata, SDL_Event *event)
 {
     SDL_Event *new_event = (SDL_Event *)userdata;
@@ -42,7 +42,7 @@ RemovePendingResizedEvents(void * userdata, SDL_Event *event)
     return 1;
 }
 
-static int
+static int SDLCALL
 RemovePendingSizeChangedEvents(void * userdata, SDL_Event *event)
 {
     SDL_Event *new_event = (SDL_Event *)userdata;
@@ -56,7 +56,7 @@ RemovePendingSizeChangedEvents(void * userdata, SDL_Event *event)
     return 1;
 }
 
-static int
+static int SDLCALL
 RemovePendingMoveEvents(void * userdata, SDL_Event *event)
 {
     SDL_Event *new_event = (SDL_Event *)userdata;
@@ -70,7 +70,7 @@ RemovePendingMoveEvents(void * userdata, SDL_Event *event)
     return 1;
 }
 
-static int
+static int SDLCALL
 RemovePendingExposedEvents(void * userdata, SDL_Event *event)
 {
     SDL_Event *new_event = (SDL_Event *)userdata;
diff --git a/src/events/SDL_windowevents_c.h b/src/events/SDL_windowevents_c.h
index 2a6a4c0..14e0a78 100644
--- a/src/events/SDL_windowevents_c.h
+++ b/src/events/SDL_windowevents_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,12 +20,12 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_windowevents_c_h
-#define _SDL_windowevents_c_h
+#ifndef SDL_windowevents_c_h_
+#define SDL_windowevents_c_h_
 
 extern int SDL_SendWindowEvent(SDL_Window * window, Uint8 windowevent,
                                int data1, int data2);
 
-#endif /* _SDL_windowevents_c_h */
+#endif /* SDL_windowevents_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/events/blank_cursor.h b/src/events/blank_cursor.h
index 5e15852..ae63f3c 100644
--- a/src/events/blank_cursor.h
+++ b/src/events/blank_cursor.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/events/default_cursor.h b/src/events/default_cursor.h
index 297dd2d..dde8448 100644
--- a/src/events/default_cursor.h
+++ b/src/events/default_cursor.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/events/scancodes_darwin.h b/src/events/scancodes_darwin.h
index 2692253..2cb84b3 100644
--- a/src/events/scancodes_darwin.h
+++ b/src/events/scancodes_darwin.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/events/scancodes_linux.h b/src/events/scancodes_linux.h
index e197ee3..af20f0e 100644
--- a/src/events/scancodes_linux.h
+++ b/src/events/scancodes_linux.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -194,7 +194,7 @@ static SDL_Scancode const linux_scancode_table[] = {
     /*  165 */    SDL_SCANCODE_AUDIOPREV, /* KEY_PREVIOUSSONG */
     /*  166 */    SDL_SCANCODE_AUDIOSTOP, /* KEY_STOPCD */
     /*  167 */    SDL_SCANCODE_UNKNOWN, /* KEY_RECORD */
-    /*  168 */    SDL_SCANCODE_UNKNOWN, /* KEY_REWIND */
+    /*  168 */    SDL_SCANCODE_AUDIOREWIND, /* KEY_REWIND */
     /*  169 */    SDL_SCANCODE_UNKNOWN, /* KEY_PHONE */
     /*  170 */    SDL_SCANCODE_UNKNOWN, /* KEY_ISO */
     /*  171 */    SDL_SCANCODE_UNKNOWN, /* KEY_CONFIG */
@@ -230,7 +230,7 @@ static SDL_Scancode const linux_scancode_table[] = {
     /*  205 */    SDL_SCANCODE_UNKNOWN, /* KEY_SUSPEND */
     /*  206 */    SDL_SCANCODE_UNKNOWN, /* KEY_CLOSE */
     /*  207 */    SDL_SCANCODE_UNKNOWN, /* KEY_PLAY */
-    /*  208 */    SDL_SCANCODE_UNKNOWN, /* KEY_FASTFORWARD */
+    /*  208 */    SDL_SCANCODE_AUDIOFASTFORWARD, /* KEY_FASTFORWARD */
     /*  209 */    SDL_SCANCODE_UNKNOWN, /* KEY_BASSBOOST */
     /*  210 */    SDL_SCANCODE_UNKNOWN, /* KEY_PRINT */
     /*  211 */    SDL_SCANCODE_UNKNOWN, /* KEY_HP */
diff --git a/src/events/scancodes_windows.h b/src/events/scancodes_windows.h
index b23a261..56d5a6d 100644
--- a/src/events/scancodes_windows.h
+++ b/src/events/scancodes_windows.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/events/scancodes_xfree86.h b/src/events/scancodes_xfree86.h
index 804196c..2a05b13 100644
--- a/src/events/scancodes_xfree86.h
+++ b/src/events/scancodes_xfree86.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -345,7 +345,7 @@ static const SDL_Scancode xfree86_scancode_table2[] = {
     /* 165 */   SDL_SCANCODE_AUDIOPREV,
     /* 166 */   SDL_SCANCODE_AUDIOSTOP,
     /* 167 */   SDL_SCANCODE_UNKNOWN,   /* XF86AudioRecord */
-    /* 168 */   SDL_SCANCODE_UNKNOWN,   /* XF86AudioRewind */
+    /* 168 */   SDL_SCANCODE_AUDIOREWIND,   /* XF86AudioRewind */
     /* 169 */   SDL_SCANCODE_UNKNOWN,   /* XF86Phone */
     /* 170 */   SDL_SCANCODE_UNKNOWN,
     /* 171 */   SDL_SCANCODE_F13,       /* XF86Tools */
diff --git a/src/file/SDL_rwops.c b/src/file/SDL_rwops.c
index 38beb62..06cdffd 100644
--- a/src/file/SDL_rwops.c
+++ b/src/file/SDL_rwops.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,14 +18,27 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
+
+/* We won't get fseeko64 on QNX if _LARGEFILE64_SOURCE is defined, but the
+   configure script knows the C runtime has it and enables it. */
+#ifndef __QNXNTO__
 /* Need this so Linux systems define fseek64o, ftell64o and off64_t */
 #define _LARGEFILE64_SOURCE
+#endif
+
 #include "../SDL_internal.h"
 
 #if defined(__WIN32__)
 #include "../core/windows/SDL_windows.h"
 #endif
 
+#ifdef HAVE_STDIO_H
+#include <stdio.h>
+#endif
+
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif
 
 /* This file provides a general interface for SDL to read and write
    data sources.  It can easily be extended to files, memory, etc.
@@ -292,6 +305,42 @@ windows_file_close(SDL_RWops * context)
 
 #ifdef HAVE_STDIO_H
 
+#ifdef HAVE_FOPEN64
+#define fopen   fopen64
+#endif
+#ifdef HAVE_FSEEKO64
+#define fseek_off_t off64_t
+#define fseek   fseeko64
+#define ftell   ftello64
+#elif defined(HAVE_FSEEKO)
+#if defined(OFF_MIN) && defined(OFF_MAX)
+#define FSEEK_OFF_MIN OFF_MIN
+#define FSEEK_OFF_MAX OFF_MAX
+#elif defined(HAVE_LIMITS_H)
+/* POSIX doesn't specify the minimum and maximum macros for off_t so
+ * we have to improvise and dance around implementation-defined
+ * behavior. This may fail if the off_t type has padding bits or
+ * is not a two's-complement representation. The compilers will detect
+ * and eliminate the dead code if off_t has 64 bits.
+ */
+#define FSEEK_OFF_MAX (((((off_t)1 << (sizeof(off_t) * CHAR_BIT - 2)) - 1) << 1) + 1)
+#define FSEEK_OFF_MIN (-(FSEEK_OFF_MAX) - 1)
+#endif
+#define fseek_off_t off_t
+#define fseek   fseeko
+#define ftell   ftello
+#elif defined(HAVE__FSEEKI64)
+#define fseek_off_t __int64
+#define fseek   _fseeki64
+#define ftell   _ftelli64
+#else
+#ifdef HAVE_LIMITS_H
+#define FSEEK_OFF_MIN LONG_MIN
+#define FSEEK_OFF_MAX LONG_MAX
+#endif
+#define fseek_off_t long
+#endif
+
 /* Functions to read/write stdio file pointers */
 
 static Sint64 SDLCALL
@@ -312,23 +361,19 @@ stdio_size(SDL_RWops * context)
 static Sint64 SDLCALL
 stdio_seek(SDL_RWops * context, Sint64 offset, int whence)
 {
-#ifdef HAVE_FSEEKO64
-    if (fseeko64(context->hidden.stdio.fp, (off64_t)offset, whence) == 0) {
-        return ftello64(context->hidden.stdio.fp);
-    }
-#elif defined(HAVE_FSEEKO)
-    if (fseeko(context->hidden.stdio.fp, (off_t)offset, whence) == 0) {
-        return ftello(context->hidden.stdio.fp);
-    }
-#elif defined(HAVE__FSEEKI64)
-    if (_fseeki64(context->hidden.stdio.fp, offset, whence) == 0) {
-        return _ftelli64(context->hidden.stdio.fp);
-    }
-#else
-    if (fseek(context->hidden.stdio.fp, offset, whence) == 0) {
-        return ftell(context->hidden.stdio.fp);
+#if defined(FSEEK_OFF_MIN) && defined(FSEEK_OFF_MAX)
+    if (offset < (Sint64)(FSEEK_OFF_MIN) || offset > (Sint64)(FSEEK_OFF_MAX)) {
+        return SDL_SetError("Seek offset out of range");
     }
 #endif
+
+    if (fseek(context->hidden.stdio.fp, (fseek_off_t)offset, whence) == 0) {
+        Sint64 pos = ftell(context->hidden.stdio.fp);
+        if (pos < 0) {
+            return SDL_SetError("Couldn't get stream offset");
+        }
+        return pos;
+    }
     return SDL_Error(SDL_EFSEEK);
 }
 
@@ -653,6 +698,59 @@ SDL_FreeRW(SDL_RWops * area)
     SDL_free(area);
 }
 
+/* Load all the data from an SDL data stream */
+void *
+SDL_LoadFile_RW(SDL_RWops * src, size_t *datasize, int freesrc)
+{
+    const int FILE_CHUNK_SIZE = 1024;
+    Sint64 size;
+    size_t size_read, size_total;
+    void *data = NULL, *newdata;
+
+    if (!src) {
+        SDL_InvalidParamError("src");
+        return NULL;
+    }
+
+    size = SDL_RWsize(src);
+    if (size < 0) {
+        size = FILE_CHUNK_SIZE;
+    }
+    data = SDL_malloc((size_t)(size + 1));
+
+    size_total = 0;
+    for (;;) {
+        if ((((Sint64)size_total) + FILE_CHUNK_SIZE) > size) {
+            size = (size_total + FILE_CHUNK_SIZE);
+            newdata = SDL_realloc(data, (size_t)(size + 1));
+            if (!newdata) {
+                SDL_free(data);
+                data = NULL;
+                SDL_OutOfMemory();
+                goto done;
+            }
+            data = newdata;
+        }
+
+        size_read = SDL_RWread(src, (char *)data+size_total, 1, (size_t)(size-size_total));
+        if (size_read == 0) {
+            break;
+        }
+        size_total += size_read;
+    }
+
+    if (datasize) {
+        *datasize = size_total;
+    }
+    ((char *)data)[size_total] = '\0';
+
+done:
+    if (freesrc && src) {
+        SDL_RWclose(src);
+    }
+    return data;
+}
+
 /* Functions for dynamically reading and writing endian-specific values */
 
 Uint8
diff --git a/src/file/cocoa/SDL_rwopsbundlesupport.h b/src/file/cocoa/SDL_rwopsbundlesupport.h
index 2c63f1d..ddae0dd 100644
--- a/src/file/cocoa/SDL_rwopsbundlesupport.h
+++ b/src/file/cocoa/SDL_rwopsbundlesupport.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/file/cocoa/SDL_rwopsbundlesupport.m b/src/file/cocoa/SDL_rwopsbundlesupport.m
index 3385d3a..be3cd49 100644
--- a/src/file/cocoa/SDL_rwopsbundlesupport.m
+++ b/src/file/cocoa/SDL_rwopsbundlesupport.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/filesystem/android/SDL_sysfilesystem.c b/src/filesystem/android/SDL_sysfilesystem.c
index 3bdf996..442d25c 100644
--- a/src/filesystem/android/SDL_sysfilesystem.c
+++ b/src/filesystem/android/SDL_sysfilesystem.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -26,7 +26,6 @@
 /* System dependent filesystem routines                                */
 
 #include <unistd.h>
-#include <errno.h>
 
 #include "SDL_error.h"
 #include "SDL_filesystem.h"
@@ -37,6 +36,7 @@ char *
 SDL_GetBasePath(void)
 {
     /* The current working directory is / on Android */
+    SDL_Unsupported();
     return NULL;
 }
 
diff --git a/src/filesystem/cocoa/SDL_sysfilesystem.m b/src/filesystem/cocoa/SDL_sysfilesystem.m
index 6dee580..3e84681 100644
--- a/src/filesystem/cocoa/SDL_sysfilesystem.m
+++ b/src/filesystem/cocoa/SDL_sysfilesystem.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -71,8 +71,15 @@ char *
 SDL_GetPrefPath(const char *org, const char *app)
 { @autoreleasepool
 {
-    char *retval = NULL;
+    if (!app) {
+        SDL_InvalidParamError("app");
+        return NULL;
+    }
+    if (!org) {
+        org = "";
+    }
 
+    char *retval = NULL;
     NSArray *array = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
 
     if ([array count] > 0) {  /* we only want the first item in the list. */
@@ -85,7 +92,11 @@ SDL_GetPrefPath(const char *org, const char *app)
                 SDL_OutOfMemory();
             } else {
                 char *ptr;
-                SDL_snprintf(retval, len, "%s/%s/%s/", base, org, app);
+                if (*org) {
+                    SDL_snprintf(retval, len, "%s/%s/%s/", base, org, app);
+                } else {
+                    SDL_snprintf(retval, len, "%s/%s/", base, app);
+                }
                 for (ptr = retval+1; *ptr; ptr++) {
                     if (*ptr == '/') {
                         *ptr = '\0';
diff --git a/src/filesystem/dummy/SDL_sysfilesystem.c b/src/filesystem/dummy/SDL_sysfilesystem.c
index 2570f4c..3074e46 100644
--- a/src/filesystem/dummy/SDL_sysfilesystem.c
+++ b/src/filesystem/dummy/SDL_sysfilesystem.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/filesystem/emscripten/SDL_sysfilesystem.c b/src/filesystem/emscripten/SDL_sysfilesystem.c
index ca49df1..14b5424 100644
--- a/src/filesystem/emscripten/SDL_sysfilesystem.c
+++ b/src/filesystem/emscripten/SDL_sysfilesystem.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -46,6 +46,14 @@ SDL_GetPrefPath(const char *org, const char *app)
     char *retval;
     size_t len = 0;
 
+    if (!app) {
+        SDL_InvalidParamError("app");
+        return NULL;
+    }
+    if (!org) {
+        org = "";
+    }
+
     len = SDL_strlen(append) + SDL_strlen(org) + SDL_strlen(app) + 3;
     retval = (char *) SDL_malloc(len);
     if (!retval) {
@@ -53,7 +61,11 @@ SDL_GetPrefPath(const char *org, const char *app)
         return NULL;
     }
 
-    SDL_snprintf(retval, len, "%s%s/%s/", append, org, app);
+    if (*org) {
+        SDL_snprintf(retval, len, "%s%s/%s/", append, org, app);
+    } else {
+        SDL_snprintf(retval, len, "%s%s/", append, app);
+    }
 
     if (mkdir(retval, 0700) != 0 && errno != EEXIST) {
         SDL_SetError("Couldn't create directory '%s': '%s'", retval, strerror(errno));
diff --git a/src/filesystem/haiku/SDL_sysfilesystem.cc b/src/filesystem/haiku/SDL_sysfilesystem.cc
index 0348916..090c808 100644
--- a/src/filesystem/haiku/SDL_sysfilesystem.cc
+++ b/src/filesystem/haiku/SDL_sysfilesystem.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,10 +25,10 @@
 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
 /* System dependent filesystem routines                                */
 
-#include <os/kernel/image.h>
-#include <os/storage/Directory.h>
-#include <os/storage/Entry.h>
-#include <os/storage/Path.h>
+#include <kernel/image.h>
+#include <storage/Directory.h>
+#include <storage/Entry.h>
+#include <storage/Path.h>
 
 #include "SDL_error.h"
 #include "SDL_stdinc.h"
@@ -75,13 +75,30 @@ SDL_GetPrefPath(const char *org, const char *app)
 {
     // !!! FIXME: is there a better way to do this?
     const char *home = SDL_getenv("HOME");
-    const char *append = "config/settings/";
-    const size_t len = SDL_strlen(home) + SDL_strlen(append) + SDL_strlen(org) + SDL_strlen(app) + 3;
+    const char *append = "/config/settings/";
+    size_t len = SDL_strlen(home);
+
+    if (!app) {
+        SDL_InvalidParamError("app");
+        return NULL;
+    }
+    if (!org) {
+        org = "";
+    }
+
+    if (!len || (home[len - 1] == '/')) {
+        ++append; // home empty or ends with separator, skip the one from append
+    }
+    len += SDL_strlen(append) + SDL_strlen(org) + SDL_strlen(app) + 3;
     char *retval = (char *) SDL_malloc(len);
     if (!retval) {
         SDL_OutOfMemory();
     } else {
-        SDL_snprintf(retval, len, "%s%s%s/%s/", home, append, org, app);
+        if (*org) {
+            SDL_snprintf(retval, len, "%s%s%s/%s/", home, append, org, app);
+        } else {
+            SDL_snprintf(retval, len, "%s%s%s/", home, append, app);
+        }
         create_directory(retval, 0700);  // Haiku api: creates missing dirs
     }
 
diff --git a/src/filesystem/nacl/SDL_sysfilesystem.c b/src/filesystem/nacl/SDL_sysfilesystem.c
index ac8fef1..767ef9a 100644
--- a/src/filesystem/nacl/SDL_sysfilesystem.c
+++ b/src/filesystem/nacl/SDL_sysfilesystem.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -40,3 +40,4 @@ SDL_GetPrefPath(const char *org, const char *app)
 
 #endif /* SDL_FILESYSTEM_NACL */
 
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/filesystem/unix/SDL_sysfilesystem.c b/src/filesystem/unix/SDL_sysfilesystem.c
index bd2e84c..0f8c3ba 100644
--- a/src/filesystem/unix/SDL_sysfilesystem.c
+++ b/src/filesystem/unix/SDL_sysfilesystem.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -32,6 +32,7 @@
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <limits.h>
+#include <fcntl.h>
 
 #if defined(__FREEBSD__) || defined(__OPENBSD__)
 #include <sys/sysctl.h>
@@ -40,7 +41,10 @@
 #include "SDL_error.h"
 #include "SDL_stdinc.h"
 #include "SDL_filesystem.h"
+#include "SDL_rwops.h"
 
+/* QNX's /proc/self/exefile is a text file and not a symlink. */
+#if !defined(__QNXNTO__)
 static char *
 readSymLink(const char *path)
 {
@@ -72,7 +76,7 @@ readSymLink(const char *path)
     SDL_free(retval);
     return NULL;
 }
-
+#endif
 
 char *
 SDL_GetBasePath(void)
@@ -122,13 +126,17 @@ SDL_GetBasePath(void)
 
     /* is a Linux-style /proc filesystem available? */
     if (!retval && (access("/proc", F_OK) == 0)) {
+        /* !!! FIXME: after 2.0.6 ships, let's delete this code and just
+                      use the /proc/%llu version. There's no reason to have
+                      two copies of this plus all the #ifdefs. --ryan. */
 #if defined(__FREEBSD__)
         retval = readSymLink("/proc/curproc/file");
 #elif defined(__NETBSD__)
         retval = readSymLink("/proc/curproc/exe");
+#elif defined(__QNXNTO__)
+        retval = SDL_LoadFile("/proc/self/exefile", NULL);
 #else
         retval = readSymLink("/proc/self/exe");  /* linux. */
-#endif
         if (retval == NULL) {
             /* older kernels don't have /proc/self ... try PID version... */
             char path[64];
@@ -139,6 +147,7 @@ SDL_GetBasePath(void)
                 retval = readSymLink(path);
             }
         }
+#endif
     }
 
     /* If we had access to argv[0] here, we could check it for a path,
@@ -180,6 +189,14 @@ SDL_GetPrefPath(const char *org, const char *app)
     char *ptr = NULL;
     size_t len = 0;
 
+    if (!app) {
+        SDL_InvalidParamError("app");
+        return NULL;
+    }
+    if (!org) {
+        org = "";
+    }
+
     if (!envr) {
         /* You end up with "$HOME/.local/share/Game Name 2" */
         envr = SDL_getenv("HOME");
@@ -204,7 +221,11 @@ SDL_GetPrefPath(const char *org, const char *app)
         return NULL;
     }
 
-    SDL_snprintf(retval, len, "%s%s%s/%s/", envr, append, org, app);
+    if (*org) {
+        SDL_snprintf(retval, len, "%s%s%s/%s/", envr, append, org, app);
+    } else {
+        SDL_snprintf(retval, len, "%s%s%s/", envr, append, app);
+    }
 
     for (ptr = retval+1; *ptr; ptr++) {
         if (*ptr == '/') {
diff --git a/src/filesystem/windows/SDL_sysfilesystem.c b/src/filesystem/windows/SDL_sysfilesystem.c
index fd942d7..1a9514a 100644
--- a/src/filesystem/windows/SDL_sysfilesystem.c
+++ b/src/filesystem/windows/SDL_sysfilesystem.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -118,6 +118,14 @@ SDL_GetPrefPath(const char *org, const char *app)
     size_t new_wpath_len = 0;
     BOOL api_result = FALSE;
 
+    if (!app) {
+        SDL_InvalidParamError("app");
+        return NULL;
+    }
+    if (!org) {
+        org = "";
+    }
+
     if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, path))) {
         WIN_SetError("Couldn't locate our prefpath");
         return NULL;
@@ -145,8 +153,10 @@ SDL_GetPrefPath(const char *org, const char *app)
         return NULL;
     }
 
-    lstrcatW(path, L"\\");
-    lstrcatW(path, worg);
+    if (*worg) {
+        lstrcatW(path, L"\\");
+        lstrcatW(path, worg);
+    }
     SDL_free(worg);
 
     api_result = CreateDirectoryW(path, NULL);
diff --git a/src/filesystem/winrt/SDL_sysfilesystem.cpp b/src/filesystem/winrt/SDL_sysfilesystem.cpp
index b4caf90..4afc96a 100644
--- a/src/filesystem/winrt/SDL_sysfilesystem.cpp
+++ b/src/filesystem/winrt/SDL_sysfilesystem.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -152,6 +152,14 @@ SDL_GetPrefPath(const char *org, const char *app)
     size_t new_wpath_len = 0;
     BOOL api_result = FALSE;
 
+    if (!app) {
+        SDL_InvalidParamError("app");
+        return NULL;
+    }
+    if (!org) {
+        org = "";
+    }
+
     srcPath = SDL_WinRTGetFSPathUNICODE(SDL_WINRT_PATH_LOCAL_FOLDER);
     if ( ! srcPath) {
         SDL_SetError("Unable to find a source path");
@@ -186,9 +194,11 @@ SDL_GetPrefPath(const char *org, const char *app)
         return NULL;
     }
 
-    SDL_wcslcat(path, L"\\", new_wpath_len + 1);
-    SDL_wcslcat(path, worg, new_wpath_len + 1);
-    SDL_free(worg);
+    if (*worg) {
+        SDL_wcslcat(path, L"\\", new_wpath_len + 1);
+        SDL_wcslcat(path, worg, new_wpath_len + 1);
+        SDL_free(worg);
+    }
 
     api_result = CreateDirectoryW(path, NULL);
     if (api_result == FALSE) {
@@ -219,3 +229,5 @@ SDL_GetPrefPath(const char *org, const char *app)
 }
 
 #endif /* __WINRT__ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/haptic/SDL_haptic.c b/src/haptic/SDL_haptic.c
index ddce908..d66a2df 100644
--- a/src/haptic/SDL_haptic.c
+++ b/src/haptic/SDL_haptic.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,9 +25,9 @@
 #include "../joystick/SDL_joystick_c.h" /* For SDL_PrivateJoystickValid */
 #include "SDL_assert.h"
 
+/* Global for SDL_windowshaptic.c */
 SDL_Haptic *SDL_haptics = NULL;
 
-
 /*
  * Initializes the Haptic devices.
  */
@@ -313,6 +313,7 @@ SDL_HapticOpenFromJoystick(SDL_Joystick * joystick)
     SDL_memset(haptic, 0, sizeof(SDL_Haptic));
     haptic->rumble_id = -1;
     if (SDL_SYS_HapticOpenFromJoystick(haptic, joystick) < 0) {
+        SDL_SetError("Haptic: SDL_SYS_HapticOpenFromJoystick failed.");
         SDL_free(haptic);
         return NULL;
     }
diff --git a/src/haptic/SDL_haptic_c.h b/src/haptic/SDL_haptic_c.h
index 5b9372b..a98667f 100644
--- a/src/haptic/SDL_haptic_c.h
+++ b/src/haptic/SDL_haptic_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/haptic/SDL_syshaptic.h b/src/haptic/SDL_syshaptic.h
index 372cefa..c3f7dab 100644
--- a/src/haptic/SDL_syshaptic.h
+++ b/src/haptic/SDL_syshaptic.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../SDL_internal.h"
 
-#ifndef _SDL_syshaptic_h
-#define _SDL_syshaptic_h
+#ifndef SDL_syshaptic_h_
+#define SDL_syshaptic_h_
 
 #include "SDL_haptic.h"
 
@@ -62,7 +62,7 @@ struct _SDL_Haptic
 extern int SDL_SYS_HapticInit(void);
 
 /* Function to return the number of haptic devices plugged in right now */
-extern int SDL_SYS_NumHaptics();
+extern int SDL_SYS_NumHaptics(void);
 
 /*
  * Gets the device dependent name of the haptic device
@@ -203,6 +203,6 @@ extern int SDL_SYS_HapticUnpause(SDL_Haptic * haptic);
  */
 extern int SDL_SYS_HapticStopAll(SDL_Haptic * haptic);
 
-#endif /* _SDL_syshaptic_h */
+#endif /* SDL_syshaptic_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/haptic/android/SDL_syshaptic.c b/src/haptic/android/SDL_syshaptic.c
new file mode 100644
index 0000000..9da1efc
--- /dev/null
+++ b/src/haptic/android/SDL_syshaptic.c
@@ -0,0 +1,358 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2014 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "../../SDL_internal.h"
+
+#ifdef SDL_HAPTIC_ANDROID
+
+#include "SDL_assert.h"
+#include "SDL_timer.h"
+#include "SDL_syshaptic_c.h"
+#include "../SDL_syshaptic.h"
+#include "SDL_haptic.h"
+#include "../../core/android/SDL_android.h"
+#include "SDL_joystick.h"
+#include "../../joystick/SDL_sysjoystick.h"     /* For the real SDL_Joystick */
+#include "../../joystick/android/SDL_sysjoystick_c.h"     /* For joystick hwdata */
+
+
+typedef struct SDL_hapticlist_item
+{
+    int device_id;
+    char *name;
+    SDL_Haptic *haptic;
+    struct SDL_hapticlist_item *next;
+} SDL_hapticlist_item;
+
+static SDL_hapticlist_item *SDL_hapticlist = NULL;
+static SDL_hapticlist_item *SDL_hapticlist_tail = NULL;
+static int numhaptics = 0;
+
+
+int
+SDL_SYS_HapticInit(void)
+{
+    /* Support for device connect/disconnect is API >= 16 only,
+     * so we poll every three seconds
+     * Ref: http://developer.android.com/reference/android/hardware/input/InputManager.InputDeviceListener.html
+     */
+    static Uint32 timeout = 0;
+    if (SDL_TICKS_PASSED(SDL_GetTicks(), timeout)) {
+        timeout = SDL_GetTicks() + 3000;
+        Android_JNI_PollHapticDevices();
+    }
+    return (numhaptics);
+}
+
+int
+SDL_SYS_NumHaptics(void)
+{
+    return (numhaptics);
+}
+
+static SDL_hapticlist_item *
+HapticByOrder(int index)
+{
+    SDL_hapticlist_item *item = SDL_hapticlist;
+    if ((index < 0) || (index >= numhaptics)) {
+        return NULL;
+    }
+    while (index > 0) {
+        SDL_assert(item != NULL);
+        --index;
+        item = item->next;
+    }
+    return item;
+}
+
+static SDL_hapticlist_item *
+HapticByDevId (int device_id)
+{
+    SDL_hapticlist_item *item;
+    for (item = SDL_hapticlist; item != NULL; item = item->next) {
+        if (device_id == item->device_id) {
+            /*SDL_Log("=+=+=+=+=+= HapticByDevId id [%d]", device_id);*/
+            return item;
+        }
+    }
+    return NULL;
+}
+
+const char *
+SDL_SYS_HapticName(int index)
+{
+    SDL_hapticlist_item *item = HapticByOrder(index);
+    if (item == NULL ) {
+        SDL_SetError("No such device");
+        return NULL;
+    }
+    return item->name;
+}
+
+
+static SDL_hapticlist_item *
+OpenHaptic(SDL_Haptic *haptic, SDL_hapticlist_item *item)
+{
+    if (item == NULL ) {
+        SDL_SetError("No such device");
+        return NULL;
+    }
+    if (item->haptic != NULL) {
+        SDL_SetError("Haptic already opened");
+        return NULL;
+    }
+
+    haptic->hwdata = (struct haptic_hwdata *)item;
+    item->haptic = haptic;
+
+    haptic->supported = SDL_HAPTIC_LEFTRIGHT;
+    haptic->neffects = 1;
+    haptic->nplaying = haptic->neffects;
+    haptic->effects = (struct haptic_effect *)SDL_malloc (sizeof (struct haptic_effect) * haptic->neffects);
+    if (haptic->effects == NULL) {
+        SDL_OutOfMemory();
+        return NULL;
+    }
+    SDL_memset(haptic->effects, 0, sizeof (struct haptic_effect) * haptic->neffects);
+    return item;
+}
+
+static SDL_hapticlist_item *
+OpenHapticByOrder(SDL_Haptic *haptic, int index)
+{
+    return OpenHaptic (haptic, HapticByOrder(index));
+}
+
+static SDL_hapticlist_item *
+OpenHapticByDevId(SDL_Haptic *haptic, int device_id)
+{
+    return OpenHaptic (haptic, HapticByDevId(device_id));
+}
+
+int
+SDL_SYS_HapticOpen(SDL_Haptic *haptic)
+{
+    return (OpenHapticByOrder(haptic, haptic->index) == NULL ? -1 : 0);
+}
+
+
+int
+SDL_SYS_HapticMouse(void)
+{
+    return 0;
+}
+
+
+int
+SDL_SYS_JoystickIsHaptic(SDL_Joystick *joystick)
+{
+    SDL_hapticlist_item *item;
+    item = HapticByDevId(((joystick_hwdata *)joystick->hwdata)->device_id);
+    int ret = (item != NULL ? 1 : 0);
+    return ret;
+}
+
+
+int
+SDL_SYS_HapticOpenFromJoystick(SDL_Haptic *haptic, SDL_Joystick *joystick)
+{
+    return (OpenHapticByDevId(haptic, ((joystick_hwdata *)joystick->hwdata)->device_id) == NULL ? -1 : 0);
+}
+
+
+int
+SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick)
+{
+    return (((SDL_hapticlist_item *)haptic->hwdata)->device_id == ((joystick_hwdata *)joystick->hwdata)->device_id ? 1 : 0);
+}
+
+
+void
+SDL_SYS_HapticClose(SDL_Haptic * haptic)
+{
+    ((SDL_hapticlist_item *)haptic->hwdata)->haptic = NULL;
+    haptic->hwdata = NULL;
+    return;
+}
+
+
+void
+SDL_SYS_HapticQuit(void)
+{
+    SDL_hapticlist_item *item = NULL;
+    SDL_hapticlist_item *next = NULL;
+
+    for (item = SDL_hapticlist; item; item = next) {
+        next = item->next;
+        SDL_free(item);
+    }
+
+    SDL_hapticlist = SDL_hapticlist_tail = NULL;
+    numhaptics = 0;
+    return;
+}
+
+
+int
+SDL_SYS_HapticNewEffect(SDL_Haptic * haptic,
+                        struct haptic_effect *effect, SDL_HapticEffect * base)
+{
+    return 0;
+}
+
+
+int
+SDL_SYS_HapticUpdateEffect(SDL_Haptic * haptic,
+                           struct haptic_effect *effect,
+                           SDL_HapticEffect * data)
+{
+    return 0;
+}
+
+
+int
+SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect,
+                        Uint32 iterations)
+{
+    Android_JNI_HapticRun (((SDL_hapticlist_item *)haptic->hwdata)->device_id, effect->effect.leftright.length);
+    return 0;
+}
+
+
+int
+SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect)
+{
+    return 0;
+}
+
+
+void
+SDL_SYS_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect *effect)
+{
+    return;
+}
+
+
+int
+SDL_SYS_HapticGetEffectStatus(SDL_Haptic * haptic,
+                              struct haptic_effect *effect)
+{
+    return 0;
+}
+
+
+int
+SDL_SYS_HapticSetGain(SDL_Haptic * haptic, int gain)
+{
+    return 0;
+}
+
+
+int
+SDL_SYS_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter)
+{
+    return 0;
+}
+
+int
+SDL_SYS_HapticPause(SDL_Haptic * haptic)
+{
+    return 0;
+}
+
+int
+SDL_SYS_HapticUnpause(SDL_Haptic * haptic)
+{
+    return 0;
+}
+
+int
+SDL_SYS_HapticStopAll(SDL_Haptic * haptic)
+{
+    return 0;
+}
+
+
+
+int
+Android_AddHaptic(int device_id, const char *name)
+{
+    SDL_hapticlist_item *item;
+    item = (SDL_hapticlist_item *) SDL_calloc(1, sizeof (SDL_hapticlist_item));
+    if (item == NULL) {
+        return -1;
+    }
+
+    item->device_id = device_id;
+    item->name = SDL_strdup (name);
+    if (item->name == NULL) {
+        SDL_free (item);
+        return -1;
+    }
+
+    if (SDL_hapticlist_tail == NULL) {
+        SDL_hapticlist = SDL_hapticlist_tail = item;
+    } else {
+        SDL_hapticlist_tail->next = item;
+        SDL_hapticlist_tail = item;
+    }
+
+    ++numhaptics;
+    return numhaptics;
+}
+
+int 
+Android_RemoveHaptic(int device_id)
+{
+    SDL_hapticlist_item *item;
+    SDL_hapticlist_item *prev = NULL;
+
+    for (item = SDL_hapticlist; item != NULL; item = item->next) {
+        /* found it, remove it. */
+        if (device_id == item->device_id) {
+            const int retval = item->haptic ? item->haptic->index : -1;
+
+            if (prev != NULL) {
+                prev->next = item->next;
+            } else {
+                SDL_assert(SDL_hapticlist == item);
+                SDL_hapticlist = item->next;
+            }
+            if (item == SDL_hapticlist_tail) {
+                SDL_hapticlist_tail = prev;
+            }
+
+            /* Need to decrement the haptic count */
+            --numhaptics;
+            /* !!! TODO: Send a haptic remove event? */
+
+            SDL_free(item->name);
+            SDL_free(item);
+            return retval;
+        }
+        prev = item;
+    }
+    return -1;
+}
+
+
+#endif /* SDL_HAPTIC_ANDROID */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/haptic/android/SDL_syshaptic_c.h b/src/haptic/android/SDL_syshaptic_c.h
new file mode 100644
index 0000000..08634d2
--- /dev/null
+++ b/src/haptic/android/SDL_syshaptic_c.h
@@ -0,0 +1,12 @@
+#include "SDL_config.h"
+
+#ifdef SDL_HAPTIC_ANDROID
+
+
+extern int Android_AddHaptic(int device_id, const char *name);
+extern int Android_RemoveHaptic(int device_id);
+
+
+#endif /* SDL_HAPTIC_ANDROID */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/haptic/darwin/SDL_syshaptic.c b/src/haptic/darwin/SDL_syshaptic.c
index d662012..5ce9979 100644
--- a/src/haptic/darwin/SDL_syshaptic.c
+++ b/src/haptic/darwin/SDL_syshaptic.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -189,7 +189,7 @@ SDL_SYS_HapticInit(void)
 }
 
 int
-SDL_SYS_NumHaptics()
+SDL_SYS_NumHaptics(void)
 {
     return numhaptics;
 }
diff --git a/src/haptic/darwin/SDL_syshaptic_c.h b/src/haptic/darwin/SDL_syshaptic_c.h
index 2b72aab..e8a9d61 100644
--- a/src/haptic/darwin/SDL_syshaptic_c.h
+++ b/src/haptic/darwin/SDL_syshaptic_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/haptic/dummy/SDL_syshaptic.c b/src/haptic/dummy/SDL_syshaptic.c
index 727e7ec..2f046e1 100644
--- a/src/haptic/dummy/SDL_syshaptic.c
+++ b/src/haptic/dummy/SDL_syshaptic.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/haptic/linux/SDL_syshaptic.c b/src/haptic/linux/SDL_syshaptic.c
index 7bd9664..a35b5aa 100644
--- a/src/haptic/linux/SDL_syshaptic.c
+++ b/src/haptic/linux/SDL_syshaptic.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -49,7 +49,7 @@
 static int MaybeAddDevice(const char *path);
 #if SDL_USE_LIBUDEV
 static int MaybeRemoveDevice(const char *path);
-void haptic_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath);
+static void haptic_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath);
 #endif /* SDL_USE_LIBUDEV */
 
 /*
@@ -187,7 +187,7 @@ SDL_SYS_HapticInit(void)
 }
 
 int
-SDL_SYS_NumHaptics()
+SDL_SYS_NumHaptics(void)
 {
     return numhaptics;
 }
@@ -211,7 +211,7 @@ HapticByDevIndex(int device_index)
 }
 
 #if SDL_USE_LIBUDEV
-void haptic_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath)
+static void haptic_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath)
 {
     if (devpath == NULL || !(udev_class & SDL_UDEV_DEVICE_JOYSTICK)) {
         return;
diff --git a/src/haptic/windows/SDL_dinputhaptic.c b/src/haptic/windows/SDL_dinputhaptic.c
index c81432c..7fdb6dc 100644
--- a/src/haptic/windows/SDL_dinputhaptic.c
+++ b/src/haptic/windows/SDL_dinputhaptic.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -59,15 +59,6 @@ DI_SetError(const char *str, HRESULT err)
 }
 
 /*
- * Checks to see if two GUID are the same.
- */
-static int
-DI_GUIDIsSame(const GUID * a, const GUID * b)
-{
-    return (SDL_memcmp(a, b, sizeof (GUID)) == 0);
-}
-
-/*
  * Callback to find the haptic devices.
  */
 static BOOL CALLBACK
@@ -219,17 +210,17 @@ DI_DeviceObjectCallback(LPCDIDEVICEOBJECTINSTANCE dev, LPVOID pvRef)
     if ((dev->dwType & DIDFT_AXIS) && (dev->dwFlags & DIDOI_FFACTUATOR)) {
         const GUID *guid = &dev->guidType;
         DWORD offset = 0;
-        if (DI_GUIDIsSame(guid, &GUID_XAxis)) {
+        if (WIN_IsEqualGUID(guid, &GUID_XAxis)) {
             offset = DIJOFS_X;
-        } else if (DI_GUIDIsSame(guid, &GUID_YAxis)) {
+        } else if (WIN_IsEqualGUID(guid, &GUID_YAxis)) {
             offset = DIJOFS_Y;
-        } else if (DI_GUIDIsSame(guid, &GUID_ZAxis)) {
+        } else if (WIN_IsEqualGUID(guid, &GUID_ZAxis)) {
             offset = DIJOFS_Z;
-        } else if (DI_GUIDIsSame(guid, &GUID_RxAxis)) {
+        } else if (WIN_IsEqualGUID(guid, &GUID_RxAxis)) {
             offset = DIJOFS_RX;
-        } else if (DI_GUIDIsSame(guid, &GUID_RyAxis)) {
+        } else if (WIN_IsEqualGUID(guid, &GUID_RyAxis)) {
             offset = DIJOFS_RY;
-        } else if (DI_GUIDIsSame(guid, &GUID_RzAxis)) {
+        } else if (WIN_IsEqualGUID(guid, &GUID_RzAxis)) {
             offset = DIJOFS_RZ;
         } else {
             return DIENUM_CONTINUE;   /* can't use this, go on. */
@@ -251,7 +242,7 @@ DI_DeviceObjectCallback(LPCDIDEVICEOBJECTINSTANCE dev, LPVOID pvRef)
  * Callback to get all supported effects.
  */
 #define EFFECT_TEST(e,s)               \
-if (DI_GUIDIsSame(&pei->guid, &(e)))   \
+if (WIN_IsEqualGUID(&pei->guid, &(e)))   \
    haptic->supported |= (s)
 static BOOL CALLBACK
 DI_EffectCallback(LPCDIEFFECTINFO pei, LPVOID pv)
@@ -481,7 +472,7 @@ SDL_DINPUT_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick)
         return 0;
     }
 
-    return DI_GUIDIsSame(&hap_instance.guidInstance, &joy_instance.guidInstance);
+    return WIN_IsEqualGUID(&hap_instance.guidInstance, &joy_instance.guidInstance);
 }
 
 int
@@ -500,7 +491,7 @@ SDL_DINPUT_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick)
 
     /* Since it comes from a joystick we have to try to match it with a haptic device on our haptic list. */
     for (item = SDL_hapticlist; item != NULL; item = item->next) {
-        if (!item->bXInputHaptic && DI_GUIDIsSame(&item->instance.guidInstance, &joy_instance.guidInstance)) {
+        if (!item->bXInputHaptic && WIN_IsEqualGUID(&item->instance.guidInstance, &joy_instance.guidInstance)) {
             haptic->index = index;
             return SDL_DINPUT_HapticOpenFromDevice(haptic, joystick->hwdata->InputDevice, SDL_TRUE);
         }
@@ -1016,6 +1007,19 @@ SDL_DINPUT_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect,
     /* Create the actual effect. */
     ret =
         IDirectInputEffect_SetParameters(effect->hweffect->ref, &temp, flags);
+    if (ret == DIERR_NOTEXCLUSIVEACQUIRED) {
+        IDirectInputDevice8_Unacquire(haptic->hwdata->device);
+        ret = IDirectInputDevice8_SetCooperativeLevel(haptic->hwdata->device, SDL_HelperWindow, DISCL_EXCLUSIVE | DISCL_BACKGROUND);
+        if (SUCCEEDED(ret)) {
+            ret = DIERR_NOTACQUIRED;
+        }
+    }
+    if (ret == DIERR_INPUTLOST || ret == DIERR_NOTACQUIRED) {
+        ret = IDirectInputDevice8_Acquire(haptic->hwdata->device);
+        if (SUCCEEDED(ret)) {
+            ret = IDirectInputEffect_SetParameters(effect->hweffect->ref, &temp, flags);
+        }
+    }
     if (FAILED(ret)) {
         DI_SetError("Unable to update effect", ret);
         goto err_update;
diff --git a/src/haptic/windows/SDL_dinputhaptic_c.h b/src/haptic/windows/SDL_dinputhaptic_c.h
index 3dc0f13..5ce020d 100644
--- a/src/haptic/windows/SDL_dinputhaptic_c.h
+++ b/src/haptic/windows/SDL_dinputhaptic_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/haptic/windows/SDL_windowshaptic.c b/src/haptic/windows/SDL_windowshaptic.c
index c6bcba1..76ebd90 100644
--- a/src/haptic/windows/SDL_windowshaptic.c
+++ b/src/haptic/windows/SDL_windowshaptic.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -98,7 +98,7 @@ SDL_SYS_RemoveHapticDevice(SDL_hapticlist_item *prev, SDL_hapticlist_item *item)
 }
 
 int
-SDL_SYS_NumHaptics()
+SDL_SYS_NumHaptics(void)
 {
     return numhaptics;
 }
diff --git a/src/haptic/windows/SDL_windowshaptic_c.h b/src/haptic/windows/SDL_windowshaptic_c.h
index f344264..0a66db0 100644
--- a/src/haptic/windows/SDL_windowshaptic_c.h
+++ b/src/haptic/windows/SDL_windowshaptic_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_windowshaptic_c_h
-#define _SDL_windowshaptic_c_h
+#ifndef SDL_windowshaptic_c_h_
+#define SDL_windowshaptic_c_h_
 
 #include "SDL_thread.h"
 #include "../SDL_syshaptic.h"
@@ -82,7 +82,7 @@ extern SDL_hapticlist_item *SDL_hapticlist;
 extern int SDL_SYS_AddHapticDevice(SDL_hapticlist_item *item);
 extern int SDL_SYS_RemoveHapticDevice(SDL_hapticlist_item *prev, SDL_hapticlist_item *item);
 
-#endif /* _SDL_windowshaptic_c_h */
+#endif /* SDL_windowshaptic_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
 
diff --git a/src/haptic/windows/SDL_xinputhaptic.c b/src/haptic/windows/SDL_xinputhaptic.c
index afbab45..419a84c 100644
--- a/src/haptic/windows/SDL_xinputhaptic.c
+++ b/src/haptic/windows/SDL_xinputhaptic.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -278,8 +278,9 @@ SDL_XINPUT_HapticUpdateEffect(SDL_Haptic * haptic, struct haptic_effect *effect,
 {
     XINPUT_VIBRATION *vib = &effect->hweffect->vibration;
     SDL_assert(data->type == SDL_HAPTIC_LEFTRIGHT);
-    vib->wLeftMotorSpeed = data->leftright.large_magnitude;
-    vib->wRightMotorSpeed = data->leftright.small_magnitude;
+    /* SDL_HapticEffect has max magnitude of 32767, XInput expects 65535 max, so multiply */
+    vib->wLeftMotorSpeed = data->leftright.large_magnitude * 2;
+    vib->wRightMotorSpeed = data->leftright.small_magnitude * 2;
     SDL_LockMutex(haptic->hwdata->mutex);
     if (haptic->hwdata->stopTicks) {  /* running right now? Update it. */
         XINPUTSETSTATE(haptic->hwdata->userid, vib);
diff --git a/src/haptic/windows/SDL_xinputhaptic_c.h b/src/haptic/windows/SDL_xinputhaptic_c.h
index f9a0c85..6768a67 100644
--- a/src/haptic/windows/SDL_xinputhaptic_c.h
+++ b/src/haptic/windows/SDL_xinputhaptic_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/joystick/SDL_gamecontroller.c b/src/joystick/SDL_gamecontroller.c
index 1d3a4c2..575593a 100644
--- a/src/joystick/SDL_gamecontroller.c
+++ b/src/joystick/SDL_gamecontroller.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,69 +25,72 @@
 #include "SDL_events.h"
 #include "SDL_assert.h"
 #include "SDL_sysjoystick.h"
+#include "SDL_joystick_c.h"
 #include "SDL_hints.h"
 #include "SDL_gamecontrollerdb.h"
 
 #if !SDL_EVENTS_DISABLED
 #include "../events/SDL_events_c.h"
 #endif
-#define ABS(_x) ((_x) < 0 ? -(_x) : (_x))
 
 #define SDL_CONTROLLER_PLATFORM_FIELD "platform:"
 
 /* a list of currently opened game controllers */
 static SDL_GameController *SDL_gamecontrollers = NULL;
 
-/* keep track of the hat and mask value that transforms this hat movement into a button/axis press */
-struct _SDL_HatMapping
+typedef struct
 {
-    int hat;
-    Uint8 mask;
-};
+    SDL_GameControllerBindType inputType;
+    union
+    {
+        int button;
 
-/* We need 36 entries for Android (as of SDL v2.0.4) */
-#define k_nMaxReverseEntries 48
+        struct {
+            int axis;
+            int axis_min;
+            int axis_max;
+        } axis;
 
-/**
- * We are encoding the "HAT" as 0xhm. where h == hat ID and m == mask
- * MAX 4 hats supported
- */
-#define k_nMaxHatEntries 0x3f + 1
+        struct {
+            int hat;
+            int hat_mask;
+        } hat;
 
-/* our in memory mapping db between joystick objects and controller mappings */
-struct _SDL_ControllerMapping
-{
-    SDL_JoystickGUID guid;
-    const char *name;
+    } input;
 
-    /* mapping of axis/button id to controller version */
-    int axes[SDL_CONTROLLER_AXIS_MAX];
-    int buttonasaxis[SDL_CONTROLLER_AXIS_MAX];
-
-    int buttons[SDL_CONTROLLER_BUTTON_MAX];
-    int axesasbutton[SDL_CONTROLLER_BUTTON_MAX];
-    struct _SDL_HatMapping hatasbutton[SDL_CONTROLLER_BUTTON_MAX];
+    SDL_GameControllerBindType outputType;
+    union
+    {
+        SDL_GameControllerButton button;
 
-    /* reverse mapping, joystick indices to buttons */
-    SDL_GameControllerAxis raxes[k_nMaxReverseEntries];
-    SDL_GameControllerAxis rbuttonasaxis[k_nMaxReverseEntries];
+        struct {
+            SDL_GameControllerAxis axis;
+            int axis_min;
+            int axis_max;
+        } axis;
 
-    SDL_GameControllerButton rbuttons[k_nMaxReverseEntries];
-    SDL_GameControllerButton raxesasbutton[k_nMaxReverseEntries];
-    SDL_GameControllerButton rhatasbutton[k_nMaxHatEntries];
-
-};
+    } output;
 
+} SDL_ExtendedGameControllerBind;
 
 /* our hard coded list of mapping support */
+typedef enum
+{
+    SDL_CONTROLLER_MAPPING_PRIORITY_DEFAULT,
+    SDL_CONTROLLER_MAPPING_PRIORITY_API,
+    SDL_CONTROLLER_MAPPING_PRIORITY_USER,
+} SDL_ControllerMappingPriority;
+
 typedef struct _ControllerMapping_t
 {
     SDL_JoystickGUID guid;
     char *name;
     char *mapping;
+    SDL_ControllerMappingPriority priority;
     struct _ControllerMapping_t *next;
 } ControllerMapping_t;
 
+static SDL_JoystickGUID s_zeroGUID;
 static ControllerMapping_t *s_pSupportedControllers = NULL;
 static ControllerMapping_t *s_pXInputMapping = NULL;
 static ControllerMapping_t *s_pEmscriptenMapping = NULL;
@@ -97,14 +100,88 @@ struct _SDL_GameController
 {
     SDL_Joystick *joystick; /* underlying joystick device */
     int ref_count;
-    Uint8 hatState[4]; /* the current hat state for this controller */
-    struct _SDL_ControllerMapping mapping; /* the mapping object for this controller */
+
+    SDL_JoystickGUID guid;
+    const char *name;
+    int num_bindings;
+    SDL_ExtendedGameControllerBind *bindings;
+    SDL_ExtendedGameControllerBind **last_match_axis;
+    Uint8 *last_hat_mask;
+
     struct _SDL_GameController *next; /* pointer to next game controller we have allocated */
 };
 
 
-int SDL_PrivateGameControllerAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis, Sint16 value);
-int SDL_PrivateGameControllerButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button, Uint8 state);
+typedef struct
+{
+    int num_entries;
+    int max_entries;
+    Uint32 *entries;
+} SDL_vidpid_list;
+
+static SDL_vidpid_list SDL_allowed_controllers;
+static SDL_vidpid_list SDL_ignored_controllers;
+
+static void
+SDL_LoadVIDPIDListFromHint(const char *hint, SDL_vidpid_list *list)
+{
+    Uint32 entry;
+    char *spot;
+    char *file = NULL;
+
+    list->num_entries = 0;
+
+    if (hint && *hint == '@') {
+        spot = file = (char *)SDL_LoadFile(hint+1, NULL);
+    } else {
+        spot = (char *)hint;
+    }
+
+    if (!spot) {
+        return;
+    }
+
+    while ((spot = SDL_strstr(spot, "0x")) != NULL) {
+        entry = (Uint16)SDL_strtol(spot, &spot, 0);
+        entry <<= 16;
+        spot = SDL_strstr(spot, "0x");
+        if (!spot) {
+            break;
+        }
+        entry |= (Uint16)SDL_strtol(spot, &spot, 0);
+
+        if (list->num_entries == list->max_entries) {
+            int max_entries = list->max_entries + 16;
+            Uint32 *entries = (Uint32 *)SDL_realloc(list->entries, max_entries*sizeof(*list->entries));
+            if (entries == NULL) {
+                /* Out of memory, go with what we have already */
+                break;
+            }
+            list->entries = entries;
+            list->max_entries = max_entries;
+        }
+        list->entries[list->num_entries++] = entry;
+    }
+
+    if (file) {
+        SDL_free(file);
+    }
+}
+
+static void SDLCALL
+SDL_GameControllerIgnoreDevicesChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
+{
+    SDL_LoadVIDPIDListFromHint(hint, &SDL_ignored_controllers);
+}
+
+static void SDLCALL
+SDL_GameControllerIgnoreDevicesExceptChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
+{
+    SDL_LoadVIDPIDListFromHint(hint, &SDL_allowed_controllers);
+}
+
+static int SDL_PrivateGameControllerAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis, Sint16 value);
+static int SDL_PrivateGameControllerButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button, Uint8 state);
 
 /*
  * If there is an existing add event in the queue, it needs to be modified
@@ -135,40 +212,136 @@ static void UpdateEventsForDeviceRemoval()
     SDL_stack_free(events);
 }
 
+static SDL_bool HasSameOutput(SDL_ExtendedGameControllerBind *a, SDL_ExtendedGameControllerBind *b)
+{
+    if (a->outputType != b->outputType) {
+        return SDL_FALSE;
+    }
+
+    if (a->outputType == SDL_CONTROLLER_BINDTYPE_AXIS) {
+        return (a->output.axis.axis == b->output.axis.axis);
+    } else {
+        return (a->output.button == b->output.button);
+    }
+}
+
+static void ResetOutput(SDL_GameController *gamecontroller, SDL_ExtendedGameControllerBind *bind)
+{
+    if (bind->outputType == SDL_CONTROLLER_BINDTYPE_AXIS) {
+        SDL_PrivateGameControllerAxis(gamecontroller, bind->output.axis.axis, 0);
+    } else {
+        SDL_PrivateGameControllerButton(gamecontroller, bind->output.button, SDL_RELEASED);
+    }
+}
+
+static void HandleJoystickAxis(SDL_GameController *gamecontroller, int axis, int value)
+{
+    int i;
+    SDL_ExtendedGameControllerBind *last_match = gamecontroller->last_match_axis[axis];
+    SDL_ExtendedGameControllerBind *match = NULL;
+
+    for (i = 0; i < gamecontroller->num_bindings; ++i) {
+        SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i];
+        if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS &&
+            axis == binding->input.axis.axis) {
+            if (binding->input.axis.axis_min < binding->input.axis.axis_max) {
+                if (value >= binding->input.axis.axis_min &&
+                    value <= binding->input.axis.axis_max) {
+                    match = binding;
+                    break;
+                }
+            } else {
+                if (value >= binding->input.axis.axis_max &&
+                    value <= binding->input.axis.axis_min) {
+                    match = binding;
+                    break;
+                }
+            }
+        }
+    }
+
+    if (last_match && (!match || !HasSameOutput(last_match, match))) {
+        /* Clear the last input that this axis generated */
+        ResetOutput(gamecontroller, last_match);
+    }
+
+    if (match) {
+        if (match->outputType == SDL_CONTROLLER_BINDTYPE_AXIS) {
+            if (match->input.axis.axis_min != match->output.axis.axis_min || match->input.axis.axis_max != match->output.axis.axis_max) {
+                float normalized_value = (float)(value - match->input.axis.axis_min) / (match->input.axis.axis_max - match->input.axis.axis_min);
+                value = match->output.axis.axis_min + (int)(normalized_value * (match->output.axis.axis_max - match->output.axis.axis_min));
+            }
+            SDL_PrivateGameControllerAxis(gamecontroller, match->output.axis.axis, (Sint16)value);
+        } else {
+            Uint8 state;
+            int threshold = match->input.axis.axis_min + (match->input.axis.axis_max - match->input.axis.axis_min) / 2;
+            if (match->input.axis.axis_max < match->input.axis.axis_min) {
+                state = (value <= threshold) ? SDL_PRESSED : SDL_RELEASED;
+            } else {
+                state = (value >= threshold) ? SDL_PRESSED : SDL_RELEASED;
+            }
+            SDL_PrivateGameControllerButton(gamecontroller, match->output.button, state);
+        }
+    }
+    gamecontroller->last_match_axis[axis] = match;
+}
+
+static void HandleJoystickButton(SDL_GameController *gamecontroller, int button, Uint8 state)
+{
+    int i;
+
+    for (i = 0; i < gamecontroller->num_bindings; ++i) {
+        SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i];
+        if (binding->inputType == SDL_CONTROLLER_BINDTYPE_BUTTON &&
+            button == binding->input.button) {
+            if (binding->outputType == SDL_CONTROLLER_BINDTYPE_AXIS) {
+                int value = state ? binding->output.axis.axis_max : binding->output.axis.axis_min;
+                SDL_PrivateGameControllerAxis(gamecontroller, binding->output.axis.axis, (Sint16)value);
+            } else {
+                SDL_PrivateGameControllerButton(gamecontroller, binding->output.button, state);
+            }
+            break;
+        }
+    }
+}
+
+static void HandleJoystickHat(SDL_GameController *gamecontroller, int hat, Uint8 value)
+{
+    int i;
+    Uint8 last_mask = gamecontroller->last_hat_mask[hat];
+    Uint8 changed_mask = (last_mask ^ value);
+
+    for (i = 0; i < gamecontroller->num_bindings; ++i) {
+        SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i];
+        if (binding->inputType == SDL_CONTROLLER_BINDTYPE_HAT && hat == binding->input.hat.hat) {
+            if ((changed_mask & binding->input.hat.hat_mask) != 0) {
+                if (value & binding->input.hat.hat_mask) {
+                    if (binding->outputType == SDL_CONTROLLER_BINDTYPE_AXIS) {
+                        SDL_PrivateGameControllerAxis(gamecontroller, binding->output.axis.axis, (Sint16)binding->output.axis.axis_max);
+                    } else {
+                        SDL_PrivateGameControllerButton(gamecontroller, binding->output.button, SDL_PRESSED);
+                    }
+                } else {
+                    ResetOutput(gamecontroller, binding);
+                }
+            }
+        }
+    }
+    gamecontroller->last_hat_mask[hat] = value;
+}
+
 /*
  * Event filter to fire controller events from joystick ones
  */
-int SDL_GameControllerEventWatcher(void *userdata, SDL_Event * event)
+static int SDLCALL SDL_GameControllerEventWatcher(void *userdata, SDL_Event * event)
 {
     switch(event->type) {
     case SDL_JOYAXISMOTION:
         {
-            SDL_GameController *controllerlist;
-
-            if (event->jaxis.axis >= k_nMaxReverseEntries)
-            {
-                SDL_SetError("SDL_GameControllerEventWatcher: Axis index %d too large, ignoring motion", (int)event->jaxis.axis);
-                break;
-            }
-
-            controllerlist = SDL_gamecontrollers;
+            SDL_GameController *controllerlist = SDL_gamecontrollers;
             while (controllerlist) {
                 if (controllerlist->joystick->instance_id == event->jaxis.which) {
-                    if (controllerlist->mapping.raxes[event->jaxis.axis] >= 0) /* simple axis to axis, send it through */ {
-                        SDL_GameControllerAxis axis = controllerlist->mapping.raxes[event->jaxis.axis];
-                        Sint16 value = event->jaxis.value;
-                        switch (axis) {
-                            case SDL_CONTROLLER_AXIS_TRIGGERLEFT:
-                            case SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
-                                value = value / 2 + 16384;
-                                break;
-                            default:
-                                break;
-                        }
-                        SDL_PrivateGameControllerAxis(controllerlist, axis, value);
-                    } else if (controllerlist->mapping.raxesasbutton[event->jaxis.axis] >= 0) { /* simulate an axis as a button */
-                        SDL_PrivateGameControllerButton(controllerlist, controllerlist->mapping.raxesasbutton[event->jaxis.axis], ABS(event->jaxis.value) > 32768/2 ? SDL_PRESSED : SDL_RELEASED);
-                    }
+                    HandleJoystickAxis(controllerlist, event->jaxis.axis, event->jaxis.value);
                     break;
                 }
                 controllerlist = controllerlist->next;
@@ -178,22 +351,10 @@ int SDL_GameControllerEventWatcher(void *userdata, SDL_Event * event)
     case SDL_JOYBUTTONDOWN:
     case SDL_JOYBUTTONUP:
         {
-            SDL_GameController *controllerlist;
-
-            if (event->jbutton.button >= k_nMaxReverseEntries)
-            {
-                SDL_SetError("SDL_GameControllerEventWatcher: Button index %d too large, ignoring update", (int)event->jbutton.button);
-                break;
-            }
-
-            controllerlist = SDL_gamecontrollers;
+            SDL_GameController *controllerlist = SDL_gamecontrollers;
             while (controllerlist) {
                 if (controllerlist->joystick->instance_id == event->jbutton.which) {
-                    if (controllerlist->mapping.rbuttons[event->jbutton.button] >= 0) { /* simple button as button */
-                        SDL_PrivateGameControllerButton(controllerlist, controllerlist->mapping.rbuttons[event->jbutton.button], event->jbutton.state);
-                    } else if (controllerlist->mapping.rbuttonasaxis[event->jbutton.button] >= 0) { /* an button pretending to be an axis */
-                        SDL_PrivateGameControllerAxis(controllerlist, controllerlist->mapping.rbuttonasaxis[event->jbutton.button], event->jbutton.state > 0 ? 32767 : 0);
-                    }
+                    HandleJoystickButton(controllerlist, event->jbutton.button, event->jbutton.state);
                     break;
                 }
                 controllerlist = controllerlist->next;
@@ -202,43 +363,10 @@ int SDL_GameControllerEventWatcher(void *userdata, SDL_Event * event)
         break;
     case SDL_JOYHATMOTION:
         {
-            SDL_GameController *controllerlist;
-
-            if (event->jhat.hat >= 4) break;
-
-            controllerlist = SDL_gamecontrollers;
+            SDL_GameController *controllerlist = SDL_gamecontrollers;
             while (controllerlist) {
                 if (controllerlist->joystick->instance_id == event->jhat.which) {
-                    Uint8 bSame = controllerlist->hatState[event->jhat.hat] & event->jhat.value;
-                    /* Get list of removed bits (button release) */
-                    Uint8 bChanged = controllerlist->hatState[event->jhat.hat] ^ bSame;
-                    /* the hat idx in the high nibble */
-                    int bHighHat = event->jhat.hat << 4;
-
-                    if (bChanged & SDL_HAT_DOWN)
-                        SDL_PrivateGameControllerButton(controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_DOWN], SDL_RELEASED);
-                    if (bChanged & SDL_HAT_UP)
-                        SDL_PrivateGameControllerButton(controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_UP], SDL_RELEASED);
-                    if (bChanged & SDL_HAT_LEFT)
-                        SDL_PrivateGameControllerButton(controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_LEFT], SDL_RELEASED);
-                    if (bChanged & SDL_HAT_RIGHT)
-                        SDL_PrivateGameControllerButton(controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_RIGHT], SDL_RELEASED);
-
-                    /* Get list of added bits (button press) */
-                    bChanged = event->jhat.value ^ bSame;
-
-                    if (bChanged & SDL_HAT_DOWN)
-                        SDL_PrivateGameControllerButton(controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_DOWN], SDL_PRESSED);
-                    if (bChanged & SDL_HAT_UP)
-                        SDL_PrivateGameControllerButton(controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_UP], SDL_PRESSED);
-                    if (bChanged & SDL_HAT_LEFT)
-                        SDL_PrivateGameControllerButton(controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_LEFT], SDL_PRESSED);
-                    if (bChanged & SDL_HAT_RIGHT)
-                        SDL_PrivateGameControllerButton(controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_RIGHT], SDL_PRESSED);
-
-                    /* update our state cache */
-                    controllerlist->hatState[event->jhat.hat] = event->jhat.value;
-
+                    HandleJoystickHat(controllerlist, event->jhat.hat, event->jhat.value);
                     break;
                 }
                 controllerlist = controllerlist->next;
@@ -283,7 +411,7 @@ int SDL_GameControllerEventWatcher(void *userdata, SDL_Event * event)
 /*
  * Helper function to scan the mappings database for a controller with the specified GUID
  */
-ControllerMapping_t *SDL_PrivateGetControllerMappingForGUID(SDL_JoystickGUID *guid)
+static ControllerMapping_t *SDL_PrivateGetControllerMappingForGUID(SDL_JoystickGUID *guid)
 {
     ControllerMapping_t *pSupportedController = s_pSupportedControllers;
     while (pSupportedController) {
@@ -311,12 +439,18 @@ static const char* map_StringForControllerAxis[] = {
 SDL_GameControllerAxis SDL_GameControllerGetAxisFromString(const char *pchString)
 {
     int entry;
-    if (!pchString || !pchString[0])
+
+    if (pchString && (*pchString == '+' || *pchString == '-')) {
+        ++pchString;
+    }
+
+    if (!pchString || !pchString[0]) {
         return SDL_CONTROLLER_AXIS_INVALID;
+    }
 
     for (entry = 0; map_StringForControllerAxis[entry]; ++entry) {
         if (!SDL_strcasecmp(pchString, map_StringForControllerAxis[entry]))
-            return entry;
+            return (SDL_GameControllerAxis) entry;
     }
     return SDL_CONTROLLER_AXIS_INVALID;
 }
@@ -362,7 +496,7 @@ SDL_GameControllerButton SDL_GameControllerGetButtonFromString(const char *pchSt
 
     for (entry = 0; map_StringForControllerButton[entry]; ++entry) {
         if (SDL_strcasecmp(pchString, map_StringForControllerButton[entry]) == 0)
-            return entry;
+            return (SDL_GameControllerButton) entry;
     }
     return SDL_CONTROLLER_BUTTON_INVALID;
 }
@@ -381,63 +515,95 @@ const char* SDL_GameControllerGetStringForButton(SDL_GameControllerButton axis)
 /*
  * given a controller button name and a joystick name update our mapping structure with it
  */
-void SDL_PrivateGameControllerParseButton(const char *szGameButton, const char *szJoystickButton, struct _SDL_ControllerMapping *pMapping)
+static void SDL_PrivateGameControllerParseElement(SDL_GameController *gamecontroller, const char *szGameButton, const char *szJoystickButton)
 {
-    int iSDLButton = 0;
+    SDL_ExtendedGameControllerBind bind;
     SDL_GameControllerButton button;
     SDL_GameControllerAxis axis;
-    button = SDL_GameControllerGetButtonFromString(szGameButton);
-    axis = SDL_GameControllerGetAxisFromString(szGameButton);
-    iSDLButton = SDL_atoi(&szJoystickButton[1]);
+    SDL_bool invert_input = SDL_FALSE;
+    char half_axis_input = 0;
+    char half_axis_output = 0;
 
-    if (szJoystickButton[0] == 'a') {
-        if (iSDLButton >= k_nMaxReverseEntries) {
-            SDL_SetError("Axis index too large: %d", iSDLButton);
-            return;
-        }
-        if (axis != SDL_CONTROLLER_AXIS_INVALID) {
-            pMapping->axes[ axis ] = iSDLButton;
-            pMapping->raxes[ iSDLButton ] = axis;
-        } else if (button != SDL_CONTROLLER_BUTTON_INVALID) {
-            pMapping->axesasbutton[ button ] = iSDLButton;
-            pMapping->raxesasbutton[ iSDLButton ] = button;
+    if (*szGameButton == '+' || *szGameButton == '-') {
+        half_axis_output = *szGameButton++;
+    }
+
+    axis = SDL_GameControllerGetAxisFromString(szGameButton);
+    button = SDL_GameControllerGetButtonFromString(szGameButton);
+    if (axis != SDL_CONTROLLER_AXIS_INVALID) {
+        bind.outputType = SDL_CONTROLLER_BINDTYPE_AXIS;
+        bind.output.axis.axis = axis;
+        if (axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT || axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT) {
+            bind.output.axis.axis_min = 0;
+            bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MAX;
         } else {
-            SDL_assert(!"How did we get here?");
+            if (half_axis_output == '+') {
+                bind.output.axis.axis_min = 0;
+                bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MAX;
+            } else if (half_axis_output == '-') {
+                bind.output.axis.axis_min = 0;
+                bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MIN;
+            } else {
+                bind.output.axis.axis_min = SDL_JOYSTICK_AXIS_MIN;
+                bind.output.axis.axis_max = SDL_JOYSTICK_AXIS_MAX;
+            }
         }
+    } else if (button != SDL_CONTROLLER_BUTTON_INVALID) {
+        bind.outputType = SDL_CONTROLLER_BINDTYPE_BUTTON;
+        bind.output.button = button;
+    } else {
+        SDL_SetError("Unexpected controller element %s", szGameButton);
+        return;
+    }
 
-    } else if (szJoystickButton[0] == 'b') {
-        if (iSDLButton >= k_nMaxReverseEntries) {
-            SDL_SetError("Button index too large: %d", iSDLButton);
-            return;
-        }
-        if (button != SDL_CONTROLLER_BUTTON_INVALID) {
-            pMapping->buttons[ button ] = iSDLButton;
-            pMapping->rbuttons[ iSDLButton ] = button;
-        } else if (axis != SDL_CONTROLLER_AXIS_INVALID) {
-            pMapping->buttonasaxis[ axis ] = iSDLButton;
-            pMapping->rbuttonasaxis[ iSDLButton ] = axis;
+    if (*szJoystickButton == '+' || *szJoystickButton == '-') {
+        half_axis_input = *szJoystickButton++;
+    }
+    if (szJoystickButton[SDL_strlen(szJoystickButton) - 1] == '~') {
+        invert_input = SDL_TRUE;
+    }
+
+    if (szJoystickButton[0] == 'a' && SDL_isdigit(szJoystickButton[1])) {
+        bind.inputType = SDL_CONTROLLER_BINDTYPE_AXIS;
+        bind.input.axis.axis = SDL_atoi(&szJoystickButton[1]);
+        if (half_axis_input == '+') {
+            bind.input.axis.axis_min = 0;
+            bind.input.axis.axis_max = SDL_JOYSTICK_AXIS_MAX;
+        } else if (half_axis_input == '-') {
+            bind.input.axis.axis_min = 0;
+            bind.input.axis.axis_max = SDL_JOYSTICK_AXIS_MIN;
         } else {
-            SDL_assert(!"How did we get here?");
+            bind.input.axis.axis_min = SDL_JOYSTICK_AXIS_MIN;
+            bind.input.axis.axis_max = SDL_JOYSTICK_AXIS_MAX;
+        }
+        if (invert_input) {
+            int tmp = bind.input.axis.axis_min;
+            bind.input.axis.axis_min = bind.input.axis.axis_max;
+            bind.input.axis.axis_max = tmp;
         }
-    } else if (szJoystickButton[0] == 'h') {
+    } else if (szJoystickButton[0] == 'b' && SDL_isdigit(szJoystickButton[1])) {
+        bind.inputType = SDL_CONTROLLER_BINDTYPE_BUTTON;
+        bind.input.button = SDL_atoi(&szJoystickButton[1]);
+    } else if (szJoystickButton[0] == 'h' && SDL_isdigit(szJoystickButton[1]) &&
+               szJoystickButton[2] == '.' && SDL_isdigit(szJoystickButton[3])) {
         int hat = SDL_atoi(&szJoystickButton[1]);
         int mask = SDL_atoi(&szJoystickButton[3]);
-        if (hat >= 4) {
-            SDL_SetError("Hat index too large: %d", iSDLButton);
-        }
+        bind.inputType = SDL_CONTROLLER_BINDTYPE_HAT;
+        bind.input.hat.hat = hat;
+        bind.input.hat.hat_mask = mask;
+    } else {
+        SDL_SetError("Unexpected joystick element: %s", szJoystickButton);
+        return;
+    }
 
-        if (button != SDL_CONTROLLER_BUTTON_INVALID) {
-            int ridx;
-            pMapping->hatasbutton[ button ].hat = hat;
-            pMapping->hatasbutton[ button ].mask = mask;
-            ridx = (hat << 4) | mask;
-            pMapping->rhatasbutton[ ridx ] = button;
-        } else if (axis != SDL_CONTROLLER_AXIS_INVALID) {
-            SDL_assert(!"Support hat as axis");
-        } else {
-            SDL_assert(!"How did we get here?");
-        }
+    ++gamecontroller->num_bindings;
+    gamecontroller->bindings = (SDL_ExtendedGameControllerBind *)SDL_realloc(gamecontroller->bindings, gamecontroller->num_bindings * sizeof(*gamecontroller->bindings));
+    if (!gamecontroller->bindings) {
+        gamecontroller->num_bindings = 0;
+        SDL_OutOfMemory();
+        return;
     }
+    gamecontroller->bindings[gamecontroller->num_bindings - 1] = bind;
 }
 
 
@@ -445,7 +611,7 @@ void SDL_PrivateGameControllerParseButton(const char *szGameButton, const char *
  * given a controller mapping string update our mapping object
  */
 static void
-SDL_PrivateGameControllerParseControllerConfigString(struct _SDL_ControllerMapping *pMapping, const char *pchString)
+SDL_PrivateGameControllerParseControllerConfigString(SDL_GameController *gamecontroller, const char *pchString)
 {
     char szGameButton[20];
     char szJoystickButton[20];
@@ -453,8 +619,8 @@ SDL_PrivateGameControllerParseControllerConfigString(struct _SDL_ControllerMappi
     int i = 0;
     const char *pchPos = pchString;
 
-    SDL_memset(szGameButton, 0x0, sizeof(szGameButton));
-    SDL_memset(szJoystickButton, 0x0, sizeof(szJoystickButton));
+    SDL_zero(szGameButton);
+    SDL_zero(szJoystickButton);
 
     while (pchPos && *pchPos) {
         if (*pchPos == ':') {
@@ -465,9 +631,9 @@ SDL_PrivateGameControllerParseControllerConfigString(struct _SDL_ControllerMappi
         } else if (*pchPos == ',') {
             i = 0;
             bGameButton = SDL_TRUE;
-            SDL_PrivateGameControllerParseButton(szGameButton, szJoystickButton, pMapping);
-            SDL_memset(szGameButton, 0x0, sizeof(szGameButton));
-            SDL_memset(szJoystickButton, 0x0, sizeof(szJoystickButton));
+            SDL_PrivateGameControllerParseElement(gamecontroller, szGameButton, szJoystickButton);
+            SDL_zero(szGameButton);
+            SDL_zero(szJoystickButton);
 
         } else if (bGameButton) {
             if (i >= sizeof(szGameButton)) {
@@ -487,50 +653,44 @@ SDL_PrivateGameControllerParseControllerConfigString(struct _SDL_ControllerMappi
         pchPos++;
     }
 
-    SDL_PrivateGameControllerParseButton(szGameButton, szJoystickButton, pMapping);
+    SDL_PrivateGameControllerParseElement(gamecontroller, szGameButton, szJoystickButton);
 
 }
 
 /*
  * Make a new button mapping struct
  */
-void SDL_PrivateLoadButtonMapping(struct _SDL_ControllerMapping *pMapping, SDL_JoystickGUID guid, const char *pchName, const char *pchMapping)
+static void SDL_PrivateLoadButtonMapping(SDL_GameController *gamecontroller, SDL_JoystickGUID guid, const char *pchName, const char *pchMapping)
 {
-    int j;
-
-    pMapping->guid = guid;
-    pMapping->name = pchName;
-
-    /* set all the button mappings to non defaults */
-    for (j = 0; j < SDL_CONTROLLER_AXIS_MAX; j++) {
-        pMapping->axes[j] = -1;
-        pMapping->buttonasaxis[j] = -1;
-    }
-    for (j = 0; j < SDL_CONTROLLER_BUTTON_MAX; j++) {
-        pMapping->buttons[j] = -1;
-        pMapping->axesasbutton[j] = -1;
-        pMapping->hatasbutton[j].hat = -1;
-    }
-
-    for (j = 0; j < k_nMaxReverseEntries; j++) {
-        pMapping->raxes[j] = SDL_CONTROLLER_AXIS_INVALID;
-        pMapping->rbuttonasaxis[j] = SDL_CONTROLLER_AXIS_INVALID;
-        pMapping->rbuttons[j] = SDL_CONTROLLER_BUTTON_INVALID;
-        pMapping->raxesasbutton[j] = SDL_CONTROLLER_BUTTON_INVALID;
-    }
-
-    for (j = 0; j < k_nMaxHatEntries; j++) {
-        pMapping->rhatasbutton[j] = SDL_CONTROLLER_BUTTON_INVALID;
+    int i;
+
+    gamecontroller->guid = guid;
+    gamecontroller->name = pchName;
+    gamecontroller->num_bindings = 0;
+    SDL_memset(gamecontroller->last_match_axis, 0, gamecontroller->joystick->naxes * sizeof(*gamecontroller->last_match_axis));
+
+    SDL_PrivateGameControllerParseControllerConfigString(gamecontroller, pchMapping);
+
+    /* Set the zero point for triggers */
+    for (i = 0; i < gamecontroller->num_bindings; ++i) {
+        SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i];
+        if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS &&
+            binding->outputType == SDL_CONTROLLER_BINDTYPE_AXIS &&
+            (binding->output.axis.axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT ||
+             binding->output.axis.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT)) {
+            if (binding->input.axis.axis < gamecontroller->joystick->naxes) {
+                gamecontroller->joystick->axes[binding->input.axis.axis].value =
+                gamecontroller->joystick->axes[binding->input.axis.axis].zero = (Sint16)binding->input.axis.axis_min;
+            }
+        }
     }
-
-    SDL_PrivateGameControllerParseControllerConfigString(pMapping, pchMapping);
 }
 
 
 /*
  * grab the guid string from a mapping string
  */
-char *SDL_PrivateGetControllerGUIDFromMappingString(const char *pMapping)
+static char *SDL_PrivateGetControllerGUIDFromMappingString(const char *pMapping)
 {
     const char *pFirstComma = SDL_strchr(pMapping, ',');
     if (pFirstComma) {
@@ -540,7 +700,26 @@ char *SDL_PrivateGetControllerGUIDFromMappingString(const char *pMapping)
             return NULL;
         }
         SDL_memcpy(pchGUID, pMapping, pFirstComma - pMapping);
-        pchGUID[ pFirstComma - pMapping ] = 0;
+        pchGUID[pFirstComma - pMapping] = '\0';
+
+        /* Convert old style GUIDs to the new style in 2.0.5 */
+#if __WIN32__
+        if (SDL_strlen(pchGUID) == 32 &&
+            SDL_memcmp(&pchGUID[20], "504944564944", 12) == 0) {
+            SDL_memcpy(&pchGUID[20], "000000000000", 12);
+            SDL_memcpy(&pchGUID[16], &pchGUID[4], 4);
+            SDL_memcpy(&pchGUID[8], &pchGUID[0], 4);
+            SDL_memcpy(&pchGUID[0], "03000000", 8);
+        }
+#elif __MACOSX__
+        if (SDL_strlen(pchGUID) == 32 &&
+            SDL_memcmp(&pchGUID[4], "000000000000", 12) == 0 &&
+            SDL_memcmp(&pchGUID[20], "000000000000", 12) == 0) {
+            SDL_memcpy(&pchGUID[20], "000000000000", 12);
+            SDL_memcpy(&pchGUID[8], &pchGUID[0], 4);
+            SDL_memcpy(&pchGUID[0], "03000000", 8);
+        }
+#endif
         return pchGUID;
     }
     return NULL;
@@ -550,7 +729,7 @@ char *SDL_PrivateGetControllerGUIDFromMappingString(const char *pMapping)
 /*
  * grab the name string from a mapping string
  */
-char *SDL_PrivateGetControllerNameFromMappingString(const char *pMapping)
+static char *SDL_PrivateGetControllerNameFromMappingString(const char *pMapping)
 {
     const char *pFirstComma, *pSecondComma;
     char *pchName;
@@ -569,7 +748,7 @@ char *SDL_PrivateGetControllerNameFromMappingString(const char *pMapping)
         return NULL;
     }
     SDL_memcpy(pchName, pFirstComma + 1, pSecondComma - pFirstComma);
-    pchName[ pSecondComma - pFirstComma - 1 ] = 0;
+    pchName[pSecondComma - pFirstComma - 1] = 0;
     return pchName;
 }
 
@@ -577,7 +756,7 @@ char *SDL_PrivateGetControllerNameFromMappingString(const char *pMapping)
 /*
  * grab the button mapping string from a mapping string
  */
-char *SDL_PrivateGetControllerMappingFromMappingString(const char *pMapping)
+static char *SDL_PrivateGetControllerMappingFromMappingString(const char *pMapping)
 {
     const char *pFirstComma, *pSecondComma;
 
@@ -595,18 +774,18 @@ char *SDL_PrivateGetControllerMappingFromMappingString(const char *pMapping)
 /*
  * Helper function to refresh a mapping
  */
-void SDL_PrivateGameControllerRefreshMapping(ControllerMapping_t *pControllerMapping)
+static void SDL_PrivateGameControllerRefreshMapping(ControllerMapping_t *pControllerMapping)
 {
     SDL_GameController *gamecontrollerlist = SDL_gamecontrollers;
     while (gamecontrollerlist) {
-        if (!SDL_memcmp(&gamecontrollerlist->mapping.guid, &pControllerMapping->guid, sizeof(pControllerMapping->guid))) {
+        if (!SDL_memcmp(&gamecontrollerlist->guid, &pControllerMapping->guid, sizeof(pControllerMapping->guid))) {
             SDL_Event event;
             event.type = SDL_CONTROLLERDEVICEREMAPPED;
             event.cdevice.which = gamecontrollerlist->joystick->instance_id;
             SDL_PushEvent(&event);
 
             /* Not really threadsafe.  Should this lock access within SDL_GameControllerEventWatcher? */
-            SDL_PrivateLoadButtonMapping(&gamecontrollerlist->mapping, pControllerMapping->guid, pControllerMapping->name, pControllerMapping->mapping);
+            SDL_PrivateLoadButtonMapping(gamecontrollerlist, pControllerMapping->guid, pControllerMapping->name, pControllerMapping->mapping);
         }
 
         gamecontrollerlist = gamecontrollerlist->next;
@@ -617,7 +796,7 @@ void SDL_PrivateGameControllerRefreshMapping(ControllerMapping_t *pControllerMap
  * Helper function to add a mapping for a guid
  */
 static ControllerMapping_t *
-SDL_PrivateAddMappingForGUID(SDL_JoystickGUID jGUID, const char *mappingString, SDL_bool *existing)
+SDL_PrivateAddMappingForGUID(SDL_JoystickGUID jGUID, const char *mappingString, SDL_bool *existing, SDL_ControllerMappingPriority priority)
 {
     char *pchName;
     char *pchMapping;
@@ -638,13 +817,20 @@ SDL_PrivateAddMappingForGUID(SDL_JoystickGUID jGUID, const char *mappingString,
 
     pControllerMapping = SDL_PrivateGetControllerMappingForGUID(&jGUID);
     if (pControllerMapping) {
-        /* Update existing mapping */
-        SDL_free(pControllerMapping->name);
-        pControllerMapping->name = pchName;
-        SDL_free(pControllerMapping->mapping);
-        pControllerMapping->mapping = pchMapping;
-        /* refresh open controllers */
-        SDL_PrivateGameControllerRefreshMapping(pControllerMapping);
+        /* Only overwrite the mapping if the priority is the same or higher. */
+        if (pControllerMapping->priority <= priority) {
+            /* Update existing mapping */
+            SDL_free(pControllerMapping->name);
+            pControllerMapping->name = pchName;
+            SDL_free(pControllerMapping->mapping);
+            pControllerMapping->mapping = pchMapping;
+            pControllerMapping->priority = priority;
+            /* refresh open controllers */
+            SDL_PrivateGameControllerRefreshMapping(pControllerMapping);
+        } else {
+            SDL_free(pchName);
+            SDL_free(pchMapping);
+        }
         *existing = SDL_TRUE;
     } else {
         pControllerMapping = SDL_malloc(sizeof(*pControllerMapping));
@@ -657,8 +843,22 @@ SDL_PrivateAddMappingForGUID(SDL_JoystickGUID jGUID, const char *mappingString,
         pControllerMapping->guid = jGUID;
         pControllerMapping->name = pchName;
         pControllerMapping->mapping = pchMapping;
-        pControllerMapping->next = s_pSupportedControllers;
-        s_pSupportedControllers = pControllerMapping;
+        pControllerMapping->next = NULL;
+        pControllerMapping->priority = priority;
+
+        if (s_pSupportedControllers) {
+            /* Add the mapping to the end of the list */
+            ControllerMapping_t *pCurrMapping, *pPrevMapping;
+
+            for ( pPrevMapping = s_pSupportedControllers, pCurrMapping = pPrevMapping->next;
+                  pCurrMapping; 
+                  pPrevMapping = pCurrMapping, pCurrMapping = pCurrMapping->next ) {
+                continue;
+            }
+            pPrevMapping->next = pControllerMapping;
+        } else {
+            s_pSupportedControllers = pControllerMapping;
+        }
         *existing = SDL_FALSE;
     }
     return pControllerMapping;
@@ -667,48 +867,51 @@ SDL_PrivateAddMappingForGUID(SDL_JoystickGUID jGUID, const char *mappingString,
 /*
  * Helper function to determine pre-calculated offset to certain joystick mappings
  */
-ControllerMapping_t *SDL_PrivateGetControllerMapping(int device_index)
+static ControllerMapping_t *SDL_PrivateGetControllerMappingForNameAndGUID(const char *name, SDL_JoystickGUID guid)
 {
-    SDL_JoystickGUID jGUID = SDL_JoystickGetDeviceGUID(device_index);
     ControllerMapping_t *mapping;
 
-    mapping = SDL_PrivateGetControllerMappingForGUID(&jGUID);
-#if SDL_JOYSTICK_XINPUT
-    if (!mapping && SDL_SYS_IsXInputGamepad_DeviceIndex(device_index)) {
-        mapping = s_pXInputMapping;
-    }
-#endif
+    mapping = SDL_PrivateGetControllerMappingForGUID(&guid);
 #if defined(SDL_JOYSTICK_EMSCRIPTEN)
     if (!mapping && s_pEmscriptenMapping) {
         mapping = s_pEmscriptenMapping;
     }
+#else
+    (void) s_pEmscriptenMapping;  /* pacify ARMCC */
 #endif
 #ifdef __LINUX__
-    if (!mapping) {
-        const char *name = SDL_JoystickNameForIndex(device_index);
-        if (name) {
-            if (SDL_strstr(name, "Xbox 360 Wireless Receiver")) {
-                /* The Linux driver xpad.c maps the wireless dpad to buttons */
-                SDL_bool existing;
-                mapping = SDL_PrivateAddMappingForGUID(jGUID,
+    if (!mapping && name) {
+        if (SDL_strstr(name, "Xbox 360 Wireless Receiver")) {
+            /* The Linux driver xpad.c maps the wireless dpad to buttons */
+            SDL_bool existing;
+            mapping = SDL_PrivateAddMappingForGUID(guid,
 "none,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
-                              &existing);
-            }
+                          &existing, SDL_CONTROLLER_MAPPING_PRIORITY_DEFAULT);
         }
     }
 #endif /* __LINUX__ */
 
-    if (!mapping) {
-        const char *name = SDL_JoystickNameForIndex(device_index);
-        if (name) {
-            if (SDL_strstr(name, "Xbox") || SDL_strstr(name, "X-Box")) {
-                mapping = s_pXInputMapping;
-            }
+    if (!mapping && name) {
+        if (SDL_strstr(name, "Xbox") || SDL_strstr(name, "X-Box") || SDL_strstr(name, "XBOX")) {
+            mapping = s_pXInputMapping;
         }
     }
     return mapping;
 }
 
+static ControllerMapping_t *SDL_PrivateGetControllerMapping(int device_index)
+{
+    const char *name = SDL_JoystickNameForIndex(device_index);
+    SDL_JoystickGUID guid = SDL_JoystickGetDeviceGUID(device_index);
+    ControllerMapping_t *mapping = SDL_PrivateGetControllerMappingForNameAndGUID(name, guid);
+#if SDL_JOYSTICK_XINPUT
+    if (!mapping && SDL_SYS_IsXInputGamepad_DeviceIndex(device_index)) {
+        mapping = s_pXInputMapping;
+    }
+#endif
+    return mapping;
+}
+
 /*
  * Add or update an entry into the Mappings Database
  */
@@ -781,10 +984,10 @@ SDL_GameControllerAddMappingsFromRW(SDL_RWops * rw, int freerw)
 }
 
 /*
- * Add or update an entry into the Mappings Database
+ * Add or update an entry into the Mappings Database with a priority
  */
-int
-SDL_GameControllerAddMapping(const char *mappingString)
+static int
+SDL_PrivateGameControllerAddMapping(const char *mappingString, SDL_ControllerMappingPriority priority)
 {
     char *pchGUID;
     SDL_JoystickGUID jGUID;
@@ -810,7 +1013,7 @@ SDL_GameControllerAddMapping(const char *mappingString)
     jGUID = SDL_JoystickGetGUIDFromString(pchGUID);
     SDL_free(pchGUID);
 
-    pControllerMapping = SDL_PrivateAddMappingForGUID(jGUID, mappingString, &existing);
+    pControllerMapping = SDL_PrivateAddMappingForGUID(jGUID, mappingString, &existing, priority);
     if (!pControllerMapping) {
         return -1;
     }
@@ -829,6 +1032,66 @@ SDL_GameControllerAddMapping(const char *mappingString)
 }
 
 /*
+ * Add or update an entry into the Mappings Database
+ */
+int
+SDL_GameControllerAddMapping(const char *mappingString)
+{
+    return SDL_PrivateGameControllerAddMapping(mappingString, SDL_CONTROLLER_MAPPING_PRIORITY_API);
+}
+
+/*
+ *  Get the number of mappings installed
+ */
+int
+SDL_GameControllerNumMappings(void)
+{
+    int num_mappings = 0;
+    ControllerMapping_t *mapping;
+
+    for (mapping = s_pSupportedControllers; mapping; mapping = mapping->next) {
+        if (SDL_memcmp(&mapping->guid, &s_zeroGUID, sizeof(mapping->guid)) == 0) {
+            continue;
+        }
+        ++num_mappings;
+    }
+    return num_mappings;
+}
+
+/*
+ *  Get the mapping at a particular index.
+ */
+char *
+SDL_GameControllerMappingForIndex(int mapping_index)
+{
+    ControllerMapping_t *mapping;
+
+    for (mapping = s_pSupportedControllers; mapping; mapping = mapping->next) {
+        if (SDL_memcmp(&mapping->guid, &s_zeroGUID, sizeof(mapping->guid)) == 0) {
+            continue;
+        }
+        if (mapping_index == 0) {
+            char *pMappingString;
+            char pchGUID[33];
+            size_t needed;
+
+            SDL_JoystickGetGUIDString(mapping->guid, pchGUID, sizeof(pchGUID));
+            /* allocate enough memory for GUID + ',' + name + ',' + mapping + \0 */
+            needed = SDL_strlen(pchGUID) + 1 + SDL_strlen(mapping->name) + 1 + SDL_strlen(mapping->mapping) + 1;
+            pMappingString = SDL_malloc(needed);
+            if (!pMappingString) {
+                SDL_OutOfMemory();
+                return NULL;
+            }
+            SDL_snprintf(pMappingString, needed, "%s,%s,%s", pchGUID, mapping->name, mapping->mapping);
+            return pMappingString;
+        }
+        --mapping_index;
+    }
+    return NULL;
+}
+
+/*
  * Get the mapping string for this GUID
  */
 char *
@@ -862,7 +1125,7 @@ SDL_GameControllerMapping(SDL_GameController * gamecontroller)
         return NULL;
     }
 
-    return SDL_GameControllerMappingForGUID(gamecontroller->mapping.guid);
+    return SDL_GameControllerMappingForGUID(gamecontroller->guid);
 }
 
 static void
@@ -882,7 +1145,7 @@ SDL_GameControllerLoadHints()
             if (pchNewLine)
                 *pchNewLine = '\0';
 
-            SDL_GameControllerAddMapping(pUserMappings);
+            SDL_PrivateGameControllerAddMapping(pUserMappings, SDL_CONTROLLER_MAPPING_PRIORITY_USER);
 
             if (pchNewLine) {
                 pUserMappings = pchNewLine + 1;
@@ -898,13 +1161,13 @@ SDL_GameControllerLoadHints()
  * Initialize the game controller system, mostly load our DB of controller config mappings
  */
 int
-SDL_GameControllerInit(void)
+SDL_GameControllerInitMappings(void)
 {
     int i = 0;
     const char *pMappingString = NULL;
     pMappingString = s_ControllerMappings[i];
     while (pMappingString) {
-        SDL_GameControllerAddMapping(pMappingString);
+        SDL_PrivateGameControllerAddMapping(pMappingString, SDL_CONTROLLER_MAPPING_PRIORITY_DEFAULT);
 
         i++;
         pMappingString = s_ControllerMappings[i];
@@ -913,6 +1176,19 @@ SDL_GameControllerInit(void)
     /* load in any user supplied config */
     SDL_GameControllerLoadHints();
 
+    SDL_AddHintCallback(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES,
+                        SDL_GameControllerIgnoreDevicesChanged, NULL);
+    SDL_AddHintCallback(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT,
+                        SDL_GameControllerIgnoreDevicesExceptChanged, NULL);
+
+    return (0);
+}
+
+int
+SDL_GameControllerInit(void)
+{
+    int i;
+
     /* watch for joy events and fire controller ones if needed */
     SDL_AddEventWatch(SDL_GameControllerEventWatcher, NULL);
 
@@ -936,7 +1212,7 @@ SDL_GameControllerInit(void)
 const char *
 SDL_GameControllerNameForIndex(int device_index)
 {
-    ControllerMapping_t *pSupportedController =  SDL_PrivateGetControllerMapping(device_index);
+    ControllerMapping_t *pSupportedController = SDL_PrivateGetControllerMapping(device_index);
     if (pSupportedController) {
         return pSupportedController->name;
     }
@@ -945,20 +1221,83 @@ SDL_GameControllerNameForIndex(int device_index)
 
 
 /*
+ * Return 1 if the joystick with this name and GUID is a supported controller
+ */
+SDL_bool
+SDL_IsGameControllerNameAndGUID(const char *name, SDL_JoystickGUID guid)
+{
+    ControllerMapping_t *pSupportedController = SDL_PrivateGetControllerMappingForNameAndGUID(name, guid);
+    if (pSupportedController) {
+        return SDL_TRUE;
+    }
+    return SDL_FALSE;
+}
+
+/*
  * Return 1 if the joystick at this device index is a supported controller
  */
 SDL_bool
 SDL_IsGameController(int device_index)
 {
-    ControllerMapping_t *pSupportedController =  SDL_PrivateGetControllerMapping(device_index);
+    ControllerMapping_t *pSupportedController = SDL_PrivateGetControllerMapping(device_index);
     if (pSupportedController) {
         return SDL_TRUE;
     }
-
     return SDL_FALSE;
 }
 
 /*
+ * Return 1 if the game controller should be ignored by SDL
+ */
+SDL_bool SDL_ShouldIgnoreGameController(const char *name, SDL_JoystickGUID guid)
+{
+    int i;
+    Uint16 vendor;
+    Uint16 product;
+    Uint32 vidpid;
+
+    if (SDL_allowed_controllers.num_entries == 0 &&
+        SDL_ignored_controllers.num_entries == 0) {
+        return SDL_FALSE;
+    }
+
+    SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL);
+    vidpid = MAKE_VIDPID(vendor, product);
+
+    if (SDL_GetHintBoolean("SDL_GAMECONTROLLER_ALLOW_STEAM_VIRTUAL_GAMEPAD", SDL_FALSE)) {
+        /* We shouldn't ignore Steam's virtual gamepad since it's using the hints to filter out the real controllers so it can remap input for the virtual controller */
+        SDL_bool bSteamVirtualGamepad = SDL_FALSE;
+#if defined(__LINUX__)
+        bSteamVirtualGamepad = (vendor == 0x28DE && product == 0x11FF);
+#elif defined(__MACOSX__)
+        bSteamVirtualGamepad = (SDL_strncmp(name, "GamePad-", 8) == 0);
+#elif defined(__WIN32__)
+        /* We can't tell on Windows, but Steam will block others in input hooks */
+        bSteamVirtualGamepad = SDL_TRUE;
+#endif
+        if (bSteamVirtualGamepad) {
+            return SDL_FALSE;
+        }
+    }
+
+    if (SDL_allowed_controllers.num_entries > 0) {
+        for (i = 0; i < SDL_allowed_controllers.num_entries; ++i) {
+            if (vidpid == SDL_allowed_controllers.entries[i]) {
+                return SDL_FALSE;
+            }
+        }
+        return SDL_TRUE;
+    } else {
+        for (i = 0; i < SDL_ignored_controllers.num_entries; ++i) {
+            if (vidpid == SDL_ignored_controllers.entries[i]) {
+                return SDL_TRUE;
+            }
+        }
+        return SDL_FALSE;
+    }
+}
+
+/*
  * Open a controller for use - the index passed as an argument refers to
  * the N'th controller on the system.  This index is the value which will
  * identify this controller in future controller events.
@@ -977,12 +1316,15 @@ SDL_GameControllerOpen(int device_index)
         return (NULL);
     }
 
+    SDL_LockJoystickList();
+
     gamecontrollerlist = SDL_gamecontrollers;
     /* If the controller is already open, return it */
     while (gamecontrollerlist) {
         if (SDL_SYS_GetInstanceIdOfDeviceIndex(device_index) == gamecontrollerlist->joystick->instance_id) {
                 gamecontroller = gamecontrollerlist;
                 ++gamecontroller->ref_count;
+                SDL_UnlockJoystickList();
                 return (gamecontroller);
         }
         gamecontrollerlist = gamecontrollerlist->next;
@@ -992,46 +1334,56 @@ SDL_GameControllerOpen(int device_index)
     pSupportedController =  SDL_PrivateGetControllerMapping(device_index);
     if (!pSupportedController) {
         SDL_SetError("Couldn't find mapping for device (%d)", device_index);
-        return (NULL);
+        SDL_UnlockJoystickList();
+        return NULL;
     }
 
-    /* Create and initialize the joystick */
-    gamecontroller = (SDL_GameController *) SDL_malloc((sizeof *gamecontroller));
+    /* Create and initialize the controller */
+    gamecontroller = (SDL_GameController *) SDL_calloc(1, sizeof(*gamecontroller));
     if (gamecontroller == NULL) {
         SDL_OutOfMemory();
+        SDL_UnlockJoystickList();
         return NULL;
     }
 
-    SDL_memset(gamecontroller, 0, (sizeof *gamecontroller));
     gamecontroller->joystick = SDL_JoystickOpen(device_index);
     if (!gamecontroller->joystick) {
         SDL_free(gamecontroller);
+        SDL_UnlockJoystickList();
         return NULL;
     }
 
-    SDL_PrivateLoadButtonMapping(&gamecontroller->mapping, pSupportedController->guid, pSupportedController->name, pSupportedController->mapping);
-
-    /* The triggers are mapped from -32768 to 32767, where -32768 is the 'unpressed' value */
-    {
-        int leftTriggerMapping = gamecontroller->mapping.axes[SDL_CONTROLLER_AXIS_TRIGGERLEFT];
-        int rightTriggerMapping = gamecontroller->mapping.axes[SDL_CONTROLLER_AXIS_TRIGGERRIGHT];
-        if (leftTriggerMapping >= 0) {
-            gamecontroller->joystick->axes[leftTriggerMapping] =
-            gamecontroller->joystick->axes_zero[leftTriggerMapping] = (Sint16)-32768;
+    if (gamecontroller->joystick->naxes) {
+        gamecontroller->last_match_axis = (SDL_ExtendedGameControllerBind **)SDL_calloc(gamecontroller->joystick->naxes, sizeof(*gamecontroller->last_match_axis));
+        if (!gamecontroller->last_match_axis) {
+            SDL_OutOfMemory();
+            SDL_JoystickClose(gamecontroller->joystick);
+            SDL_free(gamecontroller);
+            SDL_UnlockJoystickList();
+            return NULL;
         }
-        if (rightTriggerMapping >= 0) {
-            gamecontroller->joystick->axes[rightTriggerMapping] =
-            gamecontroller->joystick->axes_zero[rightTriggerMapping] = (Sint16)-32768;
+    }
+    if (gamecontroller->joystick->nhats) {
+        gamecontroller->last_hat_mask = (Uint8 *)SDL_calloc(gamecontroller->joystick->nhats, sizeof(*gamecontroller->last_hat_mask));
+        if (!gamecontroller->last_hat_mask) {
+            SDL_OutOfMemory();
+            SDL_JoystickClose(gamecontroller->joystick);
+            SDL_free(gamecontroller->last_match_axis);
+            SDL_free(gamecontroller);
+            SDL_UnlockJoystickList();
+            return NULL;
         }
     }
 
-    /* Add joystick to list */
+    SDL_PrivateLoadButtonMapping(gamecontroller, pSupportedController->guid, pSupportedController->name, pSupportedController->mapping);
+
+    /* Add the controller to list */
     ++gamecontroller->ref_count;
-    /* Link the joystick in the list */
+    /* Link the controller in the list */
     gamecontroller->next = SDL_gamecontrollers;
     SDL_gamecontrollers = gamecontroller;
 
-    SDL_SYS_JoystickUpdate(gamecontroller->joystick);
+    SDL_UnlockJoystickList();
 
     return (gamecontroller);
 }
@@ -1046,69 +1398,133 @@ SDL_GameControllerUpdate(void)
     SDL_JoystickUpdate();
 }
 
-
 /*
  * Get the current state of an axis control on a controller
  */
 Sint16
 SDL_GameControllerGetAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis)
 {
+    int i;
+
     if (!gamecontroller)
         return 0;
 
-    if (gamecontroller->mapping.axes[axis] >= 0) {
-        Sint16 value = (SDL_JoystickGetAxis(gamecontroller->joystick, gamecontroller->mapping.axes[axis]));
-        switch (axis) {
-            case SDL_CONTROLLER_AXIS_TRIGGERLEFT:
-            case SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
-                /* Shift it to be 0 - 32767 */
-                value = value / 2 + 16384;
-            default:
-                break;
+    for (i = 0; i < gamecontroller->num_bindings; ++i) {
+        SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i];
+        if (binding->outputType == SDL_CONTROLLER_BINDTYPE_AXIS && binding->output.axis.axis == axis) {
+            int value = 0;
+            SDL_bool valid_input_range;
+            SDL_bool valid_output_range;
+
+            if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS) {
+                value = SDL_JoystickGetAxis(gamecontroller->joystick, binding->input.axis.axis);
+                if (binding->input.axis.axis_min < binding->input.axis.axis_max) {
+                    valid_input_range = (value >= binding->input.axis.axis_min && value <= binding->input.axis.axis_max);
+                } else {
+                    valid_input_range = (value >= binding->input.axis.axis_max && value <= binding->input.axis.axis_min);
+                }
+                if (valid_input_range) {
+                    if (binding->input.axis.axis_min != binding->output.axis.axis_min || binding->input.axis.axis_max != binding->output.axis.axis_max) {
+                        float normalized_value = (float)(value - binding->input.axis.axis_min) / (binding->input.axis.axis_max - binding->input.axis.axis_min);
+                        value = binding->output.axis.axis_min + (int)(normalized_value * (binding->output.axis.axis_max - binding->output.axis.axis_min));
+                    }
+                }
+            } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_BUTTON) {
+                value = SDL_JoystickGetButton(gamecontroller->joystick, binding->input.button);
+                if (value == SDL_PRESSED) {
+                    value = binding->output.axis.axis_max;
+                }
+            } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_HAT) {
+                int hat_mask = SDL_JoystickGetHat(gamecontroller->joystick, binding->input.hat.hat);
+                if (hat_mask & binding->input.hat.hat_mask) {
+                    value = binding->output.axis.axis_max;
+                }
+            }
+
+            if (binding->output.axis.axis_min < binding->output.axis.axis_max) {
+                valid_output_range = (value >= binding->output.axis.axis_min && value <= binding->output.axis.axis_max);
+            } else {
+                valid_output_range = (value >= binding->output.axis.axis_max && value <= binding->output.axis.axis_min);
+            }
+            /* If the value is zero, there might be another binding that makes it non-zero */
+            if (value != 0 && valid_output_range) {
+                return (Sint16)value;
+            }
         }
-        return value;
-    } else if (gamecontroller->mapping.buttonasaxis[axis] >= 0) {
-        Uint8 value;
-        value = SDL_JoystickGetButton(gamecontroller->joystick, gamecontroller->mapping.buttonasaxis[axis]);
-        if (value > 0)
-            return 32767;
-        return 0;
     }
     return 0;
 }
 
-
 /*
  * Get the current state of a button on a controller
  */
 Uint8
 SDL_GameControllerGetButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button)
 {
-    if (!gamecontroller)
-        return 0;
+    int i;
 
-    if (gamecontroller->mapping.buttons[button] >= 0) {
-        return (SDL_JoystickGetButton(gamecontroller->joystick, gamecontroller->mapping.buttons[button]));
-    } else if (gamecontroller->mapping.axesasbutton[button] >= 0) {
-        Sint16 value;
-        value = SDL_JoystickGetAxis(gamecontroller->joystick, gamecontroller->mapping.axesasbutton[button]);
-        if (ABS(value) > 32768/2)
-            return 1;
+    if (!gamecontroller)
         return 0;
-    } else if (gamecontroller->mapping.hatasbutton[button].hat >= 0) {
-        Uint8 value;
-        value = SDL_JoystickGetHat(gamecontroller->joystick, gamecontroller->mapping.hatasbutton[button].hat);
 
-        if (value & gamecontroller->mapping.hatasbutton[button].mask)
-            return 1;
-        return 0;
+    for (i = 0; i < gamecontroller->num_bindings; ++i) {
+        SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i];
+        if (binding->outputType == SDL_CONTROLLER_BINDTYPE_BUTTON && binding->output.button == button) {
+            if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS) {
+                SDL_bool valid_input_range;
+
+                int value = SDL_JoystickGetAxis(gamecontroller->joystick, binding->input.axis.axis);
+                int threshold = binding->input.axis.axis_min + (binding->input.axis.axis_max - binding->input.axis.axis_min) / 2;
+                if (binding->input.axis.axis_min < binding->input.axis.axis_max) {
+                    valid_input_range = (value >= binding->input.axis.axis_min && value <= binding->input.axis.axis_max);
+                    if (valid_input_range) {
+                        return (value >= threshold) ? SDL_PRESSED : SDL_RELEASED;
+                    }
+                } else {
+                    valid_input_range = (value >= binding->input.axis.axis_max && value <= binding->input.axis.axis_min);
+                    if (valid_input_range) {
+                        return (value <= threshold) ? SDL_PRESSED : SDL_RELEASED;
+                    }
+                }
+            } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_BUTTON) {
+                return SDL_JoystickGetButton(gamecontroller->joystick, binding->input.button);
+            } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_HAT) {
+                int hat_mask = SDL_JoystickGetHat(gamecontroller->joystick, binding->input.hat.hat);
+                return (hat_mask & binding->input.hat.hat_mask) ? SDL_PRESSED : SDL_RELEASED;
+            }
+        }
     }
+    return SDL_RELEASED;
+}
 
-    return 0;
+const char *
+SDL_GameControllerName(SDL_GameController * gamecontroller)
+{
+    if (!gamecontroller)
+        return NULL;
+
+    return gamecontroller->name;
+}
+
+Uint16
+SDL_GameControllerGetVendor(SDL_GameController * gamecontroller)
+{
+    return SDL_JoystickGetVendor(SDL_GameControllerGetJoystick(gamecontroller));
+}
+
+Uint16
+SDL_GameControllerGetProduct(SDL_GameController * gamecontroller)
+{
+    return SDL_JoystickGetProduct(SDL_GameControllerGetJoystick(gamecontroller));
+}
+
+Uint16
+SDL_GameControllerGetProductVersion(SDL_GameController * gamecontroller)
+{
+    return SDL_JoystickGetProductVersion(SDL_GameControllerGetJoystick(gamecontroller));
 }
 
 /*
- * Return if the joystick in question is currently attached to the system,
+ * Return if the controller in question is currently attached to the system,
  *  \return 0 if not plugged in, 1 if still present.
  */
 SDL_bool
@@ -1120,17 +1536,6 @@ SDL_GameControllerGetAttached(SDL_GameController * gamecontroller)
     return SDL_JoystickGetAttached(gamecontroller->joystick);
 }
 
-
-const char *
-SDL_GameControllerName(SDL_GameController * gamecontroller)
-{
-    if (!gamecontroller)
-        return NULL;
-
-    return (gamecontroller->mapping.name);
-}
-
-
 /*
  * Get the joystick for this controller
  */
@@ -1149,64 +1554,81 @@ SDL_Joystick *SDL_GameControllerGetJoystick(SDL_GameController * gamecontroller)
 SDL_GameController *
 SDL_GameControllerFromInstanceID(SDL_JoystickID joyid)
 {
-    SDL_GameController *gamecontroller = SDL_gamecontrollers;
+    SDL_GameController *gamecontroller;
+
+    SDL_LockJoystickList();
+    gamecontroller = SDL_gamecontrollers;
     while (gamecontroller) {
         if (gamecontroller->joystick->instance_id == joyid) {
+            SDL_UnlockJoystickList();
             return gamecontroller;
         }
         gamecontroller = gamecontroller->next;
     }
-
+    SDL_UnlockJoystickList();
     return NULL;
 }
 
 
-/**
+/*
  * Get the SDL joystick layer binding for this controller axis mapping
  */
 SDL_GameControllerButtonBind SDL_GameControllerGetBindForAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis)
 {
+    int i;
     SDL_GameControllerButtonBind bind;
-    SDL_memset(&bind, 0x0, sizeof(bind));
+    SDL_zero(bind);
 
     if (!gamecontroller || axis == SDL_CONTROLLER_AXIS_INVALID)
         return bind;
 
-    if (gamecontroller->mapping.axes[axis] >= 0) {
-        bind.bindType = SDL_CONTROLLER_BINDTYPE_AXIS;
-        bind.value.button = gamecontroller->mapping.axes[axis];
-    } else if (gamecontroller->mapping.buttonasaxis[axis] >= 0) {
-        bind.bindType = SDL_CONTROLLER_BINDTYPE_BUTTON;
-        bind.value.button = gamecontroller->mapping.buttonasaxis[axis];
+    for (i = 0; i < gamecontroller->num_bindings; ++i) {
+        SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i];
+        if (binding->outputType == SDL_CONTROLLER_BINDTYPE_AXIS && binding->output.axis.axis == axis) {
+            bind.bindType = binding->inputType;
+            if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS) {
+                /* FIXME: There might be multiple axes bound now that we have axis ranges... */
+                bind.value.axis = binding->input.axis.axis;
+            } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_BUTTON) {
+                bind.value.button = binding->input.button;
+            } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_HAT) {
+                bind.value.hat.hat = binding->input.hat.hat;
+                bind.value.hat.hat_mask = binding->input.hat.hat_mask;
+            }
+            break;
+        }
     }
-
     return bind;
 }
 
 
-/**
+/*
  * Get the SDL joystick layer binding for this controller button mapping
  */
 SDL_GameControllerButtonBind SDL_GameControllerGetBindForButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button)
 {
+    int i;
     SDL_GameControllerButtonBind bind;
-    SDL_memset(&bind, 0x0, sizeof(bind));
+    SDL_zero(bind);
 
     if (!gamecontroller || button == SDL_CONTROLLER_BUTTON_INVALID)
         return bind;
 
-    if (gamecontroller->mapping.buttons[button] >= 0) {
-        bind.bindType = SDL_CONTROLLER_BINDTYPE_BUTTON;
-        bind.value.button = gamecontroller->mapping.buttons[button];
-    } else if (gamecontroller->mapping.axesasbutton[button] >= 0) {
-        bind.bindType = SDL_CONTROLLER_BINDTYPE_AXIS;
-        bind.value.axis = gamecontroller->mapping.axesasbutton[button];
-    } else if (gamecontroller->mapping.hatasbutton[button].hat >= 0) {
-        bind.bindType = SDL_CONTROLLER_BINDTYPE_HAT;
-        bind.value.hat.hat = gamecontroller->mapping.hatasbutton[button].hat;
-        bind.value.hat.hat_mask = gamecontroller->mapping.hatasbutton[button].mask;
+    for (i = 0; i < gamecontroller->num_bindings; ++i) {
+        SDL_ExtendedGameControllerBind *binding = &gamecontroller->bindings[i];
+        if (binding->outputType == SDL_CONTROLLER_BINDTYPE_BUTTON && binding->output.button == button) {
+            bind.bindType = binding->inputType;
+            if (binding->inputType == SDL_CONTROLLER_BINDTYPE_AXIS) {
+                bind.value.axis = binding->input.axis.axis;
+            } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_BUTTON) {
+                bind.value.button = binding->input.button;
+            } else if (binding->inputType == SDL_CONTROLLER_BINDTYPE_HAT) {
+                bind.value.hat.hat = binding->input.hat.hat;
+                bind.value.hat.hat_mask = binding->input.hat.hat_mask;
+            }
+            break;
+        }
     }
-
     return bind;
 }
 
@@ -1219,8 +1641,11 @@ SDL_GameControllerClose(SDL_GameController * gamecontroller)
     if (!gamecontroller)
         return;
 
+    SDL_LockJoystickList();
+
     /* First decrement ref count */
     if (--gamecontroller->ref_count > 0) {
+        SDL_UnlockJoystickList();
         return;
     }
 
@@ -1236,14 +1661,18 @@ SDL_GameControllerClose(SDL_GameController * gamecontroller)
             } else {
                 SDL_gamecontrollers = gamecontroller->next;
             }
-
             break;
         }
         gamecontrollerlistprev = gamecontrollerlist;
         gamecontrollerlist = gamecontrollerlist->next;
     }
 
+    SDL_free(gamecontroller->bindings);
+    SDL_free(gamecontroller->last_match_axis);
+    SDL_free(gamecontroller->last_hat_mask);
     SDL_free(gamecontroller);
+
+    SDL_UnlockJoystickList();
 }
 
 
@@ -1253,11 +1682,18 @@ SDL_GameControllerClose(SDL_GameController * gamecontroller)
 void
 SDL_GameControllerQuit(void)
 {
-    ControllerMapping_t *pControllerMap;
+    SDL_LockJoystickList();
     while (SDL_gamecontrollers) {
         SDL_gamecontrollers->ref_count = 1;
         SDL_GameControllerClose(SDL_gamecontrollers);
     }
+    SDL_UnlockJoystickList();
+}
+
+void
+SDL_GameControllerQuitMappings(void)
+{
+    ControllerMapping_t *pControllerMap;
 
     while (s_pSupportedControllers) {
         pControllerMap = s_pSupportedControllers;
@@ -1269,12 +1705,25 @@ SDL_GameControllerQuit(void)
 
     SDL_DelEventWatch(SDL_GameControllerEventWatcher, NULL);
 
+    SDL_DelHintCallback(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES,
+                        SDL_GameControllerIgnoreDevicesChanged, NULL);
+    SDL_DelHintCallback(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT,
+                        SDL_GameControllerIgnoreDevicesExceptChanged, NULL);
+
+    if (SDL_allowed_controllers.entries) {
+        SDL_free(SDL_allowed_controllers.entries);
+        SDL_zero(SDL_allowed_controllers);
+    }
+    if (SDL_ignored_controllers.entries) {
+        SDL_free(SDL_ignored_controllers.entries);
+        SDL_zero(SDL_ignored_controllers);
+    }
 }
 
 /*
  * Event filter to transform joystick events into appropriate game controller ones
  */
-int
+static int
 SDL_PrivateGameControllerAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis, Sint16 value)
 {
     int posted;
@@ -1298,7 +1747,7 @@ SDL_PrivateGameControllerAxis(SDL_GameController * gamecontroller, SDL_GameContr
 /*
  * Event filter to transform joystick events into appropriate game controller ones
  */
-int
+static int
 SDL_PrivateGameControllerButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button, Uint8 state)
 {
     int posted;
diff --git a/src/joystick/SDL_gamecontrollerdb.h b/src/joystick/SDL_gamecontrollerdb.h
index 1e623cb..8caf847 100644
--- a/src/joystick/SDL_gamecontrollerdb.h
+++ b/src/joystick/SDL_gamecontrollerdb.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -35,70 +35,170 @@ static const char *s_ControllerMappings [] =
     "xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
 #endif
 #if SDL_JOYSTICK_DINPUT
-    "10280900000000000000504944564944,8Bitdo SFC30 GamePad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,",
-    "341a3608000000000000504944564944,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
-    "e8206058000000000000504944564944,Cideko AK08b,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,",
-    "ffff0000000000000000504944564944,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
-    "6d0416c2000000000000504944564944,Generic DirectInput Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
-	"6d0418c2000000000000504944564944,Logitech F510 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
-	"6d0419c2000000000000504944564944,Logitech F710 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */
-    "4d6963726f736f66742050432d6a6f79,OUYA Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:b12,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:b13,rightx:a5,righty:a4,x:b1,y:b2,",
-    "88880803000000000000504944564944,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b9,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b0,y:b3,",
-    "4c056802000000000000504944564944,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,",
-    "25090500000000000000504944564944,PS3 DualShock,a:b2,b:b1,back:b9,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b0,y:b3,",
-    "4c05c405000000000000504944564944,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "03000000022000000090000000000000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,",
+    "03000000203800000900000000000000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a3,righty:a4,start:b11,x:b4,y:b3,",
+    "03000000102800000900000000000000,8Bitdo SFC30 GamePad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,",
+    "03000000a00500003232000000000000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,",
+    "03000000341a00003608000000000000,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "03000000e82000006058000000000000,Cideko AK08b,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,",
+    "03000000260900008888000000000000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a4,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,",
+    "03000000a306000022f6000000000000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,",
+    "03000000ffff00000000000000000000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
+    "030000000d0f00006e00000000000000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000000d0f00006600000000000000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000000d0f00005f00000000000000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000000d0f00005e00000000000000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000008f0e00001330000000000000,HuiJia SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b9,x:b3,y:b0,",
+    "030000006d04000016c2000000000000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000006d04000018c2000000000000,Logitech F510 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000006d04000019c2000000000000,Logitech F710 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */
+    "03000000380700005032000000000000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "03000000380700005082000000000000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "03000000790000004418000000000000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,",
+    "030000001008000001e5000000000000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,",
+    "030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
+    "03000000362800000100000000000000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:b13,rightx:a3,righty:a4,x:b1,y:b2,",
+    "03000000888800000803000000000000,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b9,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b0,y:b3,",
+    "030000004c0500006802000000000000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,",
+    "03000000250900000500000000000000,PS3 DualShock,a:b2,b:b1,back:b9,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b0,y:b3,",
+    "030000004c050000c405000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000004c050000cc09000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000004c050000a00b000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "03000000790000001100000000000000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a4,dpleft:-a3,dpright:+a3,dpup:-a4,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,",
+    "030000006b140000010d000000000000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "03000000a30600000cff000000000000,Saitek P2500 Force Rumble Pad,a:b2,b:b3,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a2,righty:a3,x:b0,y:b1,",
+    "03000000a30600000b04000000010000,Saitek P990 Dual Analog Pad,a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b8,x:b0,y:b3,",
+    "03000000172700004431000000000000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b20,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a7,rightx:a2,righty:a5,start:b11,x:b3,y:b4,",
+    "03000000830500006020000000000000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,",
 #endif
 #if defined(__MACOSX__)
-    "10280000000000000900000000000000,8Bitdo SFC30 GamePad Joystick,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,",
-    "830500000000000031b0000000000000,Cideko AK08b,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "03000000022000000090000001000000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,",
+    "03000000203800000900000000010000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,",
+    "03000000102800000900000000000000,8Bitdo SFC30 GamePad Joystick,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,",
+    "03000000a00500003232000008010000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,",
+    "030000008305000031b0000000000000,Cideko AK08b,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "03000000260900008888000088020000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a5,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,",
+    "03000000a306000022f6000001030000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,",
     "0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
-    "6d0400000000000016c2000000000000,Logitech F310 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */
-    "6d0400000000000018c2000000000000,Logitech F510 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
-    "6d040000000000001fc2000000000000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
-    "6d0400000000000019c2000000000000,Logitech Wireless Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* This includes F710 in DInput mode and the "Logitech Cordless RumblePad 2", at the very least. */
-    "4c050000000000006802000000000000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,",
-    "4c05000000000000c405000000000000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
-    "351200000000000021ab000000000000,SFC30 Joystick,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,",
-    "11010000000000002014000000000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b12,x:b2,y:b3,",
-    "11010000000000001714000000000000,SteelSeries Stratus XL,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b12,x:b2,y:b3,",
-    "5e040000000000008e02000000000000,X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
+    "030000000d0f00006e00000000010000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000000d0f00006600000000010000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000000d0f00005f00000000010000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000000d0f00005e00000000010000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000008f0e00001330000011010000,HuiJia SNES Controller,a:b4,b:b2,back:b16,dpdown:+a2,dpleft:-a0,dpright:+a0,dpup:-a2,leftshoulder:b12,rightshoulder:b14,start:b18,x:b6,y:b0,",
+    "030000006d04000016c2000014040000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000006d04000016c2000000030000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000006d04000016c2000000000000,Logitech F310 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */
+    "030000006d04000018c2000000000000,Logitech F510 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000006d0400001fc2000000000000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
+    "030000006d04000019c2000000000000,Logitech Wireless Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* This includes F710 in DInput mode and the "Logitech Cordless RumblePad 2", at the very least. */
+    "03000000380700005032000000010000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "03000000380700005082000000010000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "03000000790000004418000000010000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,",
+    "030000001008000001e5000006010000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,",
+    "030000007e0500000920000000000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
+    "030000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,",
+    "030000004c050000c405000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000004c050000a00b000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "03000000321500000010000000010000,Razer RAIJU,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "0300000032150000030a000000000000,Razer Wildcat,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
+    "03000000790000001100000006010000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a4,dpleft:-a3,dpright:+a3,dpup:-a4,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,",
+    "030000006b140000010d000000010000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000003512000021ab000000000000,SFC30 Joystick,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,",
+    "03000000110100002014000001000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,x:b2,y:b3,",
+    "03000000381000002014000001000000,SteelSeries Nimbus,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,x:b2,y:b3,",
+    "03000000110100001714000000000000,SteelSeries Stratus XL,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,start:b12,x:b2,y:b3,",
+    "03000000110100001714000020010000,SteelSeries Stratus XL,a:b0,b:b1,dpdown:b9,dpleft:b11,dpright:b10,dpup:b8,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1~,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3~,start:b12,x:b2,y:b3,",
+    "030000005e0400008e02000000000000,X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
+    "03000000c6240000045d000000000000,Xbox 360 Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
+    "030000005e040000d102000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
+    "030000005e040000e302000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
+    "030000005e040000dd02000000000000,Xbox One Wired Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
+    "030000005e040000e002000003090000,Xbox Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
+    "030000005e040000ea02000000000000,Xbox Wireless Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
+    "030000005e040000fd02000003090000,Xbox Wireless Controller,a:b0,b:b1,back:b16,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,",
+    "03000000172700004431000029010000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b15,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a5,start:b11,x:b3,y:b4,",
+    "03000000120c0000100e000000010000,ZEROPLUS P4 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "03000000830500006020000000010000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,",
 #endif
 #if defined(__LINUX__)
+    "03000000022000000090000011010000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,",
+    "05000000203800000900000000010000,8Bitdo NES30 Pro,a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b6,leftstick:b13,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:b9,rightx:a2,righty:a3,start:b11,x:b4,y:b3,",
     "05000000102800000900000000010000,8Bitdo SFC30 GamePad,a:b1,b:b0,back:b10,leftshoulder:b6,leftx:a0,lefty:a1,rightshoulder:b7,start:b11,x:b4,y:b3,",
+    "05000000a00500003232000008010000,8Bitdo Zero GamePad,a:b0,b:b1,back:b10,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b11,x:b3,y:b4,",
     "03000000100000008200000011010000,Akishop Customs PS360+ v1.66,a:b1,b:b2,back:b12,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,righttrigger:b7,start:b9,x:b0,y:b3,",
     "03000000e82000006058000001010000,Cideko AK08b,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b0,",
+    "03000000260900008888000000010000,Cyber Gadget GameCube Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b6,righttrigger:a5,rightx:a2,righty:a3~,start:b7,x:b2,y:b3,",
+    "03000000a306000022f6000011010000,Cyborg V.3 Rumble Pad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:+a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:-a3,rightx:a2,righty:a4,start:b9,x:b0,y:b3,",
+    "03000000790000000600000010010000,DragonRise Inc. Generic USB Joystick,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a4,start:b9,x:b3,y:b0,",
     "0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
     "030000006f0e00000104000000010000,Gamestop Logic3 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
+    "030000000d0f00006e00000011010000,HORIPAD 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000000d0f00006600000011010000,HORIPAD 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000000d0f00005f00000011010000,Hori Fighting Commander 4 (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000000d0f00005e00000011010000,Hori Fighting Commander 4 (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000008f0e00001330000010010000,HuiJia SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b6,rightshoulder:b7,start:b9,x:b3,y:b0,",
     "03000000ba2200002010000001010000,Jess Technology USB Game Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,",
     "030000006d04000019c2000010010000,Logitech Cordless RumblePad 2,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000006d04000016c2000011010000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "030000006d04000016c2000010010000,Logitech Dual Action,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
     "030000006d0400001dc2000014400000,Logitech F310 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
     "030000006d0400001ec2000020200000,Logitech F510 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
     "030000006d04000019c2000011010000,Logitech F710 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */
     "030000006d0400001fc2000005030000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
     "030000006d04000018c2000010010000,Logitech RumblePad 2,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "03000000380700005032000011010000,Mad Catz FightPad PRO (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
+    "03000000380700005082000011010000,Mad Catz FightPad PRO (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
     "03000000380700008433000011010000,Mad Catz FightStick TE S+ PS3,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
     "03000000380700008483000011010000,Mad Catz FightStick TE S+ PS4,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
     "03000000380700003847000090040000,Mad Catz Wired Xbox 360 Controller (SFIV),a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
     "03000000380700008034000011010000,Mad Catz fightstick (PS3),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
     "03000000380700008084000011010000,Mad Catz fightstick (PS4),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
     "03000000380700001888000010010000,MadCatz PC USB Wired Stick 8818,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
-    "03000000550900001072000011010000,NVIDIA Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b8,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,",
-    "050000007e0500003003000001000000,Nintendo Wii Remote Pro Controller,a:b1,b:b0,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
-    "050000003620000100000002010000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b1,y:b2,",
+    "03000000790000004418000010010000,Mayflash GameCube Controller,a:b1,b:b2,dpdown:b14,dpleft:b15,dpright:b13,dpup:b12,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:a4,rightx:a5,righty:a2,start:b9,x:b0,y:b3,",
+    "030000001008000001e5000010010000,NEXT SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b6,start:b9,x:b3,y:b0,",
+    "03000000550900001072000011010000,NVIDIA Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b13,leftshoulder:b4,leftstick:b8,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,",
+    "050000007e0500000920000001000000,Nintendo Switch Pro Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
+    "050000007e0500003003000001000000,Nintendo Wii Remote Pro Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b3,y:b2,",
+    "030000000d0500000308000010010000,Nostromo n45 Dual Analog Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b9,leftshoulder:b4,leftstick:b12,lefttrigger:b5,leftx:a0,lefty:a1,rightshoulder:b6,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b10,x:b2,y:b3,",
+    "05000000362800000100000002010000,OUYA Game Controller,a:b0,b:b3,dpdown:b9,dpleft:b10,dpright:b11,dpup:b8,guide:b14,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,x:b1,y:b2,",
+    "030000006f0e00006401000001010000,PDP Battlefield One,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
+    "030000004c0500006802000010010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,",
+    "050000004c0500006802000000010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:a12,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:a13,rightx:a2,righty:a3,start:b3,x:b15,y:b12,",
     "030000004c0500006802000011010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,",
+    "030000004c0500006802000010810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,",
+    "050000004c0500006802000000810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,",
+    "030000004c0500006802000011810000,PS3 Controller,a:b0,b:b1,back:b8,dpdown:b14,dpleft:b15,dpright:b16,dpup:b13,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,",
     "03000000341a00003608000011010000,PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
     "030000004c050000c405000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
     "050000004c050000c405000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
     "030000004c050000cc09000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
     "050000004c050000cc09000000010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000004c050000a00b000011010000,PS4 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "030000004c050000c405000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,",
+    "050000004c050000c405000000810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,",
+    "030000004c050000cc09000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,",
+    "050000004c050000cc09000000810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,",
+    "030000004c050000a00b000011810000,PS4 Controller,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b11,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b12,righttrigger:a5,rightx:a3,righty:a4,start:b9,x:b3,y:b2,",
+    "03000000300f00001211000011010000,QanBa Arcade JoyStick,a:b2,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b5,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,righttrigger:b6,start:b9,x:b1,y:b3,",
+    "03000000321500000010000011010000,Razer RAIJU,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
     "03000000c6240000045d000025010000,Razer Sabertooth,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
     "03000000321500000009000011010000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,",
     "050000003215000000090000163a0000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,",
+    "0300000032150000030a000001010000,Razer Wildcat,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
+    "03000000790000001100000010010000,Retrolink SNES Controller,a:b2,b:b1,back:b8,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b9,x:b3,y:b0,",
+    "030000006b140000010d000011010000,Revolution Pro Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "03000000a30600000cff000010010000,Saitek P2500 Force Rumble Pad,a:b2,b:b3,back:b11,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:b7,rightx:a3,righty:a2,x:b0,y:b1,",
+    "03000000a30600000b04000000010000,Saitek P990 Dual Analog Pad,a:b1,b:b2,back:b9,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a3,righty:a2,start:b8,x:b0,y:b3,",
+    "03000000de2800000211000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,",
     "03000000de280000fc11000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
-    "03000000de280000ff11000001000000,Valve Streaming Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
+    "03000000de280000ff11000001000000,Steam Virtual Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
     "xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
     "050000005e040000e002000003090000,Xbox One Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b10,leftshoulder:b4,leftstick:b8,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b9,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
-    "030000005e040000d102000001010000,Xbox One Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
+    "050000005e040000fd02000003090000,Xbox One Wireless Controller,a:b0,b:b1,back:b15,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b16,leftshoulder:b6,leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a4,rightx:a2,righty:a3,start:b11,x:b3,y:b4,",
+    "05000000172700004431000029010000,XiaoMi Game Controller,a:b0,b:b1,back:b10,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b20,leftshoulder:b6,leftstick:b13,lefttrigger:a7,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b14,righttrigger:a6,rightx:a2,righty:a5,start:b11,x:b3,y:b4,",
+    "03000000120c0000100e000011010000,ZEROPLUS P4 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:a3,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:a4,rightx:a2,righty:a5,start:b9,x:b0,y:b3,",
+    "03000000830500006020000010010000,iBuffalo SNES Controller,a:b1,b:b0,back:b6,dpdown:+a1,dpleft:-a0,dpright:+a0,dpup:-a1,leftshoulder:b4,rightshoulder:b5,start:b7,x:b3,y:b2,",
 #endif
 #if defined(__ANDROID__)
     "4e564944494120436f72706f72617469,NVIDIA Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,",
@@ -106,6 +206,8 @@ static const char *s_ControllerMappings [] =
 #if defined(SDL_JOYSTICK_MFI)
     "4d466947616d65706164010000000000,MFi Extended Gamepad,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a5,rightx:a3,righty:a4,start:b6,x:b2,y:b3,",
     "4d466947616d65706164020000000000,MFi Gamepad,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,rightshoulder:b5,start:b6,x:b2,y:b3,",
+    "03000000de2800000211000001000000,Steam Controller,a:b0,b:b1,back:b6,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:a3,start:b7,x:b2,y:b3,",
+    "03000000de280000fc11000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
 #endif
 #if defined(SDL_JOYSTICK_EMSCRIPTEN)
     "emscripten,Standard Gamepad,a:b0,b:b1,back:b8,dpdown:b13,dpleft:b14,dpright:b15,dpup:b12,guide:b16,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
diff --git a/src/joystick/SDL_joystick.c b/src/joystick/SDL_joystick.c
index c426a39..0724db2 100644
--- a/src/joystick/SDL_joystick.c
+++ b/src/joystick/SDL_joystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -31,12 +31,32 @@
 #if !SDL_EVENTS_DISABLED
 #include "../events/SDL_events_c.h"
 #endif
+#include "../video/SDL_sysvideo.h"
+
 
 static SDL_bool SDL_joystick_allows_background_events = SDL_FALSE;
 static SDL_Joystick *SDL_joysticks = NULL;
-static SDL_Joystick *SDL_updating_joystick = NULL;
+static SDL_bool SDL_updating_joystick = SDL_FALSE;
+static SDL_mutex *SDL_joystick_lock = NULL; /* This needs to support recursive locks */
+
+void
+SDL_LockJoystickList(void)
+{
+    if (SDL_joystick_lock) {
+        SDL_LockMutex(SDL_joystick_lock);
+    }
+}
+
+void
+SDL_UnlockJoystickList(void)
+{
+    if (SDL_joystick_lock) {
+        SDL_UnlockMutex(SDL_joystick_lock);
+    }
+}
+
 
-static void
+static void SDLCALL
 SDL_JoystickAllowBackgroundEventsChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
 {
     if (hint && *hint == '1') {
@@ -51,6 +71,13 @@ SDL_JoystickInit(void)
 {
     int status;
 
+    SDL_GameControllerInitMappings();
+
+    /* Create the joystick list lock */
+    if (!SDL_joystick_lock) {
+        SDL_joystick_lock = SDL_CreateMutex();
+    }
+
     /* See if we should allow joystick events while in the background */
     SDL_AddHintCallback(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS,
                         SDL_JoystickAllowBackgroundEventsChanged, NULL);
@@ -83,7 +110,7 @@ SDL_NumJoysticks(void)
 const char *
 SDL_JoystickNameForIndex(int device_index)
 {
-    if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) {
+    if (device_index < 0 || device_index >= SDL_NumJoysticks()) {
         SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
         return (NULL);
     }
@@ -91,6 +118,38 @@ SDL_JoystickNameForIndex(int device_index)
 }
 
 /*
+ * Return true if this joystick is known to have all axes centered at zero
+ * This isn't generally needed unless the joystick never generates an initial axis value near zero,
+ * e.g. it's emulating axes with digital buttons
+ */
+static SDL_bool
+SDL_JoystickAxesCenteredAtZero(SDL_Joystick *joystick)
+{
+    static Uint32 zero_centered_joysticks[] = {
+        MAKE_VIDPID(0x0e8f, 0x3013),    /* HuiJia SNES USB adapter */
+        MAKE_VIDPID(0x05a0, 0x3232),    /* 8Bitdo Zero Gamepad */
+    };
+
+    int i;
+    Uint32 id = MAKE_VIDPID(SDL_JoystickGetVendor(joystick),
+                            SDL_JoystickGetProduct(joystick));
+
+/*printf("JOYSTICK '%s' VID/PID 0x%.4x/0x%.4x AXES: %d\n", joystick->name, vendor, product, joystick->naxes);*/
+
+    if (joystick->naxes == 2) {
+        /* Assume D-pad or thumbstick style axes are centered at 0 */
+        return SDL_TRUE;
+    }
+
+    for (i = 0; i < SDL_arraysize(zero_centered_joysticks); ++i) {
+        if (id == zero_centered_joysticks[i]) {
+            return SDL_TRUE;
+        }
+    }
+    return SDL_FALSE;
+}
+
+/*
  * Open a joystick for use - the index passed as an argument refers to
  * the N'th joystick on the system.  This index is the value which will
  * identify this joystick in future joystick events.
@@ -109,29 +168,33 @@ SDL_JoystickOpen(int device_index)
         return (NULL);
     }
 
+    SDL_LockJoystickList();
+
     joysticklist = SDL_joysticks;
     /* If the joystick is already open, return it
-    * it is important that we have a single joystick * for each instance id
-    */
+     * it is important that we have a single joystick * for each instance id
+     */
     while (joysticklist) {
-        if (SDL_SYS_GetInstanceIdOfDeviceIndex(device_index) == joysticklist->instance_id) {
+        if (SDL_JoystickGetDeviceInstanceID(device_index) == joysticklist->instance_id) {
                 joystick = joysticklist;
                 ++joystick->ref_count;
+                SDL_UnlockJoystickList();
                 return (joystick);
         }
         joysticklist = joysticklist->next;
     }
 
     /* Create and initialize the joystick */
-    joystick = (SDL_Joystick *) SDL_malloc((sizeof *joystick));
+    joystick = (SDL_Joystick *) SDL_calloc(sizeof(*joystick), 1);
     if (joystick == NULL) {
         SDL_OutOfMemory();
+        SDL_UnlockJoystickList();
         return NULL;
     }
 
-    SDL_memset(joystick, 0, (sizeof *joystick));
     if (SDL_SYS_JoystickOpen(joystick, device_index) < 0) {
         SDL_free(joystick);
+        SDL_UnlockJoystickList();
         return NULL;
     }
 
@@ -142,20 +205,16 @@ SDL_JoystickOpen(int device_index)
         joystick->name = NULL;
 
     if (joystick->naxes > 0) {
-        joystick->axes = (Sint16 *) SDL_malloc(joystick->naxes * sizeof(Sint16));
-        joystick->axes_zero = (Sint16 *) SDL_malloc(joystick->naxes * sizeof(Sint16));
+        joystick->axes = (SDL_JoystickAxisInfo *) SDL_calloc(joystick->naxes, sizeof(SDL_JoystickAxisInfo));
     }
     if (joystick->nhats > 0) {
-        joystick->hats = (Uint8 *) SDL_malloc
-            (joystick->nhats * sizeof(Uint8));
+        joystick->hats = (Uint8 *) SDL_calloc(joystick->nhats, sizeof(Uint8));
     }
     if (joystick->nballs > 0) {
-        joystick->balls = (struct balldelta *) SDL_malloc
-            (joystick->nballs * sizeof(*joystick->balls));
+        joystick->balls = (struct balldelta *) SDL_calloc(joystick->nballs, sizeof(*joystick->balls));
     }
     if (joystick->nbuttons > 0) {
-        joystick->buttons = (Uint8 *) SDL_malloc
-            (joystick->nbuttons * sizeof(Uint8));
+        joystick->buttons = (Uint8 *) SDL_calloc(joystick->nbuttons, sizeof(Uint8));
     }
     if (((joystick->naxes > 0) && !joystick->axes)
         || ((joystick->nhats > 0) && !joystick->hats)
@@ -163,30 +222,30 @@ SDL_JoystickOpen(int device_index)
         || ((joystick->nbuttons > 0) && !joystick->buttons)) {
         SDL_OutOfMemory();
         SDL_JoystickClose(joystick);
+        SDL_UnlockJoystickList();
         return NULL;
     }
-    if (joystick->axes) {
-        SDL_memset(joystick->axes, 0, joystick->naxes * sizeof(Sint16));
-        SDL_memset(joystick->axes_zero, 0, joystick->naxes * sizeof(Sint16));
-    }
-    if (joystick->hats) {
-        SDL_memset(joystick->hats, 0, joystick->nhats * sizeof(Uint8));
-    }
-    if (joystick->balls) {
-        SDL_memset(joystick->balls, 0,
-            joystick->nballs * sizeof(*joystick->balls));
-    }
-    if (joystick->buttons) {
-        SDL_memset(joystick->buttons, 0, joystick->nbuttons * sizeof(Uint8));
-    }
     joystick->epowerlevel = SDL_JOYSTICK_POWER_UNKNOWN;
 
+    /* If this joystick is known to have all zero centered axes, skip the auto-centering code */
+    if (SDL_JoystickAxesCenteredAtZero(joystick)) {
+        int i;
+
+        for (i = 0; i < joystick->naxes; ++i) {
+            joystick->axes[i].has_initial_value = SDL_TRUE;
+        }
+    }
+
+    joystick->is_game_controller = SDL_IsGameController(device_index);
+
     /* Add joystick to list */
     ++joystick->ref_count;
     /* Link the joystick in the list */
     joystick->next = SDL_joysticks;
     SDL_joysticks = joystick;
 
+    SDL_UnlockJoystickList();
+
     SDL_SYS_JoystickUpdate(joystick);
 
     return (joystick);
@@ -271,7 +330,7 @@ SDL_JoystickGetAxis(SDL_Joystick * joystick, int axis)
         return (0);
     }
     if (axis < joystick->naxes) {
-        state = joystick->axes[axis];
+        state = joystick->axes[axis].value;
     } else {
         SDL_SetError("Joystick only has %d axes", joystick->naxes);
         state = 0;
@@ -280,6 +339,25 @@ SDL_JoystickGetAxis(SDL_Joystick * joystick, int axis)
 }
 
 /*
+ * Get the initial state of an axis control on a joystick
+ */
+SDL_bool
+SDL_JoystickGetAxisInitialState(SDL_Joystick * joystick, int axis, Sint16 *state)
+{
+    if (!SDL_PrivateJoystickValid(joystick)) {
+        return SDL_FALSE;
+    }
+    if (axis >= joystick->naxes) {
+        SDL_SetError("Joystick only has %d axes", joystick->naxes);
+        return SDL_FALSE;
+    }
+    if (state) {
+        *state = joystick->axes[axis].initial_value;
+    }
+    return joystick->axes[axis].has_initial_value;
+}
+
+/*
  * Get the current state of a hat on a joystick
  */
 Uint8
@@ -380,14 +458,16 @@ SDL_JoystickInstanceID(SDL_Joystick * joystick)
 SDL_Joystick *
 SDL_JoystickFromInstanceID(SDL_JoystickID joyid)
 {
-    SDL_Joystick *joystick = SDL_joysticks;
-    while (joystick) {
+    SDL_Joystick *joystick;
+
+    SDL_LockJoystickList();
+    for (joystick = SDL_joysticks; joystick; joystick = joystick->next) {
         if (joystick->instance_id == joyid) {
+            SDL_UnlockJoystickList();
             return joystick;
         }
-        joystick = joystick->next;
     }
-
+    SDL_UnlockJoystickList();
     return NULL;
 }
 
@@ -417,12 +497,16 @@ SDL_JoystickClose(SDL_Joystick * joystick)
         return;
     }
 
+    SDL_LockJoystickList();
+
     /* First decrement ref count */
     if (--joystick->ref_count > 0) {
+        SDL_UnlockJoystickList();
         return;
     }
 
-    if (joystick == SDL_updating_joystick) {
+    if (SDL_updating_joystick) {
+        SDL_UnlockJoystickList();
         return;
     }
 
@@ -453,6 +537,8 @@ SDL_JoystickClose(SDL_Joystick * joystick)
     SDL_free(joystick->balls);
     SDL_free(joystick->buttons);
     SDL_free(joystick);
+
+    SDL_UnlockJoystickList();
 }
 
 void
@@ -461,6 +547,8 @@ SDL_JoystickQuit(void)
     /* Make sure we're not getting called in the middle of updating joysticks */
     SDL_assert(!SDL_updating_joystick);
 
+    SDL_LockJoystickList();
+
     /* Stop the event polling */
     while (SDL_joysticks) {
         SDL_joysticks->ref_count = 1;
@@ -470,9 +558,21 @@ SDL_JoystickQuit(void)
     /* Quit the joystick setup */
     SDL_SYS_JoystickQuit();
 
+    SDL_UnlockJoystickList();
+
 #if !SDL_EVENTS_DISABLED
     SDL_QuitSubSystem(SDL_INIT_EVENTS);
 #endif
+
+    SDL_DelHintCallback(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS,
+                        SDL_JoystickAllowBackgroundEventsChanged, NULL);
+
+    if (SDL_joystick_lock) {
+        SDL_DestroyMutex(SDL_joystick_lock);
+        SDL_joystick_lock = NULL;
+    }
+
+    SDL_GameControllerQuitMappings();
 }
 
 
@@ -483,16 +583,10 @@ SDL_PrivateJoystickShouldIgnoreEvent()
         return SDL_FALSE;
     }
 
-    if (SDL_WasInit(SDL_INIT_VIDEO)) {
-        if (SDL_GetKeyboardFocus() == NULL) {
-            /* Video is initialized and we don't have focus, ignore the event. */
-            return SDL_TRUE;
-        } else {
-            return SDL_FALSE;
-        }
+    if (SDL_HasWindows() && SDL_GetKeyboardFocus() == NULL) {
+        /* We have windows but we don't have focus, ignore the event. */
+        return SDL_TRUE;
     }
-
-    /* Video subsystem wasn't initialized, always allow the event */
     return SDL_FALSE;
 }
 
@@ -507,8 +601,8 @@ void SDL_PrivateJoystickAdded(int device_index)
 
     if (SDL_GetEventState(event.type) == SDL_ENABLE) {
         event.jdevice.which = device_index;
-        if ( (SDL_EventOK == NULL) ||
-             (*SDL_EventOK) (SDL_EventOKParam, &event) ) {
+        if ((SDL_EventOK == NULL) ||
+             (*SDL_EventOK) (SDL_EventOKParam, &event)) {
             SDL_PushEvent(&event);
         }
     }
@@ -553,8 +647,8 @@ void SDL_PrivateJoystickRemoved(SDL_JoystickID device_instance)
 
     if (SDL_GetEventState(event.type) == SDL_ENABLE) {
         event.jdevice.which = device_instance;
-        if ( (SDL_EventOK == NULL) ||
-             (*SDL_EventOK) (SDL_EventOKParam, &event) ) {
+        if ((SDL_EventOK == NULL) ||
+             (*SDL_EventOK) (SDL_EventOKParam, &event)) {
             SDL_PushEvent(&event);
         }
     }
@@ -572,22 +666,38 @@ SDL_PrivateJoystickAxis(SDL_Joystick * joystick, Uint8 axis, Sint16 value)
     if (axis >= joystick->naxes) {
         return 0;
     }
-    if (value == joystick->axes[axis]) {
+    if (!joystick->axes[axis].has_initial_value) {
+        joystick->axes[axis].initial_value = value;
+        joystick->axes[axis].value = value;
+        joystick->axes[axis].zero = value;
+        joystick->axes[axis].has_initial_value = SDL_TRUE;
+    }
+    if (value == joystick->axes[axis].value) {
         return 0;
     }
+    if (!joystick->axes[axis].sent_initial_value) {
+        /* Make sure we don't send motion until there's real activity on this axis */
+        const int MAX_ALLOWED_JITTER = SDL_JOYSTICK_AXIS_MAX / 80;  /* ShanWan PS3 controller needed 96 */
+        if (SDL_abs(value - joystick->axes[axis].value) <= MAX_ALLOWED_JITTER) {
+            return 0;
+        }
+        joystick->axes[axis].sent_initial_value = SDL_TRUE;
+        joystick->axes[axis].value = value; /* Just so we pass the check above */
+        SDL_PrivateJoystickAxis(joystick, axis, joystick->axes[axis].initial_value);
+    }
 
     /* We ignore events if we don't have keyboard focus, except for centering
      * events.
      */
     if (SDL_PrivateJoystickShouldIgnoreEvent()) {
-        if ((value > joystick->axes_zero[axis] && value >= joystick->axes[axis]) ||
-            (value < joystick->axes_zero[axis] && value <= joystick->axes[axis])) {
+        if ((value > joystick->axes[axis].zero && value >= joystick->axes[axis].value) ||
+            (value < joystick->axes[axis].zero && value <= joystick->axes[axis].value)) {
             return 0;
         }
     }
 
     /* Update internal joystick state */
-    joystick->axes[axis] = value;
+    joystick->axes[axis].value = value;
 
     /* Post the event, if desired */
     posted = 0;
@@ -737,24 +847,30 @@ SDL_JoystickUpdate(void)
 {
     SDL_Joystick *joystick;
 
-    joystick = SDL_joysticks;
-    while (joystick) {
-        SDL_Joystick *joysticknext;
-        /* save off the next pointer, the Update call may cause a joystick removed event
-         * and cause our joystick pointer to be freed
-         */
-        joysticknext = joystick->next;
+    SDL_LockJoystickList();
+
+    if (SDL_updating_joystick) {
+        /* The joysticks are already being updated */
+        SDL_UnlockJoystickList();
+        return;
+    }
 
-        SDL_updating_joystick = joystick;
+    SDL_updating_joystick = SDL_TRUE;
 
+    /* Make sure the list is unlocked while dispatching events to prevent application deadlocks */
+    SDL_UnlockJoystickList();
+
+    for (joystick = SDL_joysticks; joystick; joystick = joystick->next) {
         SDL_SYS_JoystickUpdate(joystick);
 
         if (joystick->force_recentering) {
             int i;
 
-            /* Tell the app that everything is centered/unpressed...  */
+            /* Tell the app that everything is centered/unpressed... */
             for (i = 0; i < joystick->naxes; i++) {
-                SDL_PrivateJoystickAxis(joystick, i, joystick->axes_zero[i]);
+                if (joystick->axes[i].has_initial_value) {
+                    SDL_PrivateJoystickAxis(joystick, i, joystick->axes[i].zero);
+                }
             }
 
             for (i = 0; i < joystick->nbuttons; i++) {
@@ -767,21 +883,25 @@ SDL_JoystickUpdate(void)
 
             joystick->force_recentering = SDL_FALSE;
         }
+    }
+
+    SDL_LockJoystickList();
 
-        SDL_updating_joystick = NULL;
+    SDL_updating_joystick = SDL_FALSE;
 
-        /* If the joystick was closed while updating, free it here */
+    /* If any joysticks were closed while updating, free them here */
+    for (joystick = SDL_joysticks; joystick; joystick = joystick->next) {
         if (joystick->ref_count <= 0) {
             SDL_JoystickClose(joystick);
         }
-
-        joystick = joysticknext;
     }
 
     /* this needs to happen AFTER walking the joystick list above, so that any
        dangling hardware data from removed devices can be free'd
      */
     SDL_SYS_JoystickDetect();
+
+    SDL_UnlockJoystickList();
 }
 
 int
@@ -816,10 +936,154 @@ SDL_JoystickEventState(int state)
 #endif /* SDL_EVENTS_DISABLED */
 }
 
+void SDL_GetJoystickGUIDInfo(SDL_JoystickGUID guid, Uint16 *vendor, Uint16 *product, Uint16 *version)
+{
+    Uint16 *guid16 = (Uint16 *)guid.data;
+
+    /* If the GUID fits the form of BUS 0000 VENDOR 0000 PRODUCT 0000, return the data */
+    if (/* guid16[0] is device bus type */
+        guid16[1] == 0x0000 &&
+        /* guid16[2] is vendor ID */
+        guid16[3] == 0x0000 &&
+        /* guid16[4] is product ID */
+        guid16[5] == 0x0000
+        /* guid16[6] is product version */
+    ) {
+        if (vendor) {
+            *vendor = guid16[2];
+        }
+        if (product) {
+            *product = guid16[4];
+        }
+        if (version) {
+            *version = guid16[6];
+        }
+    } else {
+        if (vendor) {
+            *vendor = 0;
+        }
+        if (product) {
+            *product = 0;
+        }
+        if (version) {
+            *version = 0;
+        }
+    }
+}
+
+static SDL_bool SDL_IsJoystickProductWheel(Uint32 vidpid)
+{
+    static Uint32 wheel_joysticks[] = {
+        MAKE_VIDPID(0x046d, 0xc294),    /* Logitech generic wheel */
+        MAKE_VIDPID(0x046d, 0xc295),    /* Logitech Momo Force */
+        MAKE_VIDPID(0x046d, 0xc298),    /* Logitech Driving Force Pro */
+        MAKE_VIDPID(0x046d, 0xc299),    /* Logitech G25 */
+        MAKE_VIDPID(0x046d, 0xc29a),    /* Logitech Driving Force GT */
+        MAKE_VIDPID(0x046d, 0xc29b),    /* Logitech G27 */
+        MAKE_VIDPID(0x046d, 0xc261),    /* Logitech G920 (initial mode) */
+        MAKE_VIDPID(0x046d, 0xc262),    /* Logitech G920 (active mode) */
+        MAKE_VIDPID(0x044f, 0xb65d),    /* Thrustmaster Wheel FFB */
+        MAKE_VIDPID(0x044f, 0xb66d),    /* Thrustmaster Wheel FFB */
+        MAKE_VIDPID(0x044f, 0xb677),    /* Thrustmaster T150 */
+        MAKE_VIDPID(0x044f, 0xb664),    /* Thrustmaster TX (initial mode) */
+        MAKE_VIDPID(0x044f, 0xb669),    /* Thrustmaster TX (active mode) */
+    };
+    int i;
+
+    for (i = 0; i < SDL_arraysize(wheel_joysticks); ++i) {
+        if (vidpid == wheel_joysticks[i]) {
+            return SDL_TRUE;
+        }
+    }
+    return SDL_FALSE;
+}
+
+static SDL_bool SDL_IsJoystickProductFlightStick(Uint32 vidpid)
+{
+    static Uint32 flightstick_joysticks[] = {
+        MAKE_VIDPID(0x044f, 0x0402),    /* HOTAS Warthog Joystick */
+        MAKE_VIDPID(0x0738, 0x2221),    /* Saitek Pro Flight X-56 Rhino Stick */
+    };
+    int i;
+
+    for (i = 0; i < SDL_arraysize(flightstick_joysticks); ++i) {
+        if (vidpid == flightstick_joysticks[i]) {
+            return SDL_TRUE;
+        }
+    }
+    return SDL_FALSE;
+}
+
+static SDL_bool SDL_IsJoystickProductThrottle(Uint32 vidpid)
+{
+    static Uint32 throttle_joysticks[] = {
+        MAKE_VIDPID(0x044f, 0x0404),    /* HOTAS Warthog Throttle */
+        MAKE_VIDPID(0x0738, 0xa221),    /* Saitek Pro Flight X-56 Rhino Throttle */
+    };
+    int i;
+
+    for (i = 0; i < SDL_arraysize(throttle_joysticks); ++i) {
+        if (vidpid == throttle_joysticks[i]) {
+            return SDL_TRUE;
+        }
+    }
+    return SDL_FALSE;
+}
+
+static SDL_JoystickType SDL_GetJoystickGUIDType(SDL_JoystickGUID guid)
+{
+    Uint16 vendor;
+    Uint16 product;
+    Uint32 vidpid;
+
+    if (guid.data[14] == 'x') {
+        /* XInput GUID, get the type based on the XInput device subtype */
+        switch (guid.data[15]) {
+        case 0x01:  /* XINPUT_DEVSUBTYPE_GAMEPAD */
+            return SDL_JOYSTICK_TYPE_GAMECONTROLLER;
+        case 0x02:  /* XINPUT_DEVSUBTYPE_WHEEL */
+            return SDL_JOYSTICK_TYPE_WHEEL;
+        case 0x03:  /* XINPUT_DEVSUBTYPE_ARCADE_STICK */
+            return SDL_JOYSTICK_TYPE_ARCADE_STICK;
+        case 0x04:  /* XINPUT_DEVSUBTYPE_FLIGHT_STICK */
+            return SDL_JOYSTICK_TYPE_FLIGHT_STICK;
+        case 0x05:  /* XINPUT_DEVSUBTYPE_DANCE_PAD */
+            return SDL_JOYSTICK_TYPE_DANCE_PAD;
+        case 0x06:  /* XINPUT_DEVSUBTYPE_GUITAR */
+        case 0x07:  /* XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE */
+        case 0x0B:  /* XINPUT_DEVSUBTYPE_GUITAR_BASS */
+            return SDL_JOYSTICK_TYPE_GUITAR;
+        case 0x08:  /* XINPUT_DEVSUBTYPE_DRUM_KIT */
+            return SDL_JOYSTICK_TYPE_DRUM_KIT;
+        case 0x13:  /* XINPUT_DEVSUBTYPE_ARCADE_PAD */
+            return SDL_JOYSTICK_TYPE_ARCADE_PAD;
+        default:
+            return SDL_JOYSTICK_TYPE_UNKNOWN;
+        }
+    }
+
+    SDL_GetJoystickGUIDInfo(guid, &vendor, &product, NULL);
+    vidpid = MAKE_VIDPID(vendor, product);
+
+    if (SDL_IsJoystickProductWheel(vidpid)) {
+        return SDL_JOYSTICK_TYPE_WHEEL;
+    }
+
+    if (SDL_IsJoystickProductFlightStick(vidpid)) {
+        return SDL_JOYSTICK_TYPE_FLIGHT_STICK;
+    }
+
+    if (SDL_IsJoystickProductThrottle(vidpid)) {
+        return SDL_JOYSTICK_TYPE_THROTTLE;
+    }
+
+    return SDL_JOYSTICK_TYPE_UNKNOWN;
+}
+
 /* return the guid for this index */
 SDL_JoystickGUID SDL_JoystickGetDeviceGUID(int device_index)
 {
-    if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) {
+    if (device_index < 0 || device_index >= SDL_NumJoysticks()) {
         SDL_JoystickGUID emptyGUID;
         SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
         SDL_zero(emptyGUID);
@@ -828,7 +1092,56 @@ SDL_JoystickGUID SDL_JoystickGetDeviceGUID(int device_index)
     return SDL_SYS_JoystickGetDeviceGUID(device_index);
 }
 
-/* return the guid for this opened device */
+Uint16 SDL_JoystickGetDeviceVendor(int device_index)
+{
+    Uint16 vendor;
+    SDL_JoystickGUID guid = SDL_JoystickGetDeviceGUID(device_index);
+
+    SDL_GetJoystickGUIDInfo(guid, &vendor, NULL, NULL);
+    return vendor;
+}
+
+Uint16 SDL_JoystickGetDeviceProduct(int device_index)
+{
+    Uint16 product;
+    SDL_JoystickGUID guid = SDL_JoystickGetDeviceGUID(device_index);
+
+    SDL_GetJoystickGUIDInfo(guid, NULL, &product, NULL);
+    return product;
+}
+
+Uint16 SDL_JoystickGetDeviceProductVersion(int device_index)
+{
+    Uint16 version;
+    SDL_JoystickGUID guid = SDL_JoystickGetDeviceGUID(device_index);
+
+    SDL_GetJoystickGUIDInfo(guid, NULL, NULL, &version);
+    return version;
+}
+
+SDL_JoystickType SDL_JoystickGetDeviceType(int device_index)
+{
+    SDL_JoystickType type;
+    SDL_JoystickGUID guid = SDL_JoystickGetDeviceGUID(device_index);
+
+    type = SDL_GetJoystickGUIDType(guid);
+    if (type == SDL_JOYSTICK_TYPE_UNKNOWN) {
+        if (SDL_IsGameController(device_index)) {
+            type = SDL_JOYSTICK_TYPE_GAMECONTROLLER;
+        }
+    }
+    return type;
+}
+
+SDL_JoystickID SDL_JoystickGetDeviceInstanceID(int device_index)
+{
+    if (device_index < 0 || device_index >= SDL_NumJoysticks()) {
+        SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
+        return -1;
+    }
+    return SDL_SYS_GetInstanceIdOfDeviceIndex(device_index);
+}
+
 SDL_JoystickGUID SDL_JoystickGetGUID(SDL_Joystick * joystick)
 {
     if (!SDL_PrivateJoystickValid(joystick)) {
@@ -839,6 +1152,47 @@ SDL_JoystickGUID SDL_JoystickGetGUID(SDL_Joystick * joystick)
     return SDL_SYS_JoystickGetGUID(joystick);
 }
 
+Uint16 SDL_JoystickGetVendor(SDL_Joystick * joystick)
+{
+    Uint16 vendor;
+    SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick);
+
+    SDL_GetJoystickGUIDInfo(guid, &vendor, NULL, NULL);
+    return vendor;
+}
+
+Uint16 SDL_JoystickGetProduct(SDL_Joystick * joystick)
+{
+    Uint16 product;
+    SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick);
+
+    SDL_GetJoystickGUIDInfo(guid, NULL, &product, NULL);
+    return product;
+}
+
+Uint16 SDL_JoystickGetProductVersion(SDL_Joystick * joystick)
+{
+    Uint16 version;
+    SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick);
+
+    SDL_GetJoystickGUIDInfo(guid, NULL, NULL, &version);
+    return version;
+}
+
+SDL_JoystickType SDL_JoystickGetType(SDL_Joystick * joystick)
+{
+    SDL_JoystickType type;
+    SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick);
+
+    type = SDL_GetJoystickGUIDType(guid);
+    if (type == SDL_JOYSTICK_TYPE_UNKNOWN) {
+        if (joystick && joystick->is_game_controller) {
+            type = SDL_JOYSTICK_TYPE_GAMECONTROLLER;
+        }
+    }
+    return type;
+}
+
 /* convert the guid to a printable string */
 void SDL_JoystickGetGUIDString(SDL_JoystickGUID guid, char *pszGUID, int cbGUID)
 {
@@ -925,5 +1279,4 @@ SDL_JoystickPowerLevel SDL_JoystickCurrentPowerLevel(SDL_Joystick * joystick)
     return joystick->epowerlevel;
 }
 
-
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/joystick/SDL_joystick_c.h b/src/joystick/SDL_joystick_c.h
index cb9c925..5339b83 100644
--- a/src/joystick/SDL_joystick_c.h
+++ b/src/joystick/SDL_joystick_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -28,9 +28,23 @@ extern int SDL_JoystickInit(void);
 extern void SDL_JoystickQuit(void);
 
 /* Initialization and shutdown functions */
+extern int SDL_GameControllerInitMappings(void);
+extern void SDL_GameControllerQuitMappings(void);
 extern int SDL_GameControllerInit(void);
 extern void SDL_GameControllerQuit(void);
 
+/* Locking for multi-threaded access to the joystick API */
+extern void SDL_LockJoystickList(void);
+extern void SDL_UnlockJoystickList(void);
+
+/* Function to extract information from an SDL joystick GUID */
+extern void SDL_GetJoystickGUIDInfo(SDL_JoystickGUID guid, Uint16 *vendor, Uint16 *product, Uint16 *version);
+
+/* Function to return whether a joystick name and GUID is a game controller  */
+extern SDL_bool SDL_IsGameControllerNameAndGUID(const char *name, SDL_JoystickGUID guid);
+
+/* Function to return whether a game controller should be ignored */
+extern SDL_bool SDL_ShouldIgnoreGameController(const char *name, SDL_JoystickGUID guid);
 
 /* Internal event queueing functions */
 extern void SDL_PrivateJoystickAdded(int device_index);
diff --git a/src/joystick/SDL_sysjoystick.h b/src/joystick/SDL_sysjoystick.h
index f4cad05..e761fd2 100644
--- a/src/joystick/SDL_sysjoystick.h
+++ b/src/joystick/SDL_sysjoystick.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_sysjoystick_h
-#define _SDL_sysjoystick_h
+#ifndef SDL_sysjoystick_h_
+#define SDL_sysjoystick_h_
 
 /* This is the system specific header for the SDL joystick API */
 
@@ -29,14 +29,22 @@
 #include "SDL_joystick_c.h"
 
 /* The SDL joystick structure */
+typedef struct _SDL_JoystickAxisInfo
+{
+    Sint16 initial_value;       /* Initial axis state */
+    Sint16 value;               /* Current axis state */
+    Sint16 zero;                /* Zero point on the axis (-32768 for triggers) */
+    SDL_bool has_initial_value; /* Whether we've seen a value on the axis yet */
+    SDL_bool sent_initial_value; /* Whether we've sent the initial axis value */
+} SDL_JoystickAxisInfo;
+
 struct _SDL_Joystick
 {
     SDL_JoystickID instance_id; /* Device instance, monotonically increasing from 0 */
     char *name;                 /* Joystick name - system dependent */
 
     int naxes;                  /* Number of axis controls on the joystick */
-    Sint16 *axes;               /* Current axis states */
-    Sint16 *axes_zero;          /* Zero point on the axis (-32768 for triggers) */
+    SDL_JoystickAxisInfo *axes;
 
     int nhats;                  /* Number of hats on the joystick */
     Uint8 *hats;                /* Current hat states */
@@ -54,11 +62,15 @@ struct _SDL_Joystick
 
     int ref_count;              /* Reference count for multiple opens */
 
+    SDL_bool is_game_controller;
     SDL_bool force_recentering; /* SDL_TRUE if this device needs to have its state reset to 0 */
     SDL_JoystickPowerLevel epowerlevel; /* power level of this joystick, SDL_JOYSTICK_POWER_UNKNOWN if not supported */
     struct _SDL_Joystick *next; /* pointer to next joystick we have allocated */
 };
 
+/* Macro to combine a USB vendor ID and product ID into a single Uint32 value */
+#define MAKE_VIDPID(VID, PID)   (((Uint32)(VID))<<16|(PID))
+
 /* Function to scan the system for joysticks.
  * Joystick 0 should be the system default joystick.
  * This function should return the number of available joysticks, or -1
@@ -67,10 +79,10 @@ struct _SDL_Joystick
 extern int SDL_SYS_JoystickInit(void);
 
 /* Function to return the number of joystick devices plugged in right now */
-extern int SDL_SYS_NumJoysticks();
+extern int SDL_SYS_NumJoysticks(void);
 
 /* Function to cause any queued joystick insertions to be processed */
-extern void SDL_SYS_JoystickDetect();
+extern void SDL_SYS_JoystickDetect(void);
 
 /* Function to get the device-dependent name of a joystick */
 extern const char *SDL_SYS_JoystickNameForDeviceIndex(int device_index);
@@ -114,6 +126,6 @@ extern SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick * joystick);
 extern SDL_bool SDL_SYS_IsXInputGamepad_DeviceIndex(int device_index);
 #endif
 
-#endif /* _SDL_sysjoystick_h */
+#endif /* SDL_sysjoystick_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/joystick/android/SDL_sysjoystick.c b/src/joystick/android/SDL_sysjoystick.c
index a09e9a1..59adb85 100644
--- a/src/joystick/android/SDL_sysjoystick.c
+++ b/src/joystick/android/SDL_sysjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -167,7 +167,7 @@ keycode_to_SDL(int keycode)
             
         default:
             return -1;
-            break;
+            /* break; -Wunreachable-code-break */
     }
     
     /* This is here in case future generations, probably with six fingers per hand, 
@@ -244,7 +244,7 @@ Android_OnHat(int device_id, int hat_id, int x, int y)
 
 
 int
-Android_AddJoystick(int device_id, const char *name, SDL_bool is_accelerometer, int nbuttons, int naxes, int nhats, int nballs)
+Android_AddJoystick(int device_id, const char *name, const char *desc, SDL_bool is_accelerometer, int nbuttons, int naxes, int nhats, int nballs)
 {
     SDL_JoystickGUID guid;
     SDL_joylist_item *item;
@@ -255,7 +255,7 @@ Android_AddJoystick(int device_id, const char *name, SDL_bool is_accelerometer,
     
     /* the GUID is just the first 16 chars of the name for now */
     SDL_zero( guid );
-    SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
+    SDL_memcpy( &guid, desc, SDL_min( sizeof(guid), SDL_strlen( desc) ) );
 
     item = (SDL_joylist_item *) SDL_malloc(sizeof (SDL_joylist_item));
     if (item == NULL) {
@@ -356,19 +356,21 @@ SDL_SYS_JoystickInit(void)
     
     if (SDL_GetHintBoolean(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, SDL_TRUE)) {
         /* Default behavior, accelerometer as joystick */
-        Android_AddJoystick(ANDROID_ACCELEROMETER_DEVICE_ID, ANDROID_ACCELEROMETER_NAME, SDL_TRUE, 0, 3, 0, 0);
+        Android_AddJoystick(ANDROID_ACCELEROMETER_DEVICE_ID, ANDROID_ACCELEROMETER_NAME, ANDROID_ACCELEROMETER_NAME, SDL_TRUE, 0, 3, 0, 0);
     }
    
     return (numjoysticks);
 
 }
 
-int SDL_SYS_NumJoysticks()
+int
+SDL_SYS_NumJoysticks(void)
 {
     return numjoysticks;
 }
 
-void SDL_SYS_JoystickDetect()
+void
+SDL_SYS_JoystickDetect(void)
 {
     /* Support for device connect/disconnect is API >= 16 only,
      * so we poll every three seconds
diff --git a/src/joystick/android/SDL_sysjoystick_c.h b/src/joystick/android/SDL_sysjoystick_c.h
index 51803db..cae7aff 100644
--- a/src/joystick/android/SDL_sysjoystick_c.h
+++ b/src/joystick/android/SDL_sysjoystick_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,13 +22,17 @@
 #include "../../SDL_internal.h"
 
 #ifdef SDL_JOYSTICK_ANDROID
+
+#ifndef SDL_sysjoystick_c_h_
+#define SDL_sysjoystick_c_h_
+
 #include "../SDL_sysjoystick.h"
 
 extern int Android_OnPadDown(int device_id, int keycode);
 extern int Android_OnPadUp(int device_id, int keycode);
 extern int Android_OnJoy(int device_id, int axisnum, float value);
 extern int Android_OnHat(int device_id, int hat_id, int x, int y);
-extern int Android_AddJoystick(int device_id, const char *name, SDL_bool is_accelerometer, int nbuttons, int naxes, int nhats, int nballs);
+extern int Android_AddJoystick(int device_id, const char *name, const char *desc, SDL_bool is_accelerometer, int nbuttons, int naxes, int nhats, int nballs);
 extern int Android_RemoveJoystick(int device_id);
 
 /* A linked list of available joysticks */
@@ -47,6 +51,8 @@ typedef struct SDL_joylist_item
 
 typedef SDL_joylist_item joystick_hwdata;
 
+#endif /* SDL_sysjoystick_c_h_ */
+
 #endif /* SDL_JOYSTICK_ANDROID */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/joystick/bsd/SDL_sysjoystick.c b/src/joystick/bsd/SDL_sysjoystick.c
index ddc899f..89e1d8f 100644
--- a/src/joystick/bsd/SDL_sysjoystick.c
+++ b/src/joystick/bsd/SDL_sysjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -204,12 +204,14 @@ SDL_SYS_JoystickInit(void)
     return (SDL_SYS_numjoysticks);
 }
 
-int SDL_SYS_NumJoysticks()
+int
+SDL_SYS_NumJoysticks(void)
 {
     return SDL_SYS_numjoysticks;
 }
 
-void SDL_SYS_JoystickDetect()
+void
+SDL_SYS_JoystickDetect(void)
 {
 }
 
@@ -520,12 +522,8 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joy)
                 v *= 32768 / ((ymax - ymin + 1) / 2);
                 SDL_PrivateJoystickAxis(joy, 1, v);
             }
-            if (gameport.b1 != joy->buttons[0]) {
-                SDL_PrivateJoystickButton(joy, 0, gameport.b1);
-            }
-            if (gameport.b2 != joy->buttons[1]) {
-                SDL_PrivateJoystickButton(joy, 1, gameport.b2);
-            }
+            SDL_PrivateJoystickButton(joy, 0, gameport.b1);
+            SDL_PrivateJoystickButton(joy, 1, gameport.b2);
         }
         return;
     }
@@ -561,9 +559,7 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joy)
                             v *= 32768 /
                                 ((hitem.logical_maximum -
                                   hitem.logical_minimum + 1) / 2);
-                            if (v != joy->axes[naxe]) {
-                                SDL_PrivateJoystickAxis(joy, naxe, v);
-                            }
+                            SDL_PrivateJoystickAxis(joy, naxe, v);
                         } else if (usage == HUG_HAT_SWITCH) {
                             v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem);
                             SDL_PrivateJoystickHat(joy, 0,
@@ -574,9 +570,7 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joy)
                     }
                 case HUP_BUTTON:
                     v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem);
-                    if (joy->buttons[nbutton] != v) {
-                        SDL_PrivateJoystickButton(joy, nbutton, v);
-                    }
+                    SDL_PrivateJoystickButton(joy, nbutton, v);
                     nbutton++;
                     break;
                 default:
diff --git a/src/joystick/darwin/SDL_sysjoystick.c b/src/joystick/darwin/SDL_sysjoystick.c
index da10fba..a04a8e3 100644
--- a/src/joystick/darwin/SDL_sysjoystick.c
+++ b/src/joystick/darwin/SDL_sysjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -248,6 +248,8 @@ AddHIDElement(const void *value, void *parameter)
                         switch (usage) {
                             case kHIDUsage_Sim_Rudder:
                             case kHIDUsage_Sim_Throttle:
+                            case kHIDUsage_Sim_Accelerator:
+                            case kHIDUsage_Sim_Brake:
                                 if (!ElementAlreadyAdded(cookie, pDevice->firstAxis)) {
                                     element = (recElement *) SDL_calloc(1, sizeof (recElement));
                                     if (element) {
@@ -321,9 +323,14 @@ AddHIDElement(const void *value, void *parameter)
 static SDL_bool
 GetDeviceInfo(IOHIDDeviceRef hidDevice, recDevice *pDevice)
 {
-    Uint32 *guid32 = NULL;
+    const Uint16 BUS_USB = 0x03;
+    const Uint16 BUS_BLUETOOTH = 0x05;
+    Sint32 vendor = 0;
+    Sint32 product = 0;
+    Sint32 version = 0;
     CFTypeRef refCF = NULL;
     CFArrayRef array = NULL;
+    Uint16 *guid16 = (Uint16 *)pDevice->guid.data;
 
     /* get usage page and usage */
     refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDPrimaryUsagePageKey));
@@ -359,22 +366,32 @@ GetDeviceInfo(IOHIDDeviceRef hidDevice, recDevice *pDevice)
 
     refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDVendorIDKey));
     if (refCF) {
-        CFNumberGetValue(refCF, kCFNumberSInt32Type, &pDevice->guid.data[0]);
+        CFNumberGetValue(refCF, kCFNumberSInt32Type, &vendor);
     }
 
     refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDProductIDKey));
     if (refCF) {
-        CFNumberGetValue(refCF, kCFNumberSInt32Type, &pDevice->guid.data[8]);
+        CFNumberGetValue(refCF, kCFNumberSInt32Type, &product);
     }
 
-    /* Check to make sure we have a vendor and product ID
-       If we don't, use the same algorithm as the Linux code for Bluetooth devices */
-    guid32 = (Uint32*)pDevice->guid.data;
-    if (!guid32[0] && !guid32[1]) {
-        /* If we don't have a vendor and product ID this is probably a Bluetooth device */
-        const Uint16 BUS_BLUETOOTH = 0x05;
-        Uint16 *guid16 = (Uint16 *)guid32;
-        *guid16++ = BUS_BLUETOOTH;
+    refCF = IOHIDDeviceGetProperty(hidDevice, CFSTR(kIOHIDVersionNumberKey));
+    if (refCF) {
+        CFNumberGetValue(refCF, kCFNumberSInt32Type, &version);
+    }
+
+    SDL_memset(pDevice->guid.data, 0, sizeof(pDevice->guid.data));
+
+    if (vendor && product) {
+        *guid16++ = SDL_SwapLE16(BUS_USB);
+        *guid16++ = 0;
+        *guid16++ = SDL_SwapLE16((Uint16)vendor);
+        *guid16++ = 0;
+        *guid16++ = SDL_SwapLE16((Uint16)product);
+        *guid16++ = 0;
+        *guid16++ = SDL_SwapLE16((Uint16)version);
+        *guid16++ = 0;
+    } else {
+        *guid16++ = SDL_SwapLE16(BUS_BLUETOOTH);
         *guid16++ = 0;
         SDL_strlcpy((char*)guid16, pDevice->product, sizeof(pDevice->guid.data) - 4);
     }
@@ -428,6 +445,12 @@ JoystickDeviceWasAddedCallback(void *ctx, IOReturn res, void *sender, IOHIDDevic
         return;   /* not a device we care about, probably. */
     }
 
+    if (SDL_IsGameControllerNameAndGUID(device->product, device->guid) &&
+        SDL_ShouldIgnoreGameController(device->product, device->guid)) {
+        SDL_free(device);
+        return;
+    }
+
     /* Get notified when this device is disconnected. */
     IOHIDDeviceRegisterRemovalCallback(ioHIDDeviceObject, JoystickDeviceWasRemovedCallback, device);
     IOHIDDeviceScheduleWithRunLoop(ioHIDDeviceObject, CFRunLoopGetCurrent(), SDL_JOYSTICK_RUNLOOP_MODE);
@@ -565,7 +588,7 @@ SDL_SYS_JoystickInit(void)
 
 /* Function to return the number of joystick devices plugged in right now */
 int
-SDL_SYS_NumJoysticks()
+SDL_SYS_NumJoysticks(void)
 {
     recDevice *device = gpDeviceList;
     int nJoySticks = 0;
@@ -583,7 +606,7 @@ SDL_SYS_NumJoysticks()
 /* Function to cause any queued joystick insertions to be processed
  */
 void
-SDL_SYS_JoystickDetect()
+SDL_SYS_JoystickDetect(void)
 {
     recDevice *device = gpDeviceList;
     while (device) {
@@ -594,8 +617,8 @@ SDL_SYS_JoystickDetect()
         }
     }
 
-	// run this after the checks above so we don't set device->removed and delete the device before
-	// SDL_SYS_JoystickUpdate can run to clean up the SDL_Joystick object that owns this device
+	/* run this after the checks above so we don't set device->removed and delete the device before
+	   SDL_SYS_JoystickUpdate can run to clean up the SDL_Joystick object that owns this device */
 	while (CFRunLoopRunInMode(SDL_JOYSTICK_RUNLOOP_MODE,0,TRUE) == kCFRunLoopRunHandledSource) {
 		/* no-op. Pending callbacks will fire in CFRunLoopRunInMode(). */
 	}
@@ -677,9 +700,7 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
     i = 0;
     while (element) {
         value = GetHIDScaledCalibratedState(device, element, -32768, 32767);
-        if (value != joystick->axes[i]) {
-            SDL_PrivateJoystickAxis(joystick, i, value);
-        }
+        SDL_PrivateJoystickAxis(joystick, i, value);
         element = element->pNext;
         ++i;
     }
@@ -691,9 +712,7 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
         if (value > 1) {          /* handle pressure-sensitive buttons */
             value = 1;
         }
-        if (value != joystick->buttons[i]) {
-            SDL_PrivateJoystickButton(joystick, i, value);
-        }
+        SDL_PrivateJoystickButton(joystick, i, value);
         element = element->pNext;
         ++i;
     }
@@ -744,9 +763,7 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
             break;
         }
 
-        if (pos != joystick->hats[i]) {
-            SDL_PrivateJoystickHat(joystick, i, pos);
-        }
+        SDL_PrivateJoystickHat(joystick, i, pos);
 
         element = element->pNext;
         ++i;
diff --git a/src/joystick/darwin/SDL_sysjoystick_c.h b/src/joystick/darwin/SDL_sysjoystick_c.h
index 1c317ec..2a4c984 100644
--- a/src/joystick/darwin/SDL_sysjoystick_c.h
+++ b/src/joystick/darwin/SDL_sysjoystick_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -68,5 +68,6 @@ struct joystick_hwdata
 };
 typedef struct joystick_hwdata recDevice;
 
-
 #endif /* SDL_JOYSTICK_IOKIT_H */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/joystick/dummy/SDL_sysjoystick.c b/src/joystick/dummy/SDL_sysjoystick.c
index 10fda10..d33b3e4 100644
--- a/src/joystick/dummy/SDL_sysjoystick.c
+++ b/src/joystick/dummy/SDL_sysjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -37,12 +37,14 @@ SDL_SYS_JoystickInit(void)
     return 0;
 }
 
-int SDL_SYS_NumJoysticks()
+int
+SDL_SYS_NumJoysticks(void)
 {
     return 0;
 }
 
-void SDL_SYS_JoystickDetect()
+void
+SDL_SYS_JoystickDetect(void)
 {
 }
 
diff --git a/src/joystick/emscripten/SDL_sysjoystick.c b/src/joystick/emscripten/SDL_sysjoystick.c
index 6b20366..cd2fd56 100644
--- a/src/joystick/emscripten/SDL_sysjoystick.c
+++ b/src/joystick/emscripten/SDL_sysjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -28,7 +28,6 @@
 #include "SDL_events.h"
 
 #include "SDL_joystick.h"
-#include "SDL_hints.h"
 #include "SDL_assert.h"
 #include "SDL_timer.h"
 #include "SDL_log.h"
@@ -42,7 +41,7 @@ static SDL_joylist_item *SDL_joylist_tail = NULL;
 static int numjoysticks = 0;
 static int instance_counter = 0;
 
-EM_BOOL
+static EM_BOOL
 Emscripten_JoyStickConnected(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData)
 {
     int i;
@@ -111,7 +110,7 @@ Emscripten_JoyStickConnected(int eventType, const EmscriptenGamepadEvent *gamepa
     return 1;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_JoyStickDisconnected(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData)
 {
     SDL_joylist_item *item = SDL_joylist;
@@ -146,7 +145,7 @@ Emscripten_JoyStickDisconnected(int eventType, const EmscriptenGamepadEvent *gam
     /* Need to decrement the joystick count before we post the event */
     --numjoysticks;
 
-	SDL_PrivateJoystickRemoved(item->device_instance);
+    SDL_PrivateJoystickRemoved(item->device_instance);
 
 #ifdef DEBUG_JOYSTICK
     SDL_Log("Removed joystick with id %d", item->device_instance);
@@ -240,12 +239,14 @@ JoystickByIndex(int index)
     return item;
 }
 
-int SDL_SYS_NumJoysticks()
+int
+SDL_SYS_NumJoysticks(void)
 {
     return numjoysticks;
 }
 
-void SDL_SYS_JoystickDetect()
+void
+SDL_SYS_JoystickDetect(void)
 {
 }
 
@@ -329,7 +330,7 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
 
                 for(i = 0; i < item->naxes; i++) {
                     if(item->axis[i] != gamepadState.axis[i]) {
-                        // do we need to do conversion?
+                        /* do we need to do conversion? */
                         SDL_PrivateJoystickAxis(item->joystick, i,
                                                   (Sint16) (32767.*gamepadState.axis[i]));
                     }
diff --git a/src/joystick/emscripten/SDL_sysjoystick_c.h b/src/joystick/emscripten/SDL_sysjoystick_c.h
index 41f613e..54cd4af 100644
--- a/src/joystick/emscripten/SDL_sysjoystick_c.h
+++ b/src/joystick/emscripten/SDL_sysjoystick_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/joystick/haiku/SDL_haikujoystick.cc b/src/joystick/haiku/SDL_haikujoystick.cc
index a680189..5d49bda 100644
--- a/src/joystick/haiku/SDL_haikujoystick.cc
+++ b/src/joystick/haiku/SDL_haikujoystick.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,8 +24,8 @@
 
 /* This is the Haiku implementation of the SDL joystick API */
 
-#include <os/support/String.h>
-#include <os/device/Joystick.h>
+#include <support/String.h>
+#include <device/Joystick.h>
 
 extern "C"
 {
@@ -84,12 +84,12 @@ extern "C"
         return (SDL_SYS_numjoysticks);
     }
 
-    int SDL_SYS_NumJoysticks()
+    int SDL_SYS_NumJoysticks(void)
     {
         return SDL_SYS_numjoysticks;
     }
 
-    void SDL_SYS_JoystickDetect()
+    void SDL_SYS_JoystickDetect(void)
     {
     }
 
@@ -176,10 +176,9 @@ extern "C"
             SDL_HAT_LEFT,
             SDL_HAT_LEFTUP
         };
-        const int JITTER = (32768 / 10);        /* 10% jitter threshold (ok?) */
 
         BJoystick *stick;
-        int i, change;
+        int i;
         int16 *axes;
         uint8 *hats;
         uint32 buttons;
@@ -197,24 +196,17 @@ extern "C"
 
         /* Generate axis motion events */
         for (i = 0; i < joystick->naxes; ++i) {
-            change = ((int32) axes[i] - joystick->axes[i]);
-            if ((change > JITTER) || (change < -JITTER)) {
-                SDL_PrivateJoystickAxis(joystick, i, axes[i]);
-            }
+            SDL_PrivateJoystickAxis(joystick, i, axes[i]);
         }
 
         /* Generate hat change events */
         for (i = 0; i < joystick->nhats; ++i) {
-            if (hats[i] != joystick->hats[i]) {
-                SDL_PrivateJoystickHat(joystick, i, hat_map[hats[i]]);
-            }
+            SDL_PrivateJoystickHat(joystick, i, hat_map[hats[i]]);
         }
 
         /* Generate button events */
         for (i = 0; i < joystick->nbuttons; ++i) {
-            if ((buttons & 0x01) != joystick->buttons[i]) {
-                SDL_PrivateJoystickButton(joystick, i, (buttons & 0x01));
-            }
+            SDL_PrivateJoystickButton(joystick, i, (buttons & 0x01));
             buttons >>= 1;
         }
     }
@@ -236,12 +228,12 @@ extern "C"
     {
         int i;
 
-        for (i = 0; SDL_joyport[i]; ++i) {
+        for (i = 0; i < SDL_SYS_numjoysticks; ++i) {
             SDL_free(SDL_joyport[i]);
         }
         SDL_joyport[0] = NULL;
 
-        for (i = 0; SDL_joyname[i]; ++i) {
+        for (i = 0; i < SDL_SYS_numjoysticks; ++i) {
             SDL_free(SDL_joyname[i]);
         }
         SDL_joyname[0] = NULL;
diff --git a/src/joystick/iphoneos/SDL_sysjoystick.m b/src/joystick/iphoneos/SDL_sysjoystick.m
index eb7e000..3af5350 100644
--- a/src/joystick/iphoneos/SDL_sysjoystick.m
+++ b/src/joystick/iphoneos/SDL_sysjoystick.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -251,7 +251,7 @@ SDL_SYS_RemoveJoystickDevice(SDL_JoystickDeviceItem *device)
 }
 
 #if TARGET_OS_TV
-static void
+static void SDLCALL
 SDL_AppleTVRemoteRotationHintChanged(void *udata, const char *name, const char *oldValue, const char *newValue)
 {
     BOOL allowRotation = newValue != NULL && *newValue != '0';
@@ -326,12 +326,14 @@ SDL_SYS_JoystickInit(void)
     return numjoysticks;
 }
 
-int SDL_SYS_NumJoysticks()
+int
+SDL_SYS_NumJoysticks(void)
 {
     return numjoysticks;
 }
 
-void SDL_SYS_JoystickDetect()
+void
+SDL_SYS_JoystickDetect(void)
 {
 }
 
@@ -514,7 +516,7 @@ SDL_SYS_MFIJoystickUpdate(SDL_Joystick * joystick)
                  * initializes its values to 0. We only want to make sure the
                  * player index is up to date if the user actually moves an axis. */
                 if ((i != 2 && i != 5) || axes[i] != -32768) {
-                    updateplayerindex |= (joystick->axes[i] != axes[i]);
+                    updateplayerindex |= (joystick->axes[i].value != axes[i]);
                 }
                 SDL_PrivateJoystickAxis(joystick, i, axes[i]);
             }
@@ -551,7 +553,7 @@ SDL_SYS_MFIJoystickUpdate(SDL_Joystick * joystick)
             };
 
             for (i = 0; i < SDL_arraysize(axes); i++) {
-                updateplayerindex |= (joystick->axes[i] != axes[i]);
+                updateplayerindex |= (joystick->axes[i].value != axes[i]);
                 SDL_PrivateJoystickAxis(joystick, i, axes[i]);
             }
 
diff --git a/src/joystick/iphoneos/SDL_sysjoystick_c.h b/src/joystick/iphoneos/SDL_sysjoystick_c.h
index be0ddf0..dc0e7be 100644
--- a/src/joystick/iphoneos/SDL_sysjoystick_c.h
+++ b/src/joystick/iphoneos/SDL_sysjoystick_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/joystick/linux/SDL_sysjoystick.c b/src/joystick/linux/SDL_sysjoystick.c
index bd52b18..1f19d1d 100644
--- a/src/joystick/linux/SDL_sysjoystick.c
+++ b/src/joystick/linux/SDL_sysjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -52,7 +52,7 @@
 static int MaybeAddDevice(const char *path);
 #if SDL_USE_LIBUDEV
 static int MaybeRemoveDevice(const char *path);
-void joystick_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath);
+static void joystick_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath);
 #endif /* SDL_USE_LIBUDEV */
 
 
@@ -80,8 +80,102 @@ static int instance_counter = 0;
 static int
 IsJoystick(int fd, char *namebuf, const size_t namebuflen, SDL_JoystickGUID *guid)
 {
+    /* This list is taken from:
+       https://raw.githubusercontent.com/denilsonsa/udev-joystick-blacklist/master/generate_rules.py
+     */
+    static Uint32 joystick_blacklist[] = {
+        /* Microsoft Microsoft Wireless Optical Desktop® 2.10 */
+        /* Microsoft Wireless Desktop - Comfort Edition */
+        MAKE_VIDPID(0x045e, 0x009d),
+
+        /* Microsoft Microsoft® Digital Media Pro Keyboard */
+        /* Microsoft Corp. Digital Media Pro Keyboard */
+        MAKE_VIDPID(0x045e, 0x00b0),
+
+        /* Microsoft Microsoft® Digital Media Keyboard */
+        /* Microsoft Corp. Digital Media Keyboard 1.0A */
+        MAKE_VIDPID(0x045e, 0x00b4),
+
+        /* Microsoft Microsoft® Digital Media Keyboard 3000 */
+        MAKE_VIDPID(0x045e, 0x0730),
+
+        /* Microsoft Microsoft® 2.4GHz Transceiver v6.0 */
+        /* Microsoft Microsoft® 2.4GHz Transceiver v8.0 */
+        /* Microsoft Corp. Nano Transceiver v1.0 for Bluetooth */
+        /* Microsoft Wireless Mobile Mouse 1000 */
+        /* Microsoft Wireless Desktop 3000 */
+        MAKE_VIDPID(0x045e, 0x0745),
+
+        /* Microsoft® SideWinder(TM) 2.4GHz Transceiver */
+        MAKE_VIDPID(0x045e, 0x0748),
+
+        /* Microsoft Corp. Wired Keyboard 600 */
+        MAKE_VIDPID(0x045e, 0x0750),
+
+        /* Microsoft Corp. Sidewinder X4 keyboard */
+        MAKE_VIDPID(0x045e, 0x0768),
+
+        /* Microsoft Corp. Arc Touch Mouse Transceiver */
+        MAKE_VIDPID(0x045e, 0x0773),
+
+        /* Microsoft® 2.4GHz Transceiver v9.0 */
+        /* Microsoft® Nano Transceiver v2.1 */
+        /* Microsoft Sculpt Ergonomic Keyboard (5KV-00001) */
+        MAKE_VIDPID(0x045e, 0x07a5),
+
+        /* Microsoft® Nano Transceiver v1.0 */
+        /* Microsoft Wireless Keyboard 800 */
+        MAKE_VIDPID(0x045e, 0x07b2),
+
+        /* Microsoft® Nano Transceiver v2.0 */
+        MAKE_VIDPID(0x045e, 0x0800),
+
+        /* List of Wacom devices at: http://linuxwacom.sourceforge.net/wiki/index.php/Device_IDs */
+        MAKE_VIDPID(0x056a, 0x0010),  /* Wacom ET-0405 Graphire */
+        MAKE_VIDPID(0x056a, 0x0011),  /* Wacom ET-0405A Graphire2 (4x5) */
+        MAKE_VIDPID(0x056a, 0x0012),  /* Wacom ET-0507A Graphire2 (5x7) */
+        MAKE_VIDPID(0x056a, 0x0013),  /* Wacom CTE-430 Graphire3 (4x5) */
+        MAKE_VIDPID(0x056a, 0x0014),  /* Wacom CTE-630 Graphire3 (6x8) */
+        MAKE_VIDPID(0x056a, 0x0015),  /* Wacom CTE-440 Graphire4 (4x5) */
+        MAKE_VIDPID(0x056a, 0x0016),  /* Wacom CTE-640 Graphire4 (6x8) */
+        MAKE_VIDPID(0x056a, 0x0017),  /* Wacom CTE-450 Bamboo Fun (4x5) */
+        MAKE_VIDPID(0x056a, 0x0016),  /* Wacom CTE-640 Graphire 4 6x8 */
+        MAKE_VIDPID(0x056a, 0x0017),  /* Wacom CTE-450 Bamboo Fun 4x5 */
+        MAKE_VIDPID(0x056a, 0x0018),  /* Wacom CTE-650 Bamboo Fun 6x8 */
+        MAKE_VIDPID(0x056a, 0x0019),  /* Wacom CTE-631 Bamboo One */
+        MAKE_VIDPID(0x056a, 0x00d1),  /* Wacom Bamboo Pen and Touch CTH-460 */
+
+        MAKE_VIDPID(0x09da, 0x054f),  /* A4 Tech Co., G7 750 mouse */
+        MAKE_VIDPID(0x09da, 0x3043),  /* A4 Tech Co., Ltd Bloody R8A Gaming Mouse */
+        MAKE_VIDPID(0x09da, 0x31b5),  /* A4 Tech Co., Ltd Bloody TL80 Terminator Laser Gaming Mouse */
+        MAKE_VIDPID(0x09da, 0x3997),  /* A4 Tech Co., Ltd Bloody RT7 Terminator Wireless */
+        MAKE_VIDPID(0x09da, 0x3f8b),  /* A4 Tech Co., Ltd Bloody V8 mouse */
+        MAKE_VIDPID(0x09da, 0x51f4),  /* Modecom MC-5006 Keyboard */
+        MAKE_VIDPID(0x09da, 0x5589),  /* A4 Tech Co., Ltd Terminator TL9 Laser Gaming Mouse */
+        MAKE_VIDPID(0x09da, 0x7b22),  /* A4 Tech Co., Ltd Bloody V5 */
+        MAKE_VIDPID(0x09da, 0x7f2d),  /* A4 Tech Co., Ltd Bloody R3 mouse */
+        MAKE_VIDPID(0x09da, 0x8090),  /* A4 Tech Co., Ltd X-718BK Oscar Optical Gaming Mouse */
+        MAKE_VIDPID(0x09da, 0x9066),  /* A4 Tech Co., Sharkoon Fireglider Optical */
+        MAKE_VIDPID(0x09da, 0x9090),  /* A4 Tech Co., Ltd XL-730K / XL-750BK / XL-755BK Laser Mouse */
+        MAKE_VIDPID(0x09da, 0x90c0),  /* A4 Tech Co., Ltd X7 G800V keyboard */
+        MAKE_VIDPID(0x09da, 0xf012),  /* A4 Tech Co., Ltd Bloody V7 mouse */
+        MAKE_VIDPID(0x09da, 0xf32a),  /* A4 Tech Co., Ltd Bloody B540 keyboard */
+        MAKE_VIDPID(0x09da, 0xf613),  /* A4 Tech Co., Ltd Bloody V2 mouse */
+        MAKE_VIDPID(0x09da, 0xf624),  /* A4 Tech Co., Ltd Bloody B120 Keyboard */
+
+        MAKE_VIDPID(0x1d57, 0xad03),  /* [T3] 2.4GHz and IR Air Mouse Remote Control */
+
+        MAKE_VIDPID(0x1e7d, 0x2e4a),  /* Roccat Tyon Mouse */
+
+        MAKE_VIDPID(0x20a0, 0x422d),  /* Winkeyless.kr Keyboards */
+
+        MAKE_VIDPID(0x2516, 0x001f),  /* Cooler Master Storm Mizar Mouse */
+        MAKE_VIDPID(0x2516, 0x0028),  /* Cooler Master Storm Alcor Mouse */
+    };
     struct input_id inpid;
-    Uint16 *guid16 = (Uint16 *) ((char *) &guid->data);
+    int i;
+    Uint32 id;
+    Uint16 *guid16 = (Uint16 *)guid->data;
 
 #if !SDL_USE_LIBUDEV
     /* When udev is enabled we only get joystick devices here, so there's no need to test them */
@@ -109,33 +203,45 @@ IsJoystick(int fd, char *namebuf, const size_t namebuflen, SDL_JoystickGUID *gui
         return 0;
     }
 
+    /* Check the joystick blacklist */
+    id = MAKE_VIDPID(inpid.vendor, inpid.product);
+    for (i = 0; i < SDL_arraysize(joystick_blacklist); ++i) {
+        if (id == joystick_blacklist[i]) {
+            return 0;
+        }
+    }
+
 #ifdef DEBUG_JOYSTICK
-    printf("Joystick: %s, bustype = %d, vendor = 0x%x, product = 0x%x, version = %d\n", namebuf, inpid.bustype, inpid.vendor, inpid.product, inpid.version);
+    printf("Joystick: %s, bustype = %d, vendor = 0x%.4x, product = 0x%.4x, version = %d\n", namebuf, inpid.bustype, inpid.vendor, inpid.product, inpid.version);
 #endif
 
     SDL_memset(guid->data, 0, sizeof(guid->data));
 
     /* We only need 16 bits for each of these; space them out to fill 128. */
     /* Byteswap so devices get same GUID on little/big endian platforms. */
-    *(guid16++) = SDL_SwapLE16(inpid.bustype);
-    *(guid16++) = 0;
-
-    if (inpid.vendor && inpid.product && inpid.version) {
-        *(guid16++) = SDL_SwapLE16(inpid.vendor);
-        *(guid16++) = 0;
-        *(guid16++) = SDL_SwapLE16(inpid.product);
-        *(guid16++) = 0;
-        *(guid16++) = SDL_SwapLE16(inpid.version);
-        *(guid16++) = 0;
+    *guid16++ = SDL_SwapLE16(inpid.bustype);
+    *guid16++ = 0;
+
+    if (inpid.vendor && inpid.product) {
+        *guid16++ = SDL_SwapLE16(inpid.vendor);
+        *guid16++ = 0;
+        *guid16++ = SDL_SwapLE16(inpid.product);
+        *guid16++ = 0;
+        *guid16++ = SDL_SwapLE16(inpid.version);
+        *guid16++ = 0;
     } else {
         SDL_strlcpy((char*)guid16, namebuf, sizeof(guid->data) - 4);
     }
 
+    if (SDL_IsGameControllerNameAndGUID(namebuf, *guid) &&
+        SDL_ShouldIgnoreGameController(namebuf, *guid)) {
+        return 0;
+    }
     return 1;
 }
 
 #if SDL_USE_LIBUDEV
-void joystick_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath)
+static void joystick_udev_callback(SDL_UDEV_deviceevent udev_type, int udev_class, const char *devpath)
 {
     if (devpath == NULL) {
         return;
@@ -282,6 +388,7 @@ MaybeRemoveDevice(const char *path)
 }
 #endif
 
+#if ! SDL_USE_LIBUDEV
 static int
 JoystickInitWithoutUdev(void)
 {
@@ -298,7 +405,7 @@ JoystickInitWithoutUdev(void)
 
     return numjoysticks;
 }
-
+#endif
 
 #if SDL_USE_LIBUDEV
 static int
@@ -342,17 +449,19 @@ SDL_SYS_JoystickInit(void)
 
 #if SDL_USE_LIBUDEV
     return JoystickInitWithUdev();
-#endif
-
+#else 
     return JoystickInitWithoutUdev();
+#endif
 }
 
-int SDL_SYS_NumJoysticks()
+int
+SDL_SYS_NumJoysticks(void)
 {
     return numjoysticks;
 }
 
-void SDL_SYS_JoystickDetect()
+void
+SDL_SYS_JoystickDetect(void)
 {
 #if SDL_USE_LIBUDEV
     SDL_UDEV_Poll();
@@ -446,16 +555,16 @@ ConfigJoystick(SDL_Joystick * joystick, int fd)
 #ifdef DEBUG_INPUT_EVENTS
                 printf("Joystick has button: 0x%x\n", i);
 #endif
-                joystick->hwdata->key_map[i - BTN_MISC] = joystick->nbuttons;
+                joystick->hwdata->key_map[i] = joystick->nbuttons;
                 ++joystick->nbuttons;
             }
         }
-        for (i = BTN_MISC; i < BTN_JOYSTICK; ++i) {
+        for (i = 0; i < BTN_JOYSTICK; ++i) {
             if (test_bit(i, keybit)) {
 #ifdef DEBUG_INPUT_EVENTS
                 printf("Joystick has button: 0x%x\n", i);
 #endif
-                joystick->hwdata->key_map[i - BTN_MISC] = joystick->nbuttons;
+                joystick->hwdata->key_map[i] = joystick->nbuttons;
                 ++joystick->nbuttons;
             }
         }
@@ -712,12 +821,9 @@ HandleInputEvents(SDL_Joystick * joystick)
             code = events[i].code;
             switch (events[i].type) {
             case EV_KEY:
-                if (code >= BTN_MISC) {
-                    code -= BTN_MISC;
-                    SDL_PrivateJoystickButton(joystick,
-                                              joystick->hwdata->key_map[code],
-                                              events[i].value);
-                }
+                SDL_PrivateJoystickButton(joystick,
+                                          joystick->hwdata->key_map[code],
+                                          events[i].value);
                 break;
             case EV_ABS:
                 switch (code) {
diff --git a/src/joystick/linux/SDL_sysjoystick_c.h b/src/joystick/linux/SDL_sysjoystick_c.h
index ee77178..5c2ed5b 100644
--- a/src/joystick/linux/SDL_sysjoystick_c.h
+++ b/src/joystick/linux/SDL_sysjoystick_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -43,7 +43,7 @@ struct joystick_hwdata
     } *balls;
 
     /* Support for the Linux 2.4 unified input interface */
-    Uint8 key_map[KEY_MAX - BTN_MISC];
+    Uint8 key_map[KEY_MAX];
     Uint8 abs_map[ABS_MAX];
     struct axis_correct
     {
diff --git a/src/joystick/psp/SDL_sysjoystick.c b/src/joystick/psp/SDL_sysjoystick.c
index 352960e..5dc4db2 100644
--- a/src/joystick/psp/SDL_sysjoystick.c
+++ b/src/joystick/psp/SDL_sysjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -132,12 +132,12 @@ int SDL_SYS_JoystickInit(void)
     return 1;
 }
 
-int SDL_SYS_NumJoysticks()
+int SDL_SYS_NumJoysticks(void)
 {
     return 1;
 }
 
-void SDL_SYS_JoystickDetect()
+void SDL_SYS_JoystickDetect(void)
 {
 }
 
diff --git a/src/joystick/sort_controllers.py b/src/joystick/sort_controllers.py
index af95d65..47213c2 100755
--- a/src/joystick/sort_controllers.py
+++ b/src/joystick/sort_controllers.py
@@ -29,6 +29,7 @@ def write_controllers():
     global controller_guids
     for entry in sorted(controllers, key=lambda entry: entry[2]):
         line = "".join(entry) + "\n"
+        line = line.replace("\t", "    ")
         if not line.endswith(",\n") and not line.endswith("*/\n"):
             print("Warning: '%s' is missing a comma at the end of the line" % (line))
         if (entry[1] in controller_guids):
diff --git a/src/joystick/windows/SDL_dinputjoystick.c b/src/joystick/windows/SDL_dinputjoystick.c
index 7166075..3669e4c 100644
--- a/src/joystick/windows/SDL_dinputjoystick.c
+++ b/src/joystick/windows/SDL_dinputjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,9 +33,7 @@
 #endif
 
 #define INPUT_QSIZE 32      /* Buffer up to 32 input messages */
-#define AXIS_MIN    -32768  /* minimum value for axis coordinate */
-#define AXIS_MAX    32767   /* maximum value for axis coordinate */
-#define JOY_AXIS_THRESHOLD  (((AXIS_MAX)-(AXIS_MIN))/100)   /* 1% motion */
+#define JOY_AXIS_THRESHOLD  (((SDL_JOYSTICK_AXIS_MAX)-(SDL_JOYSTICK_AXIS_MIN))/100)   /* 1% motion */
 
 /* external variables referenced. */
 extern HWND SDL_HelperWindow;
@@ -350,21 +348,70 @@ SDL_DINPUT_JoystickInit(void)
 static BOOL CALLBACK
 EnumJoysticksCallback(const DIDEVICEINSTANCE * pdidInstance, VOID * pContext)
 {
+    const Uint16 BUS_USB = 0x03;
+    const Uint16 BUS_BLUETOOTH = 0x05;
     JoyStick_DeviceData *pNewJoystick;
     JoyStick_DeviceData *pPrevJoystick = NULL;
     const DWORD devtype = (pdidInstance->dwDevType & 0xFF);
+    Uint16 *guid16;
+    WCHAR hidPath[MAX_PATH];
 
     if (devtype == DI8DEVTYPE_SUPPLEMENTAL) {
-        return DIENUM_CONTINUE;  /* Ignore touchpads, etc. */
+        /* Add any supplemental devices that should be ignored here */
+#define MAKE_TABLE_ENTRY(VID, PID)	((((DWORD)PID)<<16)|VID)
+		static DWORD ignored_devices[] = {
+			MAKE_TABLE_ENTRY(0, 0)
+		};
+#undef MAKE_TABLE_ENTRY
+		unsigned int i;
+
+		for (i = 0; i < SDL_arraysize(ignored_devices); ++i) {
+			if (pdidInstance->guidProduct.Data1 == ignored_devices[i]) {
+				return DIENUM_CONTINUE;
+			}
+		}
     }
 
     if (SDL_IsXInputDevice(&pdidInstance->guidProduct)) {
         return DIENUM_CONTINUE;  /* ignore XInput devices here, keep going. */
     }
 
+    {
+        HRESULT result;
+        LPDIRECTINPUTDEVICE8 device;
+        LPDIRECTINPUTDEVICE8 InputDevice;
+        DIPROPGUIDANDPATH dipdw2;
+
+        result = IDirectInput8_CreateDevice(dinput, &(pdidInstance->guidInstance), &device, NULL);
+        if (FAILED(result)) {
+            return DIENUM_CONTINUE; /* better luck next time? */
+        }
+
+        /* Now get the IDirectInputDevice8 interface, instead. */
+        result = IDirectInputDevice8_QueryInterface(device, &IID_IDirectInputDevice8, (LPVOID *)&InputDevice);
+        /* We are done with this object.  Use the stored one from now on. */
+        IDirectInputDevice8_Release(device);
+        if (FAILED(result)) {
+            return DIENUM_CONTINUE; /* better luck next time? */
+        }
+        dipdw2.diph.dwSize = sizeof(dipdw2);
+        dipdw2.diph.dwHeaderSize = sizeof(dipdw2.diph);
+        dipdw2.diph.dwObj = 0; // device property
+        dipdw2.diph.dwHow = DIPH_DEVICE;
+
+        result = IDirectInputDevice8_GetProperty(InputDevice, DIPROP_GUIDANDPATH, &dipdw2.diph);
+        IDirectInputDevice8_Release(InputDevice);
+        if (FAILED(result)) {
+            return DIENUM_CONTINUE; /* better luck next time? */
+        }
+
+        /* Get device path, compare that instead of GUID, additionally update GUIDs of joysticks with matching paths, in case they're not open yet. */
+        SDL_wcslcpy(hidPath, dipdw2.wszPath, SDL_arraysize(hidPath));
+    }
+
     pNewJoystick = *(JoyStick_DeviceData **)pContext;
     while (pNewJoystick) {
-        if (!SDL_memcmp(&pNewJoystick->dxdevice.guidInstance, &pdidInstance->guidInstance, sizeof(pNewJoystick->dxdevice.guidInstance))) {
+        if (SDL_wcscmp(pNewJoystick->hidPath, hidPath) == 0) {
             /* if we are replacing the front of the list then update it */
             if (pNewJoystick == *(JoyStick_DeviceData **)pContext) {
                 *(JoyStick_DeviceData **)pContext = pNewJoystick->pNext;
@@ -372,6 +419,9 @@ EnumJoysticksCallback(const DIDEVICEINSTANCE * pdidInstance, VOID * pContext)
                 pPrevJoystick->pNext = pNewJoystick->pNext;
             }
 
+            // Update with new guid/etc, if it has changed
+            pNewJoystick->dxdevice = *pdidInstance;
+
             pNewJoystick->pNext = SYS_Joystick;
             SYS_Joystick = pNewJoystick;
 
@@ -388,6 +438,7 @@ EnumJoysticksCallback(const DIDEVICEINSTANCE * pdidInstance, VOID * pContext)
     }
 
     SDL_zerop(pNewJoystick);
+    SDL_wcslcpy(pNewJoystick->hidPath, hidPath, SDL_arraysize(pNewJoystick->hidPath));
     pNewJoystick->joystickname = WIN_StringToUTF8(pdidInstance->tszProductName);
     if (!pNewJoystick->joystickname) {
         SDL_free(pNewJoystick);
@@ -397,7 +448,30 @@ EnumJoysticksCallback(const DIDEVICEINSTANCE * pdidInstance, VOID * pContext)
     SDL_memcpy(&(pNewJoystick->dxdevice), pdidInstance,
         sizeof(DIDEVICEINSTANCE));
 
-    SDL_memcpy(&pNewJoystick->guid, &pdidInstance->guidProduct, sizeof(pNewJoystick->guid));
+    SDL_memset(pNewJoystick->guid.data, 0, sizeof(pNewJoystick->guid.data));
+
+    guid16 = (Uint16 *)pNewJoystick->guid.data;
+    if (SDL_memcmp(&pdidInstance->guidProduct.Data4[2], "PIDVID", 6) == 0) {
+        *guid16++ = SDL_SwapLE16(BUS_USB);
+        *guid16++ = 0;
+        *guid16++ = SDL_SwapLE16((Uint16)LOWORD(pdidInstance->guidProduct.Data1)); /* vendor */
+        *guid16++ = 0;
+        *guid16++ = SDL_SwapLE16((Uint16)HIWORD(pdidInstance->guidProduct.Data1)); /* product */
+        *guid16++ = 0;
+        *guid16++ = 0; /* version */
+        *guid16++ = 0;
+    } else {
+        *guid16++ = SDL_SwapLE16(BUS_BLUETOOTH);
+        *guid16++ = 0;
+        SDL_strlcpy((char*)guid16, pNewJoystick->joystickname, sizeof(pNewJoystick->guid.data) - 4);
+    }
+
+    if (SDL_IsGameControllerNameAndGUID(pNewJoystick->joystickname, pNewJoystick->guid) &&
+        SDL_ShouldIgnoreGameController(pNewJoystick->joystickname, pNewJoystick->guid)) {
+        SDL_free(pNewJoystick);
+        return DIENUM_CONTINUE;
+    }
+
     SDL_SYS_AddJoystickDevice(pNewJoystick);
 
     return DIENUM_CONTINUE; /* get next device, please */
@@ -461,8 +535,8 @@ EnumDevObjectsCallback(LPCDIDEVICEOBJECTINSTANCE dev, LPVOID pvRef)
         diprg.diph.dwHeaderSize = sizeof(diprg.diph);
         diprg.diph.dwObj = dev->dwType;
         diprg.diph.dwHow = DIPH_BYID;
-        diprg.lMin = AXIS_MIN;
-        diprg.lMax = AXIS_MAX;
+        diprg.lMin = SDL_JOYSTICK_AXIS_MIN;
+        diprg.lMax = SDL_JOYSTICK_AXIS_MAX;
 
         result =
             IDirectInputDevice8_SetProperty(joystick->hwdata->InputDevice,
diff --git a/src/joystick/windows/SDL_dinputjoystick_c.h b/src/joystick/windows/SDL_dinputjoystick_c.h
index 7e4ff3e..393fe79 100644
--- a/src/joystick/windows/SDL_dinputjoystick_c.h
+++ b/src/joystick/windows/SDL_dinputjoystick_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/joystick/windows/SDL_mmjoystick.c b/src/joystick/windows/SDL_mmjoystick.c
index 3746181..847c750 100644
--- a/src/joystick/windows/SDL_mmjoystick.c
+++ b/src/joystick/windows/SDL_mmjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -41,10 +41,6 @@
 #define MAX_JOYSTICKS   16
 #define MAX_AXES    6       /* each joystick can have up to 6 axes */
 #define MAX_BUTTONS 32      /* and 32 buttons                      */
-#define AXIS_MIN    -32768  /* minimum value for axis coordinate */
-#define AXIS_MAX    32767   /* maximum value for axis coordinate */
-/* limit axis to 256 possible positions to filter out noise */
-#define JOY_AXIS_THRESHOLD      (((AXIS_MAX)-(AXIS_MIN))/256)
 #define JOY_BUTTON_FLAG(n)  (1<<n)
 
 
@@ -89,7 +85,12 @@ GetJoystickName(int index, const char *szRegKey)
     char regvalue[256];
     char regname[256];
 
-    SDL_snprintf(regkey, SDL_arraysize(regkey), "%s\\%s\\%s",
+    SDL_snprintf(regkey, SDL_arraysize(regkey),
+#ifdef UNICODE
+                 "%S\\%s\\%S",
+#else
+                 "%s\\%s\\%s",
+#endif
                  REGSTR_PATH_JOYCONFIG, szRegKey, REGSTR_KEY_JOYCURR);
     hTopKey = HKEY_LOCAL_MACHINE;
     regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
@@ -114,8 +115,13 @@ GetJoystickName(int index, const char *szRegKey)
     }
 
     /* open that registry key */
-    SDL_snprintf(regkey, SDL_arraysize(regkey), "%s\\%s", REGSTR_PATH_JOYOEM,
-                 regname);
+    SDL_snprintf(regkey, SDL_arraysize(regkey),
+#ifdef UNICODE
+                 "%S\\%s",
+#else
+                 "%s\\%s",
+#endif
+                 REGSTR_PATH_JOYOEM, regname);
     regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
     if (regresult != ERROR_SUCCESS) {
         return NULL;
@@ -183,12 +189,14 @@ SDL_SYS_JoystickInit(void)
     return (SDL_SYS_numjoysticks);
 }
 
-int SDL_SYS_NumJoysticks()
+int
+SDL_SYS_NumJoysticks(void)
 {
     return SDL_SYS_numjoysticks;
 }
 
-void SDL_SYS_JoystickDetect()
+void
+SDL_SYS_JoystickDetect(void)
 {
 }
 
@@ -251,9 +259,9 @@ SDL_SYS_JoystickOpen(SDL_Joystick * joystick, int device_index)
     joystick->hwdata->id = SYS_JoystickID[index];
     for (i = 0; i < MAX_AXES; ++i) {
         if ((i < 2) || (SYS_Joystick[index].wCaps & caps_flags[i - 2])) {
-            joystick->hwdata->transaxis[i].offset = AXIS_MIN - axis_min[i];
+            joystick->hwdata->transaxis[i].offset = SDL_JOYSTICK_AXIS_MIN - axis_min[i];
             joystick->hwdata->transaxis[i].scale =
-                (float) (AXIS_MAX - AXIS_MIN) / (axis_max[i] - axis_min[i]);
+                (float) (SDL_JOYSTICK_AXIS_MAX - SDL_JOYSTICK_AXIS_MIN) / (axis_max[i] - axis_min[i]);
         } else {
             joystick->hwdata->transaxis[i].offset = 0;
             joystick->hwdata->transaxis[i].scale = 1.0; /* Just in case */
@@ -315,7 +323,7 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
     };
     DWORD pos[MAX_AXES];
     struct _transaxis *transaxis;
-    int value, change;
+    int value;
     JOYINFOEX joyinfo;
 
     joyinfo.dwSize = sizeof(joyinfo);
@@ -340,14 +348,8 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
     transaxis = joystick->hwdata->transaxis;
     for (i = 0; i < joystick->naxes; i++) {
         if (joyinfo.dwFlags & flags[i]) {
-            value =
-                (int) (((float) pos[i] +
-                        transaxis[i].offset) * transaxis[i].scale);
-            change = (value - joystick->axes[i]);
-            if ((change < -JOY_AXIS_THRESHOLD)
-                || (change > JOY_AXIS_THRESHOLD)) {
-                SDL_PrivateJoystickAxis(joystick, (Uint8) i, (Sint16) value);
-            }
+            value = (int) (((float) pos[i] + transaxis[i].offset) * transaxis[i].scale);
+            SDL_PrivateJoystickAxis(joystick, (Uint8) i, (Sint16) value);
         }
     }
 
@@ -355,15 +357,9 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
     if (joyinfo.dwFlags & JOY_RETURNBUTTONS) {
         for (i = 0; i < joystick->nbuttons; ++i) {
             if (joyinfo.dwButtons & JOY_BUTTON_FLAG(i)) {
-                if (!joystick->buttons[i]) {
-                    SDL_PrivateJoystickButton(joystick, (Uint8) i,
-                                              SDL_PRESSED);
-                }
+                SDL_PrivateJoystickButton(joystick, (Uint8) i, SDL_PRESSED);
             } else {
-                if (joystick->buttons[i]) {
-                    SDL_PrivateJoystickButton(joystick, (Uint8) i,
-                                              SDL_RELEASED);
-                }
+                SDL_PrivateJoystickButton(joystick, (Uint8) i, SDL_RELEASED);
             }
         }
     }
@@ -373,9 +369,7 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
         Uint8 pos;
 
         pos = TranslatePOV(joyinfo.dwPOV);
-        if (pos != joystick->hats[0]) {
-            SDL_PrivateJoystickHat(joystick, 0, pos);
-        }
+        SDL_PrivateJoystickHat(joystick, 0, pos);
     }
 }
 
diff --git a/src/joystick/windows/SDL_windowsjoystick.c b/src/joystick/windows/SDL_windowsjoystick.c
index e528afa..0babe21 100644
--- a/src/joystick/windows/SDL_windowsjoystick.c
+++ b/src/joystick/windows/SDL_windowsjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -37,8 +37,6 @@
 #include "SDL_events.h"
 #include "SDL_timer.h"
 #include "SDL_mutex.h"
-#include "SDL_events.h"
-#include "SDL_hints.h"
 #include "SDL_joystick.h"
 #include "../SDL_sysjoystick.h"
 #include "../../thread/SDL_systhread.h"
@@ -91,9 +89,10 @@ SDL_CreateDeviceNotification(SDL_DeviceNotificationData *data)
     return 0;
 }
 
-static void
-SDL_CheckDeviceNotification(SDL_DeviceNotificationData *data)
+static SDL_bool
+SDL_WaitForDeviceNotification(SDL_DeviceNotificationData *data, SDL_mutex *mutex)
 {
+    return SDL_FALSE;
 }
 
 #else /* !__WINRT__ */
@@ -106,6 +105,8 @@ typedef struct
     HDEVNOTIFY hNotify;
 } SDL_DeviceNotificationData;
 
+#define IDT_SDL_DEVICE_CHANGE_TIMER_1 1200
+#define IDT_SDL_DEVICE_CHANGE_TIMER_2 1201
 
 /* windowproc for our joystick detect thread message only window, to detect any USB device addition/removal */
 static LRESULT CALLBACK
@@ -115,17 +116,19 @@ SDL_PrivateJoystickDetectProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lPa
     case WM_DEVICECHANGE:
         switch (wParam) {
         case DBT_DEVICEARRIVAL:
-            if (((DEV_BROADCAST_HDR*)lParam)->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
-                s_bWindowsDeviceChanged = SDL_TRUE;
-            }
-            break;
         case DBT_DEVICEREMOVECOMPLETE:
             if (((DEV_BROADCAST_HDR*)lParam)->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
-                s_bWindowsDeviceChanged = SDL_TRUE;
+                /* notify 300ms and 2 seconds later to ensure all APIs have updated status */
+                SetTimer(hwnd, IDT_SDL_DEVICE_CHANGE_TIMER_1, 300, NULL);
+                SetTimer(hwnd, IDT_SDL_DEVICE_CHANGE_TIMER_2, 2000, NULL);
             }
             break;
         }
         return 0;
+    case WM_TIMER:
+        KillTimer(hwnd, wParam);
+        s_bWindowsDeviceChanged = SDL_TRUE;
+        return 0;
     }
 
     return DefWindowProc (hwnd, message, wParam, lParam);
@@ -189,21 +192,26 @@ SDL_CreateDeviceNotification(SDL_DeviceNotificationData *data)
     return 0;
 }
 
-static void
-SDL_CheckDeviceNotification(SDL_DeviceNotificationData *data)
+static SDL_bool
+SDL_WaitForDeviceNotification(SDL_DeviceNotificationData *data, SDL_mutex *mutex)
 {
     MSG msg;
+    int lastret = 1;
 
     if (!data->messageWindow) {
-        return;
+        return SDL_FALSE; /* device notifications require a window */
     }
 
-    while (PeekMessage(&msg, data->messageWindow, 0, 0, PM_NOREMOVE)) {
-        if (GetMessage(&msg, data->messageWindow, 0, 0) != 0)  {
+    SDL_UnlockMutex(mutex);
+    while (lastret > 0 && s_bWindowsDeviceChanged == SDL_FALSE) {
+        lastret = GetMessage(&msg, NULL, 0, 0); /* WM_QUIT causes return value of 0 */
+        if (lastret > 0) {
             TranslateMessage(&msg);
             DispatchMessage(&msg);
         }
     }
+    SDL_LockMutex(mutex);
+    return (lastret != -1) ? SDL_TRUE : SDL_FALSE;
 }
 
 #endif /* __WINRT__ */
@@ -227,31 +235,30 @@ SDL_JoystickThread(void *_data)
     while (s_bJoystickThreadQuit == SDL_FALSE) {
         SDL_bool bXInputChanged = SDL_FALSE;
 
-        SDL_CondWaitTimeout(s_condJoystickThread, s_mutexJoyStickEnum, 300);
-
-        SDL_CheckDeviceNotification(&notification_data);
-
+        if (SDL_WaitForDeviceNotification(&notification_data, s_mutexJoyStickEnum) == SDL_FALSE) {
 #if SDL_JOYSTICK_XINPUT
-        if (SDL_XINPUT_Enabled() && XINPUTGETCAPABILITIES) {
-            /* scan for any change in XInput devices */
-            Uint8 userId;
-            for (userId = 0; userId < XUSER_MAX_COUNT; userId++) {
-                XINPUT_CAPABILITIES capabilities;
-                const DWORD result = XINPUTGETCAPABILITIES(userId, XINPUT_FLAG_GAMEPAD, &capabilities);
-                const SDL_bool available = (result == ERROR_SUCCESS);
-                if (bOpenedXInputDevices[userId] != available) {
-                    bXInputChanged = SDL_TRUE;
-                    bOpenedXInputDevices[userId] = available;
+            /* WM_DEVICECHANGE not working, poll for new XINPUT controllers */
+            SDL_CondWaitTimeout(s_condJoystickThread, s_mutexJoyStickEnum, 1000);
+            if (SDL_XINPUT_Enabled() && XINPUTGETCAPABILITIES) {
+                /* scan for any change in XInput devices */
+                Uint8 userId;
+                for (userId = 0; userId < XUSER_MAX_COUNT; userId++) {
+                    XINPUT_CAPABILITIES capabilities;
+                    const DWORD result = XINPUTGETCAPABILITIES(userId, XINPUT_FLAG_GAMEPAD, &capabilities);
+                    const SDL_bool available = (result == ERROR_SUCCESS);
+                    if (bOpenedXInputDevices[userId] != available) {
+                        bXInputChanged = SDL_TRUE;
+                        bOpenedXInputDevices[userId] = available;
+                    }
                 }
             }
-        }
+#else
+            /* WM_DEVICECHANGE not working, no XINPUT, no point in keeping thread alive */
+            break;
 #endif /* SDL_JOYSTICK_XINPUT */
+		}
 
         if (s_bWindowsDeviceChanged || bXInputChanged) {
-            SDL_UnlockMutex(s_mutexJoyStickEnum);  /* let main thread go while we SDL_Delay(). */
-            SDL_Delay(300); /* wait for direct input to find out about this device */
-            SDL_LockMutex(s_mutexJoyStickEnum);
-
             s_bDeviceRemoved = SDL_TRUE;
             s_bDeviceAdded = SDL_TRUE;
             s_bWindowsDeviceChanged = SDL_FALSE;
@@ -307,7 +314,7 @@ SDL_SYS_JoystickInit(void)
 
 /* return the number of joysticks that are connected right now */
 int
-SDL_SYS_NumJoysticks()
+SDL_SYS_NumJoysticks(void)
 {
     int nJoysticks = 0;
     JoyStick_DeviceData *device = SYS_Joystick;
@@ -321,7 +328,7 @@ SDL_SYS_NumJoysticks()
 
 /* detect any new joysticks being inserted into the system */
 void
-SDL_SYS_JoystickDetect()
+SDL_SYS_JoystickDetect(void)
 {
     JoyStick_DeviceData *pCurList = NULL;
 
@@ -498,6 +505,9 @@ SDL_SYS_JoystickQuit(void)
         s_bJoystickThreadQuit = SDL_TRUE;
         SDL_CondBroadcast(s_condJoystickThread); /* signal the joystick thread to quit */
         SDL_UnlockMutex(s_mutexJoyStickEnum);
+#ifndef __WINRT__
+        PostThreadMessage(SDL_GetThreadID(s_threadJoystick), WM_QUIT, 0, 0);
+#endif
         SDL_WaitThread(s_threadJoystick, NULL); /* wait for it to bugger off */
 
         SDL_DestroyMutex(s_mutexJoyStickEnum);
diff --git a/src/joystick/windows/SDL_windowsjoystick_c.h b/src/joystick/windows/SDL_windowsjoystick_c.h
index d3c5fca..0b3a4d0 100644
--- a/src/joystick/windows/SDL_windowsjoystick_c.h
+++ b/src/joystick/windows/SDL_windowsjoystick_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -37,6 +37,7 @@ typedef struct JoyStick_DeviceData
     BYTE SubType;
     Uint8 XInputUserId;
     DIDEVICEINSTANCE dxdevice;
+    WCHAR hidPath[MAX_PATH];
     struct JoyStick_DeviceData *pNext;
 } JoyStick_DeviceData;
 
diff --git a/src/joystick/windows/SDL_xinputjoystick.c b/src/joystick/windows/SDL_xinputjoystick.c
index d581d45..d2ae19f 100644
--- a/src/joystick/windows/SDL_xinputjoystick.c
+++ b/src/joystick/windows/SDL_xinputjoystick.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,16 +33,22 @@
  * Internal stuff.
  */
 static SDL_bool s_bXInputEnabled = SDL_TRUE;
+static char *s_arrXInputDevicePath[XUSER_MAX_COUNT];
 
 
 static SDL_bool
 SDL_XInputUseOldJoystickMapping()
 {
+#ifdef __WINRT__
+    /* TODO: remove this __WINRT__ block, but only after integrating with UWP/WinRT's HID API */
+    return SDL_TRUE;
+#else
     static int s_XInputUseOldJoystickMapping = -1;
     if (s_XInputUseOldJoystickMapping < 0) {
         s_XInputUseOldJoystickMapping = SDL_GetHintBoolean(SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING, SDL_FALSE);
     }
     return (s_XInputUseOldJoystickMapping > 0);
+#endif
 }
 
 SDL_bool SDL_XINPUT_Enabled(void)
@@ -104,8 +110,80 @@ GetXInputName(const Uint8 userid, BYTE SubType)
     return SDL_strdup(name);
 }
 
+/* We can't really tell what device is being used for XInput, but we can guess
+   and we'll be correct for the case where only one device is connected.
+ */
+static void
+GuessXInputDevice(Uint8 userid, Uint16 *pVID, Uint16 *pPID, Uint16 *pVersion)
+{
+#ifndef __WINRT__   /* TODO: remove this ifndef __WINRT__ block, but only after integrating with UWP/WinRT's HID API */
+
+    PRAWINPUTDEVICELIST devices = NULL;
+    UINT i, j, device_count = 0;
+
+    if ((GetRawInputDeviceList(NULL, &device_count, sizeof(RAWINPUTDEVICELIST)) == -1) || (!device_count)) {
+        return;  /* oh well. */
+    }
+
+    devices = (PRAWINPUTDEVICELIST)SDL_malloc(sizeof(RAWINPUTDEVICELIST) * device_count);
+    if (devices == NULL) {
+        return;
+    }
+
+    if (GetRawInputDeviceList(devices, &device_count, sizeof(RAWINPUTDEVICELIST)) == -1) {
+        SDL_free(devices);
+        return;  /* oh well. */
+    }
+
+    for (i = 0; i < device_count; i++) {
+        RID_DEVICE_INFO rdi;
+        char devName[128];
+        UINT rdiSize = sizeof(rdi);
+        UINT nameSize = SDL_arraysize(devName);
+
+        rdi.cbSize = sizeof(rdi);
+        if ((devices[i].dwType == RIM_TYPEHID) &&
+            (GetRawInputDeviceInfoA(devices[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) != ((UINT)-1)) &&
+            (GetRawInputDeviceInfoA(devices[i].hDevice, RIDI_DEVICENAME, devName, &nameSize) != ((UINT)-1)) &&
+            (SDL_strstr(devName, "IG_") != NULL)) {
+            SDL_bool found = SDL_FALSE;
+            for (j = 0; j < SDL_arraysize(s_arrXInputDevicePath); ++j) {
+                if (j == userid) {
+                    continue;
+                }
+                if (!s_arrXInputDevicePath[j]) {
+                    continue;
+                }
+                if (SDL_strcmp(devName, s_arrXInputDevicePath[j]) == 0) {
+                    found = SDL_TRUE;
+                    break;
+                }
+            }
+            if (found) {
+                /* We already have this device in our XInput device list */
+                continue;
+            }
+
+            /* We don't actually know if this is the right device for this
+             * userid, but we'll record it so we'll at least be consistent
+             * when the raw device list changes.
+             */
+            *pVID = (Uint16)rdi.hid.dwVendorId;
+            *pPID = (Uint16)rdi.hid.dwProductId;
+            *pVersion = (Uint16)rdi.hid.dwVersionNumber;
+            if (s_arrXInputDevicePath[userid]) {
+                SDL_free(s_arrXInputDevicePath[userid]);
+            }
+            s_arrXInputDevicePath[userid] = SDL_strdup(devName);
+            break;
+        }
+    }
+    SDL_free(devices);
+#endif  /* ifndef __WINRT__ */
+}
+
 static void
-AddXInputDevice(const Uint8 userid, BYTE SubType, JoyStick_DeviceData **pContext)
+AddXInputDevice(Uint8 userid, BYTE SubType, JoyStick_DeviceData **pContext)
 {
     JoyStick_DeviceData *pPrevJoystick = NULL;
     JoyStick_DeviceData *pNewJoystick = *pContext;
@@ -150,16 +228,35 @@ AddXInputDevice(const Uint8 userid, BYTE SubType, JoyStick_DeviceData **pContext
     if (SDL_XInputUseOldJoystickMapping()) {
         SDL_zero(pNewJoystick->guid);
     } else {
-        pNewJoystick->guid.data[0] = 'x';
-        pNewJoystick->guid.data[1] = 'i';
-        pNewJoystick->guid.data[2] = 'n';
-        pNewJoystick->guid.data[3] = 'p';
-        pNewJoystick->guid.data[4] = 'u';
-        pNewJoystick->guid.data[5] = 't';
-        pNewJoystick->guid.data[6] = SubType;
+        const Uint16 BUS_USB = 0x03;
+        Uint16 vendor = 0;
+        Uint16 product = 0;
+        Uint16 version = 0;
+        Uint16 *guid16 = (Uint16 *)pNewJoystick->guid.data;
+
+        GuessXInputDevice(userid, &vendor, &product, &version);
+
+        *guid16++ = SDL_SwapLE16(BUS_USB);
+        *guid16++ = 0;
+        *guid16++ = SDL_SwapLE16(vendor);
+        *guid16++ = 0;
+        *guid16++ = SDL_SwapLE16(product);
+        *guid16++ = 0;
+        *guid16++ = SDL_SwapLE16(version);
+        *guid16++ = 0;
+
+        /* Note that this is an XInput device and what subtype it is */
+        pNewJoystick->guid.data[14] = 'x';
+        pNewJoystick->guid.data[15] = SubType;
     }
     pNewJoystick->SubType = SubType;
     pNewJoystick->XInputUserId = userid;
+
+    if (SDL_ShouldIgnoreGameController(pNewJoystick->joystickname, pNewJoystick->guid)) {
+        SDL_free(pNewJoystick);
+        return;
+    }
+
     SDL_SYS_AddJoystickDevice(pNewJoystick);
 }
 
@@ -220,14 +317,12 @@ SDL_XINPUT_JoystickOpen(SDL_Joystick * joystick, JoyStick_DeviceData *joystickde
 static void 
 UpdateXInputJoystickBatteryInformation(SDL_Joystick * joystick, XINPUT_BATTERY_INFORMATION_EX *pBatteryInformation)
 {
-    if ( pBatteryInformation->BatteryType != BATTERY_TYPE_UNKNOWN )
-    {
+    if (pBatteryInformation->BatteryType != BATTERY_TYPE_UNKNOWN) {
         SDL_JoystickPowerLevel ePowerLevel = SDL_JOYSTICK_POWER_UNKNOWN;
         if (pBatteryInformation->BatteryType == BATTERY_TYPE_WIRED) {
             ePowerLevel = SDL_JOYSTICK_POWER_WIRED;
         } else {
-            switch ( pBatteryInformation->BatteryLevel )
-            {
+            switch (pBatteryInformation->BatteryLevel) {
             case BATTERY_LEVEL_EMPTY:
                 ePowerLevel = SDL_JOYSTICK_POWER_EMPTY;
                 break;
@@ -244,7 +339,7 @@ UpdateXInputJoystickBatteryInformation(SDL_Joystick * joystick, XINPUT_BATTERY_I
             }
         }
 
-        SDL_PrivateJoystickBatteryLevel( joystick, ePowerLevel );
+        SDL_PrivateJoystickBatteryLevel(joystick, ePowerLevel);
     }
 }
 
@@ -272,7 +367,7 @@ UpdateXInputJoystickState_OLD(SDL_Joystick * joystick, XINPUT_STATE_EX *pXInputS
         SDL_PrivateJoystickButton(joystick, button, (wButtons & s_XInputButtons[button]) ? SDL_PRESSED : SDL_RELEASED);
     }
 
-    UpdateXInputJoystickBatteryInformation( joystick, pBatteryInformation );
+    UpdateXInputJoystickBatteryInformation(joystick, pBatteryInformation);
 }
 
 static void
@@ -313,7 +408,7 @@ UpdateXInputJoystickState(SDL_Joystick * joystick, XINPUT_STATE_EX *pXInputState
     }
     SDL_PrivateJoystickHat(joystick, 0, hat);
 
-    UpdateXInputJoystickBatteryInformation( joystick, pBatteryInformation );
+    UpdateXInputJoystickBatteryInformation(joystick, pBatteryInformation);
 }
 
 void
@@ -328,15 +423,20 @@ SDL_XINPUT_JoystickUpdate(SDL_Joystick * joystick)
 
     result = XINPUTGETSTATE(joystick->hwdata->userid, &XInputState);
     if (result == ERROR_DEVICE_NOT_CONNECTED) {
+        Uint8 userid = joystick->hwdata->userid;
+
         joystick->hwdata->send_remove_event = SDL_TRUE;
         joystick->hwdata->removed = SDL_TRUE;
+        if (s_arrXInputDevicePath[userid]) {
+            SDL_free(s_arrXInputDevicePath[userid]);
+            s_arrXInputDevicePath[userid] = NULL;
+        }
         return;
     }
 
-    SDL_zero( XBatteryInformation );
-    if ( XINPUTGETBATTERYINFORMATION )
-    {
-        result = XINPUTGETBATTERYINFORMATION( joystick->hwdata->userid, BATTERY_DEVTYPE_GAMEPAD, &XBatteryInformation );
+    SDL_zero(XBatteryInformation);
+    if (XINPUTGETBATTERYINFORMATION) {
+        result = XINPUTGETBATTERYINFORMATION(joystick->hwdata->userid, BATTERY_DEVTYPE_GAMEPAD, &XBatteryInformation);
     }
 
     /* only fire events if the data changed from last time */
diff --git a/src/joystick/windows/SDL_xinputjoystick_c.h b/src/joystick/windows/SDL_xinputjoystick_c.h
index b3ba8c0..26da0a2 100644
--- a/src/joystick/windows/SDL_xinputjoystick_c.h
+++ b/src/joystick/windows/SDL_xinputjoystick_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/libm/e_rem_pio2.c b/src/libm/e_rem_pio2.c
index a8ffe31..dfa5d94 100644
--- a/src/libm/e_rem_pio2.c
+++ b/src/libm/e_rem_pio2.c
@@ -24,6 +24,8 @@ static const char rcsid[] =
 #include "math_libm.h"
 #include "math_private.h"
 
+#include "SDL_assert.h"
+
 libm_hidden_proto(fabs)
 
 /*
@@ -189,7 +191,12 @@ __ieee754_rem_pio2(x, y)
     }
     tx[2] = z;
     nx = 3;
-    while (tx[nx - 1] == zero)
+
+    /* If this assertion ever fires, here's the static analysis that warned about it:
+        http://buildbot.libsdl.org/sdl-static-analysis/sdl-macosx-static-analysis/sdl-macosx-static-analysis-1101/report-8c6ccb.html#EndPath */
+    SDL_assert((tx[0] != zero) || (tx[1] != zero) || (tx[2] != zero));
+
+    while (nx && tx[nx - 1] == zero)
         nx--;                   /* skip zero term */
     n = __kernel_rem_pio2(tx, y, e0, nx, 2, two_over_pi);
     if (hx < 0) {
diff --git a/src/libm/k_rem_pio2.c b/src/libm/k_rem_pio2.c
index 23c2b61..50e1d52 100644
--- a/src/libm/k_rem_pio2.c
+++ b/src/libm/k_rem_pio2.c
@@ -204,8 +204,13 @@ __kernel_rem_pio2(x, y, e0, nx, prec, ipio2)
 
     /* compute q[0],q[1],...q[jk] */
     for (i = 0; i <= jk; i++) {
-        for (j = 0, fw = 0.0; j <= jx; j++)
-            fw += x[j] * f[jx + i - j];
+        for (j = 0, fw = 0.0; j <= jx; j++) {
+            const int32_t idx = jx + i - j;
+            SDL_assert(idx >= 0);
+            SDL_assert(idx < 20);
+            SDL_assert(idx <= m);
+            fw += x[j] * f[idx];
+        }
         q[i] = fw;
     }
 
diff --git a/src/libm/math_libm.h b/src/libm/math_libm.h
index 3fe1727..a30fa3f 100644
--- a/src/libm/math_libm.h
+++ b/src/libm/math_libm.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/loadso/dlopen/SDL_sysloadso.c b/src/loadso/dlopen/SDL_sysloadso.c
index 7b30b77..1b587d2 100644
--- a/src/loadso/dlopen/SDL_sysloadso.c
+++ b/src/loadso/dlopen/SDL_sysloadso.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/loadso/dummy/SDL_sysloadso.c b/src/loadso/dummy/SDL_sysloadso.c
index 4f132f9..778f270 100644
--- a/src/loadso/dummy/SDL_sysloadso.c
+++ b/src/loadso/dummy/SDL_sysloadso.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/loadso/haiku/SDL_sysloadso.c b/src/loadso/haiku/SDL_sysloadso.c
deleted file mode 100644
index 1336d9e..0000000
--- a/src/loadso/haiku/SDL_sysloadso.c
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
-
-  This software is provided 'as-is', without any express or implied
-  warranty.  In no event will the authors be held liable for any damages
-  arising from the use of this software.
-
-  Permission is granted to anyone to use this software for any purpose,
-  including commercial applications, and to alter it and redistribute it
-  freely, subject to the following restrictions:
-
-  1. The origin of this software must not be misrepresented; you must not
-     claim that you wrote the original software. If you use this software
-     in a product, an acknowledgment in the product documentation would be
-     appreciated but is not required.
-  2. Altered source versions must be plainly marked as such, and must not be
-     misrepresented as being the original software.
-  3. This notice may not be removed or altered from any source distribution.
-*/
-#include "../../SDL_internal.h"
-
-#ifdef SDL_LOADSO_HAIKU
-
-/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
-/* System dependent library loading routines                           */
-
-#include <stdio.h>
-#include <os/kernel/image.h>
-
-#include "SDL_loadso.h"
-
-void *
-SDL_LoadObject(const char *sofile)
-{
-    void *handle = NULL;
-    image_id library_id = load_add_on(sofile);
-    if (library_id < 0) {
-        SDL_SetError(strerror((int) library_id));
-    } else {
-        handle = (void *) (library_id);
-    }
-    return (handle);
-}
-
-void *
-SDL_LoadFunction(void *handle, const char *name)
-{
-    void *sym = NULL;
-    image_id library_id = (image_id) handle;
-    status_t rc =
-        get_image_symbol(library_id, name, B_SYMBOL_TYPE_TEXT, &sym);
-    if (rc != B_NO_ERROR) {
-        SDL_SetError(strerror(rc));
-    }
-    return (sym);
-}
-
-void
-SDL_UnloadObject(void *handle)
-{
-    image_id library_id;
-    if (handle != NULL) {
-        library_id = (image_id) handle;
-        unload_add_on(library_id);
-    }
-}
-
-#endif /* SDL_LOADSO_HAIKU */
-
-/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/loadso/windows/SDL_sysloadso.c b/src/loadso/windows/SDL_sysloadso.c
index bdb2b98..1e995e4 100644
--- a/src/loadso/windows/SDL_sysloadso.c
+++ b/src/loadso/windows/SDL_sysloadso.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/main/android/SDL_android_main.c b/src/main/android/SDL_android_main.c
index 671d932..054738a 100644
--- a/src/main/android/SDL_android_main.c
+++ b/src/main/android/SDL_android_main.c
@@ -1,83 +1,7 @@
 /*
     SDL_android_main.c, placed in the public domain by Sam Lantinga  3/13/14
-*/
-#include "../../SDL_internal.h"
-
-#ifdef __ANDROID__
-
-/* Include the SDL main definition header */
-#include "SDL_main.h"
-
-/*******************************************************************************
-                 Functions called by JNI
-*******************************************************************************/
-#include <jni.h>
-
-/* Called before SDL_main() to initialize JNI bindings in SDL library */
-extern void SDL_Android_Init(JNIEnv* env, jclass cls);
-
-/* This prototype is needed to prevent a warning about the missing prototype for global function below */
-JNIEXPORT int JNICALL Java_org_libsdl_app_SDLActivity_nativeInit(JNIEnv* env, jclass cls, jobject array);
-
-/* Start up the SDL app */
-JNIEXPORT int JNICALL Java_org_libsdl_app_SDLActivity_nativeInit(JNIEnv* env, jclass cls, jobject array)
-{
-    int i;
-    int argc;
-    int status;
-    int len;
-    char** argv;
-
-    /* This interface could expand with ABI negotiation, callbacks, etc. */
-    SDL_Android_Init(env, cls);
-
-    SDL_SetMainReady();
 
-    /* Prepare the arguments. */
-
-    len = (*env)->GetArrayLength(env, array);
-    argv = SDL_stack_alloc(char*, 1 + len + 1);
-    argc = 0;
-    /* Use the name "app_process" so PHYSFS_platformCalcBaseDir() works.
-       https://bitbucket.org/MartinFelis/love-android-sdl2/issue/23/release-build-crash-on-start
-     */
-    argv[argc++] = SDL_strdup("app_process");
-    for (i = 0; i < len; ++i) {
-        const char* utf;
-        char* arg = NULL;
-        jstring string = (*env)->GetObjectArrayElement(env, array, i);
-        if (string) {
-            utf = (*env)->GetStringUTFChars(env, string, 0);
-            if (utf) {
-                arg = SDL_strdup(utf);
-                (*env)->ReleaseStringUTFChars(env, string, utf);
-            }
-            (*env)->DeleteLocalRef(env, string);
-        }
-        if (!arg) {
-            arg = SDL_strdup("");
-        }
-        argv[argc++] = arg;
-    }
-    argv[argc] = NULL;
-
-
-    /* Run the application. */
-
-    status = SDL_main(argc, argv);
-
-    /* Release the arguments. */
-
-    for (i = 0; i < argc; ++i) {
-        SDL_free(argv[i]);
-    }
-    SDL_stack_free(argv);
-    /* Do not issue an exit or the whole application will terminate instead of just the SDL thread */
-    /* exit(status); */
-
-    return status;
-}
-
-#endif /* __ANDROID__ */
+    As of SDL 2.0.6 this file is no longer necessary.
+*/
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/main/haiku/SDL_BApp.h b/src/main/haiku/SDL_BApp.h
index 9672d46..9b5ea00 100644
--- a/src/main/haiku/SDL_BApp.h
+++ b/src/main/haiku/SDL_BApp.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,7 +22,9 @@
 #define SDL_BAPP_H
 
 #include <InterfaceKit.h>
+#if SDL_VIDEO_OPENGL
 #include <OpenGLKit.h>
+#endif
 
 #include "../../video/haiku/SDL_bkeyboard.h"
 
@@ -37,7 +39,6 @@ extern "C" {
 
 /* Local includes */
 #include "../../events/SDL_events_c.h"
-#include "../../video/haiku/SDL_bkeyboard.h"
 #include "../../video/haiku/SDL_bframebuffer.h"
 
 #ifdef __cplusplus
@@ -81,7 +82,9 @@ class SDL_BApp : public BApplication {
 public:
     SDL_BApp(const char* signature) :
         BApplication(signature) {
+#if SDL_VIDEO_OPENGL
         _current_context = NULL;
+#endif
     }
 
 
@@ -189,6 +192,7 @@ public:
         return _window_map[winID];
     }
 
+#if SDL_VIDEO_OPENGL
     void SetCurrentContext(BGLView *newContext) {
         if(_current_context)
             _current_context->UnlockGL();
@@ -196,6 +200,8 @@ public:
         if (_current_context)
 	        _current_context->LockGL();
     }
+#endif
+
 private:
     /* Event management */
     void _HandleBasicWindowEvent(BMessage *msg, int32 sdlEventType) {
@@ -385,8 +391,9 @@ private:
     /* Members */
     std::vector<SDL_Window*> _window_map; /* Keeps track of SDL_Windows by index-id */
 
-    display_mode *_saved_mode;
+#if SDL_VIDEO_OPENGL
     BGLView      *_current_context;
+#endif
 };
 
 #endif
diff --git a/src/main/haiku/SDL_BeApp.cc b/src/main/haiku/SDL_BeApp.cc
index 4c5df09..e755a6c 100644
--- a/src/main/haiku/SDL_BeApp.cc
+++ b/src/main/haiku/SDL_BeApp.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,10 @@
 /* Handle the BeApp specific portions of the application */
 
 #include <AppKit.h>
+#include <storage/AppFileInfo.h>
 #include <storage/Path.h>
 #include <storage/Entry.h>
+#include <storage/File.h>
 #include <unistd.h>
 
 #include "SDL_BApp.h"	/* SDL_BApp class definition */
@@ -43,7 +45,7 @@ extern "C" {
 #include "../../thread/SDL_systhread.h"
 
 /* Flag to tell whether or not the Be application is active or not */
-int SDL_BeAppActive = 0;
+static int SDL_BeAppActive = 0;
 static SDL_Thread *SDL_AppThread = NULL;
 
 static int
@@ -51,7 +53,24 @@ StartBeApp(void *unused)
 {
     BApplication *App;
 
-    App = new SDL_BApp("application/x-SDL-executable");
+	// default application signature
+	const char *signature = "application/x-SDL-executable";
+	// dig resources for correct signature
+	image_info info;
+	int32 cookie = 0;
+	if (get_next_image_info(B_CURRENT_TEAM, &cookie, &info) == B_OK) {
+		BFile f(info.name, O_RDONLY);
+		if (f.InitCheck() == B_OK) {
+			BAppFileInfo app_info(&f);
+			if (app_info.InitCheck() == B_OK) {
+				char sig[B_MIME_TYPE_LENGTH];
+				if (app_info.GetSignature(sig) == B_OK)
+					signature = strndup(sig, B_MIME_TYPE_LENGTH);
+			}
+		}
+	}
+
+	App = new SDL_BApp(signature);
 
     App->Run();
     delete App;
diff --git a/src/main/haiku/SDL_BeApp.h b/src/main/haiku/SDL_BeApp.h
index 6700a3b..ba81ada 100644
--- a/src/main/haiku/SDL_BeApp.h
+++ b/src/main/haiku/SDL_BeApp.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -31,8 +31,6 @@ extern int SDL_InitBeApp(void);
 /* Quit the Be Application, if there's nothing left to do */
 extern void SDL_QuitBeApp(void);
 
-/* Flag to tell whether the app is active or not */
-extern int SDL_BeAppActive;
 /* vi: set ts=4 sw=4 expandtab: */
 
 #ifdef __cplusplus
diff --git a/src/main/nacl/SDL_nacl_main.c b/src/main/nacl/SDL_nacl_main.c
index 4c01d0f..697abb5 100644
--- a/src/main/nacl/SDL_nacl_main.c
+++ b/src/main/nacl/SDL_nacl_main.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/main/windows/version.rc b/src/main/windows/version.rc
index cb79810..f02cc90 100644
--- a/src/main/windows/version.rc
+++ b/src/main/windows/version.rc
@@ -9,8 +9,8 @@ LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
 //
 
 VS_VERSION_INFO VERSIONINFO
- FILEVERSION 2,0,5,0
- PRODUCTVERSION 2,0,5,0
+ FILEVERSION 2,0,6,0
+ PRODUCTVERSION 2,0,6,0
  FILEFLAGSMASK 0x3fL
  FILEFLAGS 0x0L
  FILEOS 0x40004L
@@ -23,12 +23,12 @@ BEGIN
         BEGIN
             VALUE "CompanyName", "\0"
             VALUE "FileDescription", "SDL\0"
-            VALUE "FileVersion", "2, 0, 5, 0\0"
+            VALUE "FileVersion", "2, 0, 6, 0\0"
             VALUE "InternalName", "SDL\0"
-            VALUE "LegalCopyright", "Copyright � 2016 Sam Lantinga\0"
+            VALUE "LegalCopyright", "Copyright � 2017 Sam Lantinga\0"
             VALUE "OriginalFilename", "SDL2.dll\0"
             VALUE "ProductName", "Simple DirectMedia Layer\0"
-            VALUE "ProductVersion", "2, 0, 5, 0\0"
+            VALUE "ProductVersion", "2, 0, 6, 0\0"
         END
     END
     BLOCK "VarFileInfo"
diff --git a/src/power/SDL_power.c b/src/power/SDL_power.c
index 016013b..9e262c7 100644
--- a/src/power/SDL_power.c
+++ b/src/power/SDL_power.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,6 +20,7 @@
 */
 #include "../SDL_internal.h"
 #include "SDL_power.h"
+#include "SDL_syspower.h"
 
 /*
  * Returns SDL_TRUE if we have a definitive answer.
@@ -29,18 +30,6 @@ typedef SDL_bool
     (*SDL_GetPowerInfo_Impl) (SDL_PowerState * state, int *seconds,
                               int *percent);
 
-SDL_bool SDL_GetPowerInfo_Linux_sys_class_power_supply(SDL_PowerState *, int *, int *);
-SDL_bool SDL_GetPowerInfo_Linux_proc_acpi(SDL_PowerState *, int *, int *);
-SDL_bool SDL_GetPowerInfo_Linux_proc_apm(SDL_PowerState *, int *, int *);
-SDL_bool SDL_GetPowerInfo_Windows(SDL_PowerState *, int *, int *);
-SDL_bool SDL_GetPowerInfo_MacOSX(SDL_PowerState *, int *, int *);
-SDL_bool SDL_GetPowerInfo_Haiku(SDL_PowerState *, int *, int *);
-SDL_bool SDL_GetPowerInfo_UIKit(SDL_PowerState *, int *, int *);
-SDL_bool SDL_GetPowerInfo_Android(SDL_PowerState *, int *, int *);
-SDL_bool SDL_GetPowerInfo_PSP(SDL_PowerState *, int *, int *);
-SDL_bool SDL_GetPowerInfo_WinRT(SDL_PowerState *, int *, int *);
-SDL_bool SDL_GetPowerInfo_Emscripten(SDL_PowerState *, int *, int *);
-
 #ifndef SDL_POWER_DISABLED
 #ifdef SDL_POWER_HARDWIRED
 /* This is for things that _never_ have a battery */
@@ -59,6 +48,7 @@ SDL_GetPowerInfo_Hardwired(SDL_PowerState * state, int *seconds, int *percent)
 static SDL_GetPowerInfo_Impl implementations[] = {
 #ifndef SDL_POWER_DISABLED
 #ifdef SDL_POWER_LINUX          /* in order of preference. More than could work. */
+    SDL_GetPowerInfo_Linux_org_freedesktop_upower,
     SDL_GetPowerInfo_Linux_sys_class_power_supply,
     SDL_GetPowerInfo_Linux_proc_acpi,
     SDL_GetPowerInfo_Linux_proc_apm,
diff --git a/src/power/SDL_syspower.h b/src/power/SDL_syspower.h
new file mode 100644
index 0000000..22c35cf
--- /dev/null
+++ b/src/power/SDL_syspower.h
@@ -0,0 +1,47 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "../SDL_internal.h"
+
+/* These are functions that need to be implemented by a port of SDL */
+
+#ifndef SDL_syspower_h_
+#define SDL_syspower_h_
+
+#include "SDL_power.h"
+
+/* Not all of these are available in a given build. Use #ifdefs, etc. */
+SDL_bool SDL_GetPowerInfo_Linux_org_freedesktop_upower(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_Linux_sys_class_power_supply(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_Linux_proc_acpi(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_Linux_proc_apm(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_Windows(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_UIKit(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_MacOSX(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_Haiku(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_Android(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_PSP(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_WinRT(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_Emscripten(SDL_PowerState *, int *, int *);
+SDL_bool SDL_GetPowerInfo_Hardwired(SDL_PowerState *, int *, int *);
+
+#endif /* SDL_syspower_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/power/android/SDL_syspower.c b/src/power/android/SDL_syspower.c
index 5a4b0fc..eb710df 100644
--- a/src/power/android/SDL_syspower.c
+++ b/src/power/android/SDL_syspower.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,6 +24,7 @@
 #if SDL_POWER_ANDROID
 
 #include "SDL_power.h"
+#include "../SDL_syspower.h"
 
 #include "../../core/android/SDL_android.h"
 
diff --git a/src/power/emscripten/SDL_syspower.c b/src/power/emscripten/SDL_syspower.c
index 307f797..1ffed1d 100644
--- a/src/power/emscripten/SDL_syspower.c
+++ b/src/power/emscripten/SDL_syspower.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/power/haiku/SDL_syspower.c b/src/power/haiku/SDL_syspower.c
index cfda8c9..6a7eae4 100644
--- a/src/power/haiku/SDL_syspower.c
+++ b/src/power/haiku/SDL_syspower.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,7 +20,9 @@
 */
 #include "../../SDL_internal.h"
 
+/* uses BeOS euc.jp apm driver. */
 /* !!! FIXME: does this thing even work on Haiku? */
+
 #ifndef SDL_POWER_DISABLED
 #if SDL_POWER_HAIKU
 
diff --git a/src/power/linux/SDL_syspower.c b/src/power/linux/SDL_syspower.c
index 793e266..aa44c00 100644
--- a/src/power/linux/SDL_syspower.c
+++ b/src/power/linux/SDL_syspower.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -32,6 +32,9 @@
 #include <fcntl.h>
 
 #include "SDL_power.h"
+#include "../SDL_syspower.h"
+
+#include "../../core/linux/SDL_dbus.h"
 
 static const char *proc_apm_path = "/proc/apm";
 static const char *proc_acpi_battery_path = "/proc/acpi/battery";
@@ -425,8 +428,6 @@ SDL_GetPowerInfo_Linux_proc_apm(SDL_PowerState * state,
     return SDL_TRUE;
 }
 
-/* !!! FIXME: implement d-bus queries to org.freedesktop.UPower. */
-
 SDL_bool
 SDL_GetPowerInfo_Linux_sys_class_power_supply(SDL_PowerState *state, int *seconds, int *percent)
 {
@@ -459,6 +460,16 @@ SDL_GetPowerInfo_Linux_sys_class_power_supply(SDL_PowerState *state, int *second
             continue;  /* we don't care about UPS and such. */
         }
 
+        /* if the scope is "device," it might be something like a PS4
+           controller reporting its own battery, and not something that powers
+           the system. Most system batteries don't list a scope at all; we
+           assume it's a system battery if not specified. */
+        if (read_power_file(base, name, "scope", str, sizeof (str))) {
+            if (SDL_strcmp(str, "device\n") == 0) {
+                continue;  /* skip external devices with their own batteries. */
+            }
+        }
+
         /* some drivers don't offer this, so if it's not explicitly reported assume it's present. */
         if (read_power_file(base, name, "present", str, sizeof (str)) && (SDL_strcmp(str, "0\n") == 0)) {
             st = SDL_POWERSTATE_NO_BATTERY;
@@ -513,6 +524,118 @@ SDL_GetPowerInfo_Linux_sys_class_power_supply(SDL_PowerState *state, int *second
     return SDL_TRUE;  /* don't look any further. */
 }
 
+
+/* d-bus queries to org.freedesktop.UPower. */
+#if SDL_USE_LIBDBUS
+#define UPOWER_DBUS_NODE "org.freedesktop.UPower"
+#define UPOWER_DBUS_PATH "/org/freedesktop/UPower"
+#define UPOWER_DBUS_INTERFACE "org.freedesktop.UPower"
+#define UPOWER_DEVICE_DBUS_INTERFACE "org.freedesktop.UPower.Device"
+
+static void
+check_upower_device(DBusConnection *conn, const char *path, SDL_PowerState *state, int *seconds, int *percent)
+{
+    SDL_bool choose = SDL_FALSE;
+    SDL_PowerState st;
+    int secs;
+    int pct;
+    Uint32 ui32 = 0;
+    Sint64 si64 = 0;
+    double d = 0.0;
+
+    if (!SDL_DBus_QueryPropertyOnConnection(conn, UPOWER_DBUS_NODE, path, UPOWER_DEVICE_DBUS_INTERFACE, "Type", DBUS_TYPE_UINT32, &ui32)) {
+        return; /* Don't know _what_ we're looking at. Give up on it. */
+    } else if (ui32 != 2) {  /* 2==Battery*/
+        return;  /* we don't care about UPS and such. */
+    } else if (!SDL_DBus_QueryPropertyOnConnection(conn, UPOWER_DBUS_NODE, path, UPOWER_DEVICE_DBUS_INTERFACE, "PowerSupply", DBUS_TYPE_BOOLEAN, &ui32)) {
+        return;
+    } else if (!ui32) {
+        return;  /* we don't care about random devices with batteries, like wireless controllers, etc */
+    } else if (!SDL_DBus_QueryPropertyOnConnection(conn, UPOWER_DBUS_NODE, path, UPOWER_DEVICE_DBUS_INTERFACE, "IsPresent", DBUS_TYPE_BOOLEAN, &ui32)) {
+        return;
+    } else if (!ui32) {
+        st = SDL_POWERSTATE_NO_BATTERY;
+    } else if (!SDL_DBus_QueryPropertyOnConnection(conn, UPOWER_DBUS_NODE, path, UPOWER_DEVICE_DBUS_INTERFACE, "State", DBUS_TYPE_UINT32, &ui32)) {
+        st = SDL_POWERSTATE_UNKNOWN;  /* uh oh */
+    } else if (ui32 == 1) {  /* 1 == charging */
+        st = SDL_POWERSTATE_CHARGING;
+    } else if ((ui32 == 2) || (ui32 == 3)) {  /* 2 == discharging, 3 == empty. */
+        st = SDL_POWERSTATE_ON_BATTERY;
+    } else if (ui32 == 4) {   /* 4 == full */
+        st = SDL_POWERSTATE_CHARGED;
+    } else {
+        st = SDL_POWERSTATE_UNKNOWN;  /* uh oh */
+    }
+
+    if (!SDL_DBus_QueryPropertyOnConnection(conn, UPOWER_DBUS_NODE, path, UPOWER_DEVICE_DBUS_INTERFACE, "Percentage", DBUS_TYPE_DOUBLE, &d)) {
+        pct = -1;  /* some old/cheap batteries don't set this property. */
+    } else {
+        pct = (int) d;
+        pct = (pct > 100) ? 100 : pct; /* clamp between 0%, 100% */
+    }
+
+    if (!SDL_DBus_QueryPropertyOnConnection(conn, UPOWER_DBUS_NODE, path, UPOWER_DEVICE_DBUS_INTERFACE, "TimeToEmpty", DBUS_TYPE_INT64, &si64)) {
+        secs = -1;
+    } else {
+        secs = (int) si64;
+        secs = (secs <= 0) ? -1 : secs;  /* 0 == unknown */
+    }
+
+    /*
+     * We pick the battery that claims to have the most minutes left.
+     *  (failing a report of minutes, we'll take the highest percent.)
+     */
+    if ((secs < 0) && (*seconds < 0)) {
+        if ((pct < 0) && (*percent < 0)) {
+            choose = SDL_TRUE;  /* at least we know there's a battery. */
+        } else if (pct > *percent) {
+            choose = SDL_TRUE;
+        }
+    } else if (secs > *seconds) {
+        choose = SDL_TRUE;
+    }
+
+    if (choose) {
+        *seconds = secs;
+        *percent = pct;
+        *state = st;
+    }
+}
+#endif
+
+SDL_bool
+SDL_GetPowerInfo_Linux_org_freedesktop_upower(SDL_PowerState *state, int *seconds, int *percent)
+{
+    SDL_bool retval = SDL_FALSE;
+
+    #if SDL_USE_LIBDBUS
+    SDL_DBusContext *dbus = SDL_DBus_GetContext();
+    char **paths = NULL;
+    int i, numpaths = 0;
+
+    if (!SDL_DBus_CallMethodOnConnection(dbus->system_conn, UPOWER_DBUS_NODE, UPOWER_DBUS_PATH, UPOWER_DBUS_INTERFACE, "EnumerateDevices",
+            DBUS_TYPE_INVALID,
+            DBUS_TYPE_ARRAY, DBUS_TYPE_OBJECT_PATH, &paths, &numpaths, DBUS_TYPE_INVALID)) {
+        return SDL_FALSE;  /* try a different approach than UPower. */
+    }
+
+    retval = SDL_TRUE;  /* Clearly we can use this interface. */
+    *state = SDL_POWERSTATE_NO_BATTERY;  /* assume we're just plugged in. */
+    *seconds = -1;
+    *percent = -1;
+
+    for (i = 0; i < numpaths; i++) {
+        check_upower_device(dbus->system_conn, paths[i], state, seconds, percent);
+    }
+
+    if (dbus) {
+        dbus->free_string_array(paths);
+    }
+    #endif  /* SDL_USE_LIBDBUS */
+
+    return retval;
+}
+
 #endif /* SDL_POWER_LINUX */
 #endif /* SDL_POWER_DISABLED */
 
diff --git a/src/power/macosx/SDL_syspower.c b/src/power/macosx/SDL_syspower.c
index f865d59..4ceaf18 100644
--- a/src/power/macosx/SDL_syspower.c
+++ b/src/power/macosx/SDL_syspower.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/power/psp/SDL_syspower.c b/src/power/psp/SDL_syspower.c
index 76c21b9..0328b4b 100644
--- a/src/power/psp/SDL_syspower.c
+++ b/src/power/psp/SDL_syspower.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/power/uikit/SDL_syspower.h b/src/power/uikit/SDL_syspower.h
index 4cfa5c9..6ae5ad4 100644
--- a/src/power/uikit/SDL_syspower.h
+++ b/src/power/uikit/SDL_syspower.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/power/uikit/SDL_syspower.m b/src/power/uikit/SDL_syspower.m
index 7186b21..8656496 100644
--- a/src/power/uikit/SDL_syspower.m
+++ b/src/power/uikit/SDL_syspower.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/power/windows/SDL_syspower.c b/src/power/windows/SDL_syspower.c
index ff3784c..ed1d294 100644
--- a/src/power/windows/SDL_syspower.c
+++ b/src/power/windows/SDL_syspower.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/power/winrt/SDL_syspower.cpp b/src/power/winrt/SDL_syspower.cpp
index 94e5a28..2795b04 100644
--- a/src/power/winrt/SDL_syspower.cpp
+++ b/src/power/winrt/SDL_syspower.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/SDL_d3dmath.c b/src/render/SDL_d3dmath.c
index 83d67bf..8f99353 100644
--- a/src/render/SDL_d3dmath.c
+++ b/src/render/SDL_d3dmath.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -31,32 +31,32 @@ Float4X4 MatrixIdentity()
 {
     Float4X4 m;
     SDL_zero(m);
-    m._11 = 1.0f;
-    m._22 = 1.0f;
-    m._33 = 1.0f;
-    m._44 = 1.0f;
+    m.v._11 = 1.0f;
+    m.v._22 = 1.0f;
+    m.v._33 = 1.0f;
+    m.v._44 = 1.0f;
     return m;
 }
 
 Float4X4 MatrixMultiply(Float4X4 M1, Float4X4 M2)
 {
     Float4X4 m;
-    m._11 = M1._11 * M2._11 + M1._12 * M2._21 + M1._13 * M2._31 + M1._14 * M2._41;
-    m._12 = M1._11 * M2._12 + M1._12 * M2._22 + M1._13 * M2._32 + M1._14 * M2._42;
-    m._13 = M1._11 * M2._13 + M1._12 * M2._23 + M1._13 * M2._33 + M1._14 * M2._43;
-    m._14 = M1._11 * M2._14 + M1._12 * M2._24 + M1._13 * M2._34 + M1._14 * M2._44;
-    m._21 = M1._21 * M2._11 + M1._22 * M2._21 + M1._23 * M2._31 + M1._24 * M2._41;
-    m._22 = M1._21 * M2._12 + M1._22 * M2._22 + M1._23 * M2._32 + M1._24 * M2._42;
-    m._23 = M1._21 * M2._13 + M1._22 * M2._23 + M1._23 * M2._33 + M1._24 * M2._43;
-    m._24 = M1._21 * M2._14 + M1._22 * M2._24 + M1._23 * M2._34 + M1._24 * M2._44;
-    m._31 = M1._31 * M2._11 + M1._32 * M2._21 + M1._33 * M2._31 + M1._34 * M2._41;
-    m._32 = M1._31 * M2._12 + M1._32 * M2._22 + M1._33 * M2._32 + M1._34 * M2._42;
-    m._33 = M1._31 * M2._13 + M1._32 * M2._23 + M1._33 * M2._33 + M1._34 * M2._43;
-    m._34 = M1._31 * M2._14 + M1._32 * M2._24 + M1._33 * M2._34 + M1._34 * M2._44;
-    m._41 = M1._41 * M2._11 + M1._42 * M2._21 + M1._43 * M2._31 + M1._44 * M2._41;
-    m._42 = M1._41 * M2._12 + M1._42 * M2._22 + M1._43 * M2._32 + M1._44 * M2._42;
-    m._43 = M1._41 * M2._13 + M1._42 * M2._23 + M1._43 * M2._33 + M1._44 * M2._43;
-    m._44 = M1._41 * M2._14 + M1._42 * M2._24 + M1._43 * M2._34 + M1._44 * M2._44;
+    m.v._11 = M1.v._11 * M2.v._11 + M1.v._12 * M2.v._21 + M1.v._13 * M2.v._31 + M1.v._14 * M2.v._41;
+    m.v._12 = M1.v._11 * M2.v._12 + M1.v._12 * M2.v._22 + M1.v._13 * M2.v._32 + M1.v._14 * M2.v._42;
+    m.v._13 = M1.v._11 * M2.v._13 + M1.v._12 * M2.v._23 + M1.v._13 * M2.v._33 + M1.v._14 * M2.v._43;
+    m.v._14 = M1.v._11 * M2.v._14 + M1.v._12 * M2.v._24 + M1.v._13 * M2.v._34 + M1.v._14 * M2.v._44;
+    m.v._21 = M1.v._21 * M2.v._11 + M1.v._22 * M2.v._21 + M1.v._23 * M2.v._31 + M1.v._24 * M2.v._41;
+    m.v._22 = M1.v._21 * M2.v._12 + M1.v._22 * M2.v._22 + M1.v._23 * M2.v._32 + M1.v._24 * M2.v._42;
+    m.v._23 = M1.v._21 * M2.v._13 + M1.v._22 * M2.v._23 + M1.v._23 * M2.v._33 + M1.v._24 * M2.v._43;
+    m.v._24 = M1.v._21 * M2.v._14 + M1.v._22 * M2.v._24 + M1.v._23 * M2.v._34 + M1.v._24 * M2.v._44;
+    m.v._31 = M1.v._31 * M2.v._11 + M1.v._32 * M2.v._21 + M1.v._33 * M2.v._31 + M1.v._34 * M2.v._41;
+    m.v._32 = M1.v._31 * M2.v._12 + M1.v._32 * M2.v._22 + M1.v._33 * M2.v._32 + M1.v._34 * M2.v._42;
+    m.v._33 = M1.v._31 * M2.v._13 + M1.v._32 * M2.v._23 + M1.v._33 * M2.v._33 + M1.v._34 * M2.v._43;
+    m.v._34 = M1.v._31 * M2.v._14 + M1.v._32 * M2.v._24 + M1.v._33 * M2.v._34 + M1.v._34 * M2.v._44;
+    m.v._41 = M1.v._41 * M2.v._11 + M1.v._42 * M2.v._21 + M1.v._43 * M2.v._31 + M1.v._44 * M2.v._41;
+    m.v._42 = M1.v._41 * M2.v._12 + M1.v._42 * M2.v._22 + M1.v._43 * M2.v._32 + M1.v._44 * M2.v._42;
+    m.v._43 = M1.v._41 * M2.v._13 + M1.v._42 * M2.v._23 + M1.v._43 * M2.v._33 + M1.v._44 * M2.v._43;
+    m.v._44 = M1.v._41 * M2.v._14 + M1.v._42 * M2.v._24 + M1.v._43 * M2.v._34 + M1.v._44 * M2.v._44;
     return m;
 }
 
@@ -64,10 +64,10 @@ Float4X4 MatrixScaling(float x, float y, float z)
 {
     Float4X4 m;
     SDL_zero(m);
-    m._11 = x;
-    m._22 = y;
-    m._33 = z;
-    m._44 = 1.0f;
+    m.v._11 = x;
+    m.v._22 = y;
+    m.v._33 = z;
+    m.v._44 = 1.0f;
     return m;
 }
 
@@ -75,13 +75,13 @@ Float4X4 MatrixTranslation(float x, float y, float z)
 {
     Float4X4 m;
     SDL_zero(m);
-    m._11 = 1.0f;
-    m._22 = 1.0f;
-    m._33 = 1.0f;
-    m._44 = 1.0f;
-    m._41 = x;
-    m._42 = y;
-    m._43 = z;
+    m.v._11 = 1.0f;
+    m.v._22 = 1.0f;
+    m.v._33 = 1.0f;
+    m.v._44 = 1.0f;
+    m.v._41 = x;
+    m.v._42 = y;
+    m.v._43 = z;
     return m;
 }
 
@@ -91,12 +91,12 @@ Float4X4 MatrixRotationX(float r)
     float cosR = SDL_cosf(r);
     Float4X4 m;
     SDL_zero(m);
-    m._11 = 1.0f;
-    m._22 = cosR;
-    m._23 = sinR;
-    m._32 = -sinR;
-    m._33 = cosR;
-    m._44 = 1.0f;
+    m.v._11 = 1.0f;
+    m.v._22 = cosR;
+    m.v._23 = sinR;
+    m.v._32 = -sinR;
+    m.v._33 = cosR;
+    m.v._44 = 1.0f;
     return m;
 }
 
@@ -106,12 +106,12 @@ Float4X4 MatrixRotationY(float r)
     float cosR = SDL_cosf(r);
     Float4X4 m;
     SDL_zero(m);
-    m._11 = cosR;
-    m._13 = -sinR;
-    m._22 = 1.0f;
-    m._31 = sinR;
-    m._33 = cosR;
-    m._44 = 1.0f;
+    m.v._11 = cosR;
+    m.v._13 = -sinR;
+    m.v._22 = 1.0f;
+    m.v._31 = sinR;
+    m.v._33 = cosR;
+    m.v._44 = 1.0f;
     return m;
 }
 
@@ -121,12 +121,12 @@ Float4X4 MatrixRotationZ(float r)
     float cosR = SDL_cosf(r);
     Float4X4 m;
     SDL_zero(m);
-    m._11 = cosR;
-    m._12 = sinR;
-    m._21 = -sinR;
-    m._22 = cosR;
-    m._33 = 1.0f;
-    m._44 = 1.0f;
+    m.v._11 = cosR;
+    m.v._12 = sinR;
+    m.v._21 = -sinR;
+    m.v._22 = cosR;
+    m.v._33 = 1.0f;
+    m.v._44 = 1.0f;
     return m;
 
 }
diff --git a/src/render/SDL_d3dmath.h b/src/render/SDL_d3dmath.h
index 87c44c7..a859f44 100644
--- a/src/render/SDL_d3dmath.h
+++ b/src/render/SDL_d3dmath.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -53,7 +53,7 @@ typedef struct
             float _21, _22, _23, _24;
             float _31, _32, _33, _34;
             float _41, _42, _43, _44;
-        };
+        } v;
         float m[4][4];
     };
 } Float4X4;
diff --git a/src/render/SDL_render.c b/src/render/SDL_render.c
index 9475081..71f707c 100644
--- a/src/render/SDL_render.c
+++ b/src/render/SDL_render.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,17 +33,44 @@
 #define SDL_WINDOWRENDERDATA    "_SDL_WindowRenderData"
 
 #define CHECK_RENDERER_MAGIC(renderer, retval) \
+    SDL_assert(renderer && renderer->magic == &renderer_magic); \
     if (!renderer || renderer->magic != &renderer_magic) { \
         SDL_SetError("Invalid renderer"); \
         return retval; \
     }
 
 #define CHECK_TEXTURE_MAGIC(texture, retval) \
+    SDL_assert(texture && texture->magic == &texture_magic); \
     if (!texture || texture->magic != &texture_magic) { \
         SDL_SetError("Invalid texture"); \
         return retval; \
     }
 
+/* Predefined blend modes */
+#define SDL_COMPOSE_BLENDMODE(srcColorFactor, dstColorFactor, colorOperation, \
+                              srcAlphaFactor, dstAlphaFactor, alphaOperation) \
+    (SDL_BlendMode)(((Uint32)colorOperation << 0) | \
+                    ((Uint32)srcColorFactor << 4) | \
+                    ((Uint32)dstColorFactor << 8) | \
+                    ((Uint32)alphaOperation << 16) | \
+                    ((Uint32)srcAlphaFactor << 20) | \
+                    ((Uint32)dstAlphaFactor << 24))
+
+#define SDL_BLENDMODE_NONE_FULL \
+    SDL_COMPOSE_BLENDMODE(SDL_BLENDFACTOR_ONE, SDL_BLENDFACTOR_ZERO, SDL_BLENDOPERATION_ADD, \
+                          SDL_BLENDFACTOR_ONE, SDL_BLENDFACTOR_ZERO, SDL_BLENDOPERATION_ADD)
+
+#define SDL_BLENDMODE_BLEND_FULL \
+    SDL_COMPOSE_BLENDMODE(SDL_BLENDFACTOR_SRC_ALPHA, SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA, SDL_BLENDOPERATION_ADD, \
+                          SDL_BLENDFACTOR_ONE, SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA, SDL_BLENDOPERATION_ADD)
+
+#define SDL_BLENDMODE_ADD_FULL \
+    SDL_COMPOSE_BLENDMODE(SDL_BLENDFACTOR_SRC_ALPHA, SDL_BLENDFACTOR_ONE, SDL_BLENDOPERATION_ADD, \
+                          SDL_BLENDFACTOR_ZERO, SDL_BLENDFACTOR_ONE, SDL_BLENDOPERATION_ADD)
+
+#define SDL_BLENDMODE_MOD_FULL \
+    SDL_COMPOSE_BLENDMODE(SDL_BLENDFACTOR_ZERO, SDL_BLENDFACTOR_SRC_COLOR, SDL_BLENDOPERATION_ADD, \
+                          SDL_BLENDFACTOR_ZERO, SDL_BLENDFACTOR_ONE, SDL_BLENDOPERATION_ADD)
 
 #if !SDL_RENDER_DISABLED
 static const SDL_RenderDriver *render_drivers[] = {
@@ -102,7 +129,7 @@ SDL_GetRenderDriverInfo(int index, SDL_RendererInfo * info)
 #endif
 }
 
-static int
+static int SDLCALL
 SDL_RendererEventWatch(void *userdata, SDL_Event *event)
 {
     SDL_Renderer *renderer = (SDL_Renderer *)userdata;
@@ -168,29 +195,29 @@ SDL_RendererEventWatch(void *userdata, SDL_Event *event)
     } else if (event->type == SDL_MOUSEMOTION) {
         SDL_Window *window = SDL_GetWindowFromID(event->motion.windowID);
         if (renderer->logical_w && window == renderer->window) {
-            event->motion.x -= renderer->viewport.x;
-            event->motion.y -= renderer->viewport.y;
-            event->motion.x = (int)(event->motion.x / renderer->scale.x);
-            event->motion.y = (int)(event->motion.y / renderer->scale.y);
+            event->motion.x -= (int)(renderer->viewport.x * renderer->dpi_scale.x);
+            event->motion.y -= (int)(renderer->viewport.y * renderer->dpi_scale.y);
+            event->motion.x = (int)(event->motion.x / (renderer->scale.x * renderer->dpi_scale.x));
+            event->motion.y = (int)(event->motion.y / (renderer->scale.y * renderer->dpi_scale.y));
             if (event->motion.xrel > 0) {
-                event->motion.xrel = SDL_max(1, (int)(event->motion.xrel / renderer->scale.x));
+                event->motion.xrel = SDL_max(1, (int)(event->motion.xrel / (renderer->scale.x * renderer->dpi_scale.x)));
             } else if (event->motion.xrel < 0) {
-                event->motion.xrel = SDL_min(-1, (int)(event->motion.xrel / renderer->scale.x));
+                event->motion.xrel = SDL_min(-1, (int)(event->motion.xrel / (renderer->scale.x * renderer->dpi_scale.x)));
             }
             if (event->motion.yrel > 0) {
-                event->motion.yrel = SDL_max(1, (int)(event->motion.yrel / renderer->scale.y));
+                event->motion.yrel = SDL_max(1, (int)(event->motion.yrel / (renderer->scale.y * renderer->dpi_scale.y)));
             } else if (event->motion.yrel < 0) {
-                event->motion.yrel = SDL_min(-1, (int)(event->motion.yrel / renderer->scale.y));
+                event->motion.yrel = SDL_min(-1, (int)(event->motion.yrel / (renderer->scale.y * renderer->dpi_scale.y)));
             }
         }
     } else if (event->type == SDL_MOUSEBUTTONDOWN ||
                event->type == SDL_MOUSEBUTTONUP) {
         SDL_Window *window = SDL_GetWindowFromID(event->button.windowID);
         if (renderer->logical_w && window == renderer->window) {
-            event->button.x -= renderer->viewport.x;
-            event->button.y -= renderer->viewport.y;
-            event->button.x = (int)(event->button.x / renderer->scale.x);
-            event->button.y = (int)(event->button.y / renderer->scale.y);
+            event->button.x -= (int)(renderer->viewport.x * renderer->dpi_scale.x);
+            event->button.y -= (int)(renderer->viewport.y * renderer->dpi_scale.y);
+            event->button.x = (int)(event->button.x / (renderer->scale.x * renderer->dpi_scale.x));
+            event->button.y = (int)(event->button.y / (renderer->scale.y * renderer->dpi_scale.y));
         }
     }
     return 0;
@@ -289,6 +316,18 @@ SDL_CreateRenderer(SDL_Window * window, int index, Uint32 flags)
         renderer->window = window;
         renderer->scale.x = 1.0f;
         renderer->scale.y = 1.0f;
+        renderer->dpi_scale.x = 1.0f;
+        renderer->dpi_scale.y = 1.0f;
+
+        if (window && renderer->GetOutputSize) {
+            int window_w, window_h;
+            int output_w, output_h;
+            if (renderer->GetOutputSize(renderer, &output_w, &output_h) == 0) {
+                SDL_GetWindowSize(renderer->window, &window_w, &window_h);
+                renderer->dpi_scale.x = (float)window_w / output_w;
+                renderer->dpi_scale.y = (float)window_h / output_h;
+            }
+        }
 
         if (SDL_GetWindowFlags(window) & (SDL_WINDOW_HIDDEN|SDL_WINDOW_MINIMIZED)) {
             renderer->hidden = SDL_TRUE;
@@ -368,6 +407,23 @@ SDL_GetRendererOutputSize(SDL_Renderer * renderer, int *w, int *h)
 }
 
 static SDL_bool
+IsSupportedBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode)
+{
+    switch (blendMode)
+    {
+    /* These are required to be supported by all renderers */
+    case SDL_BLENDMODE_NONE:
+    case SDL_BLENDMODE_BLEND:
+    case SDL_BLENDMODE_ADD:
+    case SDL_BLENDMODE_MOD:
+        return SDL_TRUE;
+
+    default:
+        return renderer->SupportsBlendMode && renderer->SupportsBlendMode(renderer, blendMode);
+    }
+}
+
+static SDL_bool
 IsSupportedFormat(SDL_Renderer * renderer, Uint32 format)
 {
     Uint32 i;
@@ -694,6 +750,9 @@ SDL_SetTextureBlendMode(SDL_Texture * texture, SDL_BlendMode blendMode)
     CHECK_TEXTURE_MAGIC(texture, -1);
 
     renderer = texture->renderer;
+    if (!IsSupportedBlendMode(renderer, blendMode)) {
+        return SDL_Unsupported();
+    }
     texture->blendMode = blendMode;
     if (texture->native) {
         return SDL_SetTextureBlendMode(texture->native, blendMode);
@@ -734,8 +793,8 @@ SDL_UpdateTextureYUV(SDL_Texture * texture, const SDL_Rect * rect,
 
     if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
         /* We can lock the texture and copy to it */
-        void *native_pixels;
-        int native_pitch;
+        void *native_pixels = NULL;
+        int native_pitch = 0;
 
         if (SDL_LockTexture(native, rect, &native_pixels, &native_pitch) < 0) {
             return -1;
@@ -745,18 +804,18 @@ SDL_UpdateTextureYUV(SDL_Texture * texture, const SDL_Rect * rect,
         SDL_UnlockTexture(native);
     } else {
         /* Use a temporary buffer for updating */
-        void *temp_pixels;
-        int temp_pitch;
-
-        temp_pitch = (((rect->w * SDL_BYTESPERPIXEL(native->format)) + 3) & ~3);
-        temp_pixels = SDL_malloc(rect->h * temp_pitch);
-        if (!temp_pixels) {
-            return SDL_OutOfMemory();
+        const int temp_pitch = (((rect->w * SDL_BYTESPERPIXEL(native->format)) + 3) & ~3);
+        const size_t alloclen = rect->h * temp_pitch;
+        if (alloclen > 0) {
+            void *temp_pixels = SDL_malloc(alloclen);
+            if (!temp_pixels) {
+                return SDL_OutOfMemory();
+            }
+            SDL_SW_CopyYUVToRGB(texture->yuv, rect, native->format,
+                                rect->w, rect->h, temp_pixels, temp_pitch);
+            SDL_UpdateTexture(native, rect, temp_pixels, temp_pitch);
+            SDL_free(temp_pixels);
         }
-        SDL_SW_CopyYUVToRGB(texture->yuv, rect, native->format,
-                            rect->w, rect->h, temp_pixels, temp_pitch);
-        SDL_UpdateTexture(native, rect, temp_pixels, temp_pitch);
-        SDL_free(temp_pixels);
     }
     return 0;
 }
@@ -767,10 +826,14 @@ SDL_UpdateTextureNative(SDL_Texture * texture, const SDL_Rect * rect,
 {
     SDL_Texture *native = texture->native;
 
+    if (!rect->w || !rect->h) {
+        return 0;  /* nothing to do. */
+    }
+
     if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
         /* We can lock the texture and copy to it */
-        void *native_pixels;
-        int native_pitch;
+        void *native_pixels = NULL;
+        int native_pitch = 0;
 
         if (SDL_LockTexture(native, rect, &native_pixels, &native_pitch) < 0) {
             return -1;
@@ -781,19 +844,19 @@ SDL_UpdateTextureNative(SDL_Texture * texture, const SDL_Rect * rect,
         SDL_UnlockTexture(native);
     } else {
         /* Use a temporary buffer for updating */
-        void *temp_pixels;
-        int temp_pitch;
-
-        temp_pitch = (((rect->w * SDL_BYTESPERPIXEL(native->format)) + 3) & ~3);
-        temp_pixels = SDL_malloc(rect->h * temp_pitch);
-        if (!temp_pixels) {
-            return SDL_OutOfMemory();
+        const int temp_pitch = (((rect->w * SDL_BYTESPERPIXEL(native->format)) + 3) & ~3);
+        const size_t alloclen = rect->h * temp_pitch;
+        if (alloclen > 0) {
+            void *temp_pixels = SDL_malloc(alloclen);
+            if (!temp_pixels) {
+                return SDL_OutOfMemory();
+            }
+            SDL_ConvertPixels(rect->w, rect->h,
+                              texture->format, pixels, pitch,
+                              native->format, temp_pixels, temp_pitch);
+            SDL_UpdateTexture(native, rect, temp_pixels, temp_pitch);
+            SDL_free(temp_pixels);
         }
-        SDL_ConvertPixels(rect->w, rect->h,
-                          texture->format, pixels, pitch,
-                          native->format, temp_pixels, temp_pitch);
-        SDL_UpdateTexture(native, rect, temp_pixels, temp_pitch);
-        SDL_free(temp_pixels);
     }
     return 0;
 }
@@ -853,10 +916,14 @@ SDL_UpdateTextureYUVPlanar(SDL_Texture * texture, const SDL_Rect * rect,
     full_rect.h = texture->h;
     rect = &full_rect;
 
+    if (!rect->w || !rect->h) {
+        return 0;  /* nothing to do. */
+    }
+
     if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
         /* We can lock the texture and copy to it */
-        void *native_pixels;
-        int native_pitch;
+        void *native_pixels = NULL;
+        int native_pitch = 0;
 
         if (SDL_LockTexture(native, rect, &native_pixels, &native_pitch) < 0) {
             return -1;
@@ -866,18 +933,18 @@ SDL_UpdateTextureYUVPlanar(SDL_Texture * texture, const SDL_Rect * rect,
         SDL_UnlockTexture(native);
     } else {
         /* Use a temporary buffer for updating */
-        void *temp_pixels;
-        int temp_pitch;
-
-        temp_pitch = (((rect->w * SDL_BYTESPERPIXEL(native->format)) + 3) & ~3);
-        temp_pixels = SDL_malloc(rect->h * temp_pitch);
-        if (!temp_pixels) {
-            return SDL_OutOfMemory();
+        const int temp_pitch = (((rect->w * SDL_BYTESPERPIXEL(native->format)) + 3) & ~3);
+        const size_t alloclen = rect->h * temp_pitch;
+        if (alloclen > 0) {
+            void *temp_pixels = SDL_malloc(alloclen);
+            if (!temp_pixels) {
+                return SDL_OutOfMemory();
+            }
+            SDL_SW_CopyYUVToRGB(texture->yuv, rect, native->format,
+                                rect->w, rect->h, temp_pixels, temp_pitch);
+            SDL_UpdateTexture(native, rect, temp_pixels, temp_pitch);
+            SDL_free(temp_pixels);
         }
-        SDL_SW_CopyYUVToRGB(texture->yuv, rect, native->format,
-                            rect->w, rect->h, temp_pixels, temp_pitch);
-        SDL_UpdateTexture(native, rect, temp_pixels, temp_pitch);
-        SDL_free(temp_pixels);
     }
     return 0;
 }
@@ -924,6 +991,10 @@ int SDL_UpdateYUVTexture(SDL_Texture * texture, const SDL_Rect * rect,
         rect = &full_rect;
     }
 
+    if (!rect->w || !rect->h) {
+        return 0;  /* nothing to do. */
+    }
+
     if (texture->yuv) {
         return SDL_UpdateTextureYUVPlanar(texture, rect, Yplane, Ypitch, Uplane, Upitch, Vplane, Vpitch);
     } else {
@@ -1144,6 +1215,9 @@ UpdateLogicalSize(SDL_Renderer *renderer)
     float real_aspect;
     float scale;
     SDL_Rect viewport;
+    /* 0 is for letterbox, 1 is for overscan */
+    int scale_policy = 0;
+    const char *hint = SDL_GetHint(SDL_HINT_RENDER_LOGICAL_SIZE_MODE);
 
     if (!renderer->logical_w || !renderer->logical_h) {
         return 0;
@@ -1152,6 +1226,23 @@ UpdateLogicalSize(SDL_Renderer *renderer)
         return -1;
     }
 
+    if (!hint) {
+        scale_policy = 0;
+    } else if ( *hint == '1' || SDL_strcasecmp(hint, "overscan") == 0)  {
+        /* Unfortunately, Direct3D 9 does't support negative viewport numbers
+        which the main overscan implementation relies on.
+        D3D11 does support negative values and uses a different id string
+        so overscan will work for D3D11.
+        */
+        if(SDL_strcasecmp("direct3d", SDL_GetCurrentVideoDriver())) {
+            scale_policy = 0;
+        } else {
+            scale_policy = 1;
+        }
+    } else {
+        scale_policy = 0;
+    }
+    
     want_aspect = (float)renderer->logical_w / renderer->logical_h;
     real_aspect = (float)w / h;
 
@@ -1175,21 +1266,47 @@ UpdateLogicalSize(SDL_Renderer *renderer)
         scale = (float)w / renderer->logical_w;
         SDL_RenderSetViewport(renderer, NULL);
     } else if (want_aspect > real_aspect) {
-        /* We want a wider aspect ratio than is available - letterbox it */
-        scale = (float)w / renderer->logical_w;
-        viewport.x = 0;
-        viewport.w = w;
-        viewport.h = (int)SDL_ceil(renderer->logical_h * scale);
-        viewport.y = (h - viewport.h) / 2;
-        SDL_RenderSetViewport(renderer, &viewport);
+        if (scale_policy == 1) {
+            /* We want a wider aspect ratio than is available - 
+             zoom so logical height matches the real height 
+             and the width will grow off the screen 
+             */
+            scale = (float)h / renderer->logical_h;
+            viewport.y = 0;
+            viewport.h = h;
+            viewport.w = (int)SDL_ceil(renderer->logical_w * scale);
+            viewport.x = (w - viewport.w) / 2;
+            SDL_RenderSetViewport(renderer, &viewport);
+        } else {
+            /* We want a wider aspect ratio than is available - letterbox it */
+            scale = (float)w / renderer->logical_w;
+            viewport.x = 0;
+            viewport.w = w;
+            viewport.h = (int)SDL_ceil(renderer->logical_h * scale);
+            viewport.y = (h - viewport.h) / 2;
+            SDL_RenderSetViewport(renderer, &viewport);
+        }
     } else {
-        /* We want a narrower aspect ratio than is available - use side-bars */
-        scale = (float)h / renderer->logical_h;
-        viewport.y = 0;
-        viewport.h = h;
-        viewport.w = (int)SDL_ceil(renderer->logical_w * scale);
-        viewport.x = (w - viewport.w) / 2;
-        SDL_RenderSetViewport(renderer, &viewport);
+        if (scale_policy == 1) {
+            /* We want a narrower aspect ratio than is available -
+             zoom so logical width matches the real width
+             and the height will grow off the screen
+             */
+            scale = (float)w / renderer->logical_w;
+            viewport.x = 0;
+            viewport.w = w;
+            viewport.h = (int)SDL_ceil(renderer->logical_h * scale);
+            viewport.y = (h - viewport.h) / 2;
+            SDL_RenderSetViewport(renderer, &viewport);
+        } else {
+            /* We want a narrower aspect ratio than is available - use side-bars */
+             scale = (float)h / renderer->logical_h;
+             viewport.y = 0;
+             viewport.h = h;
+             viewport.w = (int)SDL_ceil(renderer->logical_w * scale);
+             viewport.x = (w - viewport.w) / 2;
+             SDL_RenderSetViewport(renderer, &viewport);
+        }
     }
 
     /* Set the new scale */
@@ -1382,6 +1499,9 @@ SDL_SetRenderDrawBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode)
 {
     CHECK_RENDERER_MAGIC(renderer, -1);
 
+    if (!IsSupportedBlendMode(renderer, blendMode)) {
+        return SDL_Unsupported();
+    }
     renderer->blendMode = blendMode;
     return 0;
 }
@@ -1926,7 +2046,9 @@ SDL_DestroyRenderer(SDL_Renderer * renderer)
 
     /* Free existing textures for this renderer */
     while (renderer->textures) {
+        SDL_Texture *tex = renderer->textures; (void) tex;
         SDL_DestroyTexture(renderer->textures);
+        SDL_assert(tex != renderer->textures);  /* satisfy static analysis. */
     }
 
     if (renderer->window) {
@@ -1970,4 +2092,93 @@ int SDL_GL_UnbindTexture(SDL_Texture *texture)
     return SDL_Unsupported();
 }
 
+static SDL_BlendMode
+SDL_GetShortBlendMode(SDL_BlendMode blendMode)
+{
+    if (blendMode == SDL_BLENDMODE_NONE_FULL) {
+        return SDL_BLENDMODE_NONE;
+    }
+    if (blendMode == SDL_BLENDMODE_BLEND_FULL) {
+        return SDL_BLENDMODE_BLEND;
+    }
+    if (blendMode == SDL_BLENDMODE_ADD_FULL) {
+        return SDL_BLENDMODE_ADD;
+    }
+    if (blendMode == SDL_BLENDMODE_MOD_FULL) {
+        return SDL_BLENDMODE_MOD;
+    }
+    return blendMode;
+}
+
+static SDL_BlendMode
+SDL_GetLongBlendMode(SDL_BlendMode blendMode)
+{
+    if (blendMode == SDL_BLENDMODE_NONE) {
+        return SDL_BLENDMODE_NONE_FULL;
+    }
+    if (blendMode == SDL_BLENDMODE_BLEND) {
+        return SDL_BLENDMODE_BLEND_FULL;
+    }
+    if (blendMode == SDL_BLENDMODE_ADD) {
+        return SDL_BLENDMODE_ADD_FULL;
+    }
+    if (blendMode == SDL_BLENDMODE_MOD) {
+        return SDL_BLENDMODE_MOD_FULL;
+    }
+    return blendMode;
+}
+
+SDL_BlendMode
+SDL_ComposeCustomBlendMode(SDL_BlendFactor srcColorFactor, SDL_BlendFactor dstColorFactor,
+                           SDL_BlendOperation colorOperation,
+                           SDL_BlendFactor srcAlphaFactor, SDL_BlendFactor dstAlphaFactor,
+                           SDL_BlendOperation alphaOperation)
+{
+    SDL_BlendMode blendMode = SDL_COMPOSE_BLENDMODE(srcColorFactor, dstColorFactor, colorOperation,
+                                                    srcAlphaFactor, dstAlphaFactor, alphaOperation);
+    return SDL_GetShortBlendMode(blendMode);
+}
+
+SDL_BlendFactor
+SDL_GetBlendModeSrcColorFactor(SDL_BlendMode blendMode)
+{
+    blendMode = SDL_GetLongBlendMode(blendMode);
+    return (SDL_BlendFactor)(((Uint32)blendMode >> 4) & 0xF);
+}
+
+SDL_BlendFactor
+SDL_GetBlendModeDstColorFactor(SDL_BlendMode blendMode)
+{
+    blendMode = SDL_GetLongBlendMode(blendMode);
+    return (SDL_BlendFactor)(((Uint32)blendMode >> 8) & 0xF);
+}
+
+SDL_BlendOperation
+SDL_GetBlendModeColorOperation(SDL_BlendMode blendMode)
+{
+    blendMode = SDL_GetLongBlendMode(blendMode);
+    return (SDL_BlendOperation)(((Uint32)blendMode >> 0) & 0xF);
+}
+
+SDL_BlendFactor
+SDL_GetBlendModeSrcAlphaFactor(SDL_BlendMode blendMode)
+{
+    blendMode = SDL_GetLongBlendMode(blendMode);
+    return (SDL_BlendFactor)(((Uint32)blendMode >> 20) & 0xF);
+}
+
+SDL_BlendFactor
+SDL_GetBlendModeDstAlphaFactor(SDL_BlendMode blendMode)
+{
+    blendMode = SDL_GetLongBlendMode(blendMode);
+    return (SDL_BlendFactor)(((Uint32)blendMode >> 24) & 0xF);
+}
+
+SDL_BlendOperation
+SDL_GetBlendModeAlphaOperation(SDL_BlendMode blendMode)
+{
+    blendMode = SDL_GetLongBlendMode(blendMode);
+    return (SDL_BlendOperation)(((Uint32)blendMode >> 16) & 0xF);
+}
+
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/render/SDL_sysrender.h b/src/render/SDL_sysrender.h
index 378fc4d..138407c 100644
--- a/src/render/SDL_sysrender.h
+++ b/src/render/SDL_sysrender.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_sysrender_h
-#define _SDL_sysrender_h
+#ifndef SDL_sysrender_h_
+#define SDL_sysrender_h_
 
 #include "SDL_render.h"
 #include "SDL_events.h"
@@ -79,6 +79,7 @@ struct SDL_Renderer
 
     void (*WindowEvent) (SDL_Renderer * renderer, const SDL_WindowEvent *event);
     int (*GetOutputSize) (SDL_Renderer * renderer, int *w, int *h);
+    SDL_bool (*SupportsBlendMode)(SDL_Renderer * renderer, SDL_BlendMode blendMode);
     int (*CreateTexture) (SDL_Renderer * renderer, SDL_Texture * texture);
     int (*SetTextureColorMod) (SDL_Renderer * renderer,
                                SDL_Texture * texture);
@@ -154,6 +155,9 @@ struct SDL_Renderer
     SDL_FPoint scale;
     SDL_FPoint scale_backup;
 
+    /* The pixel to point coordinate scale */
+    SDL_FPoint dpi_scale;
+
     /* The list of textures */
     SDL_Texture *textures;
     SDL_Texture *target;
@@ -173,33 +177,24 @@ struct SDL_RenderDriver
     SDL_RendererInfo info;
 };
 
-#if !SDL_RENDER_DISABLED
-
-#if SDL_VIDEO_RENDER_D3D
+/* Not all of these are available in a given build. Use #ifdefs, etc. */
 extern SDL_RenderDriver D3D_RenderDriver;
-#endif
-#if SDL_VIDEO_RENDER_D3D11
 extern SDL_RenderDriver D3D11_RenderDriver;
-#endif
-#if SDL_VIDEO_RENDER_OGL
 extern SDL_RenderDriver GL_RenderDriver;
-#endif
-#if SDL_VIDEO_RENDER_OGL_ES2
 extern SDL_RenderDriver GLES2_RenderDriver;
-#endif
-#if SDL_VIDEO_RENDER_OGL_ES
 extern SDL_RenderDriver GLES_RenderDriver;
-#endif
-#if SDL_VIDEO_RENDER_DIRECTFB
 extern SDL_RenderDriver DirectFB_RenderDriver;
-#endif
-#if SDL_VIDEO_RENDER_PSP
 extern SDL_RenderDriver PSP_RenderDriver;
-#endif
 extern SDL_RenderDriver SW_RenderDriver;
 
-#endif /* !SDL_RENDER_DISABLED */
+/* Blend mode functions */
+extern SDL_BlendFactor SDL_GetBlendModeSrcColorFactor(SDL_BlendMode blendMode);
+extern SDL_BlendFactor SDL_GetBlendModeDstColorFactor(SDL_BlendMode blendMode);
+extern SDL_BlendOperation SDL_GetBlendModeColorOperation(SDL_BlendMode blendMode);
+extern SDL_BlendFactor SDL_GetBlendModeSrcAlphaFactor(SDL_BlendMode blendMode);
+extern SDL_BlendFactor SDL_GetBlendModeDstAlphaFactor(SDL_BlendMode blendMode);
+extern SDL_BlendOperation SDL_GetBlendModeAlphaOperation(SDL_BlendMode blendMode);
 
-#endif /* _SDL_sysrender_h */
+#endif /* SDL_sysrender_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/render/SDL_yuv_mmx.c b/src/render/SDL_yuv_mmx.c
index 0de776a..90da9f9 100644
--- a/src/render/SDL_yuv_mmx.c
+++ b/src/render/SDL_yuv_mmx.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,7 +20,9 @@
 */
 #include "../SDL_internal.h"
 
-#if (__GNUC__ > 2) && defined(__i386__) && __OPTIMIZE__ && SDL_ASSEMBLY_ROUTINES
+#include "SDL_yuv_mmx_c.h"
+
+#ifdef USE_MMX_ASSEMBLY
 
 #include "SDL_stdinc.h"
 
@@ -91,22 +93,11 @@ void ColorRGBDitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix,
     mod = (mod+cols+mod)*4;               /* increment for row1 in byte */
 
     __asm__ __volatile__ (
-        /* tap dance to workaround the inability to use %%ebx at will... */
-        /*  move one thing to the stack... */
-        "pushl $0\n"  /* save a slot on the stack. */
-        "pushl %%ebx\n"  /* save %%ebx. */
-        "movl %0, %%ebx\n"  /* put the thing in ebx. */
-        "movl %%ebx,4(%%esp)\n"  /* put the thing in the stack slot. */
-        "popl %%ebx\n"  /* get back %%ebx (the PIC register). */
-
         ".align 8\n"
         "1:\n"
 
         /* create Cr (result in mm1) */
-        "pushl %%ebx\n"
-        "movl 4(%%esp),%%ebx\n"
-        "movd (%%ebx),%%mm1\n"   /*         0  0  0  0  v3 v2 v1 v0 */
-        "popl %%ebx\n"
+        "movd (%0),%%mm1\n"   /*         0  0  0  0  v3 v2 v1 v0 */
         "pxor %%mm7,%%mm7\n"      /*         00 00 00 00 00 00 00 00 */
         "movd (%2), %%mm2\n"           /*    0  0  0  0 l3 l2 l1 l0 */
         "punpcklbw %%mm7,%%mm1\n" /*         0  v3 0  v2 00 v1 00 v0 */
@@ -214,7 +205,7 @@ void ColorRGBDitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix,
         "addl $4,%2\n"            /* lum+4 */
         "leal 16(%3),%3\n"        /* row1+16 */
         "leal 16(%5),%5\n"        /* row2+16 */
-        "addl $2,(%%esp)\n"        /* cr+2 */
+        "addl $2,%0\n"        /* cr+2 */
         "addl $2,%1\n"           /* cb+2 */
 
         "addl $4,%6\n"            /* x+4 */
@@ -228,10 +219,9 @@ void ColorRGBDitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix,
         "cmpl %7,%2\n"
         "jl 1b\n"
 
-        "addl $4,%%esp\n"  /* get rid of the stack slot we reserved. */
         "emms\n"  /* reset MMX registers. */
         :
-        : "m" (cr), "r"(cb),"r"(lum),
+        : "r" (cr), "r"(cb),"r"(lum),
           "r"(row1),"r"(cols),"r"(row2),"m"(x),"m"(y),"m"(mod),
           "m"(MMX_0080w),"m"(MMX_VgrnRGB),"m"(MMX_VredRGB),
           "m"(MMX_FF00w),"m"(MMX_00FFw),"m"(MMX_UgrnRGB),
@@ -254,23 +244,12 @@ void Color565DitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix,
     mod = (mod+cols+mod)*2;               /* increment for row1 in byte */
 
     __asm__ __volatile__(
-        /* tap dance to workaround the inability to use %%ebx at will... */
-        /*  move one thing to the stack... */
-        "pushl $0\n"  /* save a slot on the stack. */
-        "pushl %%ebx\n"  /* save %%ebx. */
-        "movl %0, %%ebx\n"  /* put the thing in ebx. */
-        "movl %%ebx, 4(%%esp)\n"  /* put the thing in the stack slot. */
-        "popl %%ebx\n"  /* get back %%ebx (the PIC register). */
-
         ".align 8\n"
         "1:\n"
 
         "movd           (%1),                   %%mm0\n" /* 4 Cb         0  0  0  0 u3 u2 u1 u0 */
         "pxor           %%mm7,                  %%mm7\n"
-        "pushl %%ebx\n"
-        "movl 4(%%esp), %%ebx\n"
-        "movd (%%ebx), %%mm1\n"   /* 4 Cr                0  0  0  0 v3 v2 v1 v0 */
-        "popl %%ebx\n"
+        "movd (%0), %%mm1\n"   /* 4 Cr                0  0  0  0 v3 v2 v1 v0 */
 
         "punpcklbw      %%mm7,                  %%mm0\n" /* 4 W cb   0 u3  0 u2  0 u1  0 u0 */
         "punpcklbw      %%mm7,                  %%mm1\n" /* 4 W cr   0 v3  0 v2  0 v1  0 v0 */
@@ -400,7 +379,7 @@ void Color565DitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix,
 
         "addl           $8,                     %6\n"
         "addl           $8,                     %2\n"
-        "addl           $4,                     (%%esp)\n"
+        "addl           $4,                     %0\n"
         "addl           $4,                     %1\n"
         "cmpl           %4,                     %6\n"
         "leal           16(%3),                 %3\n"
@@ -413,10 +392,9 @@ void Color565DitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix,
         "movl           $0,     %6\n" /* x=0 */
         "cmpl           %7,     %2\n"
         "jl             1b\n"
-        "addl $4, %%esp\n"  /* get rid of the stack slot we reserved. */
         "emms\n"
         :
-        : "m" (cr), "r"(cb),"r"(lum),
+        : "r" (cr), "r"(cb),"r"(lum),
           "r"(row1),"r"(cols),"r"(row2),"m"(x),"m"(y),"m"(mod),
           "m"(MMX_0080w),"m"(MMX_Ugrn565),"m"(MMX_Ublu5x5),
           "m"(MMX_00FFw),"m"(MMX_Vgrn565),"m"(MMX_Vred5x5),
@@ -426,6 +404,6 @@ void Color565DitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix,
 
 /* *INDENT-ON* */
 
-#endif /* GCC3 i386 inline assembly */
+#endif /* USE_MMX_ASSEMBLY */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/SDL_blit_auto.h b/src/render/SDL_yuv_mmx_c.h
similarity index 75%
copy from src/video/SDL_blit_auto.h
copy to src/render/SDL_yuv_mmx_c.h
index 58a532d..d175ebf 100644
--- a/src/video/SDL_blit_auto.h
+++ b/src/render/SDL_yuv_mmx_c.h
@@ -1,7 +1,6 @@
-/* DO NOT EDIT!  This file is generated by sdlgenblit.pl */
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,10 +20,9 @@
 */
 #include "../SDL_internal.h"
 
-/* *INDENT-OFF* */
-
-extern SDL_BlitFuncEntry SDL_GeneratedBlitFuncTable[];
-
-/* *INDENT-ON* */
+/* FIXME: This breaks on various versions of GCC and should be rewritten using intrinsics */
+#if 0 /* (__GNUC__ > 2) && defined(__i386__) && __OPTIMIZE__ && SDL_ASSEMBLY_ROUTINES && !defined(__clang__) */
+#define USE_MMX_ASSEMBLY 1
+#endif
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/render/SDL_yuv_sw.c b/src/render/SDL_yuv_sw.c
index 7fc6b88..9d202e0 100644
--- a/src/render/SDL_yuv_sw.c
+++ b/src/render/SDL_yuv_sw.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -86,11 +86,12 @@
 #include "SDL_video.h"
 #include "SDL_cpuinfo.h"
 #include "SDL_yuv_sw_c.h"
+#include "SDL_yuv_mmx_c.h"
 
 
 /* The colorspace conversion functions */
 
-#if (__GNUC__ > 2) && defined(__i386__) && __OPTIMIZE__ && SDL_ASSEMBLY_ROUTINES
+#ifdef USE_MMX_ASSEMBLY
 extern void Color565DitherYV12MMX1X(int *colortab, Uint32 * rgb_2_pix,
                                     unsigned char *lum, unsigned char *cr,
                                     unsigned char *cb, unsigned char *out,
@@ -875,14 +876,16 @@ number_of_bits_set(Uint32 a)
  * Low performance, do not call often.
  */
 static int
+free_bits_at_bottom_nonzero(Uint32 a)
+{
+    SDL_assert(a != 0);
+    return (((Sint32) a) & 1l) ? 0 : 1 + free_bits_at_bottom_nonzero(a >> 1);
+}
+
+static SDL_INLINE int
 free_bits_at_bottom(Uint32 a)
 {
-    /* assume char is 8 bits */
-    if (!a)
-        return sizeof(Uint32) * 8;
-    if (((Sint32) a) & 1l)
-        return 0;
-    return 1 + free_bits_at_bottom(a >> 1);
+    return a ? free_bits_at_bottom_nonzero(a) : 32;
 }
 
 static int
@@ -894,6 +897,7 @@ SDL_SW_SetupYUVDisplay(SDL_SW_YUVTexture * swdata, Uint32 target_format)
     int i;
     int bpp;
     Uint32 Rmask, Gmask, Bmask, Amask;
+    int freebits;
 
     if (!SDL_PixelFormatEnumToMasks
         (target_format, &bpp, &Rmask, &Gmask, &Bmask, &Amask) || bpp < 15) {
@@ -910,13 +914,24 @@ SDL_SW_SetupYUVDisplay(SDL_SW_YUVTexture * swdata, Uint32 target_format)
      */
     for (i = 0; i < 256; ++i) {
         r_2_pix_alloc[i + 256] = i >> (8 - number_of_bits_set(Rmask));
-        r_2_pix_alloc[i + 256] <<= free_bits_at_bottom(Rmask);
+        freebits = free_bits_at_bottom(Rmask);
+        if (freebits < 32) {
+            r_2_pix_alloc[i + 256] <<= freebits;
+        }
         r_2_pix_alloc[i + 256] |= Amask;
+
         g_2_pix_alloc[i + 256] = i >> (8 - number_of_bits_set(Gmask));
-        g_2_pix_alloc[i + 256] <<= free_bits_at_bottom(Gmask);
+        freebits = free_bits_at_bottom(Gmask);
+        if (freebits < 32) {
+            g_2_pix_alloc[i + 256] <<= freebits;
+        }
         g_2_pix_alloc[i + 256] |= Amask;
+
         b_2_pix_alloc[i + 256] = i >> (8 - number_of_bits_set(Bmask));
-        b_2_pix_alloc[i + 256] <<= free_bits_at_bottom(Bmask);
+        freebits = free_bits_at_bottom(Bmask);
+        if (freebits < 32) {
+            b_2_pix_alloc[i + 256] <<= freebits;
+        }
         b_2_pix_alloc[i + 256] |= Amask;
     }
 
@@ -953,7 +968,7 @@ SDL_SW_SetupYUVDisplay(SDL_SW_YUVTexture * swdata, Uint32 target_format)
     case SDL_PIXELFORMAT_YV12:
     case SDL_PIXELFORMAT_IYUV:
         if (SDL_BYTESPERPIXEL(target_format) == 2) {
-#if (__GNUC__ > 2) && defined(__i386__) && __OPTIMIZE__ && SDL_ASSEMBLY_ROUTINES
+#ifdef USE_MMX_ASSEMBLY
             /* inline assembly functions */
             if (SDL_HasMMX() && (Rmask == 0xF800) &&
                 (Gmask == 0x07E0) && (Bmask == 0x001F)
@@ -974,7 +989,7 @@ SDL_SW_SetupYUVDisplay(SDL_SW_YUVTexture * swdata, Uint32 target_format)
             swdata->Display2X = Color24DitherYV12Mod2X;
         }
         if (SDL_BYTESPERPIXEL(target_format) == 4) {
-#if (__GNUC__ > 2) && defined(__i386__) && __OPTIMIZE__ && SDL_ASSEMBLY_ROUTINES
+#ifdef USE_MMX_ASSEMBLY
             /* inline assembly functions */
             if (SDL_HasMMX() && (Rmask == 0x00FF0000) &&
                 (Gmask == 0x0000FF00) &&
diff --git a/src/render/SDL_yuv_sw_c.h b/src/render/SDL_yuv_sw_c.h
index 2752096..248dd45 100644
--- a/src/render/SDL_yuv_sw_c.h
+++ b/src/render/SDL_yuv_sw_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -69,4 +69,9 @@ int SDL_SW_CopyYUVToRGB(SDL_SW_YUVTexture * swdata, const SDL_Rect * srcrect,
                         int pitch);
 void SDL_SW_DestroyYUVTexture(SDL_SW_YUVTexture * swdata);
 
+/* FIXME: This breaks on various versions of GCC and should be rewritten using intrinsics */
+#if 0 /* (__GNUC__ > 2) && defined(__i386__) && __OPTIMIZE__ && SDL_ASSEMBLY_ROUTINES && !defined(__clang__) */
+#define USE_MMX_ASSEMBLY 1
+#endif
+
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/render/direct3d/SDL_render_d3d.c b/src/render/direct3d/SDL_render_d3d.c
index 151dbbf..c40f699 100644
--- a/src/render/direct3d/SDL_render_d3d.c
+++ b/src/render/direct3d/SDL_render_d3d.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -125,6 +125,7 @@ static void PrintShaderData(LPDWORD shader_data, DWORD shader_size)
 static SDL_Renderer *D3D_CreateRenderer(SDL_Window * window, Uint32 flags);
 static void D3D_WindowEvent(SDL_Renderer * renderer,
                             const SDL_WindowEvent *event);
+static SDL_bool D3D_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode);
 static int D3D_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture);
 static int D3D_RecreateTexture(SDL_Renderer * renderer, SDL_Texture * texture);
 static int D3D_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
@@ -542,6 +543,7 @@ D3D_CreateRenderer(SDL_Window * window, Uint32 flags)
     }
 
     renderer->WindowEvent = D3D_WindowEvent;
+    renderer->SupportsBlendMode = D3D_SupportsBlendMode;
     renderer->CreateTexture = D3D_CreateTexture;
     renderer->UpdateTexture = D3D_UpdateTexture;
     renderer->UpdateTextureYUV = D3D_UpdateTextureYUV;
@@ -759,6 +761,7 @@ D3D_CreateRenderer(SDL_Window * window, Uint32 flags)
             const char *error = (const char *)pErrorMsgs->lpVtbl->GetBufferPointer(pErrorMsgs);
             SDL_SetError("Couldn't assemble shader: %s", error);
         }
+        if (shader_data != NULL)
 #else
         const DWORD shader_data[] = {
             0xffff0200, 0x05000051, 0xa00f0000, 0xbd808081, 0xbf008081, 0xbf008081,
@@ -778,7 +781,7 @@ D3D_CreateRenderer(SDL_Window * window, Uint32 flags)
             0x80e40000, 0x0000ffff
         };
 #endif
-        if (shader_data != NULL) {
+        {
             result = IDirect3DDevice9_CreatePixelShader(data->device, shader_data, &data->ps_yuv);
             if (!FAILED(result)) {
                 renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_YV12;
@@ -802,6 +805,58 @@ D3D_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event)
     }
 }
 
+static D3DBLEND GetBlendFunc(SDL_BlendFactor factor)
+{
+    switch (factor) {
+    case SDL_BLENDFACTOR_ZERO:
+        return D3DBLEND_ZERO;
+    case SDL_BLENDFACTOR_ONE:
+        return D3DBLEND_ONE;
+    case SDL_BLENDFACTOR_SRC_COLOR:
+        return D3DBLEND_SRCCOLOR;
+    case SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR:
+        return D3DBLEND_INVSRCCOLOR;
+    case SDL_BLENDFACTOR_SRC_ALPHA:
+        return D3DBLEND_SRCALPHA;
+    case SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA:
+        return D3DBLEND_INVSRCALPHA;
+    case SDL_BLENDFACTOR_DST_COLOR:
+        return D3DBLEND_DESTCOLOR;
+    case SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR:
+        return D3DBLEND_INVDESTCOLOR;
+    case SDL_BLENDFACTOR_DST_ALPHA:
+        return D3DBLEND_DESTALPHA;
+    case SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA:
+        return D3DBLEND_INVDESTALPHA;
+    default:
+        return (D3DBLEND)0;
+    }
+}
+
+static SDL_bool
+D3D_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode)
+{
+    D3D_RenderData *data = (D3D_RenderData *) renderer->driverdata;
+    SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode);
+    SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode);
+    SDL_BlendOperation colorOperation = SDL_GetBlendModeColorOperation(blendMode);
+    SDL_BlendFactor dstColorFactor = SDL_GetBlendModeDstColorFactor(blendMode);
+    SDL_BlendFactor dstAlphaFactor = SDL_GetBlendModeDstAlphaFactor(blendMode);
+    SDL_BlendOperation alphaOperation = SDL_GetBlendModeAlphaOperation(blendMode);
+
+    if (!GetBlendFunc(srcColorFactor) || !GetBlendFunc(srcAlphaFactor) ||
+        !GetBlendFunc(dstColorFactor) || !GetBlendFunc(dstAlphaFactor)) {
+        return SDL_FALSE;
+    }
+    if ((srcColorFactor != srcAlphaFactor || dstColorFactor != dstAlphaFactor) && !data->enableSeparateAlphaBlend) {
+        return SDL_FALSE;
+    }
+    if (colorOperation != SDL_BLENDOPERATION_ADD || alphaOperation != SDL_BLENDOPERATION_ADD) {
+        return SDL_FALSE;
+    }
+    return SDL_TRUE;
+}
+
 static D3DTEXTUREFILTERTYPE
 GetScaleQuality(void)
 {
@@ -1353,55 +1408,22 @@ D3D_RenderClear(SDL_Renderer * renderer)
 }
 
 static void
-D3D_SetBlendMode(D3D_RenderData * data, int blendMode)
+D3D_SetBlendMode(D3D_RenderData * data, SDL_BlendMode blendMode)
 {
-    switch (blendMode) {
-    case SDL_BLENDMODE_NONE:
-        IDirect3DDevice9_SetRenderState(data->device, D3DRS_ALPHABLENDENABLE,
-                                        FALSE);
-        break;
-    case SDL_BLENDMODE_BLEND:
-        IDirect3DDevice9_SetRenderState(data->device, D3DRS_ALPHABLENDENABLE,
-                                        TRUE);
-        IDirect3DDevice9_SetRenderState(data->device, D3DRS_SRCBLEND,
-                                        D3DBLEND_SRCALPHA);
-        IDirect3DDevice9_SetRenderState(data->device, D3DRS_DESTBLEND,
-                                        D3DBLEND_INVSRCALPHA);
-        if (data->enableSeparateAlphaBlend) {
-            IDirect3DDevice9_SetRenderState(data->device, D3DRS_SRCBLENDALPHA,
-                                            D3DBLEND_ONE);
-            IDirect3DDevice9_SetRenderState(data->device, D3DRS_DESTBLENDALPHA,
-                                            D3DBLEND_INVSRCALPHA);
-        }
-        break;
-    case SDL_BLENDMODE_ADD:
-        IDirect3DDevice9_SetRenderState(data->device, D3DRS_ALPHABLENDENABLE,
-                                        TRUE);
-        IDirect3DDevice9_SetRenderState(data->device, D3DRS_SRCBLEND,
-                                        D3DBLEND_SRCALPHA);
-        IDirect3DDevice9_SetRenderState(data->device, D3DRS_DESTBLEND,
-                                        D3DBLEND_ONE);
-        if (data->enableSeparateAlphaBlend) {
-            IDirect3DDevice9_SetRenderState(data->device, D3DRS_SRCBLENDALPHA,
-                                            D3DBLEND_ZERO);
-            IDirect3DDevice9_SetRenderState(data->device, D3DRS_DESTBLENDALPHA,
-                                            D3DBLEND_ONE);
-        }
-        break;
-    case SDL_BLENDMODE_MOD:
-        IDirect3DDevice9_SetRenderState(data->device, D3DRS_ALPHABLENDENABLE,
-                                        TRUE);
+    if (blendMode == SDL_BLENDMODE_NONE) {
+        IDirect3DDevice9_SetRenderState(data->device, D3DRS_ALPHABLENDENABLE, FALSE);
+    } else {
+        IDirect3DDevice9_SetRenderState(data->device, D3DRS_ALPHABLENDENABLE, TRUE);
         IDirect3DDevice9_SetRenderState(data->device, D3DRS_SRCBLEND,
-                                        D3DBLEND_ZERO);
+                                        GetBlendFunc(SDL_GetBlendModeSrcColorFactor(blendMode)));
         IDirect3DDevice9_SetRenderState(data->device, D3DRS_DESTBLEND,
-                                        D3DBLEND_SRCCOLOR);
+                                        GetBlendFunc(SDL_GetBlendModeDstColorFactor(blendMode)));
         if (data->enableSeparateAlphaBlend) {
             IDirect3DDevice9_SetRenderState(data->device, D3DRS_SRCBLENDALPHA,
-                                            D3DBLEND_ZERO);
+                                            GetBlendFunc(SDL_GetBlendModeSrcAlphaFactor(blendMode)));
             IDirect3DDevice9_SetRenderState(data->device, D3DRS_DESTBLENDALPHA,
-                                            D3DBLEND_ONE);
+                                            GetBlendFunc(SDL_GetBlendModeDstAlphaFactor(blendMode)));
         }
-        break;
     }
 }
 
@@ -1723,29 +1745,27 @@ D3D_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
     centerx = center->x;
     centery = center->y;
 
-    if (flip & SDL_FLIP_HORIZONTAL) {
-        minx = dstrect->w - centerx - 0.5f;
-        maxx = -centerx - 0.5f;
-    }
-    else {
-        minx = -centerx - 0.5f;
-        maxx = dstrect->w - centerx - 0.5f;
-    }
-
-    if (flip & SDL_FLIP_VERTICAL) {
-        miny = dstrect->h - centery - 0.5f;
-        maxy = -centery - 0.5f;
-    }
-    else {
-        miny = -centery - 0.5f;
-        maxy = dstrect->h - centery - 0.5f;
-    }
+    minx = -centerx;
+    maxx = dstrect->w - centerx;
+    miny = -centery;
+    maxy = dstrect->h - centery;
 
     minu = (float) srcrect->x / texture->w;
     maxu = (float) (srcrect->x + srcrect->w) / texture->w;
     minv = (float) srcrect->y / texture->h;
     maxv = (float) (srcrect->y + srcrect->h) / texture->h;
 
+    if (flip & SDL_FLIP_HORIZONTAL) {
+        float tmp = maxu;
+        maxu = minu;
+        minu = tmp;
+    }
+    if (flip & SDL_FLIP_VERTICAL) {
+        float tmp = maxv;
+        maxv = minv;
+        minv = tmp;
+    }
+
     color = D3DCOLOR_ARGB(texture->a, texture->r, texture->g, texture->b);
 
     vertices[0].x = minx;
@@ -1781,8 +1801,7 @@ D3D_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
     /* Rotate and translate */
     modelMatrix = MatrixMultiply(
             MatrixRotationZ((float)(M_PI * (float) angle / 180.0f)),
-            MatrixTranslation(dstrect->x + center->x, dstrect->y + center->y, 0)
-);
+            MatrixTranslation(dstrect->x + center->x - 0.5f, dstrect->y + center->y - 0.5f, 0));
     IDirect3DDevice9_SetTransform(data->device, D3DTS_VIEW, (D3DMATRIX*)&modelMatrix);
 
     D3D_UpdateTextureScaleMode(data, texturedata, 0);
diff --git a/src/render/direct3d11/SDL_render_d3d11.c b/src/render/direct3d11/SDL_render_d3d11.c
index df0f155..73cf680 100644
--- a/src/render/direct3d11/SDL_render_d3d11.c
+++ b/src/render/direct3d11/SDL_render_d3d11.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -93,6 +93,13 @@ typedef struct
     SDL_Rect locked_rect;
 } D3D11_TextureData;
 
+/* Blend mode data */
+typedef struct
+{
+    SDL_BlendMode blendMode;
+    ID3D11BlendState *blendState;
+} D3D11_BlendMode;
+
 /* Private renderer data */
 typedef struct
 {
@@ -112,9 +119,8 @@ typedef struct
     ID3D11PixelShader *colorPixelShader;
     ID3D11PixelShader *texturePixelShader;
     ID3D11PixelShader *yuvPixelShader;
-    ID3D11BlendState *blendModeBlend;
-    ID3D11BlendState *blendModeAdd;
-    ID3D11BlendState *blendModeMod;
+    int blendModesCount;
+    D3D11_BlendMode *blendModes;
     ID3D11SamplerState *nearestPixelSampler;
     ID3D11SamplerState *linearSampler;
     D3D_FEATURE_LEVEL featureLevel;
@@ -716,6 +722,7 @@ static const DWORD D3D11_VertexShader[] = {
 static SDL_Renderer *D3D11_CreateRenderer(SDL_Window * window, Uint32 flags);
 static void D3D11_WindowEvent(SDL_Renderer * renderer,
                             const SDL_WindowEvent *event);
+static SDL_bool D3D11_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode);
 static int D3D11_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture);
 static int D3D11_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                              const SDL_Rect * rect, const void *srcPixels,
@@ -826,6 +833,7 @@ D3D11_CreateRenderer(SDL_Window * window, Uint32 flags)
     }
 
     renderer->WindowEvent = D3D11_WindowEvent;
+    renderer->SupportsBlendMode = D3D11_SupportsBlendMode;
     renderer->CreateTexture = D3D11_CreateTexture;
     renderer->UpdateTexture = D3D11_UpdateTexture;
     renderer->UpdateTextureYUV = D3D11_UpdateTextureYUV;
@@ -898,6 +906,8 @@ D3D11_ReleaseAll(SDL_Renderer * renderer)
 
     /* Release/reset everything else */
     if (data) {
+        int i;
+
         SAFE_RELEASE(data->dxgiFactory);
         SAFE_RELEASE(data->dxgiAdapter);
         SAFE_RELEASE(data->d3dDevice);
@@ -911,9 +921,14 @@ D3D11_ReleaseAll(SDL_Renderer * renderer)
         SAFE_RELEASE(data->colorPixelShader);
         SAFE_RELEASE(data->texturePixelShader);
         SAFE_RELEASE(data->yuvPixelShader);
-        SAFE_RELEASE(data->blendModeBlend);
-        SAFE_RELEASE(data->blendModeAdd);
-        SAFE_RELEASE(data->blendModeMod);
+        if (data->blendModesCount > 0) {
+            for (i = 0; i < data->blendModesCount; ++i) {
+                SAFE_RELEASE(data->blendModes[i].blendState);
+            }
+            SDL_free(data->blendModes);
+
+            data->blendModesCount = 0;
+        }
         SAFE_RELEASE(data->nearestPixelSampler);
         SAFE_RELEASE(data->linearSampler);
         SAFE_RELEASE(data->mainRasterizer);
@@ -954,37 +969,96 @@ D3D11_DestroyRenderer(SDL_Renderer * renderer)
     SDL_free(renderer);
 }
 
-static HRESULT
-D3D11_CreateBlendMode(SDL_Renderer * renderer,
-                      BOOL enableBlending,
-                      D3D11_BLEND srcBlend,
-                      D3D11_BLEND destBlend,
-                      D3D11_BLEND srcBlendAlpha,
-                      D3D11_BLEND destBlendAlpha,
-                      ID3D11BlendState ** blendStateOutput)
+static D3D11_BLEND GetBlendFunc(SDL_BlendFactor factor)
+{
+    switch (factor) {
+    case SDL_BLENDFACTOR_ZERO:
+        return D3D11_BLEND_ZERO;
+    case SDL_BLENDFACTOR_ONE:
+        return D3D11_BLEND_ONE;
+    case SDL_BLENDFACTOR_SRC_COLOR:
+        return D3D11_BLEND_SRC_COLOR;
+    case SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR:
+        return D3D11_BLEND_INV_SRC_COLOR;
+    case SDL_BLENDFACTOR_SRC_ALPHA:
+        return D3D11_BLEND_SRC_ALPHA;
+    case SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA:
+        return D3D11_BLEND_INV_SRC_ALPHA;
+    case SDL_BLENDFACTOR_DST_COLOR:
+        return D3D11_BLEND_DEST_COLOR;
+    case SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR:
+        return D3D11_BLEND_INV_DEST_COLOR;
+    case SDL_BLENDFACTOR_DST_ALPHA:
+        return D3D11_BLEND_DEST_ALPHA;
+    case SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA:
+        return D3D11_BLEND_INV_DEST_ALPHA;
+    default:
+        return (D3D11_BLEND)0;
+    }
+}
+
+static D3D11_BLEND_OP GetBlendEquation(SDL_BlendOperation operation)
+{
+    switch (operation) {
+    case SDL_BLENDOPERATION_ADD:
+        return D3D11_BLEND_OP_ADD;
+    case SDL_BLENDOPERATION_SUBTRACT:
+        return D3D11_BLEND_OP_SUBTRACT;
+    case SDL_BLENDOPERATION_REV_SUBTRACT:
+        return D3D11_BLEND_OP_REV_SUBTRACT;
+    case SDL_BLENDOPERATION_MINIMUM:
+        return D3D11_BLEND_OP_MIN;
+    case SDL_BLENDOPERATION_MAXIMUM:
+        return D3D11_BLEND_OP_MAX;
+    default:
+        return (D3D11_BLEND_OP)0;
+    }
+}
+
+static SDL_bool
+D3D11_CreateBlendState(SDL_Renderer * renderer, SDL_BlendMode blendMode)
 {
     D3D11_RenderData *data = (D3D11_RenderData *) renderer->driverdata;
+    SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode);
+    SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode);
+    SDL_BlendOperation colorOperation = SDL_GetBlendModeColorOperation(blendMode);
+    SDL_BlendFactor dstColorFactor = SDL_GetBlendModeDstColorFactor(blendMode);
+    SDL_BlendFactor dstAlphaFactor = SDL_GetBlendModeDstAlphaFactor(blendMode);
+    SDL_BlendOperation alphaOperation = SDL_GetBlendModeAlphaOperation(blendMode);
+    ID3D11BlendState *blendState = NULL;
+    D3D11_BlendMode *blendModes;
     HRESULT result = S_OK;
 
     D3D11_BLEND_DESC blendDesc;
     SDL_zero(blendDesc);
     blendDesc.AlphaToCoverageEnable = FALSE;
     blendDesc.IndependentBlendEnable = FALSE;
-    blendDesc.RenderTarget[0].BlendEnable = enableBlending;
-    blendDesc.RenderTarget[0].SrcBlend = srcBlend;
-    blendDesc.RenderTarget[0].DestBlend = destBlend;
-    blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
-    blendDesc.RenderTarget[0].SrcBlendAlpha = srcBlendAlpha;
-    blendDesc.RenderTarget[0].DestBlendAlpha = destBlendAlpha;
-    blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
+    blendDesc.RenderTarget[0].BlendEnable = TRUE;
+    blendDesc.RenderTarget[0].SrcBlend = GetBlendFunc(srcColorFactor);
+    blendDesc.RenderTarget[0].DestBlend = GetBlendFunc(dstColorFactor);
+    blendDesc.RenderTarget[0].BlendOp = GetBlendEquation(colorOperation);
+    blendDesc.RenderTarget[0].SrcBlendAlpha = GetBlendFunc(srcAlphaFactor);
+    blendDesc.RenderTarget[0].DestBlendAlpha = GetBlendFunc(dstAlphaFactor);
+    blendDesc.RenderTarget[0].BlendOpAlpha = GetBlendEquation(alphaOperation);
     blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
-    result = ID3D11Device_CreateBlendState(data->d3dDevice, &blendDesc, blendStateOutput);
+    result = ID3D11Device_CreateBlendState(data->d3dDevice, &blendDesc, &blendState);
     if (FAILED(result)) {
         WIN_SetErrorFromHRESULT(SDL_COMPOSE_ERROR("ID3D11Device1::CreateBlendState"), result);
-        return result;
+        return SDL_FALSE;
     }
 
-    return S_OK;
+    blendModes = (D3D11_BlendMode *)SDL_realloc(data->blendModes, (data->blendModesCount + 1) * sizeof(*blendModes));
+    if (!blendModes) {
+        SAFE_RELEASE(blendState);
+        SDL_OutOfMemory();
+        return SDL_FALSE;
+    }
+    blendModes[data->blendModesCount].blendMode = blendMode;
+    blendModes[data->blendModesCount].blendState = blendState;
+    data->blendModes = blendModes;
+    ++data->blendModesCount;
+
+    return SDL_TRUE;
 }
 
 /* Create resources that depend on the device. */
@@ -1286,41 +1360,9 @@ D3D11_CreateDeviceResources(SDL_Renderer * renderer)
     }
 
     /* Create blending states: */
-    result = D3D11_CreateBlendMode(
-        renderer,
-        TRUE,
-        D3D11_BLEND_SRC_ALPHA,          /* srcBlend */
-        D3D11_BLEND_INV_SRC_ALPHA,      /* destBlend */
-        D3D11_BLEND_ONE,                /* srcBlendAlpha */
-        D3D11_BLEND_INV_SRC_ALPHA,      /* destBlendAlpha */
-        &data->blendModeBlend);
-    if (FAILED(result)) {
-        /* D3D11_CreateBlendMode will set the SDL error, if it fails */
-        goto done;
-    }
-
-    result = D3D11_CreateBlendMode(
-        renderer,
-        TRUE,
-        D3D11_BLEND_SRC_ALPHA,          /* srcBlend */
-        D3D11_BLEND_ONE,                /* destBlend */
-        D3D11_BLEND_ZERO,               /* srcBlendAlpha */
-        D3D11_BLEND_ONE,                /* destBlendAlpha */
-        &data->blendModeAdd);
-    if (FAILED(result)) {
-        /* D3D11_CreateBlendMode will set the SDL error, if it fails */
-        goto done;
-    }
-
-    result = D3D11_CreateBlendMode(
-        renderer,
-        TRUE,
-        D3D11_BLEND_ZERO,               /* srcBlend */
-        D3D11_BLEND_SRC_COLOR,          /* destBlend */
-        D3D11_BLEND_ZERO,               /* srcBlendAlpha */
-        D3D11_BLEND_ONE,                /* destBlendAlpha */
-        &data->blendModeMod);
-    if (FAILED(result)) {
+    if (!D3D11_CreateBlendState(renderer, SDL_BLENDMODE_BLEND) ||
+        !D3D11_CreateBlendState(renderer, SDL_BLENDMODE_ADD) ||
+        !D3D11_CreateBlendState(renderer, SDL_BLENDMODE_MOD)) {
         /* D3D11_CreateBlendMode will set the SDL error, if it fails */
         goto done;
     }
@@ -1694,6 +1736,25 @@ D3D11_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event)
     }
 }
 
+static SDL_bool
+D3D11_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode)
+{
+    SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode);
+    SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode);
+    SDL_BlendOperation colorOperation = SDL_GetBlendModeColorOperation(blendMode);
+    SDL_BlendFactor dstColorFactor = SDL_GetBlendModeDstColorFactor(blendMode);
+    SDL_BlendFactor dstAlphaFactor = SDL_GetBlendModeDstAlphaFactor(blendMode);
+    SDL_BlendOperation alphaOperation = SDL_GetBlendModeAlphaOperation(blendMode);
+
+    if (!GetBlendFunc(srcColorFactor) || !GetBlendFunc(srcAlphaFactor) ||
+        !GetBlendEquation(colorOperation) ||
+        !GetBlendFunc(dstColorFactor) || !GetBlendFunc(dstAlphaFactor) ||
+        !GetBlendEquation(alphaOperation)) {
+        return SDL_FALSE;
+    }
+    return SDL_TRUE;
+}
+
 static D3D11_FILTER
 GetScaleQuality(void)
 {
@@ -2443,19 +2504,21 @@ D3D11_RenderSetBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode)
 {
     D3D11_RenderData *rendererData = (D3D11_RenderData *)renderer->driverdata;
     ID3D11BlendState *blendState = NULL;
-    switch (blendMode) {
-    case SDL_BLENDMODE_BLEND:
-        blendState = rendererData->blendModeBlend;
-        break;
-    case SDL_BLENDMODE_ADD:
-        blendState = rendererData->blendModeAdd;
-        break;
-    case SDL_BLENDMODE_MOD:
-        blendState = rendererData->blendModeMod;
-        break;
-    case SDL_BLENDMODE_NONE:
-        blendState = NULL;
-        break;
+    if (blendMode != SDL_BLENDMODE_NONE) {
+        int i;
+        for (i = 0; i < rendererData->blendModesCount; ++i) {
+            if (blendMode == rendererData->blendModes[i].blendMode) {
+                blendState = rendererData->blendModes[i].blendState;
+                break;
+            }
+        }
+        if (!blendState) {
+            if (D3D11_CreateBlendState(renderer, blendMode)) {
+                /* Successfully created the blend state, try again */
+                D3D11_RenderSetBlendMode(renderer, blendMode);
+            }
+            return;
+        }
     }
     if (blendState != rendererData->currentBlendState) {
         ID3D11DeviceContext_OMSetBlendState(rendererData->d3dContext, blendState, 0, 0xFFFFFFFF);
@@ -2518,7 +2581,7 @@ D3D11_RenderDrawPoints(SDL_Renderer * renderer,
 
     vertices = SDL_stack_alloc(VertexPositionColor, count);
     for (i = 0; i < count; ++i) {
-        const VertexPositionColor v = { { points[i].x, points[i].y, 0.0f }, { 0.0f, 0.0f }, { r, g, b, a } };
+        const VertexPositionColor v = { { points[i].x + 0.5f, points[i].y + 0.5f, 0.0f }, { 0.0f, 0.0f }, { r, g, b, a } };
         vertices[i] = v;
     }
 
@@ -2557,7 +2620,7 @@ D3D11_RenderDrawLines(SDL_Renderer * renderer,
 
     vertices = SDL_stack_alloc(VertexPositionColor, count);
     for (i = 0; i < count; ++i) {
-        const VertexPositionColor v = { { points[i].x, points[i].y, 0.0f }, { 0.0f, 0.0f }, { r, g, b, a } };
+        const VertexPositionColor v = { { points[i].x + 0.5f, points[i].y + 0.5f, 0.0f }, { 0.0f, 0.0f }, { r, g, b, a } };
         vertices[i] = v;
     }
 
@@ -2576,6 +2639,12 @@ D3D11_RenderDrawLines(SDL_Renderer * renderer,
         NULL);
 
     D3D11_RenderFinishDrawOp(renderer, D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP, count);
+
+    if (points[0].x != points[count - 1].x || points[0].y != points[count - 1].y) {
+        ID3D11DeviceContext_IASetPrimitiveTopology(rendererData->d3dContext, D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
+        ID3D11DeviceContext_Draw(rendererData->d3dContext, 1, count - 1);
+    }
+
     SDL_stack_free(vertices);
     return 0;
 }
diff --git a/src/render/direct3d11/SDL_render_winrt.cpp b/src/render/direct3d11/SDL_render_winrt.cpp
index 99f2b4e..58a59ac 100644
--- a/src/render/direct3d11/SDL_render_winrt.cpp
+++ b/src/render/direct3d11/SDL_render_winrt.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/direct3d11/SDL_render_winrt.h b/src/render/direct3d11/SDL_render_winrt.h
index 734ebf4..2f10861 100644
--- a/src/render/direct3d11/SDL_render_winrt.h
+++ b/src/render/direct3d11/SDL_render_winrt.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/opengl/SDL_glfuncs.h b/src/render/opengl/SDL_glfuncs.h
index c8eba58..9f141dd 100644
--- a/src/render/opengl/SDL_glfuncs.h
+++ b/src/render/opengl/SDL_glfuncs.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -35,7 +35,8 @@ SDL_PROC(void, glBindTexture, (GLenum, GLuint))
 SDL_PROC_UNUSED(void, glBitmap,
                 (GLsizei, GLsizei, GLfloat, GLfloat, GLfloat, GLfloat,
                  const GLubyte *))
-SDL_PROC(void, glBlendFunc, (GLenum, GLenum))
+SDL_PROC(void, glBlendEquation, (GLenum))
+SDL_PROC_UNUSED(void, glBlendFunc, (GLenum, GLenum))
 SDL_PROC(void, glBlendFuncSeparate, (GLenum, GLenum, GLenum, GLenum))
 SDL_PROC_UNUSED(void, glCallList, (GLuint))
 SDL_PROC_UNUSED(void, glCallLists, (GLsizei, GLenum, const GLvoid *))
diff --git a/src/render/opengl/SDL_render_gl.c b/src/render/opengl/SDL_render_gl.c
index 1ca2cb5..305a744 100644
--- a/src/render/opengl/SDL_render_gl.c
+++ b/src/render/opengl/SDL_render_gl.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -55,6 +55,7 @@ static SDL_Renderer *GL_CreateRenderer(SDL_Window * window, Uint32 flags);
 static void GL_WindowEvent(SDL_Renderer * renderer,
                            const SDL_WindowEvent *event);
 static int GL_GetOutputSize(SDL_Renderer * renderer, int *w, int *h);
+static SDL_bool GL_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode);
 static int GL_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture);
 static int GL_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                             const SDL_Rect * rect, const void *pixels,
@@ -126,7 +127,7 @@ typedef struct
     struct {
         GL_Shader shader;
         Uint32 color;
-        int blendMode;
+        SDL_BlendMode blendMode;
     } current;
 
     SDL_bool GL_EXT_framebuffer_object_supported;
@@ -259,7 +260,7 @@ GL_CheckAllErrors (const char *prefix, SDL_Renderer *renderer, const char *file,
 
 #if 0
 #define GL_CheckError(prefix, renderer)
-#elif defined(_MSC_VER)
+#elif defined(_MSC_VER) || defined(__WATCOMC__)
 #define GL_CheckError(prefix, renderer) GL_CheckAllErrors(prefix, renderer, __FILE__, __LINE__, __FUNCTION__)
 #else
 #define GL_CheckError(prefix, renderer) GL_CheckAllErrors(prefix, renderer, __FILE__, __LINE__, __PRETTY_FUNCTION__)
@@ -275,7 +276,7 @@ GL_LoadFunctions(GL_RenderData * data)
     do { \
         data->func = SDL_GL_GetProcAddress(#func); \
         if ( ! data->func ) { \
-            return SDL_SetError("Couldn't load GL function %s: %s\n", #func, SDL_GetError()); \
+            return SDL_SetError("Couldn't load GL function %s: %s", #func, SDL_GetError()); \
         } \
     } while ( 0 );
 #endif /* __SDL_NOGETPROCADDR__ */
@@ -320,8 +321,8 @@ GL_ResetState(SDL_Renderer *renderer)
     }
 
     data->current.shader = SHADER_NONE;
-    data->current.color = 0;
-    data->current.blendMode = -1;
+    data->current.color = 0xffffffff;
+    data->current.blendMode = SDL_BLENDMODE_INVALID;
 
     data->glDisable(GL_DEPTH_TEST);
     data->glDisable(GL_CULL_FACE);
@@ -428,6 +429,7 @@ GL_CreateRenderer(SDL_Window * window, Uint32 flags)
 
     renderer->WindowEvent = GL_WindowEvent;
     renderer->GetOutputSize = GL_GetOutputSize;
+    renderer->SupportsBlendMode = GL_SupportsBlendMode;
     renderer->CreateTexture = GL_CreateTexture;
     renderer->UpdateTexture = GL_UpdateTexture;
     renderer->UpdateTextureYUV = GL_UpdateTextureYUV;
@@ -493,7 +495,7 @@ GL_CreateRenderer(SDL_Window * window, Uint32 flags)
         PFNGLDEBUGMESSAGECALLBACKARBPROC glDebugMessageCallbackARBFunc = (PFNGLDEBUGMESSAGECALLBACKARBPROC) SDL_GL_GetProcAddress("glDebugMessageCallbackARB");
 
         data->GL_ARB_debug_output_supported = SDL_TRUE;
-        data->glGetPointerv(GL_DEBUG_CALLBACK_FUNCTION_ARB, (GLvoid **)&data->next_error_callback);
+        data->glGetPointerv(GL_DEBUG_CALLBACK_FUNCTION_ARB, (GLvoid **)(char *)&data->next_error_callback);
         data->glGetPointerv(GL_DEBUG_CALLBACK_USER_PARAM_ARB, &data->next_error_userparam);
         glDebugMessageCallbackARBFunc(GL_HandleDebugMessage, renderer);
 
@@ -595,6 +597,72 @@ GL_GetOutputSize(SDL_Renderer * renderer, int *w, int *h)
     return 0;
 }
 
+static GLenum GetBlendFunc(SDL_BlendFactor factor)
+{
+    switch (factor) {
+    case SDL_BLENDFACTOR_ZERO:
+        return GL_ZERO;
+    case SDL_BLENDFACTOR_ONE:
+        return GL_ONE;
+    case SDL_BLENDFACTOR_SRC_COLOR:
+        return GL_SRC_COLOR;
+    case SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR:
+        return GL_ONE_MINUS_SRC_COLOR;
+    case SDL_BLENDFACTOR_SRC_ALPHA:
+        return GL_SRC_ALPHA;
+    case SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA:
+        return GL_ONE_MINUS_SRC_ALPHA;
+    case SDL_BLENDFACTOR_DST_COLOR:
+        return GL_DST_COLOR;
+    case SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR:
+        return GL_ONE_MINUS_DST_COLOR;
+    case SDL_BLENDFACTOR_DST_ALPHA:
+        return GL_DST_ALPHA;
+    case SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA:
+        return GL_ONE_MINUS_DST_ALPHA;
+    default:
+        return GL_INVALID_ENUM;
+    }
+}
+
+static GLenum GetBlendEquation(SDL_BlendOperation operation)
+{
+    switch (operation) {
+    case SDL_BLENDOPERATION_ADD:
+        return GL_FUNC_ADD;
+    case SDL_BLENDOPERATION_SUBTRACT:
+        return GL_FUNC_SUBTRACT;
+    case SDL_BLENDOPERATION_REV_SUBTRACT:
+        return GL_FUNC_REVERSE_SUBTRACT;
+    default:
+        return GL_INVALID_ENUM;
+    }
+}
+
+static SDL_bool
+GL_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode)
+{
+    SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode);
+    SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode);
+    SDL_BlendOperation colorOperation = SDL_GetBlendModeColorOperation(blendMode);
+    SDL_BlendFactor dstColorFactor = SDL_GetBlendModeDstColorFactor(blendMode);
+    SDL_BlendFactor dstAlphaFactor = SDL_GetBlendModeDstAlphaFactor(blendMode);
+    SDL_BlendOperation alphaOperation = SDL_GetBlendModeAlphaOperation(blendMode);
+
+    if (GetBlendFunc(srcColorFactor) == GL_INVALID_ENUM ||
+        GetBlendFunc(srcAlphaFactor) == GL_INVALID_ENUM ||
+        GetBlendEquation(colorOperation) == GL_INVALID_ENUM ||
+        GetBlendFunc(dstColorFactor) == GL_INVALID_ENUM ||
+        GetBlendFunc(dstAlphaFactor) == GL_INVALID_ENUM ||
+        GetBlendEquation(alphaOperation) == GL_INVALID_ENUM) {
+        return SDL_FALSE;
+    }
+    if (colorOperation != alphaOperation) {
+        return SDL_FALSE;
+    }
+    return SDL_TRUE;
+}
+
 SDL_FORCE_INLINE int
 power_of_2(int input)
 {
@@ -1041,6 +1109,8 @@ GL_UpdateViewport(SDL_Renderer * renderer)
                            0.0, 1.0);
         }
     }
+    data->glMatrixMode(GL_MODELVIEW);
+
     return GL_CheckError("", renderer);
 }
 
@@ -1090,25 +1160,18 @@ GL_SetColor(GL_RenderData * data, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
 }
 
 static void
-GL_SetBlendMode(GL_RenderData * data, int blendMode)
+GL_SetBlendMode(GL_RenderData * data, SDL_BlendMode blendMode)
 {
     if (blendMode != data->current.blendMode) {
-        switch (blendMode) {
-        case SDL_BLENDMODE_NONE:
+        if (blendMode == SDL_BLENDMODE_NONE) {
             data->glDisable(GL_BLEND);
-            break;
-        case SDL_BLENDMODE_BLEND:
-            data->glEnable(GL_BLEND);
-            data->glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
-            break;
-        case SDL_BLENDMODE_ADD:
-            data->glEnable(GL_BLEND);
-            data->glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE);
-            break;
-        case SDL_BLENDMODE_MOD:
+        } else {
             data->glEnable(GL_BLEND);
-            data->glBlendFuncSeparate(GL_ZERO, GL_SRC_COLOR, GL_ZERO, GL_ONE);
-            break;
+            data->glBlendFuncSeparate(GetBlendFunc(SDL_GetBlendModeSrcColorFactor(blendMode)),
+                                      GetBlendFunc(SDL_GetBlendModeDstColorFactor(blendMode)),
+                                      GetBlendFunc(SDL_GetBlendModeSrcAlphaFactor(blendMode)),
+                                      GetBlendFunc(SDL_GetBlendModeDstAlphaFactor(blendMode)));
+            data->glBlendEquation(GetBlendEquation(SDL_GetBlendModeColorOperation(blendMode)));
         }
         data->current.blendMode = blendMode;
     }
@@ -1430,18 +1493,21 @@ GL_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
 
     GL_ActivateRenderer(renderer);
 
+    if (!convert_format(data, temp_format, &internalFormat, &format, &type)) {
+        return SDL_SetError("Texture format %s not supported by OpenGL",
+                            SDL_GetPixelFormatName(temp_format));
+    }
+
+    if (!rect->w || !rect->h) {
+        return 0;  /* nothing to do. */
+    }
+
     temp_pitch = rect->w * SDL_BYTESPERPIXEL(temp_format);
     temp_pixels = SDL_malloc(rect->h * temp_pitch);
     if (!temp_pixels) {
         return SDL_OutOfMemory();
     }
 
-    if (!convert_format(data, temp_format, &internalFormat, &format, &type)) {
-        SDL_free(temp_pixels);
-        return SDL_SetError("Texture format %s not supported by OpenGL",
-                            SDL_GetPixelFormatName(temp_format));
-    }
-
     SDL_GetRendererOutputSize(renderer, &w, &h);
 
     data->glPixelStorei(GL_PACK_ALIGNMENT, 1);
@@ -1518,6 +1584,11 @@ GL_DestroyRenderer(SDL_Renderer * renderer)
     GL_RenderData *data = (GL_RenderData *) renderer->driverdata;
 
     if (data) {
+        if (data->context != NULL) {
+            /* make sure we delete the right resources! */
+            GL_ActivateRenderer(renderer);
+        }
+
         GL_ClearErrors(renderer);
         if (data->GL_ARB_debug_output_supported) {
             PFNGLDEBUGMESSAGECALLBACKARBPROC glDebugMessageCallbackARBFunc = (PFNGLDEBUGMESSAGECALLBACKARBPROC) SDL_GL_GetProcAddress("glDebugMessageCallbackARB");
diff --git a/src/render/opengl/SDL_shaders_gl.c b/src/render/opengl/SDL_shaders_gl.c
index bcf7b43..6d0bf84 100644
--- a/src/render/opengl/SDL_shaders_gl.c
+++ b/src/render/opengl/SDL_shaders_gl.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -369,7 +369,7 @@ DestroyShaderProgram(GL_ShaderContext *ctx, GL_ShaderData *data)
 }
 
 GL_ShaderContext *
-GL_CreateShaderContext()
+GL_CreateShaderContext(void)
 {
     GL_ShaderContext *ctx;
     SDL_bool shaders_supported;
diff --git a/src/render/opengl/SDL_shaders_gl.h b/src/render/opengl/SDL_shaders_gl.h
index 261627c..9489b61 100644
--- a/src/render/opengl/SDL_shaders_gl.h
+++ b/src/render/opengl/SDL_shaders_gl.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -34,7 +34,7 @@ typedef enum {
 
 typedef struct GL_ShaderContext GL_ShaderContext;
 
-extern GL_ShaderContext * GL_CreateShaderContext();
+extern GL_ShaderContext * GL_CreateShaderContext(void);
 extern void GL_SelectShader(GL_ShaderContext *ctx, GL_Shader shader);
 extern void GL_DestroyShaderContext(GL_ShaderContext *ctx);
 
diff --git a/src/render/opengles/SDL_glesfuncs.h b/src/render/opengles/SDL_glesfuncs.h
index a15d76d..c5ac337 100644
--- a/src/render/opengles/SDL_glesfuncs.h
+++ b/src/render/opengles/SDL_glesfuncs.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,6 +21,8 @@
 
 SDL_PROC(void, glBindTexture, (GLenum, GLuint))
 SDL_PROC(void, glBlendFunc, (GLenum, GLenum))
+SDL_PROC_OES(void, glBlendEquationOES, (GLenum))
+SDL_PROC_OES(void, glBlendEquationSeparateOES, (GLenum, GLenum))
 SDL_PROC_OES(void, glBlendFuncSeparateOES, (GLenum, GLenum, GLenum, GLenum))
 SDL_PROC(void, glClear, (GLbitfield))
 SDL_PROC(void, glClearColor, (GLclampf, GLclampf, GLclampf, GLclampf))
diff --git a/src/render/opengles/SDL_render_gles.c b/src/render/opengles/SDL_render_gles.c
index 71f5b3a..f531d37 100644
--- a/src/render/opengles/SDL_render_gles.c
+++ b/src/render/opengles/SDL_render_gles.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -56,6 +56,7 @@ static SDL_Renderer *GLES_CreateRenderer(SDL_Window * window, Uint32 flags);
 static void GLES_WindowEvent(SDL_Renderer * renderer,
                              const SDL_WindowEvent *event);
 static int GLES_GetOutputSize(SDL_Renderer * renderer, int *w, int *h);
+static SDL_bool GLES_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode);
 static int GLES_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture);
 static int GLES_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                               const SDL_Rect * rect, const void *pixels,
@@ -116,7 +117,7 @@ typedef struct
     SDL_GLContext context;
     struct {
         Uint32 color;
-        int blendMode;
+        SDL_BlendMode blendMode;
         SDL_bool tex_coords;
     } current;
 
@@ -130,6 +131,8 @@ typedef struct
     GLuint window_framebuffer;
 
     SDL_bool GL_OES_blend_func_separate_supported;
+    SDL_bool GL_OES_blend_equation_separate_supported;
+    SDL_bool GL_OES_blend_subtract_supported;
 } GLES_RenderData;
 
 typedef struct
@@ -197,7 +200,7 @@ static int GLES_LoadFunctions(GLES_RenderData * data)
     do { \
         data->func = SDL_GL_GetProcAddress(#func); \
         if ( ! data->func ) { \
-            return SDL_SetError("Couldn't load GLES function %s: %s\n", #func, SDL_GetError()); \
+            return SDL_SetError("Couldn't load GLES function %s: %s", #func, SDL_GetError()); \
         } \
     } while ( 0 );
 #define SDL_PROC_OES(ret,func,params) \
@@ -214,7 +217,7 @@ static int GLES_LoadFunctions(GLES_RenderData * data)
 
 static SDL_GLContext SDL_CurrentContext = NULL;
 
-GLES_FBOList *
+static GLES_FBOList *
 GLES_GetFBO(GLES_RenderData *data, Uint32 w, Uint32 h)
 {
    GLES_FBOList *result = data->framebuffers;
@@ -261,8 +264,8 @@ GLES_ResetState(SDL_Renderer *renderer)
         GLES_ActivateRenderer(renderer);
     }
 
-    data->current.color = 0;
-    data->current.blendMode = -1;
+    data->current.color = 0xffffffff;
+    data->current.blendMode = SDL_BLENDMODE_INVALID;
     data->current.tex_coords = SDL_FALSE;
 
     data->glDisable(GL_DEPTH_TEST);
@@ -319,6 +322,7 @@ GLES_CreateRenderer(SDL_Window * window, Uint32 flags)
 
     renderer->WindowEvent = GLES_WindowEvent;
     renderer->GetOutputSize = GLES_GetOutputSize;
+    renderer->SupportsBlendMode = GLES_SupportsBlendMode;
     renderer->CreateTexture = GLES_CreateTexture;
     renderer->UpdateTexture = GLES_UpdateTexture;
     renderer->LockTexture = GLES_LockTexture;
@@ -388,6 +392,12 @@ GLES_CreateRenderer(SDL_Window * window, Uint32 flags)
     if (SDL_GL_ExtensionSupported("GL_OES_blend_func_separate")) {
         data->GL_OES_blend_func_separate_supported = SDL_TRUE;
     }
+    if (SDL_GL_ExtensionSupported("GL_OES_blend_equation_separate")) {
+        data->GL_OES_blend_equation_separate_supported = SDL_TRUE;
+    }
+    if (SDL_GL_ExtensionSupported("GL_OES_blend_subtract")) {
+        data->GL_OES_blend_subtract_supported = SDL_TRUE;
+    }
 
     /* Set up parameters for rendering */
     GLES_ResetState(renderer);
@@ -430,6 +440,79 @@ GLES_GetOutputSize(SDL_Renderer * renderer, int *w, int *h)
     return 0;
 }
 
+static GLenum GetBlendFunc(SDL_BlendFactor factor)
+{
+    switch (factor) {
+    case SDL_BLENDFACTOR_ZERO:
+        return GL_ZERO;
+    case SDL_BLENDFACTOR_ONE:
+        return GL_ONE;
+    case SDL_BLENDFACTOR_SRC_COLOR:
+        return GL_SRC_COLOR;
+    case SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR:
+        return GL_ONE_MINUS_SRC_COLOR;
+    case SDL_BLENDFACTOR_SRC_ALPHA:
+        return GL_SRC_ALPHA;
+    case SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA:
+        return GL_ONE_MINUS_SRC_ALPHA;
+    case SDL_BLENDFACTOR_DST_COLOR:
+        return GL_DST_COLOR;
+    case SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR:
+        return GL_ONE_MINUS_DST_COLOR;
+    case SDL_BLENDFACTOR_DST_ALPHA:
+        return GL_DST_ALPHA;
+    case SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA:
+        return GL_ONE_MINUS_DST_ALPHA;
+    default:
+        return GL_INVALID_ENUM;
+    }
+}
+
+static GLenum GetBlendEquation(SDL_BlendOperation operation)
+{
+    switch (operation) {
+    case SDL_BLENDOPERATION_ADD:
+        return GL_FUNC_ADD_OES;
+    case SDL_BLENDOPERATION_SUBTRACT:
+        return GL_FUNC_SUBTRACT_OES;
+    case SDL_BLENDOPERATION_REV_SUBTRACT:
+        return GL_FUNC_REVERSE_SUBTRACT_OES;
+    default:
+        return GL_INVALID_ENUM;
+    }
+}
+
+static SDL_bool
+GLES_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode)
+{
+    GLES_RenderData *data = (GLES_RenderData *) renderer->driverdata;
+    SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode);
+    SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode);
+    SDL_BlendOperation colorOperation = SDL_GetBlendModeColorOperation(blendMode);
+    SDL_BlendFactor dstColorFactor = SDL_GetBlendModeDstColorFactor(blendMode);
+    SDL_BlendFactor dstAlphaFactor = SDL_GetBlendModeDstAlphaFactor(blendMode);
+    SDL_BlendOperation alphaOperation = SDL_GetBlendModeAlphaOperation(blendMode);
+
+    if (GetBlendFunc(srcColorFactor) == GL_INVALID_ENUM ||
+        GetBlendFunc(srcAlphaFactor) == GL_INVALID_ENUM ||
+        GetBlendEquation(colorOperation) == GL_INVALID_ENUM ||
+        GetBlendFunc(dstColorFactor) == GL_INVALID_ENUM ||
+        GetBlendFunc(dstAlphaFactor) == GL_INVALID_ENUM ||
+        GetBlendEquation(alphaOperation) == GL_INVALID_ENUM) {
+        return SDL_FALSE;
+    }
+    if ((srcColorFactor != srcAlphaFactor || dstColorFactor != dstAlphaFactor) && !data->GL_OES_blend_func_separate_supported) {
+        return SDL_FALSE;
+    }
+    if (colorOperation != alphaOperation && !data->GL_OES_blend_equation_separate_supported) {
+        return SDL_FALSE;
+    }
+    if (colorOperation != SDL_BLENDOPERATION_ADD && !data->GL_OES_blend_subtract_supported) {
+        return SDL_FALSE;
+    }
+    return SDL_TRUE;
+}
+
 static SDL_INLINE int
 power_of_2(int input)
 {
@@ -633,8 +716,6 @@ GLES_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture)
     GLES_TextureData *texturedata = NULL;
     GLenum status;
 
-    GLES_ActivateRenderer(renderer);
-
     if (!data->GL_OES_framebuffer_object_supported) {
         return SDL_SetError("Can't enable render target support in this renderer");
     }
@@ -694,6 +775,8 @@ GLES_UpdateViewport(SDL_Renderer * renderer)
                            0.0, 1.0);
         }
     }
+    data->glMatrixMode(GL_MODELVIEW);
+
     return 0;
 }
 
@@ -739,37 +822,28 @@ GLES_SetColor(GLES_RenderData * data, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
 }
 
 static void
-GLES_SetBlendMode(GLES_RenderData * data, int blendMode)
+GLES_SetBlendMode(GLES_RenderData * data, SDL_BlendMode blendMode)
 {
     if (blendMode != data->current.blendMode) {
-        switch (blendMode) {
-        case SDL_BLENDMODE_NONE:
+        if (blendMode == SDL_BLENDMODE_NONE) {
             data->glDisable(GL_BLEND);
-            break;
-        case SDL_BLENDMODE_BLEND:
-            data->glEnable(GL_BLEND);
-            if (data->GL_OES_blend_func_separate_supported) {
-                data->glBlendFuncSeparateOES(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
-            } else {
-                data->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-            }
-            break;
-        case SDL_BLENDMODE_ADD:
+        } else {
             data->glEnable(GL_BLEND);
             if (data->GL_OES_blend_func_separate_supported) {
-                data->glBlendFuncSeparateOES(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE);
+                data->glBlendFuncSeparateOES(GetBlendFunc(SDL_GetBlendModeSrcColorFactor(blendMode)),
+                                             GetBlendFunc(SDL_GetBlendModeDstColorFactor(blendMode)),
+                                             GetBlendFunc(SDL_GetBlendModeSrcAlphaFactor(blendMode)),
+                                             GetBlendFunc(SDL_GetBlendModeDstAlphaFactor(blendMode)));
             } else {
-                data->glBlendFunc(GL_SRC_ALPHA, GL_ONE);
+                data->glBlendFunc(GetBlendFunc(SDL_GetBlendModeSrcColorFactor(blendMode)),
+                                  GetBlendFunc(SDL_GetBlendModeDstColorFactor(blendMode)));
             }
-            break;
-        case SDL_BLENDMODE_MOD:
-            data->glEnable(GL_BLEND);
-            if (data->GL_OES_blend_func_separate_supported) {
-                data->glBlendFuncSeparateOES(GL_ZERO, GL_SRC_COLOR, GL_ZERO, GL_ONE);
-            } else {
-                data->glBlendFunc(GL_ZERO, GL_SRC_COLOR);
+            if (data->GL_OES_blend_equation_separate_supported) {
+                data->glBlendEquationSeparateOES(GetBlendEquation(SDL_GetBlendModeColorOperation(blendMode)),
+                                                 GetBlendEquation(SDL_GetBlendModeAlphaOperation(blendMode)));
+            } else if (data->GL_OES_blend_subtract_supported) {
+                data->glBlendEquationOES(GetBlendEquation(SDL_GetBlendModeColorOperation(blendMode)));
             }
-            break;
         }
         data->current.blendMode = blendMode;
     }
diff --git a/src/render/opengles2/SDL_gles2funcs.h b/src/render/opengles2/SDL_gles2funcs.h
index 0ecfa7f..84d3e48 100644
--- a/src/render/opengles2/SDL_gles2funcs.h
+++ b/src/render/opengles2/SDL_gles2funcs.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,6 +23,7 @@ SDL_PROC(void, glActiveTexture, (GLenum))
 SDL_PROC(void, glAttachShader, (GLuint, GLuint))
 SDL_PROC(void, glBindAttribLocation, (GLuint, GLuint, const char *))
 SDL_PROC(void, glBindTexture, (GLenum, GLuint))
+SDL_PROC(void, glBlendEquationSeparate, (GLenum, GLenum))
 SDL_PROC(void, glBlendFuncSeparate, (GLenum, GLenum, GLenum, GLenum))
 SDL_PROC(void, glClear, (GLbitfield))
 SDL_PROC(void, glClearColor, (GLclampf, GLclampf, GLclampf, GLclampf))
@@ -53,7 +54,11 @@ SDL_PROC(void, glPixelStorei, (GLenum, GLint))
 SDL_PROC(void, glReadPixels, (GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, GLvoid*))
 SDL_PROC(void, glScissor, (GLint, GLint, GLsizei, GLsizei))
 SDL_PROC(void, glShaderBinary, (GLsizei, const GLuint *, GLenum, const void *, GLsizei))
+#if __NACL__ || __ANDROID__
+SDL_PROC(void, glShaderSource, (GLuint, GLsizei, const GLchar **, const GLint *))
+#else
 SDL_PROC(void, glShaderSource, (GLuint, GLsizei, const GLchar* const*, const GLint *))
+#endif
 SDL_PROC(void, glTexImage2D, (GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *))
 SDL_PROC(void, glTexParameteri, (GLenum, GLenum, GLint))
 SDL_PROC(void, glTexSubImage2D, (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *))
diff --git a/src/render/opengles2/SDL_render_gles2.c b/src/render/opengles2/SDL_render_gles2.c
index c846a7b..0e87f2a 100644
--- a/src/render/opengles2/SDL_render_gles2.c
+++ b/src/render/opengles2/SDL_render_gles2.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -122,7 +122,6 @@ typedef struct GLES2_ShaderCache
 typedef struct GLES2_ProgramCacheEntry
 {
     GLuint id;
-    SDL_BlendMode blend_mode;
     GLES2_ShaderCacheEntry *vertex_shader;
     GLES2_ShaderCacheEntry *fragment_shader;
     GLuint uniform_locations[16];
@@ -177,7 +176,7 @@ typedef struct GLES2_DriverContext
     SDL_bool debug_enabled;
 
     struct {
-        int blendMode;
+        SDL_BlendMode blendMode;
         SDL_bool tex_coords;
     } current;
 
@@ -259,7 +258,7 @@ GL_CheckAllErrors (const char *prefix, SDL_Renderer *renderer, const char *file,
 
 #if 0
 #define GL_CheckError(prefix, renderer)
-#elif defined(_MSC_VER)
+#elif defined(_MSC_VER) || defined(__WATCOMC__)
 #define GL_CheckError(prefix, renderer) GL_CheckAllErrors(prefix, renderer, __FILE__, __LINE__, __FUNCTION__)
 #else
 #define GL_CheckError(prefix, renderer) GL_CheckAllErrors(prefix, renderer, __FILE__, __LINE__, __PRETTY_FUNCTION__)
@@ -297,7 +296,7 @@ static int GLES2_LoadFunctions(GLES2_DriverContext * data)
     do { \
         data->func = SDL_GL_GetProcAddress(#func); \
         if ( ! data->func ) { \
-            return SDL_SetError("Couldn't load GLES2 function %s: %s\n", #func, SDL_GetError()); \
+            return SDL_SetError("Couldn't load GLES2 function %s: %s", #func, SDL_GetError()); \
         } \
     } while ( 0 );
 #endif /* __SDL_NOGETPROCADDR__ */
@@ -307,7 +306,7 @@ static int GLES2_LoadFunctions(GLES2_DriverContext * data)
     return 0;
 }
 
-GLES2_FBOList *
+static GLES2_FBOList *
 GLES2_GetFBO(GLES2_DriverContext *data, Uint32 w, Uint32 h)
 {
    GLES2_FBOList *result = data->framebuffers;
@@ -372,6 +371,69 @@ GLES2_GetOutputSize(SDL_Renderer * renderer, int *w, int *h)
     return 0;
 }
 
+static GLenum GetBlendFunc(SDL_BlendFactor factor)
+{
+    switch (factor) {
+    case SDL_BLENDFACTOR_ZERO:
+        return GL_ZERO;
+    case SDL_BLENDFACTOR_ONE:
+        return GL_ONE;
+    case SDL_BLENDFACTOR_SRC_COLOR:
+        return GL_SRC_COLOR;
+    case SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR:
+        return GL_ONE_MINUS_SRC_COLOR;
+    case SDL_BLENDFACTOR_SRC_ALPHA:
+        return GL_SRC_ALPHA;
+    case SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA:
+        return GL_ONE_MINUS_SRC_ALPHA;
+    case SDL_BLENDFACTOR_DST_COLOR:
+        return GL_DST_COLOR;
+    case SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR:
+        return GL_ONE_MINUS_DST_COLOR;
+    case SDL_BLENDFACTOR_DST_ALPHA:
+        return GL_DST_ALPHA;
+    case SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA:
+        return GL_ONE_MINUS_DST_ALPHA;
+    default:
+        return GL_INVALID_ENUM;
+    }
+}
+
+static GLenum GetBlendEquation(SDL_BlendOperation operation)
+{
+    switch (operation) {
+    case SDL_BLENDOPERATION_ADD:
+        return GL_FUNC_ADD;
+    case SDL_BLENDOPERATION_SUBTRACT:
+        return GL_FUNC_SUBTRACT;
+    case SDL_BLENDOPERATION_REV_SUBTRACT:
+        return GL_FUNC_REVERSE_SUBTRACT;
+    default:
+        return GL_INVALID_ENUM;
+    }
+}
+
+static SDL_bool
+GLES2_SupportsBlendMode(SDL_Renderer * renderer, SDL_BlendMode blendMode)
+{
+    SDL_BlendFactor srcColorFactor = SDL_GetBlendModeSrcColorFactor(blendMode);
+    SDL_BlendFactor srcAlphaFactor = SDL_GetBlendModeSrcAlphaFactor(blendMode);
+    SDL_BlendOperation colorOperation = SDL_GetBlendModeColorOperation(blendMode);
+    SDL_BlendFactor dstColorFactor = SDL_GetBlendModeDstColorFactor(blendMode);
+    SDL_BlendFactor dstAlphaFactor = SDL_GetBlendModeDstAlphaFactor(blendMode);
+    SDL_BlendOperation alphaOperation = SDL_GetBlendModeAlphaOperation(blendMode);
+
+    if (GetBlendFunc(srcColorFactor) == GL_INVALID_ENUM ||
+        GetBlendFunc(srcAlphaFactor) == GL_INVALID_ENUM ||
+        GetBlendEquation(colorOperation) == GL_INVALID_ENUM ||
+        GetBlendFunc(dstColorFactor) == GL_INVALID_ENUM ||
+        GetBlendFunc(dstAlphaFactor) == GL_INVALID_ENUM ||
+        GetBlendEquation(alphaOperation) == GL_INVALID_ENUM) {
+        return SDL_FALSE;
+    }
+    return SDL_TRUE;
+}
+
 static int
 GLES2_UpdateViewport(SDL_Renderer * renderer)
 {
@@ -882,19 +944,16 @@ GLES2_DestroyTexture(SDL_Renderer *renderer, SDL_Texture *texture)
  * Shader management functions                                                                   *
  *************************************************************************************************/
 
-static GLES2_ShaderCacheEntry *GLES2_CacheShader(SDL_Renderer *renderer, GLES2_ShaderType type,
-                                                 SDL_BlendMode blendMode);
+static GLES2_ShaderCacheEntry *GLES2_CacheShader(SDL_Renderer *renderer, GLES2_ShaderType type);
 static void GLES2_EvictShader(SDL_Renderer *renderer, GLES2_ShaderCacheEntry *entry);
 static GLES2_ProgramCacheEntry *GLES2_CacheProgram(SDL_Renderer *renderer,
                                                    GLES2_ShaderCacheEntry *vertex,
-                                                   GLES2_ShaderCacheEntry *fragment,
-                                                   SDL_BlendMode blendMode);
-static int GLES2_SelectProgram(SDL_Renderer *renderer, GLES2_ImageSource source,
-                               SDL_BlendMode blendMode);
+                                                   GLES2_ShaderCacheEntry *fragment);
+static int GLES2_SelectProgram(SDL_Renderer *renderer, GLES2_ImageSource source);
 
 static GLES2_ProgramCacheEntry *
 GLES2_CacheProgram(SDL_Renderer *renderer, GLES2_ShaderCacheEntry *vertex,
-                   GLES2_ShaderCacheEntry *fragment, SDL_BlendMode blendMode)
+                   GLES2_ShaderCacheEntry *fragment)
 {
     GLES2_DriverContext *data = (GLES2_DriverContext *)renderer->driverdata;
     GLES2_ProgramCacheEntry *entry;
@@ -933,7 +992,6 @@ GLES2_CacheProgram(SDL_Renderer *renderer, GLES2_ShaderCacheEntry *vertex,
     }
     entry->vertex_shader = vertex;
     entry->fragment_shader = fragment;
-    entry->blend_mode = blendMode;
 
     /* Create the program and link it */
     entry->id = data->glCreateProgram();
@@ -1011,7 +1069,7 @@ GLES2_CacheProgram(SDL_Renderer *renderer, GLES2_ShaderCacheEntry *vertex,
 }
 
 static GLES2_ShaderCacheEntry *
-GLES2_CacheShader(SDL_Renderer *renderer, GLES2_ShaderType type, SDL_BlendMode blendMode)
+GLES2_CacheShader(SDL_Renderer *renderer, GLES2_ShaderType type)
 {
     GLES2_DriverContext *data = (GLES2_DriverContext *)renderer->driverdata;
     const GLES2_Shader *shader;
@@ -1021,7 +1079,7 @@ GLES2_CacheShader(SDL_Renderer *renderer, GLES2_ShaderType type, SDL_BlendMode b
     int i, j;
 
     /* Find the corresponding shader */
-    shader = GLES2_GetShader(type, blendMode);
+    shader = GLES2_GetShader(type);
     if (!shader) {
         SDL_SetError("No shader matching the requested characteristics was found");
         return NULL;
@@ -1068,7 +1126,7 @@ GLES2_CacheShader(SDL_Renderer *renderer, GLES2_ShaderType type, SDL_BlendMode b
     /* Compile or load the selected shader instance */
     entry->id = data->glCreateShader(instance->type);
     if (instance->format == (GLenum)-1) {
-        data->glShaderSource(entry->id, 1, (const char **)&instance->data, NULL);
+        data->glShaderSource(entry->id, 1, (const char **)(char *)&instance->data, NULL);
         data->glCompileShader(entry->id);
         data->glGetShaderiv(entry->id, GL_COMPILE_STATUS, &compileSuccessful);
     } else {
@@ -1130,7 +1188,7 @@ GLES2_EvictShader(SDL_Renderer *renderer, GLES2_ShaderCacheEntry *entry)
 }
 
 static int
-GLES2_SelectProgram(SDL_Renderer *renderer, GLES2_ImageSource source, SDL_BlendMode blendMode)
+GLES2_SelectProgram(SDL_Renderer *renderer, GLES2_ImageSource source)
 {
     GLES2_DriverContext *data = (GLES2_DriverContext *)renderer->driverdata;
     GLES2_ShaderCacheEntry *vertex = NULL;
@@ -1170,11 +1228,11 @@ GLES2_SelectProgram(SDL_Renderer *renderer, GLES2_ImageSource source, SDL_BlendM
     }
 
     /* Load the requested shaders */
-    vertex = GLES2_CacheShader(renderer, vtype, blendMode);
+    vertex = GLES2_CacheShader(renderer, vtype);
     if (!vertex) {
         goto fault;
     }
-    fragment = GLES2_CacheShader(renderer, ftype, blendMode);
+    fragment = GLES2_CacheShader(renderer, ftype);
     if (!fragment) {
         goto fault;
     }
@@ -1187,7 +1245,7 @@ GLES2_SelectProgram(SDL_Renderer *renderer, GLES2_ImageSource source, SDL_BlendM
     }
 
     /* Generate a matching program */
-    program = GLES2_CacheProgram(renderer, vertex, fragment, blendMode);
+    program = GLES2_CacheProgram(renderer, vertex, fragment);
     if (!program) {
         goto fault;
     }
@@ -1341,26 +1399,19 @@ GLES2_RenderClear(SDL_Renderer * renderer)
 }
 
 static void
-GLES2_SetBlendMode(GLES2_DriverContext *data, int blendMode)
+GLES2_SetBlendMode(GLES2_DriverContext *data, SDL_BlendMode blendMode)
 {
     if (blendMode != data->current.blendMode) {
-        switch (blendMode) {
-        default:
-        case SDL_BLENDMODE_NONE:
+        if (blendMode == SDL_BLENDMODE_NONE) {
             data->glDisable(GL_BLEND);
-            break;
-        case SDL_BLENDMODE_BLEND:
-            data->glEnable(GL_BLEND);
-            data->glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
-            break;
-        case SDL_BLENDMODE_ADD:
-            data->glEnable(GL_BLEND);
-            data->glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE);
-            break;
-        case SDL_BLENDMODE_MOD:
+        } else {
             data->glEnable(GL_BLEND);
-            data->glBlendFuncSeparate(GL_ZERO, GL_SRC_COLOR, GL_ZERO, GL_ONE);
-            break;
+            data->glBlendFuncSeparate(GetBlendFunc(SDL_GetBlendModeSrcColorFactor(blendMode)),
+                                      GetBlendFunc(SDL_GetBlendModeDstColorFactor(blendMode)),
+                                      GetBlendFunc(SDL_GetBlendModeSrcAlphaFactor(blendMode)),
+                                      GetBlendFunc(SDL_GetBlendModeDstAlphaFactor(blendMode)));
+            data->glBlendEquationSeparate(GetBlendEquation(SDL_GetBlendModeColorOperation(blendMode)),
+                                          GetBlendEquation(SDL_GetBlendModeAlphaOperation(blendMode)));
         }
         data->current.blendMode = blendMode;
     }
@@ -1383,18 +1434,17 @@ static int
 GLES2_SetDrawingState(SDL_Renderer * renderer)
 {
     GLES2_DriverContext *data = (GLES2_DriverContext *)renderer->driverdata;
-    const int blendMode = renderer->blendMode;
     GLES2_ProgramCacheEntry *program;
     Uint8 r, g, b, a;
 
     GLES2_ActivateRenderer(renderer);
 
-    GLES2_SetBlendMode(data, blendMode);
+    GLES2_SetBlendMode(data, renderer->blendMode);
 
     GLES2_SetTexCoords(data, SDL_FALSE);
 
     /* Activate an appropriate shader and set the projection matrix */
-    if (GLES2_SelectProgram(renderer, GLES2_IMAGESOURCE_SOLID, blendMode) < 0) {
+    if (GLES2_SelectProgram(renderer, GLES2_IMAGESOURCE_SOLID) < 0) {
         return -1;
     }
 
@@ -1555,12 +1605,10 @@ GLES2_SetupCopy(SDL_Renderer *renderer, SDL_Texture *texture)
     GLES2_DriverContext *data = (GLES2_DriverContext *)renderer->driverdata;
     GLES2_TextureData *tdata = (GLES2_TextureData *)texture->driverdata;
     GLES2_ImageSource sourceType = GLES2_IMAGESOURCE_TEXTURE_ABGR;
-    SDL_BlendMode blendMode;
     GLES2_ProgramCacheEntry *program;
     Uint8 r, g, b, a;
 
     /* Activate an appropriate shader and set the projection matrix */
-    blendMode = texture->blendMode;
     if (renderer->target) {
         /* Check if we need to do color mapping between the source and render target textures */
         if (renderer->target->format != texture->format) {
@@ -1658,7 +1706,7 @@ GLES2_SetupCopy(SDL_Renderer *renderer, SDL_Texture *texture)
         }
     }
 
-    if (GLES2_SelectProgram(renderer, sourceType, blendMode) < 0) {
+    if (GLES2_SelectProgram(renderer, sourceType) < 0) {
         return -1;
     }
 
@@ -1705,7 +1753,7 @@ GLES2_SetupCopy(SDL_Renderer *renderer, SDL_Texture *texture)
     }
 
     /* Configure texture blending */
-    GLES2_SetBlendMode(data, blendMode);
+    GLES2_SetBlendMode(data, texture->blendMode);
 
     GLES2_SetTexCoords(data, SDL_TRUE);
     return 0;
@@ -1923,7 +1971,9 @@ static int GLES2_UnbindTexture (SDL_Renderer * renderer, SDL_Texture *texture)
  * Renderer instantiation                                                                        *
  *************************************************************************************************/
 
+#ifdef ZUNE_HD
 #define GL_NVIDIA_PLATFORM_BINARY_NV 0x890B
+#endif
 
 static void
 GLES2_ResetState(SDL_Renderer *renderer)
@@ -1936,7 +1986,7 @@ GLES2_ResetState(SDL_Renderer *renderer)
         GLES2_ActivateRenderer(renderer);
     }
 
-    data->current.blendMode = -1;
+    data->current.blendMode = SDL_BLENDMODE_INVALID;
     data->current.tex_coords = SDL_FALSE;
 
     data->glActiveTexture(GL_TEXTURE0);
@@ -1963,7 +2013,7 @@ GLES2_CreateRenderer(SDL_Window *window, Uint32 flags)
 #ifndef ZUNE_HD
     GLboolean hasCompiler;
 #endif
-    Uint32 window_flags;
+    Uint32 window_flags = 0; /* -Wconditional-uninitialized */
     GLint window_framebuffer;
     GLint value;
     int profile_mask = 0, major = 0, minor = 0;
@@ -2089,28 +2139,29 @@ GLES2_CreateRenderer(SDL_Window *window, Uint32 flags)
     data->window_framebuffer = (GLuint)window_framebuffer;
 
     /* Populate the function pointers for the module */
-    renderer->WindowEvent         = &GLES2_WindowEvent;
-    renderer->GetOutputSize       = &GLES2_GetOutputSize;
-    renderer->CreateTexture       = &GLES2_CreateTexture;
-    renderer->UpdateTexture       = &GLES2_UpdateTexture;
-    renderer->UpdateTextureYUV    = &GLES2_UpdateTextureYUV;
-    renderer->LockTexture         = &GLES2_LockTexture;
-    renderer->UnlockTexture       = &GLES2_UnlockTexture;
-    renderer->SetRenderTarget     = &GLES2_SetRenderTarget;
-    renderer->UpdateViewport      = &GLES2_UpdateViewport;
-    renderer->UpdateClipRect      = &GLES2_UpdateClipRect;
-    renderer->RenderClear         = &GLES2_RenderClear;
-    renderer->RenderDrawPoints    = &GLES2_RenderDrawPoints;
-    renderer->RenderDrawLines     = &GLES2_RenderDrawLines;
-    renderer->RenderFillRects     = &GLES2_RenderFillRects;
-    renderer->RenderCopy          = &GLES2_RenderCopy;
-    renderer->RenderCopyEx        = &GLES2_RenderCopyEx;
-    renderer->RenderReadPixels    = &GLES2_RenderReadPixels;
-    renderer->RenderPresent       = &GLES2_RenderPresent;
-    renderer->DestroyTexture      = &GLES2_DestroyTexture;
-    renderer->DestroyRenderer     = &GLES2_DestroyRenderer;
-    renderer->GL_BindTexture      = &GLES2_BindTexture;
-    renderer->GL_UnbindTexture    = &GLES2_UnbindTexture;
+    renderer->WindowEvent         = GLES2_WindowEvent;
+    renderer->GetOutputSize       = GLES2_GetOutputSize;
+    renderer->SupportsBlendMode   = GLES2_SupportsBlendMode;
+    renderer->CreateTexture       = GLES2_CreateTexture;
+    renderer->UpdateTexture       = GLES2_UpdateTexture;
+    renderer->UpdateTextureYUV    = GLES2_UpdateTextureYUV;
+    renderer->LockTexture         = GLES2_LockTexture;
+    renderer->UnlockTexture       = GLES2_UnlockTexture;
+    renderer->SetRenderTarget     = GLES2_SetRenderTarget;
+    renderer->UpdateViewport      = GLES2_UpdateViewport;
+    renderer->UpdateClipRect      = GLES2_UpdateClipRect;
+    renderer->RenderClear         = GLES2_RenderClear;
+    renderer->RenderDrawPoints    = GLES2_RenderDrawPoints;
+    renderer->RenderDrawLines     = GLES2_RenderDrawLines;
+    renderer->RenderFillRects     = GLES2_RenderFillRects;
+    renderer->RenderCopy          = GLES2_RenderCopy;
+    renderer->RenderCopyEx        = GLES2_RenderCopyEx;
+    renderer->RenderReadPixels    = GLES2_RenderReadPixels;
+    renderer->RenderPresent       = GLES2_RenderPresent;
+    renderer->DestroyTexture      = GLES2_DestroyTexture;
+    renderer->DestroyRenderer     = GLES2_DestroyRenderer;
+    renderer->GL_BindTexture      = GLES2_BindTexture;
+    renderer->GL_UnbindTexture    = GLES2_UnbindTexture;
 
     renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_YV12;
     renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_IYUV;
diff --git a/src/render/opengles2/SDL_shaders_gles2.c b/src/render/opengles2/SDL_shaders_gles2.c
index 0c01a8c..77d40b3 100644
--- a/src/render/opengles2/SDL_shaders_gles2.c
+++ b/src/render/opengles2/SDL_shaders_gles2.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -259,523 +259,45 @@ static const GLES2_ShaderInstance GLES2_FragmentSrc_TextureNV21Src = {
 
 
 /*************************************************************************************************
- * Vertex/fragment shader binaries (NVIDIA Tegra 1/2)                                            *
- *************************************************************************************************/
-
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-
-#define GL_NVIDIA_PLATFORM_BINARY_NV 0x890B
-
-static const Uint8 GLES2_VertexTegra_Default_[] = {
-    243, 193, 1, 142, 31, 109, 131, 38, 6, 0, 1, 0, 5, 0, 0, 0, 17, 0, 0, 0, 1, 0, 0, 0, 73, 0,
-    0, 0, 46, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 85, 0, 0, 0, 2, 0, 0, 0, 24, 0, 0, 0, 3, 0, 0, 0,
-    91, 0, 0, 0, 1, 0, 0, 0, 16, 0, 0, 0, 5, 0, 0, 0, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 95, 0, 0, 0, 1, 0, 0, 0, 28, 0, 0, 0,
-    13, 0, 0, 0, 102, 0, 0, 0, 2, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 16, 0, 0, 0, 104, 0, 0, 0, 1, 0, 0, 0, 32, 0, 0, 0, 17, 0, 0, 0, 112, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 112, 0, 0, 0, 80, 0, 0, 0, 80, 0, 0, 0, 19, 0, 0, 0, 132, 0,
-    0, 0, 104, 0, 0, 0, 104, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 97, 110, 70, 73, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97,
-    95, 112, 111, 115, 105, 116, 105, 111, 110, 0, 97, 95, 116, 101, 120, 67, 111, 111, 114, 100,
-    0, 118, 95, 116, 101, 120, 67, 111, 111, 114, 100, 0, 117, 95, 112, 114, 111, 106, 101, 99,
-    116, 105, 111, 110, 0, 0, 0, 0, 0, 0, 0, 82, 139, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 80, 139, 0,
-    0, 1, 0, 0, 0, 22, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 33, 0, 0, 0, 92, 139, 0, 0,
-    1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 240, 0, 0, 0, 0, 0, 0, 1, 0,
-    0, 0, 64, 0, 0, 0, 80, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 193, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 128, 63, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 66, 24, 0, 6, 34, 108, 28,
-    0, 0, 42, 16, 128, 0, 195, 192, 6, 129, 252, 255, 65, 96, 108, 28, 0, 0, 0, 0, 0, 1, 195, 192,
-    6, 1, 252, 255, 33, 96, 108, 156, 31, 64, 8, 1, 64, 0, 131, 192, 6, 1, 156, 159, 65, 96, 108,
-    28, 0, 0, 85, 32, 0, 1, 195, 192, 6, 1, 252, 255, 33, 96, 108, 156, 31, 64, 0, 64, 64, 0, 131,
-    192, 134, 1, 152, 31, 65, 96, 108, 156, 31, 64, 127, 48, 0, 1, 195, 192, 6, 129, 129, 255, 33,
-    96
-};
-
-static const Uint8 GLES2_FragmentTegra_None_SolidSrc_[] = {
-    155, 191, 159, 1, 47, 109, 131, 38, 6, 0, 1, 0, 5, 0, 0, 0, 17, 0, 0, 0, 1, 0, 0, 0, 73, 0,
-    0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 75,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0,
-    75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 75, 0, 0, 0, 1, 0, 0, 0, 28, 0, 0, 0, 13, 0,
-    0, 0, 82, 0, 0, 0, 2, 0, 0, 0, 8, 0, 0, 0, 14, 0, 0, 0, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    22, 0, 0, 0, 84, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 23, 0, 0, 0, 92, 0, 0, 0, 1, 0, 0, 0, 4,
-    0, 0, 0, 15, 0, 0, 0, 93, 0, 0, 0, 1, 0, 0, 0, 80, 0, 0, 0, 17, 0, 0, 0, 113, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 0, 0, 0, 113, 0, 0,
-    0, 108, 0, 0, 0, 108, 0, 0, 0, 20, 0, 0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0,
-    0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 97, 110, 70, 73, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 117, 95, 99, 111, 108, 111, 114, 0, 0, 0, 0, 0, 82, 139, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 241, 0, 0, 0, 240, 0, 0,
-    0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 0, 0,
-    0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 21, 32, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 20, 0, 0, 0, 16, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 82, 50, 48, 45, 66, 73, 78, 1,
-    0, 0, 0, 1, 0, 0, 0, 1, 0, 65, 37, 0, 0, 0, 0, 1, 0, 0, 21, 0, 0, 0, 0, 1, 0, 1, 38, 0, 0, 0,
-    0, 1, 0, 1, 39, 0, 0, 0, 0, 1, 0, 1, 40, 1, 0, 0, 0, 8, 0, 4, 40, 0, 40, 0, 0, 0, 242, 65, 63,
-    192, 200, 0, 0, 0, 242, 65, 63, 128, 168, 0, 0, 0, 242, 65, 63, 64, 72, 0, 0, 0, 242, 65, 63,
-    1, 0, 6, 40, 0, 0, 0, 0, 1, 0, 1, 41, 5, 0, 2, 0
-};
-
-static const Uint8 GLES2_FragmentTegra_Alpha_SolidSrc_[] = {
-    169, 153, 195, 28, 47, 109, 131, 38, 6, 0, 1, 0, 5, 0, 0, 0, 17, 0, 0, 0, 1, 0, 0, 0, 73, 0,
-    0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 75,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0,
-    75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 75, 0, 0, 0, 1, 0, 0, 0, 28, 0, 0, 0, 13, 0,
-    0, 0, 82, 0, 0, 0, 2, 0, 0, 0, 8, 0, 0, 0, 14, 0, 0, 0, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    22, 0, 0, 0, 84, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 23, 0, 0, 0, 92, 0, 0, 0, 1, 0, 0, 0, 4,
-    0, 0, 0, 15, 0, 0, 0, 93, 0, 0, 0, 1, 0, 0, 0, 80, 0, 0, 0, 17, 0, 0, 0, 113, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 0, 0, 0, 113, 0, 0,
-    0, 220, 0, 0, 0, 220, 0, 0, 0, 20, 0, 0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0,
-    0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 97, 110, 70, 73, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 117, 95, 99, 111, 108, 111, 114, 0, 0, 0, 0, 0, 82, 139, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 48, 0, 0, 0, 0, 0, 0, 118, 118, 17, 241, 0, 0, 0, 240, 0,
-    0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 0,
-    0, 0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 21, 32, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 16, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 82, 50, 48, 45, 66, 73, 78,
-    1, 0, 0, 0, 3, 0, 0, 0, 3, 0, 65, 37, 8, 0, 129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 21, 0,
-    0, 0, 0, 3, 0, 1, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 39, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 3, 0, 1, 40, 1, 0, 0, 0, 5, 0, 0, 0, 9, 0, 0, 0, 24, 0, 4, 40, 232, 231, 15,
-    0, 0, 242, 65, 62, 194, 72, 1, 0, 0, 250, 65, 63, 194, 40, 1, 0, 0, 250, 65, 63, 192, 168, 1,
-    0, 0, 242, 1, 64, 192, 168, 1, 0, 0, 242, 1, 68, 168, 32, 0, 0, 0, 50, 64, 0, 192, 168, 15,
-    0, 0, 242, 1, 66, 168, 64, 0, 16, 0, 242, 65, 1, 232, 231, 15, 0, 0, 242, 65, 62, 168, 160,
-    0, 0, 0, 50, 64, 2, 104, 192, 0, 0, 36, 48, 66, 4, 232, 231, 15, 0, 0, 242, 65, 62, 3, 0, 6,
-    40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 41, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 2, 0
-};
-
-static const Uint8 GLES2_FragmentTegra_Additive_SolidSrc_[] = {
-    59, 71, 42, 17, 47, 109, 131, 38, 6, 0, 1, 0, 5, 0, 0, 0, 17, 0, 0, 0, 1, 0, 0, 0, 73, 0, 0,
-    0, 8, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 75,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0,
-    75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 75, 0, 0, 0, 1, 0, 0, 0, 28, 0, 0, 0, 13, 0,
-    0, 0, 82, 0, 0, 0, 2, 0, 0, 0, 8, 0, 0, 0, 14, 0, 0, 0, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    22, 0, 0, 0, 84, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 23, 0, 0, 0, 92, 0, 0, 0, 1, 0, 0, 0, 4,
-    0, 0, 0, 15, 0, 0, 0, 93, 0, 0, 0, 1, 0, 0, 0, 80, 0, 0, 0, 17, 0, 0, 0, 113, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 0, 0, 0, 113, 0, 0,
-    0, 108, 0, 0, 0, 108, 0, 0, 0, 20, 0, 0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0,
-    0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 97, 110, 70, 73, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 117, 95, 99, 111, 108, 111, 114, 0, 0, 0, 0, 0, 82, 139, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 48, 0, 0, 0, 0, 0, 0, 22, 22, 17, 241, 0, 0, 0, 240, 0,
-    0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 0,
-    0, 0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 21, 32, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 16, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 82, 50, 48, 45, 66, 73, 78,
-    1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 65, 37, 8, 0, 129, 0, 1, 0, 0, 21, 0, 0, 0, 0, 1, 0, 1, 38, 0,
-    0, 0, 0, 1, 0, 1, 39, 0, 0, 0, 0, 1, 0, 1, 40, 1, 0, 0, 0, 8, 0, 4, 40, 192, 200, 0, 0, 0, 26,
-    0, 70, 192, 40, 0, 0, 0, 2, 0, 64, 192, 72, 0, 0, 0, 10, 0, 66, 192, 168, 0, 0, 0, 18, 0, 68,
-    1, 0, 6, 40, 0, 0, 0, 0, 1, 0, 1, 41, 5, 0, 2, 0
-};
-
-static const Uint8 GLES2_FragmentTegra_Modulated_SolidSrc_[] = {
-    37, 191, 49, 17, 47, 109, 131, 38, 6, 0, 1, 0, 5, 0, 0, 0, 17, 0, 0, 0, 1, 0, 0, 0, 73, 0, 0,
-    0, 8, 0, 0, 0, 8, 0, 0, 0, 2, 0, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 75,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0,
-    75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 75, 0, 0, 0, 1, 0, 0, 0, 28, 0, 0, 0, 13, 0,
-    0, 0, 82, 0, 0, 0, 2, 0, 0, 0, 8, 0, 0, 0, 14, 0, 0, 0, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    22, 0, 0, 0, 84, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 23, 0, 0, 0, 92, 0, 0, 0, 1, 0, 0, 0, 4,
-    0, 0, 0, 15, 0, 0, 0, 93, 0, 0, 0, 1, 0, 0, 0, 80, 0, 0, 0, 17, 0, 0, 0, 113, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 0, 0, 0, 113, 0, 0,
-    0, 108, 0, 0, 0, 108, 0, 0, 0, 20, 0, 0, 0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0,
-    0, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 97, 110, 70, 73, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 117, 95, 99, 111, 108, 111, 114, 0, 0, 0, 0, 0, 82, 139, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 48, 0, 0, 0, 0, 0, 0, 32, 32, 17, 241, 0, 0, 0, 240, 0,
-    0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 0,
-    0, 0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 21, 32, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 16, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 82, 50, 48, 45, 66, 73, 78,
-    1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 65, 37, 8, 0, 129, 0, 1, 0, 0, 21, 0, 0, 0, 0, 1, 0, 1, 38, 0,
-    0, 0, 0, 1, 0, 1, 39, 0, 0, 0, 0, 1, 0, 1, 40, 1, 0, 0, 0, 8, 0, 4, 40, 104, 192, 0, 0, 0, 242,
-    1, 70, 8, 32, 0, 0, 0, 242, 1, 64, 40, 64, 0, 0, 0, 242, 1, 66, 72, 160, 0, 0, 0, 242, 1, 68,
-    1, 0, 6, 40, 0, 0, 0, 0, 1, 0, 1, 41, 5, 0, 2, 0
-};
-
-static const Uint8 GLES2_FragmentTegra_None_TextureSrc_[] = {
-    220, 217, 41, 211, 47, 109, 131, 38, 6, 0, 1, 0, 5, 0, 0, 0, 17, 0, 0, 0, 1, 0, 0, 0, 73, 0,
-    0, 0, 34, 0, 0, 0, 36, 0, 0, 0, 2, 0, 0, 0, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
-    82, 0, 0, 0, 1, 0, 0, 0, 20, 0, 0, 0, 6, 0, 0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0,
-    0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 87, 0, 0, 0, 2, 0, 0, 0, 56, 0, 0, 0,
-    13, 0, 0, 0, 101, 0, 0, 0, 4, 0, 0, 0, 16, 0, 0, 0, 14, 0, 0, 0, 105, 0, 0, 0, 1, 0, 0, 0, 4,
-    0, 0, 0, 22, 0, 0, 0, 106, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 23, 0, 0, 0, 114, 0, 0, 0, 1, 0,
-    0, 0, 4, 0, 0, 0, 15, 0, 0, 0, 115, 0, 0, 0, 1, 0, 0, 0, 80, 0, 0, 0, 17, 0, 0, 0, 135, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 0, 0, 0, 135,
-    0, 0, 0, 120, 0, 0, 0, 120, 0, 0, 0, 20, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21,
-    0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 97, 110, 70, 73, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 118, 95, 116, 101, 120, 67, 111, 111, 114, 100, 0, 117, 95, 109, 111, 100, 117, 108,
-    97, 116, 105, 111, 110, 0, 117, 95, 116, 101, 120, 116, 117, 114, 101, 0, 0, 0, 0, 0, 0, 0,
-    2, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 82, 139, 0, 0, 1, 0, 0, 0, 1,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 94, 139, 0, 0, 1, 0, 0, 0, 1, 0, 0,
-    0, 2, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 5, 48, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 1, 0, 0, 0, 241, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240,
-    0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 1, 0,
-    0, 0, 1, 0, 0, 0, 21, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 16, 0, 0, 0, 16, 0, 0,
-    0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 65, 82, 50, 48, 45, 66, 73, 78, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 65, 37, 0, 0, 0, 0, 1, 0,
-    0, 21, 0, 0, 0, 0, 1, 0, 1, 38, 1, 0, 0, 0, 2, 0, 4, 38, 186, 81, 78, 16, 2, 1, 0, 0, 1, 0,
-    1, 39, 0, 4, 0, 0, 1, 0, 1, 40, 1, 0, 0, 0, 8, 0, 4, 40, 104, 192, 0, 0, 0, 242, 1, 70, 8, 32,
-    0, 0, 0, 242, 1, 64, 40, 64, 0, 0, 0, 242, 1, 66, 72, 160, 0, 0, 0, 242, 1, 68, 1, 0, 6, 40,
-    0, 0, 0, 0, 1, 0, 1, 41, 5, 0, 2, 0
-};
-
-static const Uint8 GLES2_FragmentTegra_Alpha_TextureSrc_[] = {
-    71, 202, 114, 229, 47, 109, 131, 38, 6, 0, 1, 0, 5, 0, 0, 0, 17, 0, 0, 0, 1, 0, 0, 0, 73, 0,
-    0, 0, 34, 0, 0, 0, 36, 0, 0, 0, 2, 0, 0, 0, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
-    82, 0, 0, 0, 1, 0, 0, 0, 20, 0, 0, 0, 6, 0, 0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0,
-    0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 87, 0, 0, 0, 2, 0, 0, 0, 56, 0, 0, 0,
-    13, 0, 0, 0, 101, 0, 0, 0, 4, 0, 0, 0, 16, 0, 0, 0, 14, 0, 0, 0, 105, 0, 0, 0, 1, 0, 0, 0, 4,
-    0, 0, 0, 22, 0, 0, 0, 106, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 23, 0, 0, 0, 114, 0, 0, 0, 1, 0,
-    0, 0, 4, 0, 0, 0, 15, 0, 0, 0, 115, 0, 0, 0, 1, 0, 0, 0, 80, 0, 0, 0, 17, 0, 0, 0, 135, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 0, 0, 0, 135,
-    0, 0, 0, 176, 0, 0, 0, 176, 0, 0, 0, 20, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21,
-    0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 97, 110, 70, 73, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 118, 95, 116, 101, 120, 67, 111, 111, 114, 100, 0, 117, 95, 109, 111, 100, 117, 108,
-    97, 116, 105, 111, 110, 0, 117, 95, 116, 101, 120, 116, 117, 114, 101, 0, 0, 0, 0, 0, 0, 0,
-    2, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 82, 139, 0, 0, 1, 0, 0, 0, 1,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 94, 139, 0, 0, 1, 0, 0, 0, 1, 0, 0,
-    0, 2, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 5, 48, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 1, 118, 118, 17, 241, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0,
-    240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 2, 0, 0, 0,
-    1, 0, 0, 0, 2, 0, 0, 0, 21, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 16, 0, 0, 0, 16,
-    0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 65, 82, 50, 48, 45, 66, 73, 78, 1, 0, 0, 0, 2, 0, 0, 0, 2, 0, 65, 37, 0, 0, 0, 0,
-    8, 0, 129, 0, 1, 0, 0, 21, 0, 0, 0, 0, 2, 0, 1, 38, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 4, 38, 186,
-    81, 78, 16, 2, 1, 0, 0, 2, 0, 1, 39, 0, 4, 0, 0, 0, 0, 0, 0, 2, 0, 1, 40, 1, 0, 0, 0, 5, 0,
-    0, 0, 16, 0, 4, 40, 40, 160, 1, 0, 0, 242, 1, 66, 8, 192, 1, 0, 0, 242, 1, 64, 104, 32, 1, 0,
-    0, 242, 1, 70, 72, 64, 1, 0, 0, 242, 1, 68, 154, 192, 0, 0, 37, 34, 64, 3, 8, 32, 0, 0, 5, 58,
-    208, 4, 40, 64, 0, 0, 5, 50, 208, 4, 72, 160, 0, 0, 37, 42, 208, 4, 2, 0, 6, 40, 0, 0, 0, 0,
-    0, 0, 0, 0, 2, 0, 1, 41, 0, 0, 0, 0, 5, 0, 2, 0
-};
-
-static const Uint8 GLES2_FragmentTegra_Additive_TextureSrc_[] = {
-    161, 234, 193, 234, 47, 109, 131, 38, 6, 0, 1, 0, 5, 0, 0, 0, 17, 0, 0, 0, 1, 0, 0, 0, 73, 0,
-    0, 0, 34, 0, 0, 0, 36, 0, 0, 0, 2, 0, 0, 0, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
-    82, 0, 0, 0, 1, 0, 0, 0, 20, 0, 0, 0, 6, 0, 0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0,
-    0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 87, 0, 0, 0, 2, 0, 0, 0, 56, 0, 0, 0,
-    13, 0, 0, 0, 101, 0, 0, 0, 4, 0, 0, 0, 16, 0, 0, 0, 14, 0, 0, 0, 105, 0, 0, 0, 1, 0, 0, 0, 4,
-    0, 0, 0, 22, 0, 0, 0, 106, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 23, 0, 0, 0, 114, 0, 0, 0, 1, 0,
-    0, 0, 4, 0, 0, 0, 15, 0, 0, 0, 115, 0, 0, 0, 1, 0, 0, 0, 80, 0, 0, 0, 17, 0, 0, 0, 135, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 0, 0, 0, 135,
-    0, 0, 0, 176, 0, 0, 0, 176, 0, 0, 0, 20, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21,
-    0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 97, 110, 70, 73, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 118, 95, 116, 101, 120, 67, 111, 111, 114, 100, 0, 117, 95, 109, 111, 100, 117, 108,
-    97, 116, 105, 111, 110, 0, 117, 95, 116, 101, 120, 116, 117, 114, 101, 0, 0, 0, 0, 0, 0, 0,
-    2, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 82, 139, 0, 0, 1, 0, 0, 0, 1,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 94, 139, 0, 0, 1, 0, 0, 0, 1, 0, 0,
-    0, 2, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 5, 48, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 1, 22, 22, 17, 241, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240,
-    0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 2, 0, 0, 0, 1, 0,
-    0, 0, 2, 0, 0, 0, 21, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 16, 0, 0, 0, 16, 0, 0,
-    0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 65, 82, 50, 48, 45, 66, 73, 78, 1, 0, 0, 0, 2, 0, 0, 0, 2, 0, 65, 37, 0, 0, 0, 0, 8, 0,
-    129, 0, 1, 0, 0, 21, 0, 0, 0, 0, 2, 0, 1, 38, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 4, 38, 186, 81,
-    78, 16, 2, 1, 0, 0, 2, 0, 1, 39, 0, 4, 0, 0, 0, 0, 0, 0, 2, 0, 1, 40, 1, 0, 0, 0, 5, 0, 0, 0,
-    16, 0, 4, 40, 40, 160, 1, 0, 0, 242, 1, 66, 104, 32, 1, 0, 0, 242, 1, 70, 8, 192, 1, 0, 0, 242,
-    1, 64, 72, 64, 1, 0, 0, 242, 1, 68, 136, 192, 0, 0, 0, 26, 64, 4, 136, 32, 0, 0, 0, 2, 64, 7,
-    136, 64, 0, 0, 0, 10, 64, 6, 136, 160, 0, 0, 0, 18, 64, 5, 2, 0, 6, 40, 0, 0, 0, 0, 0, 0, 0,
-    0, 2, 0, 1, 41, 0, 0, 0, 0, 5, 0, 2, 0
-};
-
-static const Uint8 GLES2_FragmentTegra_Modulated_TextureSrc_[] = {
-    75, 132, 201, 227, 47, 109, 131, 38, 6, 0, 1, 0, 5, 0, 0, 0, 17, 0, 0, 0, 1, 0, 0, 0, 73, 0,
-    0, 0, 34, 0, 0, 0, 36, 0, 0, 0, 2, 0, 0, 0, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
-    82, 0, 0, 0, 1, 0, 0, 0, 20, 0, 0, 0, 6, 0, 0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0,
-    0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 87, 0, 0, 0, 2, 0, 0, 0, 56, 0, 0, 0,
-    13, 0, 0, 0, 101, 0, 0, 0, 4, 0, 0, 0, 16, 0, 0, 0, 14, 0, 0, 0, 105, 0, 0, 0, 1, 0, 0, 0, 4,
-    0, 0, 0, 22, 0, 0, 0, 106, 0, 0, 0, 8, 0, 0, 0, 32, 0, 0, 0, 23, 0, 0, 0, 114, 0, 0, 0, 1, 0,
-    0, 0, 4, 0, 0, 0, 15, 0, 0, 0, 115, 0, 0, 0, 1, 0, 0, 0, 80, 0, 0, 0, 17, 0, 0, 0, 135, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 0, 0, 0, 135,
-    0, 0, 0, 176, 0, 0, 0, 176, 0, 0, 0, 20, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21,
-    0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 97, 110, 70, 73, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 118, 95, 116, 101, 120, 67, 111, 111, 114, 100, 0, 117, 95, 109, 111, 100, 117, 108,
-    97, 116, 105, 111, 110, 0, 117, 95, 116, 101, 120, 116, 117, 114, 101, 0, 0, 0, 0, 0, 0, 0,
-    2, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 82, 139, 0, 0, 1, 0, 0, 0, 1,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 94, 139, 0, 0, 1, 0, 0, 0, 1, 0, 0,
-    0, 2, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 5, 48, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 1, 32, 32, 17, 241, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 240,
-    0, 0, 0, 240, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 2, 0, 0, 0, 1, 0,
-    0, 0, 2, 0, 0, 0, 21, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 16, 0, 0, 0, 16, 0, 0,
-    0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 65, 82, 50, 48, 45, 66, 73, 78, 1, 0, 0, 0, 2, 0, 0, 0, 2, 0, 65, 37, 0, 0, 0, 0, 8, 0,
-    129, 0, 1, 0, 0, 21, 0, 0, 0, 0, 2, 0, 1, 38, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 4, 38, 186, 81,
-    78, 16, 2, 1, 0, 0, 2, 0, 1, 39, 0, 4, 0, 0, 0, 0, 0, 0, 2, 0, 1, 40, 1, 0, 0, 0, 5, 0, 0, 0,
-    16, 0, 4, 40, 40, 160, 1, 0, 0, 242, 1, 66, 8, 192, 1, 0, 0, 242, 1, 64, 104, 32, 1, 0, 0, 242,
-    1, 70, 72, 64, 1, 0, 0, 242, 1, 68, 104, 192, 0, 0, 0, 242, 65, 4, 232, 32, 0, 0, 0, 242, 65,
-    0, 40, 64, 0, 0, 0, 242, 65, 6, 72, 160, 0, 0, 0, 242, 65, 5, 2, 0, 6, 40, 0, 0, 0, 0, 0, 0,
-    0, 0, 2, 0, 1, 41, 0, 0, 0, 0, 5, 0, 2, 0
-};
-
-static const GLES2_ShaderInstance GLES2_VertexTegra_Default = {
-    GL_VERTEX_SHADER,
-    GL_NVIDIA_PLATFORM_BINARY_NV,
-    sizeof(GLES2_VertexTegra_Default_),
-    GLES2_VertexTegra_Default_
-};
-
-static const GLES2_ShaderInstance GLES2_FragmentTegra_None_SolidSrc = {
-    GL_FRAGMENT_SHADER,
-    GL_NVIDIA_PLATFORM_BINARY_NV,
-    sizeof(GLES2_FragmentTegra_None_SolidSrc_),
-    GLES2_FragmentTegra_None_SolidSrc_
-};
-
-static const GLES2_ShaderInstance GLES2_FragmentTegra_Alpha_SolidSrc = {
-    GL_FRAGMENT_SHADER,
-    GL_NVIDIA_PLATFORM_BINARY_NV,
-    sizeof(GLES2_FragmentTegra_Alpha_SolidSrc_),
-    GLES2_FragmentTegra_Alpha_SolidSrc_
-};
-
-static const GLES2_ShaderInstance GLES2_FragmentTegra_Additive_SolidSrc = {
-    GL_FRAGMENT_SHADER,
-    GL_NVIDIA_PLATFORM_BINARY_NV,
-    sizeof(GLES2_FragmentTegra_Additive_SolidSrc_),
-    GLES2_FragmentTegra_Additive_SolidSrc_
-};
-
-static const GLES2_ShaderInstance GLES2_FragmentTegra_Modulated_SolidSrc = {
-    GL_FRAGMENT_SHADER,
-    GL_NVIDIA_PLATFORM_BINARY_NV,
-    sizeof(GLES2_FragmentTegra_Modulated_SolidSrc_),
-    GLES2_FragmentTegra_Modulated_SolidSrc_
-};
-
-static const GLES2_ShaderInstance GLES2_FragmentTegra_None_TextureSrc = {
-    GL_FRAGMENT_SHADER,
-    GL_NVIDIA_PLATFORM_BINARY_NV,
-    sizeof(GLES2_FragmentTegra_None_TextureSrc_),
-    GLES2_FragmentTegra_None_TextureSrc_
-};
-
-static const GLES2_ShaderInstance GLES2_FragmentTegra_Alpha_TextureSrc = {
-    GL_FRAGMENT_SHADER,
-    GL_NVIDIA_PLATFORM_BINARY_NV,
-    sizeof(GLES2_FragmentTegra_Alpha_TextureSrc_),
-    GLES2_FragmentTegra_Alpha_TextureSrc_
-};
-
-static const GLES2_ShaderInstance GLES2_FragmentTegra_Additive_TextureSrc = {
-    GL_FRAGMENT_SHADER,
-    GL_NVIDIA_PLATFORM_BINARY_NV,
-    sizeof(GLES2_FragmentTegra_Additive_TextureSrc_),
-    GLES2_FragmentTegra_Additive_TextureSrc_
-};
-
-static const GLES2_ShaderInstance GLES2_FragmentTegra_Modulated_TextureSrc = {
-    GL_FRAGMENT_SHADER,
-    GL_NVIDIA_PLATFORM_BINARY_NV,
-    sizeof(GLES2_FragmentTegra_Modulated_TextureSrc_),
-    GLES2_FragmentTegra_Modulated_TextureSrc_
-};
-
-#endif /* GLES2_INCLUDE_NVIDIA_SHADERS */
-
-/*************************************************************************************************
  * Vertex/fragment shader definitions                                                            *
  *************************************************************************************************/
 
 static GLES2_Shader GLES2_VertexShader_Default = {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-    2,
-#else
     1,
-#endif
     {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-        &GLES2_VertexTegra_Default,
-#endif
         &GLES2_VertexSrc_Default
     }
 };
 
-static GLES2_Shader GLES2_FragmentShader_None_SolidSrc = {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-    2,
-#else
-    1,
-#endif
-    {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-        &GLES2_FragmentTegra_None_SolidSrc,
-#endif
-        &GLES2_FragmentSrc_SolidSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Alpha_SolidSrc = {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-    2,
-#else
+static GLES2_Shader GLES2_FragmentShader_SolidSrc = {
     1,
-#endif
     {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-        &GLES2_FragmentTegra_Alpha_SolidSrc,
-#endif
         &GLES2_FragmentSrc_SolidSrc
     }
 };
 
-static GLES2_Shader GLES2_FragmentShader_Additive_SolidSrc = {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-    2,
-#else
-    1,
-#endif
-    {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-        &GLES2_FragmentTegra_Additive_SolidSrc,
-#endif
-        &GLES2_FragmentSrc_SolidSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Modulated_SolidSrc = {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-    2,
-#else
-    1,
-#endif
-    {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-        &GLES2_FragmentTegra_Modulated_SolidSrc,
-#endif
-        &GLES2_FragmentSrc_SolidSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_None_TextureABGRSrc = {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-    2,
-#else
-    1,
-#endif
-    {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-        &GLES2_FragmentTegra_None_TextureSrc,
-#endif
-        &GLES2_FragmentSrc_TextureABGRSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Alpha_TextureABGRSrc = {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-    2,
-#else
-    1,
-#endif
-    {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-        &GLES2_FragmentTegra_Alpha_TextureSrc,
-#endif
-        &GLES2_FragmentSrc_TextureABGRSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Additive_TextureABGRSrc = {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-    2,
-#else
+static GLES2_Shader GLES2_FragmentShader_TextureABGRSrc = {
     1,
-#endif
     {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-        &GLES2_FragmentTegra_Additive_TextureSrc,
-#endif
         &GLES2_FragmentSrc_TextureABGRSrc
     }
 };
 
-static GLES2_Shader GLES2_FragmentShader_Modulated_TextureABGRSrc = {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-    2,
-#else
-    1,
-#endif
-    {
-#if GLES2_INCLUDE_NVIDIA_SHADERS
-        &GLES2_FragmentTegra_Modulated_TextureSrc,
-#endif
-        &GLES2_FragmentSrc_TextureABGRSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_None_TextureARGBSrc = {
-    1,
-    {
-        &GLES2_FragmentSrc_TextureARGBSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Alpha_TextureARGBSrc = {
-    1,
-    {
-        &GLES2_FragmentSrc_TextureARGBSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Additive_TextureARGBSrc = {
+static GLES2_Shader GLES2_FragmentShader_TextureARGBSrc = {
     1,
     {
         &GLES2_FragmentSrc_TextureARGBSrc
     }
 };
 
-static GLES2_Shader GLES2_FragmentShader_Modulated_TextureARGBSrc = {
-    1,
-    {
-        &GLES2_FragmentSrc_TextureARGBSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_None_TextureRGBSrc = {
-    1,
-    {
-        &GLES2_FragmentSrc_TextureRGBSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Alpha_TextureRGBSrc = {
-    1,
-    {
-        &GLES2_FragmentSrc_TextureRGBSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Additive_TextureRGBSrc = {
-    1,
-    {
-        &GLES2_FragmentSrc_TextureRGBSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Modulated_TextureRGBSrc = {
+static GLES2_Shader GLES2_FragmentShader_TextureRGBSrc = {
     1,
     {
         &GLES2_FragmentSrc_TextureRGBSrc
     }
 };
 
-static GLES2_Shader GLES2_FragmentShader_None_TextureBGRSrc = {
-    1,
-    {
-        &GLES2_FragmentSrc_TextureBGRSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Alpha_TextureBGRSrc = {
-    1,
-    {
-        &GLES2_FragmentSrc_TextureBGRSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Additive_TextureBGRSrc = {
-    1,
-    {
-        &GLES2_FragmentSrc_TextureBGRSrc
-    }
-};
-
-static GLES2_Shader GLES2_FragmentShader_Modulated_TextureBGRSrc = {
+static GLES2_Shader GLES2_FragmentShader_TextureBGRSrc = {
     1,
     {
         &GLES2_FragmentSrc_TextureBGRSrc
@@ -808,94 +330,27 @@ static GLES2_Shader GLES2_FragmentShader_TextureNV21Src = {
  * Shader selector                                                                               *
  *************************************************************************************************/
 
-const GLES2_Shader *GLES2_GetShader(GLES2_ShaderType type, SDL_BlendMode blendMode)
+const GLES2_Shader *GLES2_GetShader(GLES2_ShaderType type)
 {
     switch (type) {
     case GLES2_SHADER_VERTEX_DEFAULT:
         return &GLES2_VertexShader_Default;
     case GLES2_SHADER_FRAGMENT_SOLID_SRC:
-    switch (blendMode) {
-    case SDL_BLENDMODE_NONE:
-        return &GLES2_FragmentShader_None_SolidSrc;
-    case SDL_BLENDMODE_BLEND:
-        return &GLES2_FragmentShader_Alpha_SolidSrc;
-    case SDL_BLENDMODE_ADD:
-        return &GLES2_FragmentShader_Additive_SolidSrc;
-    case SDL_BLENDMODE_MOD:
-        return &GLES2_FragmentShader_Modulated_SolidSrc;
-    default:
-        return NULL;
-    }
+        return &GLES2_FragmentShader_SolidSrc;
     case GLES2_SHADER_FRAGMENT_TEXTURE_ABGR_SRC:
-        switch (blendMode) {
-        case SDL_BLENDMODE_NONE:
-            return &GLES2_FragmentShader_None_TextureABGRSrc;
-        case SDL_BLENDMODE_BLEND:
-            return &GLES2_FragmentShader_Alpha_TextureABGRSrc;
-        case SDL_BLENDMODE_ADD:
-            return &GLES2_FragmentShader_Additive_TextureABGRSrc;
-        case SDL_BLENDMODE_MOD:
-            return &GLES2_FragmentShader_Modulated_TextureABGRSrc;
-        default:
-            return NULL;
-    }
+        return &GLES2_FragmentShader_TextureABGRSrc;
     case GLES2_SHADER_FRAGMENT_TEXTURE_ARGB_SRC:
-        switch (blendMode) {
-        case SDL_BLENDMODE_NONE:
-            return &GLES2_FragmentShader_None_TextureARGBSrc;
-        case SDL_BLENDMODE_BLEND:
-            return &GLES2_FragmentShader_Alpha_TextureARGBSrc;
-        case SDL_BLENDMODE_ADD:
-            return &GLES2_FragmentShader_Additive_TextureARGBSrc;
-        case SDL_BLENDMODE_MOD:
-            return &GLES2_FragmentShader_Modulated_TextureARGBSrc;
-        default:
-            return NULL;
-    }
-
+        return &GLES2_FragmentShader_TextureARGBSrc;
     case GLES2_SHADER_FRAGMENT_TEXTURE_RGB_SRC:
-        switch (blendMode) {
-        case SDL_BLENDMODE_NONE:
-            return &GLES2_FragmentShader_None_TextureRGBSrc;
-        case SDL_BLENDMODE_BLEND:
-            return &GLES2_FragmentShader_Alpha_TextureRGBSrc;
-        case SDL_BLENDMODE_ADD:
-            return &GLES2_FragmentShader_Additive_TextureRGBSrc;
-        case SDL_BLENDMODE_MOD:
-            return &GLES2_FragmentShader_Modulated_TextureRGBSrc;
-        default:
-            return NULL;
-    }
-
+        return &GLES2_FragmentShader_TextureRGBSrc;
     case GLES2_SHADER_FRAGMENT_TEXTURE_BGR_SRC:
-        switch (blendMode) {
-        case SDL_BLENDMODE_NONE:
-            return &GLES2_FragmentShader_None_TextureBGRSrc;
-        case SDL_BLENDMODE_BLEND:
-            return &GLES2_FragmentShader_Alpha_TextureBGRSrc;
-        case SDL_BLENDMODE_ADD:
-            return &GLES2_FragmentShader_Additive_TextureBGRSrc;
-        case SDL_BLENDMODE_MOD:
-            return &GLES2_FragmentShader_Modulated_TextureBGRSrc;
-        default:
-            return NULL;
-    }
-    
+        return &GLES2_FragmentShader_TextureBGRSrc;
     case GLES2_SHADER_FRAGMENT_TEXTURE_YUV_SRC:
-    {
         return &GLES2_FragmentShader_TextureYUVSrc;
-    }
-
     case GLES2_SHADER_FRAGMENT_TEXTURE_NV12_SRC:
-    {
         return &GLES2_FragmentShader_TextureNV12Src;
-    }
-
     case GLES2_SHADER_FRAGMENT_TEXTURE_NV21_SRC:
-    {
         return &GLES2_FragmentShader_TextureNV21Src;
-    }
-
     default:
         return NULL;
     }
diff --git a/src/render/opengles2/SDL_shaders_gles2.h b/src/render/opengles2/SDL_shaders_gles2.h
index 3958ae0..1f2667e 100644
--- a/src/render/opengles2/SDL_shaders_gles2.h
+++ b/src/render/opengles2/SDL_shaders_gles2.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,8 +22,8 @@
 
 #if SDL_VIDEO_RENDER_OGL_ES2
 
-#ifndef SDL_shaderdata_h_
-#define SDL_shaderdata_h_
+#ifndef SDL_shaders_gles2_h_
+#define SDL_shaders_gles2_h_
 
 typedef struct GLES2_ShaderInstance
 {
@@ -54,9 +54,9 @@ typedef enum
 
 #define GLES2_SOURCE_SHADER (GLenum)-1
 
-const GLES2_Shader *GLES2_GetShader(GLES2_ShaderType type, SDL_BlendMode blendMode);
+const GLES2_Shader *GLES2_GetShader(GLES2_ShaderType type);
 
-#endif /* SDL_shaderdata_h_ */
+#endif /* SDL_shaders_gles2_h_ */
 
 #endif /* SDL_VIDEO_RENDER_OGL_ES2 */
 
diff --git a/src/render/psp/SDL_render_psp.c b/src/render/psp/SDL_render_psp.c
index f285131..d32205f 100644
--- a/src/render/psp/SDL_render_psp.c
+++ b/src/render/psp/SDL_render_psp.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -949,11 +949,11 @@ PSP_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
     vertices[3].y = y + sw - ch;
     vertices[3].z = 0;
 
-    if (flip & SDL_FLIP_HORIZONTAL) {
+    if (flip & SDL_FLIP_VERTICAL) {
                 Swap(&vertices[0].v, &vertices[2].v);
                 Swap(&vertices[1].v, &vertices[3].v);
     }
-    if (flip & SDL_FLIP_VERTICAL) {
+    if (flip & SDL_FLIP_HORIZONTAL) {
                 Swap(&vertices[0].u, &vertices[2].u);
                 Swap(&vertices[1].u, &vertices[3].u);
     }
diff --git a/src/render/software/SDL_blendfillrect.c b/src/render/software/SDL_blendfillrect.c
index 7cfb274..e90396c 100644
--- a/src/render/software/SDL_blendfillrect.c
+++ b/src/render/software/SDL_blendfillrect.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -245,7 +245,7 @@ SDL_BlendFillRect(SDL_Surface * dst, const SDL_Rect * rect,
             } else {
                 return SDL_BlendFillRect_ARGB8888(dst, rect, blendMode, r, g, b, a);
             }
-            break;
+            /* break; -Wunreachable-code-break */
         }
         break;
     default:
diff --git a/src/render/software/SDL_blendfillrect.h b/src/render/software/SDL_blendfillrect.h
index 88bb2e2..bac4fe8 100644
--- a/src/render/software/SDL_blendfillrect.h
+++ b/src/render/software/SDL_blendfillrect.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/software/SDL_blendline.c b/src/render/software/SDL_blendline.c
index ef0d585..b21653b 100644
--- a/src/render/software/SDL_blendline.c
+++ b/src/render/software/SDL_blendline.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -685,7 +685,7 @@ SDL_CalculateBlendLineFunc(const SDL_PixelFormat * fmt)
         } else {
             return SDL_BlendLine_RGB2;
         }
-        break;
+        /* break; -Wunreachable-code-break */
     case 4:
         if (fmt->Rmask == 0x00FF0000) {
             if (fmt->Amask) {
diff --git a/src/render/software/SDL_blendline.h b/src/render/software/SDL_blendline.h
index c0b545f..ab84986 100644
--- a/src/render/software/SDL_blendline.h
+++ b/src/render/software/SDL_blendline.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/software/SDL_blendpoint.c b/src/render/software/SDL_blendpoint.c
index fc42dfe..c814df0 100644
--- a/src/render/software/SDL_blendpoint.c
+++ b/src/render/software/SDL_blendpoint.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -235,13 +235,11 @@ SDL_BlendPoint(SDL_Surface * dst, int x, int y, SDL_BlendMode blendMode, Uint8 r
         switch (dst->format->Rmask) {
         case 0x00FF0000:
             if (!dst->format->Amask) {
-                return SDL_BlendPoint_RGB888(dst, x, y, blendMode, r, g, b,
-                                             a);
+                return SDL_BlendPoint_RGB888(dst, x, y, blendMode, r, g, b, a);
             } else {
-                return SDL_BlendPoint_ARGB8888(dst, x, y, blendMode, r, g, b,
-                                               a);
+                return SDL_BlendPoint_ARGB8888(dst, x, y, blendMode, r, g, b, a);
             }
-            break;
+            /* break; -Wunreachable-code-break */
         }
         break;
     default:
diff --git a/src/render/software/SDL_blendpoint.h b/src/render/software/SDL_blendpoint.h
index 58ddec7..f46ba95 100644
--- a/src/render/software/SDL_blendpoint.h
+++ b/src/render/software/SDL_blendpoint.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/software/SDL_draw.h b/src/render/software/SDL_draw.h
index 3a5e7cf..fb8b382 100644
--- a/src/render/software/SDL_draw.h
+++ b/src/render/software/SDL_draw.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -562,10 +562,10 @@ do { \
     while (height--) { \
         { int n = (width+3)/4; \
             switch (width & 3) { \
-            case 0: do {   op; pixel++; \
-            case 3:        op; pixel++; \
-            case 2:        op; pixel++; \
-            case 1:        op; pixel++; \
+            case 0: do {   op; pixel++; /* fallthrough */ \
+            case 3:        op; pixel++; /* fallthrough */ \
+            case 2:        op; pixel++; /* fallthrough */ \
+            case 1:        op; pixel++; /* fallthrough */ \
                     } while ( --n > 0 ); \
             } \
         } \
diff --git a/src/render/software/SDL_drawline.c b/src/render/software/SDL_drawline.c
index fd50ea7..e9f68c6 100644
--- a/src/render/software/SDL_drawline.c
+++ b/src/render/software/SDL_drawline.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/software/SDL_drawline.h b/src/render/software/SDL_drawline.h
index 40721c3..c49feca 100644
--- a/src/render/software/SDL_drawline.h
+++ b/src/render/software/SDL_drawline.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/software/SDL_drawpoint.c b/src/render/software/SDL_drawpoint.c
index 98f0d83..b15c635 100644
--- a/src/render/software/SDL_drawpoint.c
+++ b/src/render/software/SDL_drawpoint.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/software/SDL_drawpoint.h b/src/render/software/SDL_drawpoint.h
index e77857a..5454f8b 100644
--- a/src/render/software/SDL_drawpoint.h
+++ b/src/render/software/SDL_drawpoint.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/software/SDL_render_sw.c b/src/render/software/SDL_render_sw.c
index e7a6cd8..62b680e 100644
--- a/src/render/software/SDL_render_sw.c
+++ b/src/render/software/SDL_render_sw.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -239,7 +239,10 @@ SW_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
     SDL_SetSurfaceAlphaMod(texture->driverdata, texture->a);
     SDL_SetSurfaceBlendMode(texture->driverdata, texture->blendMode);
 
-    if (texture->access == SDL_TEXTUREACCESS_STATIC) {
+    /* Only RLE encode textures without an alpha channel since the RLE coder
+     * discards the color values of pixels with an alpha value of zero.
+     */
+    if (texture->access == SDL_TEXTUREACCESS_STATIC && !Amask) {
         SDL_SetSurfaceRLE(texture->driverdata, 1);
     }
 
@@ -368,9 +371,14 @@ SW_UpdateClipRect(SDL_Renderer * renderer)
     SDL_Surface *surface = data->surface;
     if (surface) {
         if (renderer->clipping_enabled) {
-            SDL_SetClipRect(surface, &renderer->clip_rect);
+            SDL_Rect clip_rect;
+            clip_rect = renderer->clip_rect;
+            clip_rect.x += renderer->viewport.x;
+            clip_rect.y += renderer->viewport.y;
+            SDL_IntersectRect(&renderer->viewport, &clip_rect, &clip_rect);
+            SDL_SetClipRect(surface, &clip_rect);
         } else {
-            SDL_SetClipRect(surface, NULL);
+            SDL_SetClipRect(surface, &renderer->viewport);
         }
     }
     return 0;
@@ -599,9 +607,15 @@ SW_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
     SDL_Surface *surface = SW_ActivateRenderer(renderer);
     SDL_Surface *src = (SDL_Surface *) texture->driverdata;
     SDL_Rect final_rect, tmp_rect;
-    SDL_Surface *surface_rotated, *surface_scaled;
-    int retval, dstwidth, dstheight, abscenterx, abscentery;
+    SDL_Surface *src_clone, *src_rotated, *src_scaled;
+    SDL_Surface *mask = NULL, *mask_rotated = NULL;
+    int retval = 0, dstwidth, dstheight, abscenterx, abscentery;
     double cangle, sangle, px, py, p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y;
+    SDL_BlendMode blendmode;
+    Uint8 alphaMod, rMod, gMod, bMod;
+    int applyModulation = SDL_FALSE;
+    int blitRequired = SDL_FALSE;
+    int isOpaque = SDL_FALSE;
 
     if (!surface) {
         return -1;
@@ -617,69 +631,104 @@ SW_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
     final_rect.w = (int)dstrect->w;
     final_rect.h = (int)dstrect->h;
 
-    /* SDLgfx_rotateSurface doesn't accept a source rectangle, so crop and scale if we need to */
     tmp_rect = final_rect;
     tmp_rect.x = 0;
     tmp_rect.y = 0;
-    if (srcrect->w == final_rect.w && srcrect->h == final_rect.h && srcrect->x == 0 && srcrect->y == 0) {
-        surface_scaled = src; /* but if we don't need to, just use the original */
-        retval = 0;
-    } else {
-        SDL_Surface *blit_src = src;
-        Uint32 colorkey;
-        SDL_BlendMode blendMode;
-        Uint8 alphaMod, r, g, b;
-        SDL_bool cloneSource = SDL_FALSE;
-
-        surface_scaled = SDL_CreateRGBSurface(SDL_SWSURFACE, final_rect.w, final_rect.h, src->format->BitsPerPixel,
-                                              src->format->Rmask, src->format->Gmask,
-                                              src->format->Bmask, src->format->Amask );
-        if (!surface_scaled) {
-            return -1;
-        }
 
-        /* copy the color key, alpha mod, blend mode, and color mod so the scaled surface behaves like the source */
-        if (SDL_GetColorKey(src, &colorkey) == 0) {
-            SDL_SetColorKey(surface_scaled, SDL_TRUE, colorkey);
-            cloneSource = SDL_TRUE;
+    /* It is possible to encounter an RLE encoded surface here and locking it is
+     * necessary because this code is going to access the pixel buffer directly.
+     */
+    if (SDL_MUSTLOCK(src)) {
+        SDL_LockSurface(src);
+    }
+
+    /* Clone the source surface but use its pixel buffer directly.
+     * The original source surface must be treated as read-only.
+     */
+    src_clone = SDL_CreateRGBSurfaceFrom(src->pixels, src->w, src->h, src->format->BitsPerPixel, src->pitch,
+                                         src->format->Rmask, src->format->Gmask,
+                                         src->format->Bmask, src->format->Amask);
+    if (src_clone == NULL) {
+        if (SDL_MUSTLOCK(src)) {
+            SDL_UnlockSurface(src);
         }
-        SDL_GetSurfaceAlphaMod(src, &alphaMod); /* these will be copied to surface_scaled below if necessary */
-        SDL_GetSurfaceBlendMode(src, &blendMode);
-        SDL_GetSurfaceColorMod(src, &r, &g, &b);
-
-        /* now we need to blit the src into surface_scaled. since we want to copy the colors from the source to
-         * surface_scaled rather than blend them, etc. we'll need to disable the blend mode, alpha mod, etc.
-         * but we don't want to modify src (in case it's being used on other threads), so we'll need to clone it
-         * before changing the blend options
-         */
-        cloneSource |= blendMode != SDL_BLENDMODE_NONE || (alphaMod & r & g & b) != 255;
-        if (cloneSource) {
-            blit_src = SDL_ConvertSurface(src, src->format, src->flags); /* clone src */
-            if (!blit_src) {
-                SDL_FreeSurface(surface_scaled);
-                return -1;
-            }
-            SDL_SetSurfaceAlphaMod(blit_src, 255); /* disable all blending options in blit_src */
-            SDL_SetSurfaceBlendMode(blit_src, SDL_BLENDMODE_NONE);
-            SDL_SetColorKey(blit_src, 0, 0);
-            SDL_SetSurfaceColorMod(blit_src, 255, 255, 255);
-            SDL_SetSurfaceRLE(blit_src, 0); /* don't RLE encode a surface we'll only use once */
-
-            SDL_SetSurfaceAlphaMod(surface_scaled, alphaMod); /* copy blending options to surface_scaled */
-            SDL_SetSurfaceBlendMode(surface_scaled, blendMode);
-            SDL_SetSurfaceColorMod(surface_scaled, r, g, b);
+        return -1;
+    }
+
+    SDL_GetSurfaceBlendMode(src, &blendmode);
+    SDL_GetSurfaceAlphaMod(src, &alphaMod);
+    SDL_GetSurfaceColorMod(src, &rMod, &gMod, &bMod);
+
+    /* SDLgfx_rotateSurface only accepts 32-bit surfaces with a 8888 layout. Everything else has to be converted. */
+    if (src->format->BitsPerPixel != 32 || SDL_PIXELLAYOUT(src->format->format) != SDL_PACKEDLAYOUT_8888 || !src->format->Amask) {
+        blitRequired = SDL_TRUE;
+    }
+
+    /* If scaling and cropping is necessary, it has to be taken care of before the rotation. */
+    if (!(srcrect->w == final_rect.w && srcrect->h == final_rect.h && srcrect->x == 0 && srcrect->y == 0)) {
+        blitRequired = SDL_TRUE;
+    }
+
+    /* The color and alpha modulation has to be applied before the rotation when using the NONE and MOD blend modes. */
+    if ((blendmode == SDL_BLENDMODE_NONE || blendmode == SDL_BLENDMODE_MOD) && (alphaMod & rMod & gMod & bMod) != 255) {
+        applyModulation = SDL_TRUE;
+        SDL_SetSurfaceAlphaMod(src_clone, alphaMod);
+        SDL_SetSurfaceColorMod(src_clone, rMod, gMod, bMod);
+    }
+
+    /* Opaque surfaces are much easier to handle with the NONE blend mode. */
+    if (blendmode == SDL_BLENDMODE_NONE && !src->format->Amask && alphaMod == 255) {
+        isOpaque = SDL_TRUE;
+    }
+
+    /* The NONE blend mode requires a mask for non-opaque surfaces. This mask will be used
+     * to clear the pixels in the destination surface. The other steps are explained below.
+     */
+    if (blendmode == SDL_BLENDMODE_NONE && !isOpaque) {
+        mask = SDL_CreateRGBSurface(0, final_rect.w, final_rect.h, 32,
+                                    0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
+        if (mask == NULL) {
+            retval = -1;
+        } else {
+            SDL_SetSurfaceBlendMode(mask, SDL_BLENDMODE_MOD);
         }
+    }
 
-        retval = SDL_BlitScaled(blit_src, srcrect, surface_scaled, &tmp_rect);
-        if (blit_src != src) {
-            SDL_FreeSurface(blit_src);
+    /* Create a new surface should there be a format mismatch or if scaling, cropping,
+     * or modulation is required. It's possible to use the source surface directly otherwise.
+     */
+    if (!retval && (blitRequired || applyModulation)) {
+        SDL_Rect scale_rect = tmp_rect;
+        src_scaled = SDL_CreateRGBSurface(0, final_rect.w, final_rect.h, 32,
+                                          0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
+        if (src_scaled == NULL) {
+            retval = -1;
+        } else {
+            SDL_SetSurfaceBlendMode(src_clone, SDL_BLENDMODE_NONE);
+            retval = SDL_BlitScaled(src_clone, srcrect, src_scaled, &scale_rect);
+            SDL_FreeSurface(src_clone);
+            src_clone = src_scaled;
+            src_scaled = NULL;
         }
     }
 
+    /* SDLgfx_rotateSurface is going to make decisions depending on the blend mode. */
+    SDL_SetSurfaceBlendMode(src_clone, blendmode);
+
     if (!retval) {
         SDLgfx_rotozoomSurfaceSizeTrig(tmp_rect.w, tmp_rect.h, angle, &dstwidth, &dstheight, &cangle, &sangle);
-        surface_rotated = SDLgfx_rotateSurface(surface_scaled, angle, dstwidth/2, dstheight/2, GetScaleQuality(), flip & SDL_FLIP_HORIZONTAL, flip & SDL_FLIP_VERTICAL, dstwidth, dstheight, cangle, sangle);
-        if(surface_rotated) {
+        src_rotated = SDLgfx_rotateSurface(src_clone, angle, dstwidth/2, dstheight/2, GetScaleQuality(), flip & SDL_FLIP_HORIZONTAL, flip & SDL_FLIP_VERTICAL, dstwidth, dstheight, cangle, sangle);
+        if (src_rotated == NULL) {
+            retval = -1;
+        }
+        if (!retval && mask != NULL) {
+            /* The mask needed for the NONE blend mode gets rotated with the same parameters. */
+            mask_rotated = SDLgfx_rotateSurface(mask, angle, dstwidth/2, dstheight/2, SDL_FALSE, 0, 0, dstwidth, dstheight, cangle, sangle);
+            if (mask_rotated == NULL) {
+                retval = -1;
+            }
+        }
+        if (!retval) {
             /* Find out where the new origin is by rotating the four final_rect points around the center and then taking the extremes */
             abscenterx = final_rect.x + (int)center->x;
             abscentery = final_rect.y + (int)center->y;
@@ -715,13 +764,69 @@ SW_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture,
             tmp_rect.w = dstwidth;
             tmp_rect.h = dstheight;
 
-            retval = SDL_BlitSurface(surface_rotated, NULL, surface, &tmp_rect);
-            SDL_FreeSurface(surface_rotated);
+            /* The NONE blend mode needs some special care with non-opaque surfaces.
+             * Other blend modes or opaque surfaces can be blitted directly.
+             */
+            if (blendmode != SDL_BLENDMODE_NONE || isOpaque) {
+                if (applyModulation == SDL_FALSE) {
+                    /* If the modulation wasn't already applied, make it happen now. */
+                    SDL_SetSurfaceAlphaMod(src_rotated, alphaMod);
+                    SDL_SetSurfaceColorMod(src_rotated, rMod, gMod, bMod);
+                }
+                retval = SDL_BlitSurface(src_rotated, NULL, surface, &tmp_rect);
+            } else {
+                /* The NONE blend mode requires three steps to get the pixels onto the destination surface.
+                 * First, the area where the rotated pixels will be blitted to get set to zero.
+                 * This is accomplished by simply blitting a mask with the NONE blend mode.
+                 * The colorkey set by the rotate function will discard the correct pixels.
+                 */
+                SDL_Rect mask_rect = tmp_rect;
+                SDL_SetSurfaceBlendMode(mask_rotated, SDL_BLENDMODE_NONE);
+                retval = SDL_BlitSurface(mask_rotated, NULL, surface, &mask_rect);
+                if (!retval) {
+                    /* The next step copies the alpha value. This is done with the BLEND blend mode and
+                     * by modulating the source colors with 0. Since the destination is all zeros, this
+                     * will effectively set the destination alpha to the source alpha.
+                     */
+                    SDL_SetSurfaceColorMod(src_rotated, 0, 0, 0);
+                    mask_rect = tmp_rect;
+                    retval = SDL_BlitSurface(src_rotated, NULL, surface, &mask_rect);
+                    if (!retval) {
+                        /* The last step gets the color values in place. The ADD blend mode simply adds them to
+                         * the destination (where the color values are all zero). However, because the ADD blend
+                         * mode modulates the colors with the alpha channel, a surface without an alpha mask needs
+                         * to be created. This makes all source pixels opaque and the colors get copied correctly.
+                         */
+                        SDL_Surface *src_rotated_rgb;
+                        src_rotated_rgb = SDL_CreateRGBSurfaceFrom(src_rotated->pixels, src_rotated->w, src_rotated->h,
+                                                                   src_rotated->format->BitsPerPixel, src_rotated->pitch,
+                                                                   src_rotated->format->Rmask, src_rotated->format->Gmask,
+                                                                   src_rotated->format->Bmask, 0);
+                        if (src_rotated_rgb == NULL) {
+                            retval = -1;
+                        } else {
+                            SDL_SetSurfaceBlendMode(src_rotated_rgb, SDL_BLENDMODE_ADD);
+                            retval = SDL_BlitSurface(src_rotated_rgb, NULL, surface, &tmp_rect);
+                            SDL_FreeSurface(src_rotated_rgb);
+                        }
+                    }
+                }
+                SDL_FreeSurface(mask_rotated);
+            }
+            if (src_rotated != NULL) {
+                SDL_FreeSurface(src_rotated);
+            }
         }
     }
 
-    if (surface_scaled != src) {
-        SDL_FreeSurface(surface_scaled);
+    if (SDL_MUSTLOCK(src)) {
+        SDL_UnlockSurface(src);
+    }
+    if (mask != NULL) {
+        SDL_FreeSurface(mask);
+    }
+    if (src_clone != NULL) {
+        SDL_FreeSurface(src_clone);
     }
     return retval;
 }
@@ -733,19 +838,14 @@ SW_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
     SDL_Surface *surface = SW_ActivateRenderer(renderer);
     Uint32 src_format;
     void *src_pixels;
-    SDL_Rect final_rect;
 
     if (!surface) {
         return -1;
     }
 
-    if (renderer->viewport.x || renderer->viewport.y) {
-        final_rect.x = renderer->viewport.x + rect->x;
-        final_rect.y = renderer->viewport.y + rect->y;
-        final_rect.w = rect->w;
-        final_rect.h = rect->h;
-        rect = &final_rect;
-    }
+    /* NOTE: The rect is already adjusted according to the viewport by
+     * SDL_RenderReadPixels.
+     */
 
     if (rect->x < 0 || rect->x+rect->w > surface->w ||
         rect->y < 0 || rect->y+rect->h > surface->h) {
diff --git a/src/render/software/SDL_render_sw_c.h b/src/render/software/SDL_render_sw_c.h
index 89b4e8a..0dd8a88 100644
--- a/src/render/software/SDL_render_sw_c.h
+++ b/src/render/software/SDL_render_sw_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/render/software/SDL_rotate.c b/src/render/software/SDL_rotate.c
index 0141d17..4476204 100644
--- a/src/render/software/SDL_rotate.c
+++ b/src/render/software/SDL_rotate.c
@@ -77,11 +77,6 @@ to a situation where the program can segfault.
 #define GUARD_ROWS (2)
 
 /* !
-\brief Lower limit of absolute zoom factor or rotation degrees.
-*/
-#define VALUE_LIMIT 0.001
-
-/* !
 \brief Returns colorkey info for a surface
 */
 static Uint32
@@ -142,7 +137,7 @@ SDLgfx_rotozoomSurfaceSizeTrig(int width, int height, double angle,
         cy = *cangle * y;
         sx = *sangle * x;
         sy = *sangle * y;
-        
+
         dstwidthhalf = MAX((int)
             SDL_ceil(MAX(MAX(MAX(SDL_fabs(cx + sy), SDL_fabs(cx - sy)), SDL_fabs(-cx + sy)), SDL_fabs(-cx - sy))), 1);
         dstheighthalf = MAX((int)
@@ -262,7 +257,7 @@ _transformSurfaceRGBA(SDL_Surface * src, SDL_Surface * dst, int cx, int cy, int
                 dy = (sdy >> 16);
                 if (flipx) dx = sw - dx;
                 if (flipy) dy = sh - dy;
-                if ((unsigned)dx < (unsigned)sw && (unsigned)dy < (unsigned)sh) {
+                if ((dx > -1) && (dy > -1) && (dx < (src->w-1)) && (dy < (src->h-1))) {
                     sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy) + dx;
                     c00 = *sp;
                     sp += 1;
@@ -390,10 +385,14 @@ transformSurfaceY(SDL_Surface * src, SDL_Surface * dst, int cx, int cy, int isin
 /* !
 \brief Rotates and zooms a surface with different horizontal and vertival scaling factors and optional anti-aliasing.
 
-Rotates a 32bit or 8bit 'src' surface to newly created 'dst' surface.
+Rotates a 32-bit or 8-bit 'src' surface to newly created 'dst' surface.
 'angle' is the rotation in degrees, 'centerx' and 'centery' the rotation center. If 'smooth' is set
-then the destination 32bit surface is anti-aliased. If the surface is not 8bit
-or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
+then the destination 32-bit surface is anti-aliased. 8-bit surfaces must have a colorkey. 32-bit
+surfaces must have a 8888 layout with red, green, blue and alpha masks (any ordering goes).
+The blend mode of the 'src' surface has some effects on generation of the 'dst' surface: The NONE
+mode will set the BLEND mode on the 'dst' surface. The MOD mode either generates a white 'dst'
+surface and sets the colorkey or fills the it with the colorkey before copying the pixels.
+When using the NONE and MOD modes, color and alpha modulation must be applied before using this function.
 
 \param src The surface to rotozoom.
 \param angle The angle to rotate in degrees.
@@ -413,69 +412,47 @@ or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
 SDL_Surface *
 SDLgfx_rotateSurface(SDL_Surface * src, double angle, int centerx, int centery, int smooth, int flipx, int flipy, int dstwidth, int dstheight, double cangle, double sangle)
 {
-    SDL_Surface *rz_src;
     SDL_Surface *rz_dst;
-    int is32bit, angle90;
+    int is8bit, angle90;
     int i;
-    Uint8 r = 0, g = 0, b = 0;
+    SDL_BlendMode blendmode;
     Uint32 colorkey = 0;
-    int colorKeyAvailable = 0;
+    int colorKeyAvailable = SDL_FALSE;
     double sangleinv, cangleinv;
 
-    /*
-    * Sanity check
-    */
+    /* Sanity check */
     if (src == NULL)
-        return (NULL);
+        return NULL;
 
-    if (src->flags & SDL_TRUE/* SDL_SRCCOLORKEY */)
-    {
-        colorkey = _colorkey(src);
-        SDL_GetRGB(colorkey, src->format, &r, &g, &b);
-        colorKeyAvailable = 1;
-    }
-    /*
-    * Determine if source surface is 32bit or 8bit
-    */
-    is32bit = (src->format->BitsPerPixel == 32);
-    if ((is32bit) || (src->format->BitsPerPixel == 8)) {
-        /*
-        * Use source surface 'as is'
-        */
-        rz_src = src;
-    } else {
-        rz_src = SDL_ConvertSurfaceFormat(src, SDL_PIXELFORMAT_ARGB32, src->flags);
-        if (rz_src == NULL) {
-            return NULL;
-        }
-        is32bit = 1;
+    if (SDL_GetColorKey(src, &colorkey) == 0) {
+        colorKeyAvailable = SDL_TRUE;
     }
 
-    /* Determine target size */
-    /* _rotozoomSurfaceSizeTrig(rz_src->w, rz_src->h, angle, &dstwidth, &dstheight, &cangle, &sangle); */
+    /* This function requires a 32-bit surface or 8-bit surface with a colorkey */
+    is8bit = src->format->BitsPerPixel == 8 && colorKeyAvailable;
+    if (!(is8bit || (src->format->BitsPerPixel == 32 && src->format->Amask)))
+        return NULL;
 
-    /*
-    * Calculate target factors from sin/cos and zoom
-    */
+    /* Calculate target factors from sin/cos and zoom */
     sangleinv = sangle*65536.0;
     cangleinv = cangle*65536.0;
 
-    /*
-    * Alloc space to completely contain the rotated surface
-    */
-    if (is32bit) {
-        /*
-        * Target surface is 32bit with source RGBA/ABGR ordering
-        */
-        rz_dst =
-            SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight + GUARD_ROWS, 32,
-            rz_src->format->Rmask, rz_src->format->Gmask,
-            rz_src->format->Bmask, rz_src->format->Amask);
+    /* Alloc space to completely contain the rotated surface */
+    rz_dst = NULL;
+    if (is8bit) {
+        /* Target surface is 8 bit */
+        rz_dst = SDL_CreateRGBSurface(0, dstwidth, dstheight + GUARD_ROWS, 8, 0, 0, 0, 0);
+        if (rz_dst != NULL) {
+            for (i = 0; i < src->format->palette->ncolors; i++) {
+                rz_dst->format->palette->colors[i] = src->format->palette->colors[i];
+            }
+            rz_dst->format->palette->ncolors = src->format->palette->ncolors;
+        }
     } else {
-        /*
-        * Target surface is 8bit
-        */
-        rz_dst = SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight + GUARD_ROWS, 8, 0, 0, 0, 0);
+        /* Target surface is 32 bit with source RGBA ordering */
+        rz_dst = SDL_CreateRGBSurface(0, dstwidth, dstheight + GUARD_ROWS, 32,
+                                      src->format->Rmask, src->format->Gmask,
+                                      src->format->Bmask, src->format->Amask);
     }
 
     /* Check target */
@@ -485,17 +462,32 @@ SDLgfx_rotateSurface(SDL_Surface * src, double angle, int centerx, int centery,
     /* Adjust for guard rows */
     rz_dst->h = dstheight;
 
-    if (colorKeyAvailable == 1){
-        colorkey = SDL_MapRGB(rz_dst->format, r, g, b);
-
-        SDL_FillRect(rz_dst, NULL, colorkey );
+    SDL_GetSurfaceBlendMode(src, &blendmode);
+
+    if (colorKeyAvailable == SDL_TRUE) {
+        /* If available, the colorkey will be used to discard the pixels that are outside of the rotated area. */
+        SDL_SetColorKey(rz_dst, SDL_TRUE, colorkey);
+        SDL_FillRect(rz_dst, NULL, colorkey);
+    } else if (blendmode == SDL_BLENDMODE_NONE) {
+        blendmode = SDL_BLENDMODE_BLEND;
+    } else if (blendmode == SDL_BLENDMODE_MOD) {
+        /* Without a colorkey, the target texture has to be white for the MOD blend mode so
+         * that the pixels outside the rotated area don't affect the destination surface.
+         */
+        colorkey = SDL_MapRGBA(rz_dst->format, 255, 255, 255, 0);
+        SDL_FillRect(rz_dst, NULL, colorkey);
+        /* Setting a white colorkey for the destination surface makes the final blit discard
+         * all pixels outside of the rotated area. This doesn't interfere with anything because
+         * white pixels are already a no-op and the MOD blend mode does not interact with alpha.
+         */
+        SDL_SetColorKey(rz_dst, SDL_TRUE, colorkey);
     }
 
-    /*
-    * Lock source surface
-    */
-    if (SDL_MUSTLOCK(rz_src)) {
-        SDL_LockSurface(rz_src);
+    SDL_SetSurfaceBlendMode(rz_dst, blendmode);
+
+    /* Lock source surface */
+    if (SDL_MUSTLOCK(src)) {
+        SDL_LockSurface(src);
     }
 
     /* check if the rotation is a multiple of 90 degrees so we can take a fast path and also somewhat reduce
@@ -510,70 +502,29 @@ SDLgfx_rotateSurface(SDL_Surface * src, double angle, int centerx, int centery,
         angle90 = -1;
     }
 
-    /*
-    * Check which kind of surface we have
-    */
-    if (is32bit) {
-        /*
-        * Call the 32bit transformation routine to do the rotation (using alpha)
-        */
-        if (angle90 >= 0) {
-            transformSurfaceRGBA90(rz_src, rz_dst, angle90, flipx, flipy);
+    if (is8bit) {
+        /* Call the 8-bit transformation routine to do the rotation */
+        if(angle90 >= 0) {
+            transformSurfaceY90(src, rz_dst, angle90, flipx, flipy);
         } else {
-            _transformSurfaceRGBA(rz_src, rz_dst, centerx, centery, (int) (sangleinv), (int) (cangleinv), flipx, flipy, smooth);
+            transformSurfaceY(src, rz_dst, centerx, centery, (int)sangleinv, (int)cangleinv,
+                              flipx, flipy);
         }
-        /*
-        * Turn on source-alpha support
-        */
-        /* SDL_SetAlpha(rz_dst, SDL_SRCALPHA, 255); */
-        SDL_SetColorKey(rz_dst, /* SDL_SRCCOLORKEY */ SDL_TRUE | SDL_RLEACCEL, _colorkey(rz_src));
     } else {
-        /*
-        * Copy palette and colorkey info
-        */
-        for (i = 0; i < rz_src->format->palette->ncolors; i++) {
-            rz_dst->format->palette->colors[i] = rz_src->format->palette->colors[i];
-        }
-        rz_dst->format->palette->ncolors = rz_src->format->palette->ncolors;
-        /*
-        * Call the 8bit transformation routine to do the rotation
-        */
-        if(angle90 >= 0) {
-            transformSurfaceY90(rz_src, rz_dst, angle90, flipx, flipy);
+        /* Call the 32-bit transformation routine to do the rotation */
+        if (angle90 >= 0) {
+            transformSurfaceRGBA90(src, rz_dst, angle90, flipx, flipy);
         } else {
-            transformSurfaceY(rz_src, rz_dst, centerx, centery, (int)(sangleinv), (int)(cangleinv), flipx, flipy);
+            _transformSurfaceRGBA(src, rz_dst, centerx, centery, (int)sangleinv, (int)cangleinv,
+                                  flipx, flipy, smooth);
         }
-        SDL_SetColorKey(rz_dst, /* SDL_SRCCOLORKEY */ SDL_TRUE | SDL_RLEACCEL, _colorkey(rz_src));
     }
 
-    /* copy alpha mod, color mod, and blend mode */
-    {
-      SDL_BlendMode blendMode;
-      Uint8 alphaMod, cr, cg, cb;
-      SDL_GetSurfaceAlphaMod(src, &alphaMod);
-      SDL_GetSurfaceBlendMode(src, &blendMode);
-      SDL_GetSurfaceColorMod(src, &cr, &cg, &cb);
-      SDL_SetSurfaceAlphaMod(rz_dst, alphaMod);
-      SDL_SetSurfaceBlendMode(rz_dst, blendMode);
-      SDL_SetSurfaceColorMod(rz_dst, cr, cg, cb);
-    }
-
-    /*
-    * Unlock source surface
-    */
-    if (SDL_MUSTLOCK(rz_src)) {
-        SDL_UnlockSurface(rz_src);
+    /* Unlock source surface */
+    if (SDL_MUSTLOCK(src)) {
+        SDL_UnlockSurface(src);
     }
 
-    /*
-    * Cleanup temp surface
-    */
-    if (rz_src != src) {
-        SDL_FreeSurface(rz_src);
-    }
-
-    /*
-    * Return destination surface
-    */
-    return (rz_dst);
+    /* Return rotated surface */
+    return rz_dst;
 }
diff --git a/src/render/software/SDL_rotate.h b/src/render/software/SDL_rotate.h
index 338109f..e446b41 100644
--- a/src/render/software/SDL_rotate.h
+++ b/src/render/software/SDL_rotate.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/stdlib/SDL_getenv.c b/src/stdlib/SDL_getenv.c
index 3fc4119..305307f 100644
--- a/src/stdlib/SDL_getenv.c
+++ b/src/stdlib/SDL_getenv.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -60,9 +60,7 @@ SDL_setenv(const char *name, const char *value, int overwrite)
     }
     
     if (!overwrite) {
-        char ch = 0;
-        const size_t len = GetEnvironmentVariableA(name, &ch, sizeof (ch));
-        if (len > 0) {
+        if (GetEnvironmentVariableA(name, NULL, 0) > 0) {
             return 0;  /* asked not to overwrite existing value. */
         }
     }
diff --git a/src/stdlib/SDL_iconv.c b/src/stdlib/SDL_iconv.c
index 34bcd84..cbd5d8a 100644
--- a/src/stdlib/SDL_iconv.c
+++ b/src/stdlib/SDL_iconv.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -38,6 +38,7 @@
    If we get this wrong, it's just a warning, so no big deal.
 */
 #if defined(_XGP6) || defined(__APPLE__) || \
+    defined(__EMSCRIPTEN__) || \
     (defined(__GLIBC__) && ((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)) || \
     (defined(_NEWLIB_VERSION)))
 #define ICONV_INBUF_NONCONST
@@ -797,6 +798,7 @@ SDL_iconv(SDL_iconv_t cd,
             if (ch > 0x10FFFF) {
                 ch = UNKNOWN_UNICODE;
             }
+            /* fallthrough */
         case ENCODING_UCS4BE:
             if (ch > 0x7FFFFFFF) {
                 ch = UNKNOWN_UNICODE;
@@ -818,6 +820,7 @@ SDL_iconv(SDL_iconv_t cd,
             if (ch > 0x10FFFF) {
                 ch = UNKNOWN_UNICODE;
             }
+            /* fallthrough */
         case ENCODING_UCS4LE:
             if (ch > 0x7FFFFFFF) {
                 ch = UNKNOWN_UNICODE;
diff --git a/src/stdlib/SDL_malloc.c b/src/stdlib/SDL_malloc.c
index d640c8f..db3b107 100644
--- a/src/stdlib/SDL_malloc.c
+++ b/src/stdlib/SDL_malloc.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -2946,13 +2946,17 @@ static void
 internal_malloc_stats(mstate m)
 {
     if (!PREACTION(m)) {
+#ifndef LACKS_STDIO_H
         size_t maxfp = 0;
+#endif
         size_t fp = 0;
         size_t used = 0;
         check_malloc_state(m);
         if (is_initialized(m)) {
             msegmentptr s = &m->seg;
+#ifndef LACKS_STDIO_H
             maxfp = m->max_footprint;
+#endif
             fp = m->footprint;
             used = fp - (m->topsize + TOP_FOOT_SIZE);
 
diff --git a/src/stdlib/SDL_qsort.c b/src/stdlib/SDL_qsort.c
index 2ef33b1..6233ea4 100644
--- a/src/stdlib/SDL_qsort.c
+++ b/src/stdlib/SDL_qsort.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -275,7 +275,7 @@ typedef struct { char * first; char * last; } stack_entry;
 
 /* and so is the pivoting logic (note: last is inclusive): */
 #define Pivot(swapper,sz)			\
-  if (last-first>PIVOT_THRESHOLD*sz) mid=pivot_big(first,mid,last,sz,compare);\
+  if ((size_t)(last-first)>PIVOT_THRESHOLD*sz) mid=pivot_big(first,mid,last,sz,compare);\
   else {	\
     if (compare(first,mid)<0) {			\
       if (compare(mid,last)>0) {		\
@@ -362,7 +362,7 @@ typedef struct { char * first; char * last; } stack_entry;
 
 static char * pivot_big(char *first, char *mid, char *last, size_t size,
                         int compare(const void *, const void *)) {
-  int d=(((last-first)/size)>>3)*size;
+  size_t d=(((last-first)/size)>>3)*size;
 #ifdef DEBUG_QSORT
 fprintf(stderr, "pivot_big: first=%p last=%p size=%lu n=%lu\n", first, (unsigned long)last, size, (unsigned long)((last-first+1)/size));
 #endif
@@ -413,7 +413,7 @@ static void qsort_nonaligned(void *base, size_t nmemb, size_t size,
 
   first=(char*)base; last=first+(nmemb-1)*size;
 
-  if (last-first>=trunc) {
+  if ((size_t)(last-first)>=trunc) {
     char *ffirst=first, *llast=last;
     while (1) {
       /* Select pivot */
@@ -444,7 +444,7 @@ static void qsort_aligned(void *base, size_t nmemb, size_t size,
 
   first=(char*)base; last=first+(nmemb-1)*size;
 
-  if (last-first>=trunc) {
+  if ((size_t)(last-first)>=trunc) {
     char *ffirst=first,*llast=last;
     while (1) {
       /* Select pivot */
@@ -519,7 +519,7 @@ extern void qsortG(void *base, size_t nmemb, size_t size,
            int (*compare)(const void *, const void *)) {
 
   if (nmemb<=1) return;
-  if (((int)base|size)&(WORD_BYTES-1))
+  if (((size_t)base|size)&(WORD_BYTES-1))
     qsort_nonaligned(base,nmemb,size,compare);
   else if (size!=WORD_BYTES)
     qsort_aligned(base,nmemb,size,compare);
diff --git a/src/stdlib/SDL_stdlib.c b/src/stdlib/SDL_stdlib.c
index 14ec5a9..36b5548 100644
--- a/src/stdlib/SDL_stdlib.c
+++ b/src/stdlib/SDL_stdlib.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -109,6 +109,12 @@ SDL_copysign(double x, double y)
     return copysign(x, y);
 #elif defined(HAVE__COPYSIGN)
     return _copysign(x, y);
+#elif defined(__WATCOMC__) && defined(__386__)
+    /* this is nasty as hell, but it works.. */
+    unsigned int *xi = (unsigned int *) &x,
+                 *yi = (unsigned int *) &y;
+    xi[1] = (yi[1] & 0x80000000) | (xi[1] & 0x7fffffff);
+    return x;
 #else
     return SDL_uclibc_copysign(x, y);
 #endif /* HAVE_COPYSIGN */
@@ -181,6 +187,10 @@ SDL_scalbn(double x, int n)
     return scalbn(x, n);
 #elif defined(HAVE__SCALB)
     return _scalb(x, n);
+#elif defined(HAVE_LIBC) && defined(HAVE_FLOAT_H) && (FLT_RADIX == 2)
+/* from scalbn(3): If FLT_RADIX equals 2 (which is
+ * usual), then scalbn() is equivalent to ldexp(3). */
+    return ldexp(x, n);
 #else
     return SDL_uclibc_scalbn(x, n);
 #endif /* HAVE_SCALBN */
@@ -375,35 +385,35 @@ _ftol2_sse()
     _ftol();
 }
 
-/* 64-bit math operators for 32-bit systems */
-void
-__declspec(naked)
-_allmul()
-{
-    /* *INDENT-OFF* */
-    __asm {
-        mov         eax, dword ptr[esp+8]
-        mov         ecx, dword ptr[esp+10h]
-        or          ecx, eax
-        mov         ecx, dword ptr[esp+0Ch]
-        jne         hard
-        mov         eax, dword ptr[esp+4]
-        mul         ecx
-        ret         10h
-hard:
-        push        ebx
-        mul         ecx
-        mov         ebx, eax
-        mov         eax, dword ptr[esp+8]
-        mul         dword ptr[esp+14h]
-        add         ebx, eax
-        mov         eax, dword ptr[esp+8]
-        mul         ecx
-        add         edx, ebx
-        pop         ebx
-        ret         10h
-    }
-    /* *INDENT-ON* */
+/* 64-bit math operators for 32-bit systems */
+void
+__declspec(naked)
+_allmul()
+{
+    /* *INDENT-OFF* */
+    __asm {
+        mov         eax, dword ptr[esp+8]
+        mov         ecx, dword ptr[esp+10h]
+        or          ecx, eax
+        mov         ecx, dword ptr[esp+0Ch]
+        jne         hard
+        mov         eax, dword ptr[esp+4]
+        mul         ecx
+        ret         10h
+hard:
+        push        ebx
+        mul         ecx
+        mov         ebx, eax
+        mov         eax, dword ptr[esp+8]
+        mul         dword ptr[esp+14h]
+        add         ebx, eax
+        mov         eax, dword ptr[esp+8]
+        mul         ecx
+        add         edx, ebx
+        pop         ebx
+        ret         10h
+    }
+    /* *INDENT-ON* */
 }
 
 void
@@ -914,8 +924,8 @@ _allshr()
 {
     /* *INDENT-OFF* */
     __asm {
-        cmp         cl,40h
-        jae         RETZERO
+        cmp         cl,3Fh
+        jae         RETSIGN
         cmp         cl,20h
         jae         MORE32
         shrd        eax,edx,cl
@@ -923,13 +933,13 @@ _allshr()
         ret
 MORE32:
         mov         eax,edx
-        xor         edx,edx
+        sar         edx,1Fh
         and         cl,1Fh
         sar         eax,cl
         ret
-RETZERO:
-        xor         eax,eax
-        xor         edx,edx
+RETSIGN:
+        sar         edx,1Fh
+        mov         eax,edx
         ret
     }
     /* *INDENT-ON* */
diff --git a/src/stdlib/SDL_string.c b/src/stdlib/SDL_string.c
index debbeba..1b6c393 100644
--- a/src/stdlib/SDL_string.c
+++ b/src/stdlib/SDL_string.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,24 +18,20 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-
-#if defined(__clang_analyzer__) && !defined(SDL_DISABLE_ANALYZE_MACROS)
+#if defined(__clang_analyzer__)
 #define SDL_DISABLE_ANALYZE_MACROS 1
 #endif
 
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE 1
-#endif
-
 #include "../SDL_internal.h"
 
 /* This file contains portable string manipulation functions for SDL */
 
 #include "SDL_stdinc.h"
 
-
+#if !defined(HAVE_VSSCANF) || !defined(HAVE_STRTOL) || !defined(HAVE_STRTOUL)  || !defined(HAVE_STRTOLL) || !defined(HAVE_STRTOULL) || !defined(HAVE_STRTOD)
 #define SDL_isupperhex(X)   (((X) >= 'A') && ((X) <= 'F'))
 #define SDL_islowerhex(X)   (((X) >= 'a') && ((X) <= 'f'))
+#endif
 
 #define UTF8_IsLeadByte(c) ((c) >= 0xC0 && (c) <= 0xF4)
 #define UTF8_IsTrailingByte(c) ((c) >= 0x80 && (c) <= 0xBF)
@@ -82,7 +78,7 @@ SDL_ScanLong(const char *text, int radix, long *valuep)
         value += v;
         ++text;
     }
-    if (valuep) {
+    if (valuep && text > textstart) {
         if (negative && value) {
             *valuep = -value;
         } else {
@@ -118,7 +114,7 @@ SDL_ScanUnsignedLong(const char *text, int radix, unsigned long *valuep)
         value += v;
         ++text;
     }
-    if (valuep) {
+    if (valuep && text > textstart) {
         *valuep = value;
     }
     return (text - textstart);
@@ -150,7 +146,7 @@ SDL_ScanUintPtrT(const char *text, int radix, uintptr_t * valuep)
         value += v;
         ++text;
     }
-    if (valuep) {
+    if (valuep && text > textstart) {
         *valuep = value;
     }
     return (text - textstart);
@@ -187,7 +183,7 @@ SDL_ScanLongLong(const char *text, int radix, Sint64 * valuep)
         value += v;
         ++text;
     }
-    if (valuep) {
+    if (valuep && text > textstart) {
         if (negative && value) {
             *valuep = -value;
         } else {
@@ -223,7 +219,7 @@ SDL_ScanUnsignedLongLong(const char *text, int radix, Uint64 * valuep)
         value += v;
         ++text;
     }
-    if (valuep) {
+    if (valuep && text > textstart) {
         *valuep = value;
     }
     return (text - textstart);
@@ -255,7 +251,7 @@ SDL_ScanFloat(const char *text, double *valuep)
             ++text;
         }
     }
-    if (valuep) {
+    if (valuep && text > textstart) {
         if (negative && value) {
             *valuep = -value;
         } else {
@@ -465,6 +461,22 @@ SDL_wcslcat(SDL_INOUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t max
 #endif /* HAVE_WCSLCAT */
 }
 
+int
+SDL_wcscmp(const wchar_t *str1, const wchar_t *str2)
+{
+#if defined(HAVE_WCSCMP)
+    return wcscmp(str1, str2);
+#else
+    while (*str1 && *str2) {
+        if (*str1 != *str2)
+            break;
+        ++str1;
+        ++str2;
+    }
+    return (int)(*str1 - *str2);
+#endif /* HAVE_WCSCMP */
+}
+
 size_t
 SDL_strlcpy(SDL_OUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen)
 {
@@ -481,7 +493,8 @@ SDL_strlcpy(SDL_OUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen)
 #endif /* HAVE_STRLCPY */
 }
 
-size_t SDL_utf8strlcpy(SDL_OUT_Z_CAP(dst_bytes) char *dst, const char *src, size_t dst_bytes)
+size_t
+SDL_utf8strlcpy(SDL_OUT_Z_CAP(dst_bytes) char *dst, const char *src, size_t dst_bytes)
 {
     size_t src_bytes = SDL_strlen(src);
     size_t bytes = SDL_min(src_bytes, dst_bytes - 1);
@@ -514,6 +527,23 @@ size_t SDL_utf8strlcpy(SDL_OUT_Z_CAP(dst_bytes) char *dst, const char *src, size
 }
 
 size_t
+SDL_utf8strlen(const char *str)
+{
+    size_t retval = 0;
+    const char *p = str;
+    char ch;
+
+    while ((ch = *(p++))) {
+        /* if top two bits are 1 and 0, it's a continuation byte. */
+        if ((ch & 0xc0) != 0x80) {
+            retval++;
+        }
+    }
+    
+    return retval;
+}
+
+size_t
 SDL_strlcat(SDL_INOUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen)
 {
 #if defined(HAVE_STRLCAT)
@@ -789,7 +819,7 @@ SDL_strtol(const char *string, char **endp, int base)
     return strtol(string, endp, base);
 #else
     size_t len;
-    long value;
+    long value = 0;
 
     if (!base) {
         if ((SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0)) {
@@ -814,7 +844,7 @@ SDL_strtoul(const char *string, char **endp, int base)
     return strtoul(string, endp, base);
 #else
     size_t len;
-    unsigned long value;
+    unsigned long value = 0;
 
     if (!base) {
         if ((SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0)) {
@@ -839,7 +869,7 @@ SDL_strtoll(const char *string, char **endp, int base)
     return strtoll(string, endp, base);
 #else
     size_t len;
-    Sint64 value;
+    Sint64 value = 0;
 
     if (!base) {
         if ((SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0)) {
@@ -864,7 +894,7 @@ SDL_strtoull(const char *string, char **endp, int base)
     return strtoull(string, endp, base);
 #else
     size_t len;
-    Uint64 value;
+    Uint64 value = 0;
 
     if (!base) {
         if ((SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0)) {
@@ -889,7 +919,7 @@ SDL_strtod(const char *string, char **endp)
     return strtod(string, endp);
 #else
     size_t len;
-    double value;
+    double value = 0.0;
 
     len = SDL_ScanFloat(string, &value);
     if (endp) {
@@ -911,7 +941,7 @@ SDL_strcmp(const char *str1, const char *str2)
         ++str1;
         ++str2;
     }
-    return (int) ((unsigned char) *str1 - (unsigned char) *str2);
+    return (int)((unsigned char) *str1 - (unsigned char) *str2);
 #endif /* HAVE_STRCMP */
 }
 
@@ -1011,6 +1041,10 @@ SDL_vsscanf(const char *text, const char *fmt, va_list ap)
 {
     int retval = 0;
 
+    if (!text || !*text) {
+        return -1;
+    }
+
     while (*fmt) {
         if (*fmt == ' ') {
             while (SDL_isspace((unsigned char) *text)) {
@@ -1030,6 +1064,7 @@ SDL_vsscanf(const char *text, const char *fmt, va_list ap)
                 DO_LONG,
                 DO_LONGLONG
             } inttype = DO_INT;
+            size_t advance;
             SDL_bool suppress = SDL_FALSE;
 
             ++fmt;
@@ -1109,16 +1144,18 @@ SDL_vsscanf(const char *text, const char *fmt, va_list ap)
                 case 'd':
                     if (inttype == DO_LONGLONG) {
                         Sint64 value;
-                        text += SDL_ScanLongLong(text, radix, &value);
-                        if (!suppress) {
+                        advance = SDL_ScanLongLong(text, radix, &value);
+                        text += advance;
+                        if (advance && !suppress) {
                             Sint64 *valuep = va_arg(ap, Sint64 *);
                             *valuep = value;
                             ++retval;
                         }
                     } else {
                         long value;
-                        text += SDL_ScanLong(text, radix, &value);
-                        if (!suppress) {
+                        advance = SDL_ScanLong(text, radix, &value);
+                        text += advance;
+                        if (advance && !suppress) {
                             switch (inttype) {
                             case DO_SHORT:
                                 {
@@ -1160,17 +1197,19 @@ SDL_vsscanf(const char *text, const char *fmt, va_list ap)
                     /* Fall through to unsigned handling */
                 case 'u':
                     if (inttype == DO_LONGLONG) {
-                        Uint64 value;
-                        text += SDL_ScanUnsignedLongLong(text, radix, &value);
-                        if (!suppress) {
+                        Uint64 value = 0;
+                        advance = SDL_ScanUnsignedLongLong(text, radix, &value);
+                        text += advance;
+                        if (advance && !suppress) {
                             Uint64 *valuep = va_arg(ap, Uint64 *);
                             *valuep = value;
                             ++retval;
                         }
                     } else {
-                        unsigned long value;
-                        text += SDL_ScanUnsignedLong(text, radix, &value);
-                        if (!suppress) {
+                        unsigned long value = 0;
+                        advance = SDL_ScanUnsignedLong(text, radix, &value);
+                        text += advance;
+                        if (advance && !suppress) {
                             switch (inttype) {
                             case DO_SHORT:
                                 {
@@ -1201,9 +1240,10 @@ SDL_vsscanf(const char *text, const char *fmt, va_list ap)
                     break;
                 case 'p':
                     {
-                        uintptr_t value;
-                        text += SDL_ScanUintPtrT(text, 16, &value);
-                        if (!suppress) {
+                        uintptr_t value = 0;
+                        advance = SDL_ScanUintPtrT(text, 16, &value);
+                        text += advance;
+                        if (advance && !suppress) {
                             void **valuep = va_arg(ap, void **);
                             *valuep = (void *) value;
                             ++retval;
@@ -1214,8 +1254,9 @@ SDL_vsscanf(const char *text, const char *fmt, va_list ap)
                 case 'f':
                     {
                         double value;
-                        text += SDL_ScanFloat(text, &value);
-                        if (!suppress) {
+                        advance = SDL_ScanFloat(text, &value);
+                        text += advance;
+                        if (advance && !suppress) {
                             float *valuep = va_arg(ap, float *);
                             *valuep = (float) value;
                             ++retval;
@@ -1317,6 +1358,10 @@ SDL_PrintString(char *text, size_t maxlen, SDL_FormatInfo *info, const char *str
     size_t length = 0;
     size_t slen;
 
+    if (string == NULL) {
+        string = "(null)";
+    }
+
     if (info && info->width && (size_t)info->width > SDL_strlen(string)) {
         char fill = info->pad_zeroes ? '0' : ' ';
         size_t width = info->width - SDL_strlen(string);
@@ -1488,7 +1533,7 @@ SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt,
     if (!fmt) {
         fmt = "";
     }
-    while (*fmt) {
+    while (*fmt && left > 1) {
         if (*fmt == '%') {
             SDL_bool done = SDL_FALSE;
             size_t len = 0;
@@ -1632,6 +1677,16 @@ SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt,
                     len = SDL_PrintFloat(text, left, &info, va_arg(ap, double));
                     done = SDL_TRUE;
                     break;
+                case 'S':
+                    {
+                        /* In practice this is used on Windows for WCHAR strings */
+                        wchar_t *wide_arg = va_arg(ap, wchar_t *);
+                        char *arg = SDL_iconv_string("UTF-8", "UTF-16LE", (char *)(wide_arg), (SDL_wcslen(wide_arg)+1)*sizeof(*wide_arg));
+                        len = SDL_PrintString(text, left, &info, arg);
+                        SDL_free(arg);
+                        done = SDL_TRUE;
+                    }
+                    break;
                 case 's':
                     len = SDL_PrintString(text, left, &info, va_arg(ap, char *));
                     done = SDL_TRUE;
@@ -1650,12 +1705,8 @@ SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt,
                 left -= len;
             }
         } else {
-            if (left > 1) {
-                *text = *fmt;
-                --left;
-            }
-            ++fmt;
-            ++text;
+            *text++ = *fmt++;
+            --left;
         }
     }
     if (left > 0) {
diff --git a/src/test/SDL_test_assert.c b/src/test/SDL_test_assert.c
index ee2f132..5362201 100644
--- a/src/test/SDL_test_assert.c
+++ b/src/test/SDL_test_assert.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -148,3 +148,5 @@ int SDLTest_AssertSummaryToTestResult()
         }
     }
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_common.c b/src/test/SDL_test_common.c
index 1d0b005..5bade2a 100644
--- a/src/test/SDL_test_common.c
+++ b/src/test/SDL_test_common.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -32,6 +32,18 @@
 #define AUDIO_USAGE \
 "[--rate N] [--format U8|S8|U16|U16LE|U16BE|S16|S16LE|S16BE] [--channels N] [--samples N]"
 
+static void SDL_snprintfcat(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ... )
+{
+    size_t length = SDL_strlen(text);
+    va_list ap;
+
+    va_start(ap, fmt);
+    text += length;
+    maxlen -= length;
+    SDL_vsnprintf(text, maxlen, fmt, ap);
+    va_end(ap);
+}
+
 SDLTest_CommonState *
 SDLTest_CommonCreateState(char **argv, Uint32 flags)
 {
@@ -463,123 +475,129 @@ SDLTest_CommonUsage(SDLTest_CommonState * state)
 }
 
 static void
-SDLTest_PrintRendererFlag(Uint32 flag)
+SDLTest_PrintRendererFlag(char *text, size_t maxlen, Uint32 flag)
 {
     switch (flag) {
-    case SDL_RENDERER_PRESENTVSYNC:
-        fprintf(stderr, "PresentVSync");
+    case SDL_RENDERER_SOFTWARE:
+        SDL_snprintfcat(text, maxlen, "Software");
         break;
     case SDL_RENDERER_ACCELERATED:
-        fprintf(stderr, "Accelerated");
+        SDL_snprintfcat(text, maxlen, "Accelerated");
+        break;
+    case SDL_RENDERER_PRESENTVSYNC:
+        SDL_snprintfcat(text, maxlen, "PresentVSync");
+        break;
+    case SDL_RENDERER_TARGETTEXTURE:
+        SDL_snprintfcat(text, maxlen, "TargetTexturesSupported");
         break;
     default:
-        fprintf(stderr, "0x%8.8x", flag);
+        SDL_snprintfcat(text, maxlen, "0x%8.8x", flag);
         break;
     }
 }
 
 static void
-SDLTest_PrintPixelFormat(Uint32 format)
+SDLTest_PrintPixelFormat(char *text, size_t maxlen, Uint32 format)
 {
     switch (format) {
     case SDL_PIXELFORMAT_UNKNOWN:
-        fprintf(stderr, "Unknwon");
+        SDL_snprintfcat(text, maxlen, "Unknown");
         break;
     case SDL_PIXELFORMAT_INDEX1LSB:
-        fprintf(stderr, "Index1LSB");
+        SDL_snprintfcat(text, maxlen, "Index1LSB");
         break;
     case SDL_PIXELFORMAT_INDEX1MSB:
-        fprintf(stderr, "Index1MSB");
+        SDL_snprintfcat(text, maxlen, "Index1MSB");
         break;
     case SDL_PIXELFORMAT_INDEX4LSB:
-        fprintf(stderr, "Index4LSB");
+        SDL_snprintfcat(text, maxlen, "Index4LSB");
         break;
     case SDL_PIXELFORMAT_INDEX4MSB:
-        fprintf(stderr, "Index4MSB");
+        SDL_snprintfcat(text, maxlen, "Index4MSB");
         break;
     case SDL_PIXELFORMAT_INDEX8:
-        fprintf(stderr, "Index8");
+        SDL_snprintfcat(text, maxlen, "Index8");
         break;
     case SDL_PIXELFORMAT_RGB332:
-        fprintf(stderr, "RGB332");
+        SDL_snprintfcat(text, maxlen, "RGB332");
         break;
     case SDL_PIXELFORMAT_RGB444:
-        fprintf(stderr, "RGB444");
+        SDL_snprintfcat(text, maxlen, "RGB444");
         break;
     case SDL_PIXELFORMAT_RGB555:
-        fprintf(stderr, "RGB555");
+        SDL_snprintfcat(text, maxlen, "RGB555");
         break;
     case SDL_PIXELFORMAT_BGR555:
-        fprintf(stderr, "BGR555");
+        SDL_snprintfcat(text, maxlen, "BGR555");
         break;
     case SDL_PIXELFORMAT_ARGB4444:
-        fprintf(stderr, "ARGB4444");
+        SDL_snprintfcat(text, maxlen, "ARGB4444");
         break;
     case SDL_PIXELFORMAT_ABGR4444:
-        fprintf(stderr, "ABGR4444");
+        SDL_snprintfcat(text, maxlen, "ABGR4444");
         break;
     case SDL_PIXELFORMAT_ARGB1555:
-        fprintf(stderr, "ARGB1555");
+        SDL_snprintfcat(text, maxlen, "ARGB1555");
         break;
     case SDL_PIXELFORMAT_ABGR1555:
-        fprintf(stderr, "ABGR1555");
+        SDL_snprintfcat(text, maxlen, "ABGR1555");
         break;
     case SDL_PIXELFORMAT_RGB565:
-        fprintf(stderr, "RGB565");
+        SDL_snprintfcat(text, maxlen, "RGB565");
         break;
     case SDL_PIXELFORMAT_BGR565:
-        fprintf(stderr, "BGR565");
+        SDL_snprintfcat(text, maxlen, "BGR565");
         break;
     case SDL_PIXELFORMAT_RGB24:
-        fprintf(stderr, "RGB24");
+        SDL_snprintfcat(text, maxlen, "RGB24");
         break;
     case SDL_PIXELFORMAT_BGR24:
-        fprintf(stderr, "BGR24");
+        SDL_snprintfcat(text, maxlen, "BGR24");
         break;
     case SDL_PIXELFORMAT_RGB888:
-        fprintf(stderr, "RGB888");
+        SDL_snprintfcat(text, maxlen, "RGB888");
         break;
     case SDL_PIXELFORMAT_BGR888:
-        fprintf(stderr, "BGR888");
+        SDL_snprintfcat(text, maxlen, "BGR888");
         break;
     case SDL_PIXELFORMAT_ARGB8888:
-        fprintf(stderr, "ARGB8888");
+        SDL_snprintfcat(text, maxlen, "ARGB8888");
         break;
     case SDL_PIXELFORMAT_RGBA8888:
-        fprintf(stderr, "RGBA8888");
+        SDL_snprintfcat(text, maxlen, "RGBA8888");
         break;
     case SDL_PIXELFORMAT_ABGR8888:
-        fprintf(stderr, "ABGR8888");
+        SDL_snprintfcat(text, maxlen, "ABGR8888");
         break;
     case SDL_PIXELFORMAT_BGRA8888:
-        fprintf(stderr, "BGRA8888");
+        SDL_snprintfcat(text, maxlen, "BGRA8888");
         break;
     case SDL_PIXELFORMAT_ARGB2101010:
-        fprintf(stderr, "ARGB2101010");
+        SDL_snprintfcat(text, maxlen, "ARGB2101010");
         break;
     case SDL_PIXELFORMAT_YV12:
-        fprintf(stderr, "YV12");
+        SDL_snprintfcat(text, maxlen, "YV12");
         break;
     case SDL_PIXELFORMAT_IYUV:
-        fprintf(stderr, "IYUV");
+        SDL_snprintfcat(text, maxlen, "IYUV");
         break;
     case SDL_PIXELFORMAT_YUY2:
-        fprintf(stderr, "YUY2");
+        SDL_snprintfcat(text, maxlen, "YUY2");
         break;
     case SDL_PIXELFORMAT_UYVY:
-        fprintf(stderr, "UYVY");
+        SDL_snprintfcat(text, maxlen, "UYVY");
         break;
     case SDL_PIXELFORMAT_YVYU:
-        fprintf(stderr, "YVYU");
+        SDL_snprintfcat(text, maxlen, "YVYU");
         break;
     case SDL_PIXELFORMAT_NV12:
-        fprintf(stderr, "NV12");
+        SDL_snprintfcat(text, maxlen, "NV12");
         break;
     case SDL_PIXELFORMAT_NV21:
-        fprintf(stderr, "NV21");
+        SDL_snprintfcat(text, maxlen, "NV21");
         break;
     default:
-        fprintf(stderr, "0x%8.8x", format);
+        SDL_snprintfcat(text, maxlen, "0x%8.8x", format);
         break;
     }
 }
@@ -588,35 +606,37 @@ static void
 SDLTest_PrintRenderer(SDL_RendererInfo * info)
 {
     int i, count;
+    char text[1024];
 
-    fprintf(stderr, "  Renderer %s:\n", info->name);
+    SDL_Log("  Renderer %s:\n", info->name);
 
-    fprintf(stderr, "    Flags: 0x%8.8X", info->flags);
-    fprintf(stderr, " (");
+    SDL_snprintf(text, sizeof(text), "    Flags: 0x%8.8X", info->flags);
+    SDL_snprintfcat(text, sizeof(text), " (");
     count = 0;
     for (i = 0; i < sizeof(info->flags) * 8; ++i) {
         Uint32 flag = (1 << i);
         if (info->flags & flag) {
             if (count > 0) {
-                fprintf(stderr, " | ");
+                SDL_snprintfcat(text, sizeof(text), " | ");
             }
-            SDLTest_PrintRendererFlag(flag);
+            SDLTest_PrintRendererFlag(text, sizeof(text), flag);
             ++count;
         }
     }
-    fprintf(stderr, ")\n");
+    SDL_snprintfcat(text, sizeof(text), ")");
+    SDL_Log("%s\n", text);
 
-    fprintf(stderr, "    Texture formats (%d): ", info->num_texture_formats);
+    SDL_snprintf(text, sizeof(text), "    Texture formats (%d): ", info->num_texture_formats);
     for (i = 0; i < (int) info->num_texture_formats; ++i) {
         if (i > 0) {
-            fprintf(stderr, ", ");
+            SDL_snprintfcat(text, sizeof(text), ", ");
         }
-        SDLTest_PrintPixelFormat(info->texture_formats[i]);
+        SDLTest_PrintPixelFormat(text, sizeof(text), info->texture_formats[i]);
     }
-    fprintf(stderr, "\n");
+    SDL_Log("%s\n", text);
 
     if (info->max_texture_width || info->max_texture_height) {
-        fprintf(stderr, "    Max Texture Size: %dx%d\n",
+        SDL_Log("    Max Texture Size: %dx%d\n",
                 info->max_texture_width, info->max_texture_height);
     }
 }
@@ -629,7 +649,7 @@ SDLTest_LoadIcon(const char *file)
     /* Load the icon surface */
     icon = SDL_LoadBMP(file);
     if (icon == NULL) {
-        fprintf(stderr, "Couldn't load %s: %s\n", file, SDL_GetError());
+        SDL_Log("Couldn't load %s: %s\n", file, SDL_GetError());
         return (NULL);
     }
 
@@ -646,30 +666,31 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
 {
     int i, j, m, n, w, h;
     SDL_DisplayMode fullscreen_mode;
+    char text[1024];
 
     if (state->flags & SDL_INIT_VIDEO) {
         if (state->verbose & VERBOSE_VIDEO) {
             n = SDL_GetNumVideoDrivers();
             if (n == 0) {
-                fprintf(stderr, "No built-in video drivers\n");
+                SDL_Log("No built-in video drivers\n");
             } else {
-                fprintf(stderr, "Built-in video drivers:");
+                SDL_snprintf(text, sizeof(text), "Built-in video drivers:");
                 for (i = 0; i < n; ++i) {
                     if (i > 0) {
-                        fprintf(stderr, ",");
+                        SDL_snprintfcat(text, sizeof(text), ",");
                     }
-                    fprintf(stderr, " %s", SDL_GetVideoDriver(i));
+                    SDL_snprintfcat(text, sizeof(text), " %s", SDL_GetVideoDriver(i));
                 }
-                fprintf(stderr, "\n");
+                SDL_Log("%s\n", text);
             }
         }
         if (SDL_VideoInit(state->videodriver) < 0) {
-            fprintf(stderr, "Couldn't initialize video driver: %s\n",
+            SDL_Log("Couldn't initialize video driver: %s\n",
                     SDL_GetError());
             return SDL_FALSE;
         }
         if (state->verbose & VERBOSE_VIDEO) {
-            fprintf(stderr, "Video driver: %s\n",
+            SDL_Log("Video driver: %s\n",
                     SDL_GetCurrentVideoDriver());
         }
 
@@ -706,7 +727,9 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
         }
 
         if (state->verbose & VERBOSE_MODES) {
-            SDL_Rect bounds;
+            SDL_Rect bounds, usablebounds;
+            float hdpi = 0;
+            float vdpi = 0;
             SDL_DisplayMode mode;
             int bpp;
             Uint32 Rmask, Gmask, Bmask, Amask;
@@ -715,53 +738,58 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
 			int outputIndex = 0;
 #endif
             n = SDL_GetNumVideoDisplays();
-            fprintf(stderr, "Number of displays: %d\n", n);
+            SDL_Log("Number of displays: %d\n", n);
             for (i = 0; i < n; ++i) {
-                fprintf(stderr, "Display %d: %s\n", i, SDL_GetDisplayName(i));
+                SDL_Log("Display %d: %s\n", i, SDL_GetDisplayName(i));
 
                 SDL_zero(bounds);
                 SDL_GetDisplayBounds(i, &bounds);
-                fprintf(stderr, "Bounds: %dx%d at %d,%d\n", bounds.w, bounds.h, bounds.x, bounds.y);
+
+                SDL_zero(usablebounds);
+                SDL_GetDisplayUsableBounds(i, &usablebounds);
+
+                SDL_GetDisplayDPI(i, NULL, &hdpi, &vdpi);
+
+                SDL_Log("Bounds: %dx%d at %d,%d\n", bounds.w, bounds.h, bounds.x, bounds.y);
+                SDL_Log("Usable bounds: %dx%d at %d,%d\n", usablebounds.w, usablebounds.h, usablebounds.x, usablebounds.y);
+                SDL_Log("DPI: %fx%f\n", hdpi, vdpi);
 
                 SDL_GetDesktopDisplayMode(i, &mode);
                 SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask,
                                            &Bmask, &Amask);
-                fprintf(stderr,
-                        "  Current mode: %dx%d@%dHz, %d bits-per-pixel (%s)\n",
+                SDL_Log("  Current mode: %dx%d@%dHz, %d bits-per-pixel (%s)\n",
                         mode.w, mode.h, mode.refresh_rate, bpp,
                         SDL_GetPixelFormatName(mode.format));
                 if (Rmask || Gmask || Bmask) {
-                    fprintf(stderr, "      Red Mask   = 0x%.8x\n", Rmask);
-                    fprintf(stderr, "      Green Mask = 0x%.8x\n", Gmask);
-                    fprintf(stderr, "      Blue Mask  = 0x%.8x\n", Bmask);
+                    SDL_Log("      Red Mask   = 0x%.8x\n", Rmask);
+                    SDL_Log("      Green Mask = 0x%.8x\n", Gmask);
+                    SDL_Log("      Blue Mask  = 0x%.8x\n", Bmask);
                     if (Amask)
-                        fprintf(stderr, "      Alpha Mask = 0x%.8x\n", Amask);
+                        SDL_Log("      Alpha Mask = 0x%.8x\n", Amask);
                 }
 
                 /* Print available fullscreen video modes */
                 m = SDL_GetNumDisplayModes(i);
                 if (m == 0) {
-                    fprintf(stderr, "No available fullscreen video modes\n");
+                    SDL_Log("No available fullscreen video modes\n");
                 } else {
-                    fprintf(stderr, "  Fullscreen video modes:\n");
+                    SDL_Log("  Fullscreen video modes:\n");
                     for (j = 0; j < m; ++j) {
                         SDL_GetDisplayMode(i, j, &mode);
                         SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask,
                                                    &Gmask, &Bmask, &Amask);
-                        fprintf(stderr,
-                                "    Mode %d: %dx%d@%dHz, %d bits-per-pixel (%s)\n",
+						SDL_Log("    Mode %d: %dx%d@%dHz, %d bits-per-pixel (%s)\n",
                                 j, mode.w, mode.h, mode.refresh_rate, bpp,
                                 SDL_GetPixelFormatName(mode.format));
                         if (Rmask || Gmask || Bmask) {
-                            fprintf(stderr, "        Red Mask   = 0x%.8x\n",
+                            SDL_Log("        Red Mask   = 0x%.8x\n",
                                     Rmask);
-                            fprintf(stderr, "        Green Mask = 0x%.8x\n",
+                            SDL_Log("        Green Mask = 0x%.8x\n",
                                     Gmask);
-                            fprintf(stderr, "        Blue Mask  = 0x%.8x\n",
+                            SDL_Log("        Blue Mask  = 0x%.8x\n",
                                     Bmask);
                             if (Amask)
-                                fprintf(stderr,
-                                        "        Alpha Mask = 0x%.8x\n",
+								SDL_Log("        Alpha Mask = 0x%.8x\n",
                                         Amask);
                         }
                     }
@@ -770,11 +798,11 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
 #if SDL_VIDEO_DRIVER_WINDOWS
 				/* Print the D3D9 adapter index */
 				adapterIndex = SDL_Direct3D9GetAdapterIndex( i );
-				fprintf( stderr, "D3D9 Adapter Index: %d", adapterIndex );
+				SDL_Log("D3D9 Adapter Index: %d", adapterIndex);
 
 				/* Print the DXGI adapter and output indices */
 				SDL_DXGIGetOutputInfo(i, &adapterIndex, &outputIndex);
-				fprintf( stderr, "DXGI Adapter Index: %d  Output Index: %d", adapterIndex, outputIndex );
+				SDL_Log("DXGI Adapter Index: %d  Output Index: %d", adapterIndex, outputIndex);
 #endif
             }
         }
@@ -784,9 +812,9 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
 
             n = SDL_GetNumRenderDrivers();
             if (n == 0) {
-                fprintf(stderr, "No built-in render drivers\n");
+                SDL_Log("No built-in render drivers\n");
             } else {
-                fprintf(stderr, "Built-in render drivers:\n");
+                SDL_Log("Built-in render drivers:\n");
                 for (i = 0; i < n; ++i) {
                     SDL_GetRenderDriverInfo(i, &info);
                     SDLTest_PrintRenderer(&info);
@@ -815,16 +843,16 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
         fullscreen_mode.refresh_rate = state->refresh_rate;
 
         state->windows =
-            (SDL_Window **) SDL_malloc(state->num_windows *
+            (SDL_Window **) SDL_calloc(state->num_windows,
                                         sizeof(*state->windows));
         state->renderers =
-            (SDL_Renderer **) SDL_malloc(state->num_windows *
+            (SDL_Renderer **) SDL_calloc(state->num_windows,
                                         sizeof(*state->renderers));
         state->targets =
-            (SDL_Texture **) SDL_malloc(state->num_windows *
+            (SDL_Texture **) SDL_calloc(state->num_windows,
                                         sizeof(*state->targets));
         if (!state->windows || !state->renderers) {
-            fprintf(stderr, "Out of memory!\n");
+            SDL_Log("Out of memory!\n");
             return SDL_FALSE;
         }
         for (i = 0; i < state->num_windows; ++i) {
@@ -841,7 +869,7 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
                                  state->window_w, state->window_h,
                                  state->window_flags);
             if (!state->windows[i]) {
-                fprintf(stderr, "Couldn't create window: %s\n",
+                SDL_Log("Couldn't create window: %s\n",
                         SDL_GetError());
                 return SDL_FALSE;
             }
@@ -859,7 +887,7 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
                 state->window_h = h;
             }
             if (SDL_SetWindowDisplayMode(state->windows[i], &fullscreen_mode) < 0) {
-                fprintf(stderr, "Can't set up fullscreen display mode: %s\n",
+                SDL_Log("Can't set up fullscreen display mode: %s\n",
                         SDL_GetError());
                 return SDL_FALSE;
             }
@@ -874,12 +902,9 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
 
             SDL_ShowWindow(state->windows[i]);
 
-            state->renderers[i] = NULL;
-            state->targets[i] = NULL;
-
             if (!state->skip_renderer
                 && (state->renderdriver
-                    || !(state->window_flags & SDL_WINDOW_OPENGL))) {
+                    || !(state->window_flags & (SDL_WINDOW_OPENGL | SDL_WINDOW_VULKAN)))) {
                 m = -1;
                 if (state->renderdriver) {
                     SDL_RendererInfo info;
@@ -893,8 +918,7 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
                         }
                     }
                     if (m == -1) {
-                        fprintf(stderr,
-                                "Couldn't find render driver named %s",
+						SDL_Log("Couldn't find render driver named %s",
                                 state->renderdriver);
                         return SDL_FALSE;
                     }
@@ -902,7 +926,7 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
                 state->renderers[i] = SDL_CreateRenderer(state->windows[i],
                                             m, state->render_flags);
                 if (!state->renderers[i]) {
-                    fprintf(stderr, "Couldn't create renderer: %s\n",
+                    SDL_Log("Couldn't create renderer: %s\n",
                             SDL_GetError());
                     return SDL_FALSE;
                 }
@@ -914,7 +938,7 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
                 if (state->verbose & VERBOSE_RENDER) {
                     SDL_RendererInfo info;
 
-                    fprintf(stderr, "Current renderer:\n");
+                    SDL_Log("Current renderer:\n");
                     SDL_GetRendererInfo(state->renderers[i], &info);
                     SDLTest_PrintRenderer(&info);
                 }
@@ -926,30 +950,30 @@ SDLTest_CommonInit(SDLTest_CommonState * state)
         if (state->verbose & VERBOSE_AUDIO) {
             n = SDL_GetNumAudioDrivers();
             if (n == 0) {
-                fprintf(stderr, "No built-in audio drivers\n");
+                SDL_Log("No built-in audio drivers\n");
             } else {
-                fprintf(stderr, "Built-in audio drivers:");
+                SDL_snprintf(text, sizeof(text), "Built-in audio drivers:");
                 for (i = 0; i < n; ++i) {
                     if (i > 0) {
-                        fprintf(stderr, ",");
+                        SDL_snprintfcat(text, sizeof(text), ",");
                     }
-                    fprintf(stderr, " %s", SDL_GetAudioDriver(i));
+                    SDL_snprintfcat(text, sizeof(text), " %s", SDL_GetAudioDriver(i));
                 }
-                fprintf(stderr, "\n");
+                SDL_Log("%s\n", text);
             }
         }
         if (SDL_AudioInit(state->audiodriver) < 0) {
-            fprintf(stderr, "Couldn't initialize audio driver: %s\n",
+            SDL_Log("Couldn't initialize audio driver: %s\n",
                     SDL_GetError());
             return SDL_FALSE;
         }
         if (state->verbose & VERBOSE_VIDEO) {
-            fprintf(stderr, "Audio driver: %s\n",
+            SDL_Log("Audio driver: %s\n",
                     SDL_GetCurrentAudioDriver());
         }
 
         if (SDL_OpenAudio(&state->audiospec, NULL) < 0) {
-            fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
+            SDL_Log("Couldn't open audio: %s\n", SDL_GetError());
             return SDL_FALSE;
         }
     }
@@ -1071,7 +1095,7 @@ SDLTest_PrintEvent(SDL_Event * event)
             SDL_Log("SDL EVENT: Window %d hit test", event->window.windowID);
             break;
         default:
-            SDL_Log("SDL EVENT: Window %d got unknown event %d",
+            SDL_Log("SDL EVENT: Window %d got unknown event 0x%4.4x",
                     event->window.windowID, event->window.event);
             break;
         }
@@ -1090,10 +1114,17 @@ SDLTest_PrintEvent(SDL_Event * event)
                 SDL_GetScancodeName(event->key.keysym.scancode),
                 event->key.keysym.sym, SDL_GetKeyName(event->key.keysym.sym));
         break;
+    case SDL_TEXTEDITING:
+        SDL_Log("SDL EVENT: Keyboard: text editing \"%s\" in window %d",
+                event->edit.text, event->edit.windowID);
+        break;
     case SDL_TEXTINPUT:
         SDL_Log("SDL EVENT: Keyboard: text input \"%s\" in window %d",
                 event->text.text, event->text.windowID);
         break;
+    case SDL_KEYMAPCHANGED:
+        SDL_Log("SDL EVENT: Keymap changed");
+        break;
     case SDL_MOUSEMOTION:
         SDL_Log("SDL EVENT: Mouse: moved to %d,%d (%d,%d) in window %d",
                 event->motion.x, event->motion.y,
@@ -1200,6 +1231,13 @@ SDLTest_PrintEvent(SDL_Event * event)
         SDL_Log("SDL EVENT: Clipboard updated");
         break;
 
+    case SDL_FINGERMOTION:
+        SDL_Log("SDL EVENT: Finger: motion touch=%ld, finger=%ld, x=%f, y=%f, dx=%f, dy=%f, pressure=%f",
+                (long) event->tfinger.touchId,
+                (long) event->tfinger.fingerId,
+                event->tfinger.x, event->tfinger.y,
+                event->tfinger.dx, event->tfinger.dy, event->tfinger.pressure);
+        break;
     case SDL_FINGERDOWN:
     case SDL_FINGERUP:
         SDL_Log("SDL EVENT: Finger: %s touch=%ld, finger=%ld, x=%f, y=%f, dx=%f, dy=%f, pressure=%f",
@@ -1210,10 +1248,10 @@ SDLTest_PrintEvent(SDL_Event * event)
                 event->tfinger.dx, event->tfinger.dy, event->tfinger.pressure);
         break;
     case SDL_DOLLARGESTURE:
-        SDL_Log("SDL_EVENT: Dollar gesture detect: %"SDL_PRIs64, (Sint64) event->dgesture.gestureId);
+        SDL_Log("SDL_EVENT: Dollar gesture detect: %ld", (long) event->dgesture.gestureId);
         break;
     case SDL_DOLLARRECORD:
-        SDL_Log("SDL_EVENT: Dollar gesture record: %"SDL_PRIs64, (Sint64) event->dgesture.gestureId);
+        SDL_Log("SDL_EVENT: Dollar gesture record: %ld", (long) event->dgesture.gestureId);
         break;
     case SDL_MULTIGESTURE:
         SDL_Log("SDL_EVENT: Multi gesture fingers: %d", event->mgesture.numFingers);
@@ -1226,6 +1264,25 @@ SDLTest_PrintEvent(SDL_Event * event)
         SDL_Log("SDL EVENT: render targets reset");
         break;
 
+    case SDL_APP_TERMINATING:
+        SDL_Log("SDL EVENT: App terminating");
+        break;
+    case SDL_APP_LOWMEMORY:
+        SDL_Log("SDL EVENT: App running low on memory");
+        break;
+    case SDL_APP_WILLENTERBACKGROUND:
+        SDL_Log("SDL EVENT: App will enter the background");
+        break;
+    case SDL_APP_DIDENTERBACKGROUND:
+        SDL_Log("SDL EVENT: App entered the background");
+        break;
+    case SDL_APP_WILLENTERFOREGROUND:
+        SDL_Log("SDL EVENT: App will enter the foreground");
+        break;
+    case SDL_APP_DIDENTERFOREGROUND:
+        SDL_Log("SDL EVENT: App entered the foreground");
+        break;
+
     case SDL_QUIT:
         SDL_Log("SDL EVENT: Quit requested");
         break;
@@ -1233,7 +1290,7 @@ SDLTest_PrintEvent(SDL_Event * event)
         SDL_Log("SDL EVENT: User event %d", event->user.code);
         break;
     default:
-        SDL_Log("Unknown event %04x", event->type);
+        SDL_Log("Unknown event 0x%4.4x", event->type);
         break;
     }
 }
@@ -1257,19 +1314,19 @@ SDLTest_ScreenShot(SDL_Renderer *renderer)
 #endif
                     0x00000000);
     if (!surface) {
-        fprintf(stderr, "Couldn't create surface: %s\n", SDL_GetError());
+        SDL_Log("Couldn't create surface: %s\n", SDL_GetError());
         return;
     }
 
     if (SDL_RenderReadPixels(renderer, NULL, surface->format->format,
                              surface->pixels, surface->pitch) < 0) {
-        fprintf(stderr, "Couldn't read screen: %s\n", SDL_GetError());
+        SDL_Log("Couldn't read screen: %s\n", SDL_GetError());
         SDL_free(surface);
         return;
     }
 
     if (SDL_SaveBMP(surface, "screenshot.bmp") < 0) {
-        fprintf(stderr, "Couldn't save screenshot.bmp: %s\n", SDL_GetError());
+        SDL_Log("Couldn't save screenshot.bmp: %s\n", SDL_GetError());
         SDL_free(surface);
         return;
     }
@@ -1374,6 +1431,49 @@ SDLTest_CommonEvent(SDLTest_CommonState * state, SDL_Event * event, int *done)
                 }
             }
             break;
+        case SDLK_UP:
+        case SDLK_DOWN:
+        case SDLK_LEFT:
+        case SDLK_RIGHT:
+            if (withAlt) {
+                /* Alt-Up/Down/Left/Right switches between displays */
+                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
+                if (window) {
+                    int currentIndex = SDL_GetWindowDisplayIndex(window);
+                    int numDisplays = SDL_GetNumVideoDisplays();
+
+                    if (currentIndex >= 0 && numDisplays >= 1) {
+                        int dest;
+                        if (event->key.keysym.sym == SDLK_UP || event->key.keysym.sym == SDLK_LEFT) {
+                            dest = (currentIndex + numDisplays - 1) % numDisplays;
+                        } else {
+                            dest = (currentIndex + numDisplays + 1) % numDisplays;
+                        }
+                        SDL_Log("Centering on display %d\n", dest);
+                        SDL_SetWindowPosition(window,
+                            SDL_WINDOWPOS_CENTERED_DISPLAY(dest),
+                            SDL_WINDOWPOS_CENTERED_DISPLAY(dest));
+                    }
+                }
+            }
+            if (withShift) {
+                /* Shift-Up/Down/Left/Right shift the window by 100px */
+                SDL_Window *window = SDL_GetWindowFromID(event->key.windowID);
+                if (window) {
+                    const int delta = 100;
+                    int x, y;
+                    SDL_GetWindowPosition(window, &x, &y);
+                    
+                    if (event->key.keysym.sym == SDLK_UP)    y -= delta;
+                    if (event->key.keysym.sym == SDLK_DOWN)  y += delta;
+                    if (event->key.keysym.sym == SDLK_LEFT)  x -= delta;
+                    if (event->key.keysym.sym == SDLK_RIGHT) x += delta;
+
+                    SDL_Log("Setting position to (%d, %d)\n", x, y);
+                    SDL_SetWindowPosition(window, x, y);
+                }
+            }
+            break;
         case SDLK_o:
             if (withControl) {
                 /* Ctrl-O (or Ctrl-Shift-O) changes window opacity. */
diff --git a/src/test/SDL_test_compare.c b/src/test/SDL_test_compare.c
index d06ead9..af1b102 100644
--- a/src/test/SDL_test_compare.c
+++ b/src/test/SDL_test_compare.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -113,3 +113,5 @@ int SDLTest_CompareSurfaces(SDL_Surface *surface, SDL_Surface *referenceSurface,
 
    return ret;
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_crc32.c b/src/test/SDL_test_crc32.c
index 6e12208..a8878ea 100644
--- a/src/test/SDL_test_crc32.c
+++ b/src/test/SDL_test_crc32.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -69,7 +69,7 @@ int SDLTest_Crc32Init(SDLTest_Crc32Context *crcContext)
 }
 
 /* Complete CRC32 calculation on a memory block */
-
+/* un-used
 int SDLTest_Crc32Calc(SDLTest_Crc32Context * crcContext, CrcUint8 *inBuf, CrcUint32 inLen, CrcUint32 *crc32)
 {
   if (SDLTest_Crc32CalcStart(crcContext,crc32)) {
@@ -86,6 +86,7 @@ int SDLTest_Crc32Calc(SDLTest_Crc32Context * crcContext, CrcUint8 *inBuf, CrcUin
 
   return 0;
 }
+*/
 
 /* Start crc calculation */
 
@@ -163,3 +164,5 @@ int SDLTest_Crc32Done(SDLTest_Crc32Context * crcContext)
 
   return 0;
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_font.c b/src/test/SDL_test_font.c
index afd35c6..04051a5 100644
--- a/src/test/SDL_test_font.c
+++ b/src/test/SDL_test_font.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -3116,9 +3116,9 @@ static SDL_Texture *SDLTest_CharTextureCache[256];
 
 int SDLTest_DrawCharacter(SDL_Renderer *renderer, int x, int y, char c)
 {
-	const Uint32 charWidth = FONT_CHARACTER_SIZE;
-	const Uint32 charHeight = FONT_CHARACTER_SIZE;
-	const Uint32 charSize = FONT_CHARACTER_SIZE;
+    const Uint32 charWidth = FONT_CHARACTER_SIZE;
+    const Uint32 charHeight = FONT_CHARACTER_SIZE;
+    const Uint32 charSize = FONT_CHARACTER_SIZE;
     SDL_Rect srect;
     SDL_Rect drect;
     int result;
@@ -3133,16 +3133,16 @@ int SDLTest_DrawCharacter(SDL_Renderer *renderer, int x, int y, char c)
     Uint8 r, g, b, a;
 
     /*
-    * Setup source rectangle
-    */
+     * Setup source rectangle
+     */
     srect.x = 0;
     srect.y = 0;
     srect.w = charWidth;
     srect.h = charHeight;
 
     /*
-    * Setup destination rectangle
-    */
+     * Setup destination rectangle
+     */
     drect.x = x;
     drect.y = y;
     drect.w = charWidth;
@@ -3152,12 +3152,12 @@ int SDLTest_DrawCharacter(SDL_Renderer *renderer, int x, int y, char c)
     ci = (unsigned char)c;
 
     /*
-    * Create new charWidth x charHeight bitmap surface if not already present.
-    */
+     * Create new charWidth x charHeight bitmap surface if not already present.
+     */
     if (SDLTest_CharTextureCache[ci] == NULL) {
         /*
-        * Redraw character into surface
-        */
+         * Redraw character into surface
+         */
         character = SDL_CreateRGBSurface(SDL_SWSURFACE,
             charWidth, charHeight, 32,
             0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
@@ -3170,8 +3170,8 @@ int SDLTest_DrawCharacter(SDL_Renderer *renderer, int x, int y, char c)
         pitch = character->pitch;
 
         /*
-        * Drawing loop
-        */
+         * Drawing loop
+         */
         patt = 0;
         for (iy = 0; iy < charWidth; iy++) {
             mask = 0x00;
@@ -3196,24 +3196,24 @@ int SDLTest_DrawCharacter(SDL_Renderer *renderer, int x, int y, char c)
         SDL_FreeSurface(character);
 
         /*
-        * Check pointer
-        */
+         * Check pointer
+         */
         if (SDLTest_CharTextureCache[ci] == NULL) {
             return (-1);
         }
     }
 
     /*
-    * Set color
-    */
+     * Set color
+     */
     result = 0;
     result |= SDL_GetRenderDrawColor(renderer, &r, &g, &b, &a);
     result |= SDL_SetTextureColorMod(SDLTest_CharTextureCache[ci], r, g, b);
     result |= SDL_SetTextureAlphaMod(SDLTest_CharTextureCache[ci], a);
 
     /*
-    * Draw texture onto destination
-    */
+     * Draw texture onto destination
+     */
     result |= SDL_RenderCopy(renderer, SDLTest_CharTextureCache[ci], &srect, &drect);
 
     return (result);
@@ -3221,7 +3221,7 @@ int SDLTest_DrawCharacter(SDL_Renderer *renderer, int x, int y, char c)
 
 int SDLTest_DrawString(SDL_Renderer * renderer, int x, int y, const char *s)
 {
-	const Uint32 charWidth = FONT_CHARACTER_SIZE;
+    const Uint32 charWidth = FONT_CHARACTER_SIZE;
     int result = 0;
     int curx = x;
     int cury = y;
@@ -3236,3 +3236,15 @@ int SDLTest_DrawString(SDL_Renderer * renderer, int x, int y, const char *s)
     return (result);
 }
 
+void SDLTest_CleanupTextDrawing(void)
+{
+    unsigned int i;
+    for (i = 0; i < SDL_arraysize(SDLTest_CharTextureCache); ++i) {
+        if (SDLTest_CharTextureCache[i]) {
+            SDL_DestroyTexture(SDLTest_CharTextureCache[i]);
+            SDLTest_CharTextureCache[i] = NULL;
+        }
+    }
+}
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_fuzzer.c b/src/test/SDL_test_fuzzer.c
index 1bd8dfa..4b38100 100644
--- a/src/test/SDL_test_fuzzer.c
+++ b/src/test/SDL_test_fuzzer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,19 +27,20 @@
 
 #include "SDL_config.h"
 
+#include <limits.h>
 /* Visual Studio 2008 doesn't have stdint.h */
 #if defined(_MSC_VER) && _MSC_VER <= 1500
-#define UINT8_MAX   ~(Uint8)0
-#define UINT16_MAX  ~(Uint16)0
-#define UINT32_MAX  ~(Uint32)0
-#define UINT64_MAX  ~(Uint64)0
+#define UINT8_MAX   _UI8_MAX
+#define UINT16_MAX  _UI16_MAX
+#define UINT32_MAX  _UI32_MAX
+#define INT64_MIN    _I64_MIN
+#define INT64_MAX    _I64_MAX
+#define UINT64_MAX  _UI64_MAX
 #else
-#define _GNU_SOURCE
 #include <stdint.h>
 #endif
 #include <stdio.h>
 #include <stdlib.h>
-#include <limits.h>
 #include <float.h>
 
 #include "SDL_test.h"
@@ -197,7 +198,7 @@ SDLTest_RandomIntegerInRange(Sint32 pMin, Sint32 pMax)
  *
  * \returns Returns a random boundary value for the domain or 0 in case of error
  */
-Uint64
+static Uint64
 SDLTest_GenerateUnsignedBoundaryValues(const Uint64 maxValue, Uint64 boundary1, Uint64 boundary2, SDL_bool validDomain)
 {
         Uint64 b1, b2;
@@ -298,7 +299,7 @@ Uint64
 SDLTest_RandomUint64BoundaryValue(Uint64 boundary1, Uint64 boundary2, SDL_bool validDomain)
 {
     /* max value for Uint64 */
-    const Uint64 maxValue = ULLONG_MAX;
+    const Uint64 maxValue = UINT64_MAX;
     return SDLTest_GenerateUnsignedBoundaryValues(maxValue,
                 (Uint64) boundary1, (Uint64) boundary2,
                 validDomain);
@@ -329,7 +330,7 @@ SDLTest_RandomUint64BoundaryValue(Uint64 boundary1, Uint64 boundary2, SDL_bool v
  *
  * \returns Returns a random boundary value for the domain or 0 in case of error
  */
-Sint64
+static Sint64
 SDLTest_GenerateSignedBoundaryValues(const Sint64 minValue, const Sint64 maxValue, Sint64 boundary1, Sint64 boundary2, SDL_bool validDomain)
 {
         Sint64 b1, b2;
@@ -434,8 +435,8 @@ Sint64
 SDLTest_RandomSint64BoundaryValue(Sint64 boundary1, Sint64 boundary2, SDL_bool validDomain)
 {
     /* min & max values for Sint64 */
-    const Sint64 maxValue = LLONG_MAX;
-    const Sint64 minValue = LLONG_MIN;
+    const Sint64 maxValue = INT64_MAX;
+    const Sint64 minValue = INT64_MIN;
     return SDLTest_GenerateSignedBoundaryValues(minValue, maxValue,
                 boundary1, boundary2,
                 validDomain);
@@ -444,7 +445,7 @@ SDLTest_RandomSint64BoundaryValue(Sint64 boundary1, Sint64 boundary2, SDL_bool v
 float
 SDLTest_RandomUnitFloat()
 {
-    return (float) SDLTest_RandomUint32() / UINT_MAX;
+    return SDLTest_RandomUint32() / (float) UINT_MAX;
 }
 
 float
@@ -523,3 +524,5 @@ SDLTest_RandomAsciiStringOfSize(int size)
 
     return string;
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_harness.c b/src/test/SDL_test_harness.c
index 4b86c7a..f4d557b 100644
--- a/src/test/SDL_test_harness.c
+++ b/src/test/SDL_test_harness.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -97,17 +97,17 @@ SDLTest_GenerateRunSeed(const int length)
 * \returns The generated execution key to initialize the fuzzer with.
 *
 */
-Uint64
-SDLTest_GenerateExecKey(char *runSeed, char *suiteName, char *testName, int iteration)
+static Uint64
+SDLTest_GenerateExecKey(const char *runSeed, char *suiteName, char *testName, int iteration)
 {
     SDLTest_Md5Context md5Context;
     Uint64 *keys;
     char iterationString[16];
-    Uint32 runSeedLength;
-    Uint32 suiteNameLength;
-    Uint32 testNameLength;
-    Uint32 iterationStringLength;
-    Uint32 entireStringLength;
+    size_t runSeedLength;
+    size_t suiteNameLength;
+    size_t testNameLength;
+    size_t iterationStringLength;
+    size_t entireStringLength;
     char *buffer;
 
     if (runSeed == NULL || runSeed[0] == '\0') {
@@ -150,7 +150,7 @@ SDLTest_GenerateExecKey(char *runSeed, char *suiteName, char *testName, int iter
 
     /* Hash string and use half of the digest as 64bit exec key */
     SDLTest_Md5Init(&md5Context);
-    SDLTest_Md5Update(&md5Context, (unsigned char *)buffer, entireStringLength);
+    SDLTest_Md5Update(&md5Context, (unsigned char *)buffer, (unsigned int) entireStringLength);
     SDLTest_Md5Final(&md5Context);
     SDL_free(buffer);
     keys = (Uint64 *)md5Context.digest;
@@ -168,7 +168,7 @@ SDLTest_GenerateExecKey(char *runSeed, char *suiteName, char *testName, int iter
 *
 * \return Timer id or -1 on failure.
 */
-SDL_TimerID
+static SDL_TimerID
 SDLTest_SetTestTimeout(int timeout, void (*callback)())
 {
     Uint32 timeoutInMilliseconds;
@@ -206,8 +206,8 @@ SDLTest_SetTestTimeout(int timeout, void (*callback)())
 /**
 * \brief Timeout handler. Aborts test run and exits harness process.
 */
-void
-    SDLTest_BailOut()
+static SDL_NORETURN void
+SDLTest_BailOut()
 {
     SDLTest_LogError("TestCaseTimeout timer expired. Aborting test run.");
     exit(TEST_ABORTED); /* bail out from the test */
@@ -223,8 +223,8 @@ void
 *
 * \returns Test case result.
 */
-int
-SDLTest_RunTest(SDLTest_TestSuiteReference *testSuite, SDLTest_TestCaseReference *testCase, Uint64 execKey, SDL_bool forceTestRun)
+static int
+SDLTest_RunTest(SDLTest_TestSuiteReference *testSuite, const SDLTest_TestCaseReference *testCase, Uint64 execKey, SDL_bool forceTestRun)
 {
     SDL_TimerID timer = 0;
     int testCaseResult = 0;
@@ -313,7 +313,8 @@ SDLTest_RunTest(SDLTest_TestSuiteReference *testSuite, SDLTest_TestCaseReference
 }
 
 /* Prints summary of all suites/tests contained in the given reference */
-void SDLTest_LogTestSuiteSummary(SDLTest_TestSuiteReference *testSuites)
+#if 0 
+static void SDLTest_LogTestSuiteSummary(SDLTest_TestSuiteReference *testSuites)
 {
     int suiteCounter;
     int testCounter;
@@ -340,12 +341,13 @@ void SDLTest_LogTestSuiteSummary(SDLTest_TestSuiteReference *testSuites)
         }
     }
 }
+#endif
 
 /* Gets a timer value in seconds */
-float GetClock()
+static float GetClock()
 {
-    float currentClock = (float)clock();
-    return currentClock / (float)CLOCKS_PER_SEC;
+    float currentClock = clock() / (float) CLOCKS_PER_SEC;
+    return currentClock;
 }
 
 /**
@@ -370,7 +372,7 @@ int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *user
     int testCounter;
     int iterationCounter;
     SDLTest_TestSuiteReference *testSuite;
-    SDLTest_TestCaseReference *testCase;
+    const SDLTest_TestCaseReference *testCase;
     const char *runSeed = NULL;
     char *currentSuiteName;
     char *currentTestName;
@@ -396,7 +398,7 @@ int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *user
     Uint32 testPassedCount = 0;
     Uint32 testSkippedCount = 0;
     Uint32 countSum = 0;
-    SDLTest_TestCaseReference **failedTests;
+    const SDLTest_TestCaseReference **failedTests;
 
     /* Sanitize test iterations */
     if (testIterations < 1) {
@@ -440,7 +442,7 @@ int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *user
 	}
 
 	/* Pre-allocate an array for tracking failed tests (potentially all test cases) */
-	failedTests = (SDLTest_TestCaseReference **)SDL_malloc(totalNumberOfTests * sizeof(SDLTest_TestCaseReference *));
+	failedTests = (const SDLTest_TestCaseReference **)SDL_malloc(totalNumberOfTests * sizeof(SDLTest_TestCaseReference *));
 	if (failedTests == NULL) {	
 	   SDLTest_LogError("Unable to allocate cache for failed tests");
            SDL_Error(SDL_ENOMEM);	   
@@ -466,7 +468,7 @@ int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *user
             testCounter = 0;
             while (testSuite->testCases[testCounter] && testFilter == 0)
             {
-                testCase=(SDLTest_TestCaseReference *)testSuite->testCases[testCounter];
+                testCase = testSuite->testCases[testCounter];
                 testCounter++;
                 if (testCase->name != NULL && SDL_strcmp(filter, testCase->name) == 0) {
                     /* Matched a test name */
@@ -483,7 +485,7 @@ int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *user
         if (suiteFilter == 0 && testFilter == 0) {
             SDLTest_LogError("Filter '%s' did not match any test suite/case.", filter);
             SDLTest_Log("Exit code: 2");
-            SDL_free(failedTests);
+            SDL_free((void *) failedTests);
             return 2;
         }
     }
@@ -521,7 +523,7 @@ int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *user
             testCounter = 0;
             while(testSuite->testCases[testCounter])
             {
-                testCase=(SDLTest_TestCaseReference *)testSuite->testCases[testCounter];
+                testCase = testSuite->testCases[testCounter];
                 currentTestName = (char *)((testCase->name) ? testCase->name : SDLTEST_INVALID_NAME_FORMAT);
                 testCounter++;
 
@@ -562,7 +564,7 @@ int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *user
                         if (userExecKey != 0) {
                             execKey = userExecKey;
                         } else {
-                            execKey = SDLTest_GenerateExecKey((char *)runSeed, testSuite->name, testCase->name, iterationCounter);
+                            execKey = SDLTest_GenerateExecKey(runSeed, testSuite->name, testCase->name, iterationCounter);
                         }
 
                         SDLTest_Log("Test Iteration %i: execKey %" SDL_PRIu64, iterationCounter, execKey);
@@ -669,8 +671,10 @@ int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *user
           SDLTest_Log(" --seed %s --filter %s", runSeed, failedTests[testCounter]->name);
         }
     }
-    SDL_free(failedTests);
+    SDL_free((void *) failedTests);
 
     SDLTest_Log("Exit code: %d", runResult);
     return runResult;
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_imageBlit.c b/src/test/SDL_test_imageBlit.c
index 5896ca0..8906763 100644
--- a/src/test/SDL_test_imageBlit.c
+++ b/src/test/SDL_test_imageBlit.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,7 +24,7 @@
 
 /* GIMP RGB C-Source image dump (blit.c) */
 
-const SDLTest_SurfaceImage_t SDLTest_imageBlit = {
+static const SDLTest_SurfaceImage_t SDLTest_imageBlit = {
   80, 60, 3,
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
@@ -561,7 +561,7 @@ SDL_Surface *SDLTest_ImageBlit()
    return surface;
 }
 
-const SDLTest_SurfaceImage_t SDLTest_imageBlitColor = {
+static const SDLTest_SurfaceImage_t SDLTest_imageBlitColor = {
   80, 60, 3,
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
@@ -1044,7 +1044,7 @@ SDL_Surface *SDLTest_ImageBlitColor()
    return surface;
 }
 
-const SDLTest_SurfaceImage_t SDLTest_imageBlitAlpha = {
+static const SDLTest_SurfaceImage_t SDLTest_imageBlitAlpha = {
   80, 60, 3,
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
@@ -1555,3 +1555,5 @@ SDL_Surface *SDLTest_ImageBlitAlpha()
          );
    return surface;
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_imageBlitBlend.c b/src/test/SDL_test_imageBlitBlend.c
index 6e8c2f1..657ab8a 100644
--- a/src/test/SDL_test_imageBlitBlend.c
+++ b/src/test/SDL_test_imageBlitBlend.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,7 +24,7 @@
 
 /* GIMP RGB C-Source image dump (alpha.c) */
 
-const SDLTest_SurfaceImage_t SDLTest_imageBlitBlendAdd = {
+static const SDLTest_SurfaceImage_t SDLTest_imageBlitBlendAdd = {
   80, 60, 3,
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
@@ -601,7 +601,7 @@ SDL_Surface *SDLTest_ImageBlitBlendAdd()
    return surface;
 }
 
-const SDLTest_SurfaceImage_t SDLTest_imageBlitBlend = {
+static const SDLTest_SurfaceImage_t SDLTest_imageBlitBlend = {
   80, 60, 3,
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
@@ -1131,7 +1131,7 @@ SDL_Surface *SDLTest_ImageBlitBlend()
    return surface;
 }
 
-const SDLTest_SurfaceImage_t SDLTest_imageBlitBlendMod = {
+static const SDLTest_SurfaceImage_t SDLTest_imageBlitBlendMod = {
   80, 60, 3,
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
@@ -1561,7 +1561,7 @@ SDL_Surface *SDLTest_ImageBlitBlendMod()
    return surface;
 }
 
-const SDLTest_SurfaceImage_t SDLTest_imageBlitBlendNone = {
+static const SDLTest_SurfaceImage_t SDLTest_imageBlitBlendNone = {
   80, 60, 3,
   "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377"
   "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377"
@@ -2374,7 +2374,7 @@ SDL_Surface *SDLTest_ImageBlitBlendNone()
    return surface;
 }
 
-const SDLTest_SurfaceImage_t SDLTest_imageBlitBlendAll = {
+static const SDLTest_SurfaceImage_t SDLTest_imageBlitBlendAll = {
   80, 60, 3,
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
@@ -2841,3 +2841,5 @@ SDL_Surface *SDLTest_ImageBlitBlendAll()
          );
    return surface;
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_imageFace.c b/src/test/SDL_test_imageFace.c
index 84f5037..b633e97 100644
--- a/src/test/SDL_test_imageFace.c
+++ b/src/test/SDL_test_imageFace.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,7 +24,7 @@
 
 /* GIMP RGBA C-Source image dump (face.c) */
 
-const SDLTest_SurfaceImage_t SDLTest_imageFace = {
+static const SDLTest_SurfaceImage_t SDLTest_imageFace = {
   32, 32, 4,
   "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
   "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
@@ -244,3 +244,4 @@ SDL_Surface *SDLTest_ImageFace()
    return surface;
 }
 
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_imagePrimitives.c b/src/test/SDL_test_imagePrimitives.c
index 4ab48d2..0b7e510 100644
--- a/src/test/SDL_test_imagePrimitives.c
+++ b/src/test/SDL_test_imagePrimitives.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,7 +24,7 @@
 
 /* GIMP RGB C-Source image dump (primitives.c) */
 
-const SDLTest_SurfaceImage_t SDLTest_imagePrimitives = {
+static const SDLTest_SurfaceImage_t SDLTest_imagePrimitives = {
   80, 60, 3,
   "\5ii\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
@@ -510,3 +510,5 @@ SDL_Surface *SDLTest_ImagePrimitives()
          );
    return surface;
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_imagePrimitivesBlend.c b/src/test/SDL_test_imagePrimitivesBlend.c
index 5e53862..32cc234 100644
--- a/src/test/SDL_test_imagePrimitivesBlend.c
+++ b/src/test/SDL_test_imagePrimitivesBlend.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,7 +24,7 @@
 
 /* GIMP RGB C-Source image dump (alpha.c) */
 
-const SDLTest_SurfaceImage_t SDLTest_imagePrimitivesBlend = {
+static const SDLTest_SurfaceImage_t SDLTest_imagePrimitivesBlend = {
   80, 60, 3,
   "\260e\15\222\356/\37\313\15\36\330\17K\3745D\3471\0\20\0D\3502D\3502<\321"
   ",\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\0-\0\377\377"
@@ -692,3 +692,5 @@ SDL_Surface *SDLTest_ImagePrimitivesBlend()
          );
    return surface;
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_log.c b/src/test/SDL_test_log.c
index a2f857f..ec57dc2 100644
--- a/src/test/SDL_test_log.c
+++ b/src/test/SDL_test_log.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -26,7 +26,9 @@
 */
 
 /* quiet windows compiler warnings */
-#define _CRT_SECURE_NO_WARNINGS
+#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
+# define _CRT_SECURE_NO_WARNINGS
+#endif
 
 #include "SDL_config.h"
 
@@ -39,6 +41,19 @@
 
 #include "SDL_test.h"
 
+/* work around compiler warning on older GCCs. */
+#if (defined(__GNUC__) && (__GNUC__ <= 2))
+static size_t
+strftime_gcc2_workaround(char *s, size_t max, const char *fmt, const struct tm *tm)
+{
+    return strftime(s, max, fmt, tm);
+}
+#ifdef strftime
+#undef strftime
+#endif
+#define strftime strftime_gcc2_workaround
+#endif
+
 /* !
  * Converts unix timestamp to its ascii representation in localtime
  *
@@ -50,7 +65,7 @@
  *
  * \return Ascii representation of the timestamp in localtime in the format '08/23/01 14:55:02'
  */
-char *SDLTest_TimestampToString(const time_t timestamp)
+static char *SDLTest_TimestampToString(const time_t timestamp)
 {
     time_t copy;
     static char buffer[64];
@@ -99,3 +114,5 @@ void SDLTest_LogError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
     /* Log with timestamp and newline */
     SDL_LogMessage(SDL_LOG_CATEGORY_TEST, SDL_LOG_PRIORITY_ERROR, "%s: %s", SDLTest_TimestampToString(time(0)), logMessage);
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_md5.c b/src/test/SDL_test_md5.c
index 7cc3567..73da473 100644
--- a/src/test/SDL_test_md5.c
+++ b/src/test/SDL_test_md5.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -334,3 +334,5 @@ static void SDLTest_Md5Transform(MD5UINT4 * buf, MD5UINT4 * in)
   buf[2] += c;
   buf[3] += d;
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/test/SDL_test_random.c b/src/test/SDL_test_random.c
index c5baaa6..68f60a6 100644
--- a/src/test/SDL_test_random.c
+++ b/src/test/SDL_test_random.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -92,3 +92,5 @@ unsigned int SDLTest_Random(SDLTest_RandomContext * rndContext)
     rndContext->c++;
   return (rndContext->x);
 }
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/thread/SDL_systhread.h b/src/thread/SDL_systhread.h
index 05a0125..5513d73 100644
--- a/src/thread/SDL_systhread.h
+++ b/src/thread/SDL_systhread.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,8 +22,8 @@
 
 /* These are functions that need to be implemented by a port of SDL */
 
-#ifndef _SDL_systhread_h
-#define _SDL_systhread_h
+#ifndef SDL_systhread_h_
+#define SDL_systhread_h_
 
 #include "SDL_thread.h"
 #include "SDL_thread_c.h"
@@ -55,7 +55,7 @@ extern void SDL_SYS_WaitThread(SDL_Thread * thread);
 extern void SDL_SYS_DetachThread(SDL_Thread * thread);
 
 /* Get the thread local storage for this thread */
-extern SDL_TLSData *SDL_SYS_GetTLSData();
+extern SDL_TLSData *SDL_SYS_GetTLSData(void);
 
 /* Set the thread local storage for this thread */
 extern int SDL_SYS_SetTLSData(SDL_TLSData *data);
@@ -65,6 +65,6 @@ extern SDL_Thread *
 SDL_CreateThreadInternal(int (SDLCALL * fn) (void *), const char *name,
                          const size_t stacksize, void *data);
 
-#endif /* _SDL_systhread_h */
+#endif /* SDL_systhread_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/thread/SDL_thread.c b/src/thread/SDL_thread.c
index ae86579..78f725e 100644
--- a/src/thread/SDL_thread.c
+++ b/src/thread/SDL_thread.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -50,7 +50,7 @@ SDL_TLSGet(SDL_TLSID id)
 }
 
 int
-SDL_TLSSet(SDL_TLSID id, const void *value, void (*destructor)(void *))
+SDL_TLSSet(SDL_TLSID id, const void *value, void (SDLCALL *destructor)(void *))
 {
     SDL_TLSData *storage;
 
@@ -121,7 +121,7 @@ static SDL_TLSEntry *SDL_generic_TLS;
 
 
 SDL_TLSData *
-SDL_Generic_GetTLSData()
+SDL_Generic_GetTLSData(void)
 {
     SDL_threadID thread = SDL_ThreadID();
     SDL_TLSEntry *entry;
diff --git a/src/thread/SDL_thread_c.h b/src/thread/SDL_thread_c.h
index 554325d..d3553fd 100644
--- a/src/thread/SDL_thread_c.h
+++ b/src/thread/SDL_thread_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_thread_c_h
-#define _SDL_thread_c_h
+#ifndef SDL_thread_c_h_
+#define SDL_thread_c_h_
 
 #include "SDL_thread.h"
 
@@ -71,7 +71,7 @@ typedef struct {
     unsigned int limit;
     struct {
         void *data;
-        void (*destructor)(void*);
+        void (SDLCALL *destructor)(void*);
     } array[1];
 } SDL_TLSData;
 
@@ -82,7 +82,7 @@ typedef struct {
    This is only intended as a fallback if getting real thread-local
    storage fails or isn't supported on this platform.
  */
-extern SDL_TLSData *SDL_Generic_GetTLSData();
+extern SDL_TLSData *SDL_Generic_GetTLSData(void);
 
 /* Set cross-platform, slow, thread local storage for this thread.
    This is only intended as a fallback if getting real thread-local
@@ -90,6 +90,6 @@ extern SDL_TLSData *SDL_Generic_GetTLSData();
  */
 extern int SDL_Generic_SetTLSData(SDL_TLSData *data);
 
-#endif /* _SDL_thread_c_h */
+#endif /* SDL_thread_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/thread/generic/SDL_syscond.c b/src/thread/generic/SDL_syscond.c
index e2ccd88..cb1c707 100644
--- a/src/thread/generic/SDL_syscond.c
+++ b/src/thread/generic/SDL_syscond.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/generic/SDL_sysmutex.c b/src/thread/generic/SDL_sysmutex.c
index f2f6689..5e26f8c 100644
--- a/src/thread/generic/SDL_sysmutex.c
+++ b/src/thread/generic/SDL_sysmutex.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/generic/SDL_sysmutex_c.h b/src/thread/generic/SDL_sysmutex_c.h
index 9dba5e1..e669a86 100644
--- a/src/thread/generic/SDL_sysmutex_c.h
+++ b/src/thread/generic/SDL_sysmutex_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/generic/SDL_syssem.c b/src/thread/generic/SDL_syssem.c
index 92afcb0..e7d8a91 100644
--- a/src/thread/generic/SDL_syssem.c
+++ b/src/thread/generic/SDL_syssem.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/generic/SDL_systhread.c b/src/thread/generic/SDL_systhread.c
index 7a81a62..c612192 100644
--- a/src/thread/generic/SDL_systhread.c
+++ b/src/thread/generic/SDL_systhread.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/generic/SDL_systhread_c.h b/src/thread/generic/SDL_systhread_c.h
index ea9b714..a477b6b 100644
--- a/src/thread/generic/SDL_systhread_c.h
+++ b/src/thread/generic/SDL_systhread_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/generic/SDL_systls.c b/src/thread/generic/SDL_systls.c
index e29c198..15067a0 100644
--- a/src/thread/generic/SDL_systls.c
+++ b/src/thread/generic/SDL_systls.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,7 +24,7 @@
 
 
 SDL_TLSData *
-SDL_SYS_GetTLSData()
+SDL_SYS_GetTLSData(void)
 {
     return SDL_Generic_GetTLSData();
 }
diff --git a/src/thread/psp/SDL_syscond.c b/src/thread/psp/SDL_syscond.c
index a84b206..1a5c966 100644
--- a/src/thread/psp/SDL_syscond.c
+++ b/src/thread/psp/SDL_syscond.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/psp/SDL_sysmutex.c b/src/thread/psp/SDL_sysmutex.c
index 78129fa..8c07165 100644
--- a/src/thread/psp/SDL_sysmutex.c
+++ b/src/thread/psp/SDL_sysmutex.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/psp/SDL_sysmutex_c.h b/src/thread/psp/SDL_sysmutex_c.h
index 9dba5e1..e669a86 100644
--- a/src/thread/psp/SDL_sysmutex_c.h
+++ b/src/thread/psp/SDL_sysmutex_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/psp/SDL_syssem.c b/src/thread/psp/SDL_syssem.c
index 643406c..c76a9e2 100644
--- a/src/thread/psp/SDL_syssem.c
+++ b/src/thread/psp/SDL_syssem.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -108,7 +108,7 @@ int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout)
                case SCE_KERNEL_ERROR_WAIT_TIMEOUT:
                        return SDL_MUTEX_TIMEDOUT;
                default:
-                       return SDL_SetError("WaitForSingleObject() failed");
+                       return SDL_SetError("sceKernelWaitSema() failed");
     }
 }
 
diff --git a/src/thread/psp/SDL_systhread.c b/src/thread/psp/SDL_systhread.c
index c6003b8..98a5ff5 100644
--- a/src/thread/psp/SDL_systhread.c
+++ b/src/thread/psp/SDL_systhread.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/psp/SDL_systhread_c.h b/src/thread/psp/SDL_systhread_c.h
index 4f74df0..ed8b84a 100644
--- a/src/thread/psp/SDL_systhread_c.h
+++ b/src/thread/psp/SDL_systhread_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/pthread/SDL_syscond.c b/src/thread/pthread/SDL_syscond.c
index 998ac55..d43871e 100644
--- a/src/thread/pthread/SDL_syscond.c
+++ b/src/thread/pthread/SDL_syscond.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -129,7 +129,7 @@ SDL_CondWaitTimeout(SDL_cond * cond, SDL_mutex * mutex, Uint32 ms)
     switch (retval) {
     case EINTR:
         goto tryagain;
-        break;
+        /* break; -Wunreachable-code-break */
     case ETIMEDOUT:
         retval = SDL_MUTEX_TIMEDOUT;
         break;
diff --git a/src/thread/pthread/SDL_sysmutex.c b/src/thread/pthread/SDL_sysmutex.c
index f24cfda..72d3bf3 100644
--- a/src/thread/pthread/SDL_sysmutex.c
+++ b/src/thread/pthread/SDL_sysmutex.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,9 +20,6 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
 #include <errno.h>
 #include <pthread.h>
 
@@ -137,7 +134,7 @@ SDL_TryLockMutex(SDL_mutex * mutex)
          We set the locking thread id after we obtain the lock
          so unlocks from other threads will fail.
          */
-        if (pthread_mutex_lock(&mutex->id) == 0) {
+        if (pthread_mutex_trylock(&mutex->id) == 0) {
             mutex->owner = this_thread;
             mutex->recursive = 0;
         } else if (errno == EBUSY) {
diff --git a/src/thread/pthread/SDL_sysmutex_c.h b/src/thread/pthread/SDL_sysmutex_c.h
index ee60ca0..017410e 100644
--- a/src/thread/pthread/SDL_sysmutex_c.h
+++ b/src/thread/pthread/SDL_sysmutex_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,13 +20,13 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_mutex_c_h
-#define _SDL_mutex_c_h
+#ifndef SDL_mutex_c_h_
+#define SDL_mutex_c_h_
 
 struct SDL_mutex
 {
     pthread_mutex_t id;
 };
 
-#endif /* _SDL_mutex_c_h */
+#endif /* SDL_mutex_c_h_ */
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/thread/pthread/SDL_syssem.c b/src/thread/pthread/SDL_syssem.c
index b7547e6..26adbeb 100644
--- a/src/thread/pthread/SDL_syssem.c
+++ b/src/thread/pthread/SDL_syssem.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,9 +20,6 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
 #include <errno.h>
 #include <pthread.h>
 #include <semaphore.h>
diff --git a/src/thread/pthread/SDL_systhread.c b/src/thread/pthread/SDL_systhread.c
index 4958f6f..1eea63a 100644
--- a/src/thread/pthread/SDL_systhread.c
+++ b/src/thread/pthread/SDL_systhread.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -52,7 +52,7 @@
 #endif
 
 #ifdef __HAIKU__
-#include <be/kernel/OS.h>
+#include <kernel/OS.h>
 #endif
 
 #include "SDL_assert.h"
diff --git a/src/thread/pthread/SDL_systhread_c.h b/src/thread/pthread/SDL_systhread_c.h
index 4ad1884..7bde574 100644
--- a/src/thread/pthread/SDL_systhread_c.h
+++ b/src/thread/pthread/SDL_systhread_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/pthread/SDL_systls.c b/src/thread/pthread/SDL_systls.c
index 622ad02..de651dc 100644
--- a/src/thread/pthread/SDL_systls.c
+++ b/src/thread/pthread/SDL_systls.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,6 +20,7 @@
 */
 #include "../../SDL_internal.h"
 #include "SDL_thread.h"
+#include "../SDL_systhread.h"
 #include "../SDL_thread_c.h"
 
 #include <pthread.h>
@@ -31,7 +32,7 @@ static pthread_key_t thread_local_storage = INVALID_PTHREAD_KEY;
 static SDL_bool generic_local_storage = SDL_FALSE;
 
 SDL_TLSData *
-SDL_SYS_GetTLSData()
+SDL_SYS_GetTLSData(void)
 {
     if (thread_local_storage == INVALID_PTHREAD_KEY && !generic_local_storage) {
         static SDL_SpinLock lock;
diff --git a/src/thread/stdcpp/SDL_syscond.cpp b/src/thread/stdcpp/SDL_syscond.cpp
index 976bff4..fd8445c 100644
--- a/src/thread/stdcpp/SDL_syscond.cpp
+++ b/src/thread/stdcpp/SDL_syscond.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/stdcpp/SDL_sysmutex.cpp b/src/thread/stdcpp/SDL_sysmutex.cpp
index 0402862..c770772 100644
--- a/src/thread/stdcpp/SDL_sysmutex.cpp
+++ b/src/thread/stdcpp/SDL_sysmutex.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/stdcpp/SDL_sysmutex_c.h b/src/thread/stdcpp/SDL_sysmutex_c.h
index ab0f2dd..a984b71 100644
--- a/src/thread/stdcpp/SDL_sysmutex_c.h
+++ b/src/thread/stdcpp/SDL_sysmutex_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/stdcpp/SDL_systhread.cpp b/src/thread/stdcpp/SDL_systhread.cpp
index 6e5ef47..7a0d721 100644
--- a/src/thread/stdcpp/SDL_systhread.cpp
+++ b/src/thread/stdcpp/SDL_systhread.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -153,7 +153,7 @@ SDL_SYS_DetachThread(SDL_Thread * thread)
 
 extern "C"
 SDL_TLSData *
-SDL_SYS_GetTLSData()
+SDL_SYS_GetTLSData(void)
 {
     return SDL_Generic_GetTLSData();
 }
diff --git a/src/thread/stdcpp/SDL_systhread_c.h b/src/thread/stdcpp/SDL_systhread_c.h
index c3cc507..68eaebc 100644
--- a/src/thread/stdcpp/SDL_systhread_c.h
+++ b/src/thread/stdcpp/SDL_systhread_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/windows/SDL_sysmutex.c b/src/thread/windows/SDL_sysmutex.c
index 413cb67..e9dd322 100644
--- a/src/thread/windows/SDL_sysmutex.c
+++ b/src/thread/windows/SDL_sysmutex.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/windows/SDL_syssem.c b/src/thread/windows/SDL_syssem.c
index 86b5888..138cadc 100644
--- a/src/thread/windows/SDL_syssem.c
+++ b/src/thread/windows/SDL_syssem.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/thread/windows/SDL_systhread.c b/src/thread/windows/SDL_systhread.c
index 20a4bd6..37a6350 100644
--- a/src/thread/windows/SDL_systhread.c
+++ b/src/thread/windows/SDL_systhread.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -164,26 +164,55 @@ typedef struct tagTHREADNAME_INFO
 } THREADNAME_INFO;
 #pragma pack(pop)
 
+
+typedef HRESULT (WINAPI *pfnSetThreadDescription)(HANDLE, PCWSTR);
+
 void
 SDL_SYS_SetupThread(const char *name)
 {
-    if ((name != NULL) && IsDebuggerPresent()) {
-        THREADNAME_INFO inf;
+    if (name != NULL) {
+        #ifndef __WINRT__   /* !!! FIXME: There's no LoadLibrary() in WinRT; don't know if SetThreadDescription is available there at all at the moment. */
+        static pfnSetThreadDescription pSetThreadDescription = NULL;
+        static HMODULE kernel32 = 0;
+
+        if (!kernel32) {
+            kernel32 = LoadLibraryW(L"kernel32.dll");
+            if (kernel32) {
+                pSetThreadDescription = (pfnSetThreadDescription) GetProcAddress(kernel32, "SetThreadDescription");
+            }
+        }
 
-        /* C# and friends will try to catch this Exception, let's avoid it. */
-        if (SDL_GetHintBoolean(SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING, SDL_FALSE)) {
-            return;
+        if (pSetThreadDescription != NULL) {
+            WCHAR *strw = WIN_UTF8ToString(name);
+            if (strw) {
+                pSetThreadDescription(GetCurrentThread(), strw);
+                SDL_free(strw);
+            }
         }
+        #endif
 
-        /* This magic tells the debugger to name a thread if it's listening. */
-        SDL_zero(inf);
-        inf.dwType = 0x1000;
-        inf.szName = name;
-        inf.dwThreadID = (DWORD) -1;
-        inf.dwFlags = 0;
+        /* Presumably some version of Visual Studio will understand SetThreadDescription(),
+           but we still need to deal with older OSes and debuggers. Set it with the arcane
+           exception magic, too. */
 
-        /* The debugger catches this, renames the thread, continues on. */
-        RaiseException(0x406D1388, 0, sizeof(inf) / sizeof(ULONG), (const ULONG_PTR*) &inf);
+        if (IsDebuggerPresent()) {
+            THREADNAME_INFO inf;
+
+            /* C# and friends will try to catch this Exception, let's avoid it. */
+            if (SDL_GetHintBoolean(SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING, SDL_TRUE)) {
+                return;
+            }
+
+            /* This magic tells the debugger to name a thread if it's listening. */
+            SDL_zero(inf);
+            inf.dwType = 0x1000;
+            inf.szName = name;
+            inf.dwThreadID = (DWORD) -1;
+            inf.dwFlags = 0;
+
+            /* The debugger catches this, renames the thread, continues on. */
+            RaiseException(0x406D1388, 0, sizeof(inf) / sizeof(ULONG), (const ULONG_PTR*) &inf);
+        }
     }
 }
 
diff --git a/src/thread/windows/SDL_systhread_c.h b/src/thread/windows/SDL_systhread_c.h
index 90866a7..1e5d39d 100644
--- a/src/thread/windows/SDL_systhread_c.h
+++ b/src/thread/windows/SDL_systhread_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,13 +20,13 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_systhread_c_h
-#define _SDL_systhread_c_h
+#ifndef SDL_systhread_c_h_
+#define SDL_systhread_c_h_
 
 #include "../../core/windows/SDL_windows.h"
 
 typedef HANDLE SYS_ThreadHandle;
 
-#endif /* _SDL_systhread_c_h */
+#endif /* SDL_systhread_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/thread/windows/SDL_systls.c b/src/thread/windows/SDL_systls.c
index 7ec630e..1faa76a 100644
--- a/src/thread/windows/SDL_systls.c
+++ b/src/thread/windows/SDL_systls.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -32,7 +32,7 @@ static DWORD thread_local_storage = TLS_OUT_OF_INDEXES;
 static SDL_bool generic_local_storage = SDL_FALSE;
 
 SDL_TLSData *
-SDL_SYS_GetTLSData()
+SDL_SYS_GetTLSData(void)
 {
     if (thread_local_storage == TLS_OUT_OF_INDEXES && !generic_local_storage) {
         static SDL_SpinLock lock;
diff --git a/src/timer/SDL_timer.c b/src/timer/SDL_timer.c
index abe968e..a0f663e 100644
--- a/src/timer/SDL_timer.c
+++ b/src/timer/SDL_timer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -97,7 +97,7 @@ SDL_AddTimerInternal(SDL_TimerData *data, SDL_Timer *timer)
     timer->next = curr;
 }
 
-static int
+static int SDLCALL
 SDL_TimerThread(void *_data)
 {
     SDL_TimerData *data = (SDL_TimerData *)_data;
@@ -168,6 +168,7 @@ SDL_TimerThread(void *_data)
 
             if (interval > 0) {
                 /* Reschedule this timer */
+                current->interval = interval;
                 current->scheduled = tick + interval;
                 SDL_AddTimerInternal(data, current);
             } else {
diff --git a/src/timer/SDL_timer_c.h b/src/timer/SDL_timer_c.h
index 6ae8170..e70771b 100644
--- a/src/timer/SDL_timer_c.h
+++ b/src/timer/SDL_timer_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/timer/dummy/SDL_systimer.c b/src/timer/dummy/SDL_systimer.c
index 1174d22..33a0ff0 100644
--- a/src/timer/dummy/SDL_systimer.c
+++ b/src/timer/dummy/SDL_systimer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/timer/haiku/SDL_systimer.c b/src/timer/haiku/SDL_systimer.c
index f45aa64..0141df4 100644
--- a/src/timer/haiku/SDL_systimer.c
+++ b/src/timer/haiku/SDL_systimer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,7 +22,7 @@
 
 #ifdef SDL_TIMER_HAIKU
 
-#include <os/kernel/OS.h>
+#include <kernel/OS.h>
 
 #include "SDL_timer.h"
 
diff --git a/src/timer/psp/SDL_systimer.c b/src/timer/psp/SDL_systimer.c
index 1e8802c..e6aef42 100644
--- a/src/timer/psp/SDL_systimer.c
+++ b/src/timer/psp/SDL_systimer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/timer/unix/SDL_systimer.c b/src/timer/unix/SDL_systimer.c
index 217fe32..159bda5 100644
--- a/src/timer/unix/SDL_systimer.c
+++ b/src/timer/unix/SDL_systimer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -29,6 +29,7 @@
 
 #include "SDL_timer.h"
 #include "SDL_assert.h"
+#include "../SDL_timer_c.h"
 
 /* The clock_gettime provides monotonous time, so we should use it if
    it's available. The clock_gettime function is behind ifdef
diff --git a/src/timer/windows/SDL_systimer.c b/src/timer/windows/SDL_systimer.c
index 5c9121a..31663ac 100644
--- a/src/timer/windows/SDL_systimer.c
+++ b/src/timer/windows/SDL_systimer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -60,7 +60,7 @@ SDL_SetSystemTimerResolution(const UINT uPeriod)
 #endif
 }
 
-static void
+static void SDLCALL
 SDL_TimerResolutionChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
 {
     UINT uPeriod;
diff --git a/src/video/SDL_RLEaccel.c b/src/video/SDL_RLEaccel.c
index 67baaf6..02b28ce 100644
--- a/src/video/SDL_RLEaccel.c
+++ b/src/video/SDL_RLEaccel.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -90,9 +90,6 @@
 #include "SDL_blit.h"
 #include "SDL_RLEaccel_c.h"
 
-#ifndef MAX
-#define MAX(a, b) ((a) > (b) ? (a) : (b))
-#endif
 #ifndef MIN
 #define MIN(a, b) ((a) < (b) ? (a) : (b))
 #endif
@@ -448,7 +445,7 @@ RLEClipBlit(int w, Uint8 * srcbuf, SDL_Surface * surf_dst,
 
 
 /* blit a colorkeyed RLE surface */
-int
+int SDLCALL
 SDL_RLEBlit(SDL_Surface * surf_src, SDL_Rect * srcrect,
             SDL_Surface * surf_dst, SDL_Rect * dstrect)
 {
@@ -726,7 +723,7 @@ RLEAlphaClipBlit(int w, Uint8 * srcbuf, SDL_Surface * surf_dst,
 }
 
 /* blit a pixel-alpha RLE surface */
-int
+int SDLCALL
 SDL_RLEAlphaBlit(SDL_Surface * surf_src, SDL_Rect * srcrect,
                  SDL_Surface * surf_dst, SDL_Rect * dstrect)
 {
@@ -1280,7 +1277,7 @@ RLEColorkeySurface(SDL_Surface * surface)
     int y;
     Uint8 *srcbuf, *lastline;
     int maxsize = 0;
-    int bpp = surface->format->BytesPerPixel;
+    const int bpp = surface->format->BytesPerPixel;
     getpix_func getpix;
     Uint32 ckey, rgbmask;
     int w, h;
@@ -1303,6 +1300,9 @@ RLEColorkeySurface(SDL_Surface * surface)
         maxsize = surface->h * (4 * (surface->w / 65535 + 1)
                                 + surface->w * 4) + 4;
         break;
+
+    default:
+        return -1;
     }
 
     rlebuf = (Uint8 *) SDL_malloc(maxsize);
@@ -1396,7 +1396,7 @@ RLEColorkeySurface(SDL_Surface * surface)
         surface->map->data = p;
     }
 
-    return (0);
+    return 0;
 }
 
 int
diff --git a/src/video/SDL_RLEaccel_c.h b/src/video/SDL_RLEaccel_c.h
index c04fc15..8931b15 100644
--- a/src/video/SDL_RLEaccel_c.h
+++ b/src/video/SDL_RLEaccel_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,9 +23,9 @@
 /* Useful functions and variables from SDL_RLEaccel.c */
 
 extern int SDL_RLESurface(SDL_Surface * surface);
-extern int SDL_RLEBlit(SDL_Surface * src, SDL_Rect * srcrect,
-                       SDL_Surface * dst, SDL_Rect * dstrect);
-extern int SDL_RLEAlphaBlit(SDL_Surface * src, SDL_Rect * srcrect,
-                            SDL_Surface * dst, SDL_Rect * dstrect);
+extern int SDLCALL SDL_RLEBlit     (SDL_Surface * src, SDL_Rect * srcrect,
+                                    SDL_Surface * dst, SDL_Rect * dstrect);
+extern int SDLCALL SDL_RLEAlphaBlit(SDL_Surface * src, SDL_Rect * srcrect,
+                                    SDL_Surface * dst, SDL_Rect * dstrect);
 extern void SDL_UnRLESurface(SDL_Surface * surface, int recode);
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/SDL_blit.c b/src/video/SDL_blit.c
index 90aa878..2e74042 100644
--- a/src/video/SDL_blit.c
+++ b/src/video/SDL_blit.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -30,7 +30,7 @@
 #include "SDL_pixels_c.h"
 
 /* The general purpose software blit routine */
-static int
+static int SDLCALL
 SDL_SoftBlit(SDL_Surface * src, SDL_Rect * srcrect,
              SDL_Surface * dst, SDL_Rect * dstrect)
 {
@@ -219,6 +219,12 @@ SDL_CalculateBlit(SDL_Surface * surface)
     SDL_BlitMap *map = surface->map;
     SDL_Surface *dst = map->dst;
 
+    /* We don't currently support blitting to < 8 bpp surfaces */
+    if (dst->format->BitsPerPixel < 8) {
+        SDL_InvalidateMap(map);
+        return SDL_SetError("Blit combination not supported");
+    }
+
     /* Clean everything out to start */
     if ((surface->flags & SDL_RLEACCEL) == SDL_RLEACCEL) {
         SDL_UnRLESurface(surface, 1);
@@ -239,6 +245,10 @@ SDL_CalculateBlit(SDL_Surface * surface)
     /* Choose a standard blit function */
     if (map->identity && !(map->info.flags & ~SDL_COPY_RLE_DESIRED)) {
         blit = SDL_BlitCopy;
+    } else if (surface->format->Rloss > 8 || dst->format->Rloss > 8) {
+        /* Greater than 8 bits per channel not supported yet */
+        SDL_InvalidateMap(map);
+        return SDL_SetError("Blit combination not supported");
     } else if (surface->format->BitsPerPixel < 8 &&
                SDL_ISPIXELFORMAT_INDEXED(surface->format->format)) {
         blit = SDL_CalculateBlit0(surface);
diff --git a/src/video/SDL_blit.h b/src/video/SDL_blit.h
index e30f8af..736e783 100644
--- a/src/video/SDL_blit.h
+++ b/src/video/SDL_blit.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_blit_h
-#define _SDL_blit_h
+#ifndef SDL_blit_h_
+#define SDL_blit_h_
 
 #include "SDL_cpuinfo.h"
 #include "SDL_endian.h"
@@ -70,7 +70,8 @@ typedef struct
     Uint8 r, g, b, a;
 } SDL_BlitInfo;
 
-typedef void (SDLCALL * SDL_BlitFunc) (SDL_BlitInfo * info);
+typedef void (*SDL_BlitFunc) (SDL_BlitInfo *info);
+
 
 typedef struct
 {
@@ -443,19 +444,19 @@ do {                                                                    \
 /* Blend the RGB values of two pixels with an alpha value */
 #define ALPHA_BLEND_RGB(sR, sG, sB, A, dR, dG, dB)                      \
 do {                                                                    \
-    dR = ((((unsigned)(sR-dR)*(unsigned)A)/255)+dR);                    \
-    dG = ((((unsigned)(sG-dG)*(unsigned)A)/255)+dG);                    \
-    dB = ((((unsigned)(sB-dB)*(unsigned)A)/255)+dB);                    \
+    dR = (Uint8)((((int)(sR-dR)*(int)A)/255)+dR);                       \
+    dG = (Uint8)((((int)(sG-dG)*(int)A)/255)+dG);                       \
+    dB = (Uint8)((((int)(sB-dB)*(int)A)/255)+dB);                       \
 } while(0)
 
 
 /* Blend the RGBA values of two pixels */
 #define ALPHA_BLEND_RGBA(sR, sG, sB, sA, dR, dG, dB, dA)                \
 do {                                                                    \
-    dR = ((((unsigned)(sR-dR)*(unsigned)sA)/255)+dR);                   \
-    dG = ((((unsigned)(sG-dG)*(unsigned)sA)/255)+dG);                   \
-    dB = ((((unsigned)(sB-dB)*(unsigned)sA)/255)+dB);                   \
-    dA = ((unsigned)sA+(unsigned)dA-((unsigned)sA*dA)/255);             \
+    dR = (Uint8)((((int)(sR-dR)*(int)sA)/255)+dR);                      \
+    dG = (Uint8)((((int)(sG-dG)*(int)sA)/255)+dG);                      \
+    dB = (Uint8)((((int)(sB-dB)*(int)sA)/255)+dB);                      \
+    dA = (Uint8)((int)sA+dA-((int)sA*dA)/255);                          \
 } while(0)
 
 
@@ -471,14 +472,14 @@ do {                                                                    \
 #define DUFFS_LOOP8(pixel_copy_increment, width)                        \
 { int n = (width+7)/8;                                                  \
     switch (width & 7) {                                                \
-    case 0: do {    pixel_copy_increment;                               \
-    case 7:     pixel_copy_increment;                                   \
-    case 6:     pixel_copy_increment;                                   \
-    case 5:     pixel_copy_increment;                                   \
-    case 4:     pixel_copy_increment;                                   \
-    case 3:     pixel_copy_increment;                                   \
-    case 2:     pixel_copy_increment;                                   \
-    case 1:     pixel_copy_increment;                                   \
+    case 0: do {    pixel_copy_increment; /* fallthrough */             \
+    case 7:     pixel_copy_increment;     /* fallthrough */             \
+    case 6:     pixel_copy_increment;     /* fallthrough */             \
+    case 5:     pixel_copy_increment;     /* fallthrough */             \
+    case 4:     pixel_copy_increment;     /* fallthrough */             \
+    case 3:     pixel_copy_increment;     /* fallthrough */             \
+    case 2:     pixel_copy_increment;     /* fallthrough */             \
+    case 1:     pixel_copy_increment;     /* fallthrough */             \
         } while ( --n > 0 );                                            \
     }                                                                   \
 }
@@ -487,10 +488,10 @@ do {                                                                    \
 #define DUFFS_LOOP4(pixel_copy_increment, width)                        \
 { int n = (width+3)/4;                                                  \
     switch (width & 3) {                                                \
-    case 0: do {    pixel_copy_increment;                               \
-    case 3:     pixel_copy_increment;                                   \
-    case 2:     pixel_copy_increment;                                   \
-    case 1:     pixel_copy_increment;                                   \
+    case 0: do {    pixel_copy_increment;   /* fallthrough */           \
+    case 3:     pixel_copy_increment;       /* fallthrough */           \
+    case 2:     pixel_copy_increment;       /* fallthrough */           \
+    case 1:     pixel_copy_increment;       /* fallthrough */           \
         } while (--n > 0);                                              \
     }                                                                   \
 }
@@ -547,6 +548,6 @@ do {                                                                    \
 #pragma warning(disable: 4550)
 #endif
 
-#endif /* _SDL_blit_h */
+#endif /* SDL_blit_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/SDL_blit_0.c b/src/video/SDL_blit_0.c
index fe7330d..523367f 100644
--- a/src/video/SDL_blit_0.c
+++ b/src/video/SDL_blit_0.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/SDL_blit_1.c b/src/video/SDL_blit_1.c
index 69c15d0..27af3c8 100644
--- a/src/video/SDL_blit_1.c
+++ b/src/video/SDL_blit_1.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -70,12 +70,14 @@ Blit1to1(SDL_BlitInfo * info)
 }
 
 /* This is now endian dependent */
-#if ( SDL_BYTEORDER == SDL_LIL_ENDIAN )
-#define HI	1
-#define LO	0
-#else /* ( SDL_BYTEORDER == SDL_BIG_ENDIAN ) */
-#define HI	0
-#define LO	1
+#ifndef USE_DUFFS_LOOP
+# if ( SDL_BYTEORDER == SDL_LIL_ENDIAN )
+#  define HI	1
+#  define LO	0
+# else /* ( SDL_BYTEORDER == SDL_BIG_ENDIAN ) */
+#  define HI	0
+#  define LO	1
+# endif
 #endif
 static void
 Blit1to2(SDL_BlitInfo * info)
diff --git a/src/video/SDL_blit_A.c b/src/video/SDL_blit_A.c
index 0190ffd..e90604e 100644
--- a/src/video/SDL_blit_A.c
+++ b/src/video/SDL_blit_A.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -1317,9 +1317,9 @@ SDL_CalculateBlitA(SDL_Surface * surface)
 
         case 3:
         default:
-            return BlitNtoNPixelAlpha;
+            break;
         }
-        break;
+        return BlitNtoNPixelAlpha;
 
     case SDL_COPY_MODULATE_ALPHA | SDL_COPY_BLEND:
         if (sf->Amask == 0) {
diff --git a/src/video/SDL_blit_N.c b/src/video/SDL_blit_N.c
index 94894a7..af5e150 100644
--- a/src/video/SDL_blit_N.c
+++ b/src/video/SDL_blit_N.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -118,12 +118,6 @@ calc_swizzle32(const SDL_PixelFormat * srcfmt, const SDL_PixelFormat * dstfmt)
         16, 8, 0, 24,
         0, NULL
     };
-    if (!srcfmt) {
-        srcfmt = &default_pixel_format;
-    }
-    if (!dstfmt) {
-        dstfmt = &default_pixel_format;
-    }
     const vector unsigned char plus = VECUINT8_LITERAL(0x00, 0x00, 0x00, 0x00,
                                                        0x04, 0x04, 0x04, 0x04,
                                                        0x08, 0x08, 0x08, 0x08,
@@ -131,11 +125,20 @@ calc_swizzle32(const SDL_PixelFormat * srcfmt, const SDL_PixelFormat * dstfmt)
                                                        0x0C);
     vector unsigned char vswiz;
     vector unsigned int srcvec;
+    Uint32 rmask, gmask, bmask, amask;
+
+    if (!srcfmt) {
+        srcfmt = &default_pixel_format;
+    }
+    if (!dstfmt) {
+        dstfmt = &default_pixel_format;
+    }
+
 #define RESHIFT(X) (3 - ((X) >> 3))
-    Uint32 rmask = RESHIFT(srcfmt->Rshift) << (dstfmt->Rshift);
-    Uint32 gmask = RESHIFT(srcfmt->Gshift) << (dstfmt->Gshift);
-    Uint32 bmask = RESHIFT(srcfmt->Bshift) << (dstfmt->Bshift);
-    Uint32 amask;
+    rmask = RESHIFT(srcfmt->Rshift) << (dstfmt->Rshift);
+    gmask = RESHIFT(srcfmt->Gshift) << (dstfmt->Gshift);
+    bmask = RESHIFT(srcfmt->Bshift) << (dstfmt->Bshift);
+
     /* Use zero for alpha if either surface doesn't have alpha */
     if (dstfmt->Amask) {
         amask =
@@ -147,6 +150,7 @@ calc_swizzle32(const SDL_PixelFormat * srcfmt, const SDL_PixelFormat * dstfmt)
                           0xFFFFFFFF);
     }
 #undef RESHIFT
+
     ((unsigned int *) (char *) &srcvec)[0] = (rmask | gmask | bmask | amask);
     vswiz = vec_add(plus, (vector unsigned char) vec_splat(srcvec, 0));
     return (vswiz);
@@ -1109,6 +1113,7 @@ Blit_RGB101010_index8(SDL_BlitInfo * info)
                                 (((*src)&0x0000F800)>>6)| \
                                 (((*src)&0x000000F8)>>3)); \
 }
+#ifndef USE_DUFFS_LOOP
 #define RGB888_RGB555_TWO(dst, src) { \
     *(Uint32 *)(dst) = (((((src[HI])&0x00F80000)>>9)| \
                          (((src[HI])&0x0000F800)>>6)| \
@@ -1117,6 +1122,7 @@ Blit_RGB101010_index8(SDL_BlitInfo * info)
                          (((src[LO])&0x0000F800)>>6)| \
                          (((src[LO])&0x000000F8)>>3); \
 }
+#endif
 static void
 Blit_RGB888_RGB555(SDL_BlitInfo * info)
 {
@@ -1233,6 +1239,7 @@ Blit_RGB888_RGB555(SDL_BlitInfo * info)
                                 (((*src)&0x0000FC00)>>5)| \
                                 (((*src)&0x000000F8)>>3)); \
 }
+#ifndef USE_DUFFS_LOOP
 #define RGB888_RGB565_TWO(dst, src) { \
     *(Uint32 *)(dst) = (((((src[HI])&0x00F80000)>>8)| \
                          (((src[HI])&0x0000FC00)>>5)| \
@@ -1241,6 +1248,7 @@ Blit_RGB888_RGB555(SDL_BlitInfo * info)
                          (((src[LO])&0x0000FC00)>>5)| \
                          (((src[LO])&0x000000F8)>>3); \
 }
+#endif
 static void
 Blit_RGB888_RGB565(SDL_BlitInfo * info)
 {
@@ -2455,6 +2463,9 @@ BlitNto2101010(SDL_BlitInfo * info)
 }
 
 /* Normal N to N optimized blitters */
+#define NO_ALPHA   1
+#define SET_ALPHA  2
+#define COPY_ALPHA 4
 struct blit_table
 {
     Uint32 srcR, srcG, srcB;
@@ -2462,8 +2473,7 @@ struct blit_table
     Uint32 dstR, dstG, dstB;
     Uint32 blit_features;
     SDL_BlitFunc blitfunc;
-    enum
-    { NO_ALPHA = 1, SET_ALPHA = 2, COPY_ALPHA = 4 } alpha;
+    Uint32 alpha;  /* bitwise NO_ALPHA, SET_ALPHA, COPY_ALPHA */
 };
 static const struct blit_table normal_blit_1[] = {
     /* Default for 8-bit RGB source, never optimized */
diff --git a/src/video/SDL_blit_auto.c b/src/video/SDL_blit_auto.c
index f122819..7b8ae28 100644
--- a/src/video/SDL_blit_auto.c
+++ b/src/video/SDL_blit_auto.c
@@ -1,7 +1,7 @@
 /* DO NOT EDIT!  This file is generated by sdlgenblit.pl */
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/SDL_blit_auto.h b/src/video/SDL_blit_auto.h
index 58a532d..4c8d84e 100644
--- a/src/video/SDL_blit_auto.h
+++ b/src/video/SDL_blit_auto.h
@@ -1,7 +1,7 @@
 /* DO NOT EDIT!  This file is generated by sdlgenblit.pl */
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/SDL_blit_copy.c b/src/video/SDL_blit_copy.c
index 674650d..c84788b 100644
--- a/src/video/SDL_blit_copy.c
+++ b/src/video/SDL_blit_copy.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/SDL_blit_copy.h b/src/video/SDL_blit_copy.h
index 060026d..ecb7d0f 100644
--- a/src/video/SDL_blit_copy.h
+++ b/src/video/SDL_blit_copy.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/SDL_blit_slow.c b/src/video/SDL_blit_slow.c
index 02ab41d..cd32201 100644
--- a/src/video/SDL_blit_slow.c
+++ b/src/video/SDL_blit_slow.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/SDL_blit_slow.h b/src/video/SDL_blit_slow.h
index 75005fc..9f1c7c7 100644
--- a/src/video/SDL_blit_slow.h
+++ b/src/video/SDL_blit_slow.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/SDL_bmp.c b/src/video/SDL_bmp.c
index 2d9cf24..1e77b98 100644
--- a/src/video/SDL_bmp.c
+++ b/src/video/SDL_bmp.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -124,6 +124,9 @@ SDL_LoadBMP_RW(SDL_RWops * src, int freesrc)
     Uint32 biClrUsed = 0;
     /* Uint32 biClrImportant = 0; */
 
+    (void) haveRGBMasks;
+    (void) haveAlphaMask;
+
     /* Make sure we are passed a valid data source */
     surface = NULL;
     was_error = SDL_FALSE;
diff --git a/src/video/SDL_clipboard.c b/src/video/SDL_clipboard.c
index 91d1eee..033ad8d 100644
--- a/src/video/SDL_clipboard.c
+++ b/src/video/SDL_clipboard.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/SDL_egl.c b/src/video/SDL_egl.c
index c903805..9ccc2c3 100644
--- a/src/video/SDL_egl.c
+++ b/src/video/SDL_egl.c
@@ -1,6 +1,6 @@
 /*
  *  Simple DirectMedia Layer
- *  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+ *  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
  * 
  *  This software is provided 'as-is', without any express or implied
  *  warranty.  In no event will the authors be held liable for any damages
@@ -25,8 +25,12 @@
 #if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT
 #include "../core/windows/SDL_windows.h"
 #endif
+#if SDL_VIDEO_DRIVER_ANDROID
+#include <android/native_window.h>
+#endif
 
 #include "SDL_sysvideo.h"
+#include "SDL_log.h"
 #include "SDL_egl_c.h"
 #include "SDL_loadso.h"
 #include "SDL_hints.h"
@@ -40,8 +44,10 @@
 
 #if SDL_VIDEO_DRIVER_RPI
 /* Raspbian places the OpenGL ES/EGL binaries in a non standard path */
-#define DEFAULT_EGL "/opt/vc/lib/libEGL.so"
-#define DEFAULT_OGL_ES2 "/opt/vc/lib/libGLESv2.so"
+#define DEFAULT_EGL "/opt/vc/lib/libbrcmEGL.so"
+#define DEFAULT_OGL_ES2 "/opt/vc/lib/libbrcmGLESv2.so"
+#define ALT_EGL "/opt/vc/lib/libEGL.so"
+#define ALT_OGL_ES2 "/opt/vc/lib/libGLESv2.so"
 #define DEFAULT_OGL_ES_PVR "/opt/vc/lib/libGLES_CM.so"
 #define DEFAULT_OGL_ES "/opt/vc/lib/libGLESv1_CM.so"
 
@@ -68,46 +74,130 @@
 #define DEFAULT_OGL_ES "libGLESv1_CM.so.1"
 #endif /* SDL_VIDEO_DRIVER_RPI */
 
+#ifdef SDL_VIDEO_STATIC_ANGLE
+#define LOAD_FUNC(NAME) \
+_this->egl_data->NAME = (void *)NAME;
+#else
 #define LOAD_FUNC(NAME) \
 _this->egl_data->NAME = SDL_LoadFunction(_this->egl_data->dll_handle, #NAME); \
 if (!_this->egl_data->NAME) \
 { \
     return SDL_SetError("Could not retrieve EGL function " #NAME); \
 }
-    
+#endif
+
+static const char * SDL_EGL_GetErrorName(EGLint eglErrorCode)
+{
+#define SDL_EGL_ERROR_TRANSLATE(e) case e: return #e;
+    switch (eglErrorCode) {
+        SDL_EGL_ERROR_TRANSLATE(EGL_SUCCESS);
+        SDL_EGL_ERROR_TRANSLATE(EGL_NOT_INITIALIZED);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_ACCESS);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_ALLOC);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_ATTRIBUTE);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_CONTEXT);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_CONFIG);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_CURRENT_SURFACE);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_DISPLAY);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_SURFACE);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_MATCH);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_PARAMETER);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_NATIVE_PIXMAP);
+        SDL_EGL_ERROR_TRANSLATE(EGL_BAD_NATIVE_WINDOW);
+        SDL_EGL_ERROR_TRANSLATE(EGL_CONTEXT_LOST);
+    }
+    return "";
+}
+
+int SDL_EGL_SetErrorEx(const char * message, const char * eglFunctionName, EGLint eglErrorCode)
+{
+    const char * errorText = SDL_EGL_GetErrorName(eglErrorCode);
+    char altErrorText[32];
+    if (errorText[0] == '\0') {
+        /* An unknown-to-SDL error code was reported.  Report its hexadecimal value, instead of its name. */
+        SDL_snprintf(altErrorText, SDL_arraysize(altErrorText), "0x%x", (unsigned int)eglErrorCode);
+        errorText = altErrorText;
+    }
+    return SDL_SetError("%s (call to %s failed, reporting an error of %s)", message, eglFunctionName, errorText);
+}
+
 /* EGL implementation of SDL OpenGL ES support */
-#ifdef EGL_KHR_create_context        
-static int SDL_EGL_HasExtension(_THIS, const char *ext)
+typedef enum {
+    SDL_EGL_DISPLAY_EXTENSION,
+    SDL_EGL_CLIENT_EXTENSION
+} SDL_EGL_ExtensionType;
+
+static SDL_bool SDL_EGL_HasExtension(_THIS, SDL_EGL_ExtensionType type, const char *ext)
 {
-    int i;
-    int len = 0;
     size_t ext_len;
-    const char *exts;
-    const char *ext_word;
+    const char *ext_override;
+    const char *egl_extstr;
+    const char *ext_start;
+
+    /* Invalid extensions can be rejected early */
+    if (ext == NULL || *ext == 0 || SDL_strchr(ext, ' ') != NULL) {
+        /* SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "SDL_EGL_HasExtension: Invalid EGL extension"); */
+        return SDL_FALSE;
+    }
+
+    /* Extensions can be masked with an environment variable.
+     * Unlike the OpenGL override, this will use the set bits of an integer
+     * to disable the extension.
+     *  Bit   Action
+     *  0     If set, the display extension is masked and not present to SDL.
+     *  1     If set, the client extension is masked and not present to SDL.
+     */
+    ext_override = SDL_getenv(ext);
+    if (ext_override != NULL) {
+        int disable_ext = SDL_atoi(ext_override);
+        if (disable_ext & 0x01 && type == SDL_EGL_DISPLAY_EXTENSION) {
+            return SDL_FALSE;
+        } else if (disable_ext & 0x02 && type == SDL_EGL_CLIENT_EXTENSION) {
+            return SDL_FALSE;
+        }
+    }
 
     ext_len = SDL_strlen(ext);
-    exts = _this->egl_data->eglQueryString(_this->egl_data->egl_display, EGL_EXTENSIONS);
+    switch (type) {
+    case SDL_EGL_DISPLAY_EXTENSION:
+        egl_extstr = _this->egl_data->eglQueryString(_this->egl_data->egl_display, EGL_EXTENSIONS);
+        break;
+    case SDL_EGL_CLIENT_EXTENSION:
+        /* EGL_EXT_client_extensions modifies eglQueryString to return client extensions
+         * if EGL_NO_DISPLAY is passed. Implementations without it are required to return NULL.
+         * This behavior is included in EGL 1.5.
+         */
+        egl_extstr = _this->egl_data->eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
+        break;
+    default:
+        /* SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "SDL_EGL_HasExtension: Invalid extension type"); */
+        return SDL_FALSE;
+    }
 
-    if (exts) {
-        ext_word = exts;
+    if (egl_extstr != NULL) {
+        ext_start = egl_extstr;
 
-        for (i = 0; exts[i] != 0; i++) {
-            if (exts[i] == ' ') {
-                if (ext_len == len && !SDL_strncmp(ext_word, ext, len)) {
-                    return 1;
+        while (*ext_start) {
+            ext_start = SDL_strstr(ext_start, ext);
+            if (ext_start == NULL) {
+                return SDL_FALSE;
+            }
+            /* Check if the match is not just a substring of one of the extensions */
+            if (ext_start == egl_extstr || *(ext_start - 1) == ' ') {
+                if (ext_start[ext_len] == ' ' || ext_start[ext_len] == 0) {
+                    return SDL_TRUE;
                 }
-
-                len = 0;
-                ext_word = &exts[i + 1];
-            } else {
-                len++;
+            }
+            /* If the search stopped in the middle of an extension, skip to the end of it */
+            ext_start += ext_len;
+            while (*ext_start != ' ' && *ext_start != 0) {
+                ext_start++;
             }
         }
     }
 
-    return 0;
+    return SDL_FALSE;
 }
-#endif /* EGL_KHR_create_context */
 
 void *
 SDL_EGL_GetProcAddress(_THIS, const char *proc)
@@ -116,7 +206,7 @@ SDL_EGL_GetProcAddress(_THIS, const char *proc)
     void *retval;
     
     /* eglGetProcAddress is busted on Android http://code.google.com/p/android/issues/detail?id=7681 */
-#if !defined(SDL_VIDEO_DRIVER_ANDROID) && !defined(SDL_VIDEO_DRIVER_MIR) 
+#if !defined(SDL_VIDEO_DRIVER_ANDROID)
     if (_this->egl_data->eglGetProcAddress) {
         retval = _this->egl_data->eglGetProcAddress(proc);
         if (retval) {
@@ -158,10 +248,11 @@ SDL_EGL_UnloadLibrary(_THIS)
 }
 
 int
-SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_display)
+SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_display, EGLenum platform)
 {
     void *dll_handle = NULL, *egl_dll_handle = NULL; /* The naming is counter intuitive, but hey, I just work here -- Gabriel */
     const char *path = NULL;
+    int egl_version_major = 0, egl_version_minor = 0;
 #if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT
     const char *d3dcompiler;
 #endif
@@ -185,10 +276,13 @@ SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_displa
         }
     }
     if (SDL_strcasecmp(d3dcompiler, "none") != 0) {
-        SDL_LoadObject(d3dcompiler);
+        if (SDL_LoadObject(d3dcompiler) == NULL) {
+            SDL_ClearError();
+        }
     }
 #endif
 
+#ifndef SDL_VIDEO_STATIC_ANGLE
     /* A funny thing, loading EGL.so first does not work on the Raspberry, so we load libGL* first */
     path = SDL_getenv("SDL_VIDEO_GL_DRIVER");
     if (path != NULL) {
@@ -200,6 +294,13 @@ SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_displa
             if (_this->gl_config.major_version > 1) {
                 path = DEFAULT_OGL_ES2;
                 egl_dll_handle = SDL_LoadObject(path);
+#ifdef ALT_OGL_ES2
+                if (egl_dll_handle == NULL) {
+                    path = ALT_OGL_ES2;
+                    egl_dll_handle = SDL_LoadObject(path);
+                }
+#endif
+
             } else {
                 path = DEFAULT_OGL_ES;
                 egl_dll_handle = SDL_LoadObject(path);
@@ -236,6 +337,14 @@ SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_displa
             path = DEFAULT_EGL;
         }
         dll_handle = SDL_LoadObject(path);
+
+#ifdef ALT_EGL
+        if (dll_handle == NULL) {
+            path = ALT_EGL;
+            dll_handle = SDL_LoadObject(path);
+        }
+#endif
+
         if (dll_handle == NULL || SDL_LoadFunction(dll_handle, "eglChooseConfig") == NULL) {
             if (dll_handle != NULL) {
                 SDL_UnloadObject(dll_handle);
@@ -244,6 +353,7 @@ SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_displa
         }
         SDL_ClearError();
     }
+#endif
 
     _this->egl_data->dll_handle = dll_handle;
 
@@ -265,10 +375,43 @@ SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_displa
     LOAD_FUNC(eglWaitGL);
     LOAD_FUNC(eglBindAPI);
     LOAD_FUNC(eglQueryString);
-    
+    LOAD_FUNC(eglGetError);
+
+    if (_this->egl_data->eglQueryString) {
+        /* EGL 1.5 allows querying for client version */
+        const char *egl_version = _this->egl_data->eglQueryString(EGL_NO_DISPLAY, EGL_VERSION);
+        if (egl_version != NULL) {
+            if (SDL_sscanf(egl_version, "%d.%d", &egl_version_major, &egl_version_minor) != 2) {
+                egl_version_major = 0;
+                egl_version_minor = 0;
+                SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "Could not parse EGL version string: %s", egl_version);
+            }
+        }
+    }
+
+    if (egl_version_major == 1 && egl_version_minor == 5) {
+        LOAD_FUNC(eglGetPlatformDisplay);
+    }
+
+    _this->egl_data->egl_display = EGL_NO_DISPLAY;
 #if !defined(__WINRT__)
-    _this->egl_data->egl_display = _this->egl_data->eglGetDisplay(native_display);
-    if (!_this->egl_data->egl_display) {
+    if (platform) {
+        if (egl_version_major == 1 && egl_version_minor == 5) {
+            _this->egl_data->egl_display = _this->egl_data->eglGetPlatformDisplay(platform, (void *)(size_t)native_display, NULL);
+        } else {
+            if (SDL_EGL_HasExtension(_this, SDL_EGL_CLIENT_EXTENSION, "EGL_EXT_platform_base")) {
+                _this->egl_data->eglGetPlatformDisplayEXT = SDL_EGL_GetProcAddress(_this, "eglGetPlatformDisplayEXT");
+                if (_this->egl_data->eglGetPlatformDisplayEXT) {
+                    _this->egl_data->egl_display = _this->egl_data->eglGetPlatformDisplayEXT(platform, (void *)(size_t)native_display, NULL);
+                }
+            }
+        }
+    }
+    /* Try the implementation-specific eglGetDisplay even if eglGetPlatformDisplay fails */
+    if (_this->egl_data->egl_display == EGL_NO_DISPLAY) {
+        _this->egl_data->egl_display = _this->egl_data->eglGetDisplay(native_display);
+    }
+    if (_this->egl_data->egl_display == EGL_NO_DISPLAY) {
         return SDL_SetError("Could not get EGL display");
     }
     
@@ -277,8 +420,6 @@ SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_displa
     }
 #endif
 
-    _this->gl_config.driver_loaded = 1;
-
     if (path) {
         SDL_strlcpy(_this->gl_config.driver_path, path, sizeof(_this->gl_config.driver_path) - 1);
     } else {
@@ -291,13 +432,19 @@ SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_displa
 int
 SDL_EGL_ChooseConfig(_THIS) 
 {
-    /* 64 seems nice. */
+/* 64 seems nice. */
     EGLint attribs[64];
     EGLint found_configs = 0, value;
+#ifdef SDL_VIDEO_DRIVER_KMSDRM
+    /* Intel EGL on KMS/DRM (al least) returns invalid configs that confuse the bitdiff search used */
+    /* later in this function, so we simply use the first one when using the KMSDRM driver for now. */
+    EGLConfig configs[1];
+#else
     /* 128 seems even nicer here */
     EGLConfig configs[128];
+#endif
     int i, j, best_bitdiff = -1, bitdiff;
-    
+   
     if (!_this->egl_data) {
         /* The EGL library wasn't loaded, SDL_GetError() should have info */
         return -1;
@@ -342,7 +489,7 @@ SDL_EGL_ChooseConfig(_THIS)
 
     if (_this->gl_config.framebuffer_srgb_capable) {
 #ifdef EGL_KHR_gl_colorspace
-        if (SDL_EGL_HasExtension(_this, "EGL_KHR_gl_colorspace")) {
+        if (SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_gl_colorspace")) {
             attribs[i++] = EGL_GL_COLORSPACE_KHR;
             attribs[i++] = EGL_GL_COLORSPACE_SRGB_KHR;
         } else
@@ -356,7 +503,7 @@ SDL_EGL_ChooseConfig(_THIS)
     if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) {
 #ifdef EGL_KHR_create_context
         if (_this->gl_config.major_version >= 3 &&
-            SDL_EGL_HasExtension(_this, "EGL_KHR_create_context")) {
+            SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_create_context")) {
             attribs[i++] = EGL_OPENGL_ES3_BIT_KHR;
         } else
 #endif
@@ -378,7 +525,7 @@ SDL_EGL_ChooseConfig(_THIS)
         configs, SDL_arraysize(configs),
         &found_configs) == EGL_FALSE ||
         found_configs == 0) {
-        return SDL_SetError("Couldn't find matching EGL config");
+        return SDL_EGL_SetError("Couldn't find matching EGL config", "eglChooseConfig");
     }
 
     /* eglChooseConfig returns a number of configurations that match or exceed the requested attribs. */
@@ -458,7 +605,7 @@ SDL_EGL_CreateContext(_THIS, EGLSurface egl_surface)
         /* The Major/minor version, context profiles, and context flags can
          * only be specified when this extension is available.
          */
-        if (SDL_EGL_HasExtension(_this, "EGL_KHR_create_context")) {
+        if (SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_create_context")) {
             attribs[attr++] = EGL_CONTEXT_MAJOR_VERSION_KHR;
             attribs[attr++] = major_version;
             attribs[attr++] = EGL_CONTEXT_MINOR_VERSION_KHR;
@@ -483,6 +630,19 @@ SDL_EGL_CreateContext(_THIS, EGLSurface egl_surface)
         }
     }
 
+    if (_this->gl_config.no_error) {
+#ifdef EGL_KHR_create_context_no_error
+        if (SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_create_context_no_error")) {
+            attribs[attr++] = EGL_CONTEXT_OPENGL_NO_ERROR_KHR;
+            attribs[attr++] = _this->gl_config.no_error;
+        } else
+#endif
+        {
+            SDL_SetError("EGL implementation does not support no_error contexts");
+            return NULL;
+        }
+    }
+
     attribs[attr++] = EGL_NONE;
 
     /* Bind the API */
@@ -497,15 +657,23 @@ SDL_EGL_CreateContext(_THIS, EGLSurface egl_surface)
                                       share_context, attribs);
 
     if (egl_context == EGL_NO_CONTEXT) {
-        SDL_SetError("Could not create EGL context");
+        SDL_EGL_SetError("Could not create EGL context", "eglCreateContext");
         return NULL;
     }
 
     _this->egl_data->egl_swapinterval = 0;
 
     if (SDL_EGL_MakeCurrent(_this, egl_surface, egl_context) < 0) {
+        /* Save the SDL error set by SDL_EGL_MakeCurrent */
+        char errorText[1024];
+        SDL_strlcpy(errorText, SDL_GetError(), SDL_arraysize(errorText));
+
+        /* Delete the context, which may alter the value returned by SDL_GetError() */
         SDL_EGL_DeleteContext(_this, egl_context);
-        SDL_SetError("Could not make EGL context current");
+
+        /* Restore the SDL error */
+        SDL_SetError("%s", errorText);
+
         return NULL;
     }
 
@@ -529,7 +697,7 @@ SDL_EGL_MakeCurrent(_THIS, EGLSurface egl_surface, SDL_GLContext context)
     } else {
         if (!_this->egl_data->eglMakeCurrent(_this->egl_data->egl_display,
             egl_surface, egl_surface, egl_context)) {
-            return SDL_SetError("Unable to make EGL context current");
+            return SDL_EGL_SetError("Unable to make EGL context current", "eglMakeCurrent");
         }
     }
       
@@ -551,7 +719,7 @@ SDL_EGL_SetSwapInterval(_THIS, int interval)
         return 0;
     }
     
-    return SDL_SetError("Unable to set the EGL swap interval");
+    return SDL_EGL_SetError("Unable to set the EGL swap interval", "eglSwapInterval");
 }
 
 int
@@ -565,10 +733,13 @@ SDL_EGL_GetSwapInterval(_THIS)
     return _this->egl_data->egl_swapinterval;
 }
 
-void
+int
 SDL_EGL_SwapBuffers(_THIS, EGLSurface egl_surface)
 {
-    _this->egl_data->eglSwapBuffers(_this->egl_data->egl_display, egl_surface);
+    if (!_this->egl_data->eglSwapBuffers(_this->egl_data->egl_display, egl_surface)) {
+        return SDL_EGL_SetError("unable to show color buffer in an OS-native window", "eglSwapBuffers");
+    }
+    return 0;
 }
 
 void
@@ -591,11 +762,13 @@ SDL_EGL_DeleteContext(_THIS, SDL_GLContext context)
 EGLSurface *
 SDL_EGL_CreateSurface(_THIS, NativeWindowType nw) 
 {
+    EGLSurface * surface;
+
     if (SDL_EGL_ChooseConfig(_this) != 0) {
         return EGL_NO_SURFACE;
     }
     
-#if __ANDROID__
+#if SDL_VIDEO_DRIVER_ANDROID
     {
         /* Android docs recommend doing this!
          * Ref: http://developer.android.com/reference/android/app/NativeActivity.html 
@@ -609,10 +782,14 @@ SDL_EGL_CreateSurface(_THIS, NativeWindowType nw)
     }
 #endif    
     
-    return _this->egl_data->eglCreateWindowSurface(
+    surface = _this->egl_data->eglCreateWindowSurface(
             _this->egl_data->egl_display,
             _this->egl_data->egl_config,
             nw, NULL);
+    if (surface == EGL_NO_SURFACE) {
+        SDL_EGL_SetError("unable to create an EGL window surface", "eglCreateWindowSurface");
+    }
+    return surface;
 }
 
 void
@@ -630,4 +807,4 @@ SDL_EGL_DestroySurface(_THIS, EGLSurface egl_surface)
 #endif /* SDL_VIDEO_OPENGL_EGL */
 
 /* vi: set ts=4 sw=4 expandtab: */
-    
+
diff --git a/src/video/SDL_egl_c.h b/src/video/SDL_egl_c.h
index c683dff..f727e66 100644
--- a/src/video/SDL_egl_c.h
+++ b/src/video/SDL_egl_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_egl_h
-#define _SDL_egl_h
+#ifndef SDL_egl_h_
+#define SDL_egl_h_
 
 #if SDL_VIDEO_OPENGL_EGL
 
@@ -37,6 +37,12 @@ typedef struct SDL_EGL_VideoData
     int egl_swapinterval;
     
     EGLDisplay(EGLAPIENTRY *eglGetDisplay) (NativeDisplayType display);
+    EGLDisplay(EGLAPIENTRY *eglGetPlatformDisplay) (EGLenum platform,
+                                void *native_display,
+                                const EGLint *attrib_list);
+    EGLDisplay(EGLAPIENTRY *eglGetPlatformDisplayEXT) (EGLenum platform,
+                                void *native_display,
+                                const EGLint *attrib_list);
     EGLBoolean(EGLAPIENTRY *eglInitialize) (EGLDisplay dpy, EGLint * major,
                                 EGLint * minor);
     EGLBoolean(EGLAPIENTRY  *eglTerminate) (EGLDisplay dpy);
@@ -79,11 +85,16 @@ typedef struct SDL_EGL_VideoData
     
     EGLBoolean(EGLAPIENTRY *eglBindAPI)(EGLenum);
 
+    EGLint(EGLAPIENTRY *eglGetError)(void);
+
 } SDL_EGL_VideoData;
 
 /* OpenGLES functions */
 extern int SDL_EGL_GetAttribute(_THIS, SDL_GLattr attrib, int *value);
-extern int SDL_EGL_LoadLibrary(_THIS, const char *path, NativeDisplayType native_display);
+/* SDL_EGL_LoadLibrary can get a display for a specific platform (EGL_PLATFORM_*)
+ * or, if 0 is passed, let the implementation decide.
+ */
+extern int SDL_EGL_LoadLibrary(_THIS, const char *path, NativeDisplayType native_display, EGLenum platform);
 extern void *SDL_EGL_GetProcAddress(_THIS, const char *proc);
 extern void SDL_EGL_UnloadLibrary(_THIS);
 extern int SDL_EGL_ChooseConfig(_THIS);
@@ -96,14 +107,18 @@ extern void SDL_EGL_DestroySurface(_THIS, EGLSurface egl_surface);
 /* These need to be wrapped to get the surface for the window by the platform GLES implementation */
 extern SDL_GLContext SDL_EGL_CreateContext(_THIS, EGLSurface egl_surface);
 extern int SDL_EGL_MakeCurrent(_THIS, EGLSurface egl_surface, SDL_GLContext context);
-extern void SDL_EGL_SwapBuffers(_THIS, EGLSurface egl_surface);
+extern int SDL_EGL_SwapBuffers(_THIS, EGLSurface egl_surface);
+
+/* SDL Error-reporting */
+extern int SDL_EGL_SetErrorEx(const char * message, const char * eglFunctionName, EGLint eglErrorCode);
+#define SDL_EGL_SetError(message, eglFunctionName) SDL_EGL_SetErrorEx(message, eglFunctionName, _this->egl_data->eglGetError())
 
 /* A few of useful macros */
 
-#define SDL_EGL_SwapWindow_impl(BACKEND) void \
+#define SDL_EGL_SwapWindow_impl(BACKEND) int \
 BACKEND ## _GLES_SwapWindow(_THIS, SDL_Window * window) \
 {\
-    SDL_EGL_SwapBuffers(_this, ((SDL_WindowData *) window->driverdata)->egl_surface);\
+    return SDL_EGL_SwapBuffers(_this, ((SDL_WindowData *) window->driverdata)->egl_surface);\
 }
 
 #define SDL_EGL_MakeCurrent_impl(BACKEND) int \
@@ -125,6 +140,6 @@ BACKEND ## _GLES_CreateContext(_THIS, SDL_Window * window) \
 
 #endif /* SDL_VIDEO_OPENGL_EGL */
 
-#endif /* _SDL_egl_h */
+#endif /* SDL_egl_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/SDL_fillrect.c b/src/video/SDL_fillrect.c
index e34a43c..4634656 100644
--- a/src/video/SDL_fillrect.c
+++ b/src/video/SDL_fillrect.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -144,13 +144,13 @@ SDL_FillRect1(Uint8 * pixels, int pitch, Uint32 color, int w, int h)
             switch ((uintptr_t) p & 3) {
             case 1:
                 *p++ = (Uint8) color;
-                --n;
+                --n;                    /* fallthrough */
             case 2:
                 *p++ = (Uint8) color;
-                --n;
+                --n;                    /* fallthrough */
             case 3:
                 *p++ = (Uint8) color;
-                --n;
+                --n;                    /* fallthrough */
             }
             SDL_memset4(p, color, (n >> 2));
         }
@@ -158,11 +158,11 @@ SDL_FillRect1(Uint8 * pixels, int pitch, Uint32 color, int w, int h)
             p += (n & ~3);
             switch (n & 3) {
             case 3:
-                *p++ = (Uint8) color;
+                *p++ = (Uint8) color;   /* fallthrough */
             case 2:
-                *p++ = (Uint8) color;
+                *p++ = (Uint8) color;   /* fallthrough */
             case 1:
-                *p++ = (Uint8) color;
+                *p++ = (Uint8) color;   /* fallthrough */
             }
         }
         pixels += pitch;
diff --git a/src/video/SDL_pixels.c b/src/video/SDL_pixels.c
index d905656..649303c 100644
--- a/src/video/SDL_pixels.c
+++ b/src/video/SDL_pixels.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -326,7 +326,7 @@ SDL_MasksToPixelFormatEnum(int bpp, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask,
         if (Rmask == 0) {
             return SDL_PIXELFORMAT_RGB555;
         }
-        /* Fall through to 16-bit checks */
+	/* fallthrough */
     case 16:
         if (Rmask == 0) {
             return SDL_PIXELFORMAT_RGB565;
@@ -403,6 +403,13 @@ SDL_MasksToPixelFormatEnum(int bpp, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask,
             Amask == 0x0000) {
             return SDL_PIXELFORMAT_BGR565;
         }
+        if (Rmask == 0x003F &&
+            Gmask == 0x07C0 &&
+            Bmask == 0xF800 &&
+            Amask == 0x0000) {
+            /* Technically this would be BGR556, but Witek says this works in bug 3158 */
+            return SDL_PIXELFORMAT_RGB565;
+        }
         break;
     case 24:
         switch (Rmask) {
@@ -651,7 +658,7 @@ SDL_SetPixelFormatPalette(SDL_PixelFormat * format, SDL_Palette *palette)
         return SDL_SetError("SDL_SetPixelFormatPalette() passed NULL format");
     }
 
-    if (palette && palette->ncolors != (1 << format->BitsPerPixel)) {
+    if (palette && palette->ncolors > (1 << format->BitsPerPixel)) {
         return SDL_SetError("SDL_SetPixelFormatPalette() passed a palette that doesn't match the format");
     }
 
diff --git a/src/video/SDL_pixels_c.h b/src/video/SDL_pixels_c.h
index 4ee91b8..e79e831 100644
--- a/src/video/SDL_pixels_c.h
+++ b/src/video/SDL_pixels_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/SDL_rect.c b/src/video/SDL_rect.c
index 2b29451..3b3e3fc 100644
--- a/src/video/SDL_rect.c
+++ b/src/video/SDL_rect.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,7 +22,7 @@
 
 #include "SDL_rect.h"
 #include "SDL_rect_c.h"
-
+#include "SDL_assert.h"
 
 SDL_bool
 SDL_HasIntersection(const SDL_Rect * A, const SDL_Rect * B)
@@ -441,9 +441,15 @@ SDL_IntersectRectAndLine(const SDL_Rect * rect, int *X1, int *Y1, int *X2,
                 y = recty2;
                 x = x1 + ((x2 - x1) * (y - y1)) / (y2 - y1);
             } else if (outcode2 & CODE_LEFT) {
+                /* If this assertion ever fires, here's the static analysis that warned about it:
+                   http://buildbot.libsdl.org/sdl-static-analysis/sdl-macosx-static-analysis/sdl-macosx-static-analysis-1101/report-b0d01a.html#EndPath */
+                SDL_assert(x2 != x1);  /* if equal: division by zero. */
                 x = rectx1;
                 y = y1 + ((y2 - y1) * (x - x1)) / (x2 - x1);
             } else if (outcode2 & CODE_RIGHT) {
+                /* If this assertion ever fires, here's the static analysis that warned about it:
+                   http://buildbot.libsdl.org/sdl-static-analysis/sdl-macosx-static-analysis/sdl-macosx-static-analysis-1101/report-39b114.html#EndPath */
+                SDL_assert(x2 != x1);  /* if equal: division by zero. */
                 x = rectx2;
                 y = y1 + ((y2 - y1) * (x - x1)) / (x2 - x1);
             }
diff --git a/src/video/SDL_rect_c.h b/src/video/SDL_rect_c.h
index aa5fbde..6f2d824 100644
--- a/src/video/SDL_rect_c.h
+++ b/src/video/SDL_rect_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/SDL_shape.c b/src/video/SDL_shape.c
index 4a2e546..d56722d 100644
--- a/src/video/SDL_shape.c
+++ b/src/video/SDL_shape.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -35,6 +35,10 @@ SDL_CreateShapedWindow(const char *title,unsigned int x,unsigned int y,unsigned
     SDL_Window *result = NULL;
     result = SDL_CreateWindow(title,-1000,-1000,w,h,(flags | SDL_WINDOW_BORDERLESS) & (~SDL_WINDOW_FULLSCREEN) & (~SDL_WINDOW_RESIZABLE) /* & (~SDL_WINDOW_SHOWN) */);
     if(result != NULL) {
+        if (SDL_GetVideoDevice()->shape_driver.CreateShaper == NULL) {
+            SDL_DestroyWindow(result);
+            return NULL;
+        }
         result->shaper = SDL_GetVideoDevice()->shape_driver.CreateShaper(result);
         if(result->shaper != NULL) {
             result->shaper->userx = x;
@@ -70,11 +74,14 @@ SDL_CalculateShapeBitmap(SDL_WindowShapeMode mode,SDL_Surface *shape,Uint8* bitm
     int y = 0;
     Uint8 r = 0,g = 0,b = 0,alpha = 0;
     Uint8* pixel = NULL;
-    Uint32 bitmap_pixel,pixel_value = 0,mask_value = 0;
+    Uint32 pixel_value = 0,mask_value = 0;
+    int bytes_per_scanline = (shape->w + (ppb - 1)) / ppb;
+    Uint8 *bitmap_scanline;
     SDL_Color key;
     if(SDL_MUSTLOCK(shape))
         SDL_LockSurface(shape);
     for(y = 0;y<shape->h;y++) {
+        bitmap_scanline = bitmap + y * bytes_per_scanline;
         for(x=0;x<shape->w;x++) {
             alpha = 0;
             pixel_value = 0;
@@ -94,7 +101,6 @@ SDL_CalculateShapeBitmap(SDL_WindowShapeMode mode,SDL_Surface *shape,Uint8* bitm
                     break;
             }
             SDL_GetRGBA(pixel_value,shape->format,&r,&g,&b,&alpha);
-            bitmap_pixel = y*shape->w + x;
             switch(mode.mode) {
                 case(ShapeModeDefault):
                     mask_value = (alpha >= 1 ? 1 : 0);
@@ -110,7 +116,7 @@ SDL_CalculateShapeBitmap(SDL_WindowShapeMode mode,SDL_Surface *shape,Uint8* bitm
                     mask_value = ((key.r != r || key.g != g || key.b != b) ? 1 : 0);
                     break;
             }
-            bitmap[bitmap_pixel / ppb] |= mask_value << (7 - ((ppb - 1) - (bitmap_pixel % ppb)));
+            bitmap_scanline[x / ppb] |= mask_value << (x % ppb);
         }
     }
     if(SDL_MUSTLOCK(shape))
@@ -206,8 +212,14 @@ RecursivelyCalculateShapeTree(SDL_WindowShapeMode mode,SDL_Surface* mask,SDL_Rec
 SDL_ShapeTree*
 SDL_CalculateShapeTree(SDL_WindowShapeMode mode,SDL_Surface* shape)
 {
-    SDL_Rect dimensions = {0,0,shape->w,shape->h};
+    SDL_Rect dimensions;
     SDL_ShapeTree* result = NULL;
+
+    dimensions.x = 0;
+    dimensions.y = 0;
+    dimensions.w = shape->w;
+    dimensions.h = shape->h;
+
     if(SDL_MUSTLOCK(shape))
         SDL_LockSurface(shape);
     result = RecursivelyCalculateShapeTree(mode,shape,dimensions);
@@ -234,10 +246,10 @@ void
 SDL_FreeShapeTree(SDL_ShapeTree** shape_tree)
 {
     if((*shape_tree)->kind == QuadShape) {
-        SDL_FreeShapeTree((SDL_ShapeTree **)&(*shape_tree)->data.children.upleft);
-        SDL_FreeShapeTree((SDL_ShapeTree **)&(*shape_tree)->data.children.upright);
-        SDL_FreeShapeTree((SDL_ShapeTree **)&(*shape_tree)->data.children.downleft);
-        SDL_FreeShapeTree((SDL_ShapeTree **)&(*shape_tree)->data.children.downright);
+        SDL_FreeShapeTree((SDL_ShapeTree **)(char*)&(*shape_tree)->data.children.upleft);
+        SDL_FreeShapeTree((SDL_ShapeTree **)(char*)&(*shape_tree)->data.children.upright);
+        SDL_FreeShapeTree((SDL_ShapeTree **)(char*)&(*shape_tree)->data.children.downleft);
+        SDL_FreeShapeTree((SDL_ShapeTree **)(char*)&(*shape_tree)->data.children.downright);
     }
     SDL_free(*shape_tree);
     *shape_tree = NULL;
diff --git a/src/video/SDL_shape_internals.h b/src/video/SDL_shape_internals.h
index bdb0ee9..0fa8175 100644
--- a/src/video/SDL_shape_internals.h
+++ b/src/video/SDL_shape_internals.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_shape_internals_h
-#define _SDL_shape_internals_h
+#ifndef SDL_shape_internals_h_
+#define SDL_shape_internals_h_
 
 #include "SDL_rect.h"
 #include "SDL_shape.h"
diff --git a/src/video/SDL_stretch.c b/src/video/SDL_stretch.c
index bb34dff..5bfe556 100644
--- a/src/video/SDL_stretch.c
+++ b/src/video/SDL_stretch.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,8 +33,8 @@
    into the general blitting mechanism.
 */
 
-#if ((defined(_MFC_VER) && defined(_M_IX86)) || \
-     defined(__WATCOMC__) || \
+#if ((defined(_MSC_VER) && defined(_M_IX86))    || \
+     (defined(__WATCOMC__) && defined(__386__)) || \
      (defined(__GNUC__) && defined(__i386__))) && SDL_ASSEMBLY_ROUTINES
 /* There's a bug with gcc 4.4.1 and -O2 where srcp doesn't get the correct
  * value after the first scanline.  FIXME? */
@@ -53,7 +53,7 @@
 #define PAGE_ALIGNED
 #endif
 
-#if defined(_M_IX86) || defined(i386)
+#if defined(_M_IX86) || defined(__i386__) || defined(__386__)
 #define PREFIX16    0x66
 #define STORE_BYTE  0xAA
 #define STORE_WORD  0xAB
@@ -102,7 +102,7 @@ generate_rowbytes(int src_w, int dst_w, int bpp)
         store = STORE_WORD;
         break;
     default:
-        return SDL_SetError("ASM stretch of %d bytes isn't supported\n", bpp);
+        return SDL_SetError("ASM stretch of %d bytes isn't supported", bpp);
     }
 #ifdef HAVE_MPROTECT
     /* Make the code writeable */
diff --git a/src/video/SDL_surface.c b/src/video/SDL_surface.c
index 9d52e5c..600056f 100644
--- a/src/video/SDL_surface.c
+++ b/src/video/SDL_surface.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -778,8 +778,8 @@ SDL_UpperBlitScaled(SDL_Surface * src, const SDL_Rect * srcrect,
 
     final_src.x = (int)SDL_floor(src_x0 + 0.5);
     final_src.y = (int)SDL_floor(src_y0 + 0.5);
-    final_src.w = (int)SDL_floor(src_x1 - src_x0 + 1.5);
-    final_src.h = (int)SDL_floor(src_y1 - src_y0 + 1.5);
+    final_src.w = (int)SDL_floor(src_x1 + 1 + 0.5) - (int)SDL_floor(src_x0 + 0.5);
+    final_src.h = (int)SDL_floor(src_y1 + 1 + 0.5) - (int)SDL_floor(src_y0 + 0.5);
 
     final_dst.x = (int)SDL_floor(dst_x0 + 0.5);
     final_dst.y = (int)SDL_floor(dst_y0 + 0.5);
@@ -871,6 +871,15 @@ SDL_UnlockSurface(SDL_Surface * surface)
 }
 
 /*
+ * Creates a new surface identical to the existing surface
+ */
+SDL_Surface *
+SDL_DuplicateSurface(SDL_Surface * surface)
+{
+    return SDL_ConvertSurface(surface, surface->format, surface->flags);
+}
+
+/*
  * Convert a surface into the specified pixel format.
  */
 SDL_Surface *
@@ -882,6 +891,15 @@ SDL_ConvertSurface(SDL_Surface * surface, const SDL_PixelFormat * format,
     SDL_Color copy_color;
     SDL_Rect bounds;
 
+    if (!surface) {
+        SDL_InvalidParamError("surface");
+        return NULL;
+    }
+    if (!format) {
+        SDL_InvalidParamError("format");
+        return NULL;
+    }
+
     /* Check for empty destination palette! (results in empty image) */
     if (format->palette != NULL) {
         int i;
@@ -970,13 +988,37 @@ SDL_ConvertSurface(SDL_Surface * surface, const SDL_PixelFormat * format,
         }
 
         if (set_colorkey_by_color) {
-            /* Set the colorkey by color, which needs to be unique */
-            Uint8 keyR, keyG, keyB, keyA;
+            SDL_Surface *tmp;
+            SDL_Surface *tmp2;
+            int converted_colorkey = 0;
+
+            /* Create a dummy surface to get the colorkey converted */
+            tmp = SDL_CreateRGBSurface(0, 1, 1,
+                                   surface->format->BitsPerPixel, surface->format->Rmask,
+                                   surface->format->Gmask, surface->format->Bmask,
+                                   surface->format->Amask);
+
+            /* Share the palette, if any */
+            if (surface->format->palette) {
+                SDL_SetSurfacePalette(tmp, surface->format->palette);
+            }
+            
+            SDL_FillRect(tmp, NULL, surface->map->info.colorkey);
+
+            tmp->map->info.flags &= ~SDL_COPY_COLORKEY;
+
+            /* Convertion of the colorkey */
+            tmp2 = SDL_ConvertSurface(tmp, format, 0);
+
+            /* Get the converted colorkey */
+            SDL_memcpy(&converted_colorkey, tmp2->pixels, tmp2->format->BytesPerPixel);
+
+            SDL_FreeSurface(tmp);
+            SDL_FreeSurface(tmp2);
+
+            /* Set the converted colorkey on the new surface */
+            SDL_SetColorKey(convert, 1, converted_colorkey);
 
-            SDL_GetRGBA(surface->map->info.colorkey, surface->format, &keyR,
-                        &keyG, &keyB, &keyA);
-            SDL_SetColorKey(convert, 1,
-                            SDL_MapRGBA(convert->format, keyR, keyG, keyB, keyA));
             /* This is needed when converting for 3D texture upload */
             SDL_ConvertColorkeyToAlpha(convert);
         }
@@ -986,7 +1028,7 @@ SDL_ConvertSurface(SDL_Surface * surface, const SDL_PixelFormat * format,
     /* Enable alpha blending by default if the new surface has an
      * alpha channel or alpha modulation */
     if ((surface->format->Amask && format->Amask) ||
-        (copy_flags & (SDL_COPY_COLORKEY|SDL_COPY_MODULATE_ALPHA))) {
+        (copy_flags & SDL_COPY_MODULATE_ALPHA)) {
         SDL_SetSurfaceBlendMode(convert, SDL_BLENDMODE_BLEND);
     }
     if ((copy_flags & SDL_COPY_RLE_DESIRED) || (flags & SDL_RLEACCEL)) {
@@ -1156,6 +1198,10 @@ SDL_FreeSurface(SDL_Surface * surface)
     if (surface->flags & SDL_DONTFREE) {
         return;
     }
+    if (surface->map != NULL) {
+        SDL_FreeBlitMap(surface->map);
+        surface->map = NULL;
+    }
     if (--surface->refcount > 0) {
         return;
     }
@@ -1170,10 +1216,6 @@ SDL_FreeSurface(SDL_Surface * surface)
         SDL_FreeFormat(surface->format);
         surface->format = NULL;
     }
-    if (surface->map != NULL) {
-        SDL_FreeBlitMap(surface->map);
-        surface->map = NULL;
-    }
     if (!(surface->flags & SDL_PREALLOC)) {
         SDL_free(surface->pixels);
     }
diff --git a/src/video/SDL_sysvideo.h b/src/video/SDL_sysvideo.h
index cd2ed2a..811fe19 100644
--- a/src/video/SDL_sysvideo.h
+++ b/src/video/SDL_sysvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,13 +20,15 @@
 */
 #include "../SDL_internal.h"
 
-#ifndef _SDL_sysvideo_h
-#define _SDL_sysvideo_h
+#ifndef SDL_sysvideo_h_
+#define SDL_sysvideo_h_
 
 #include "SDL_messagebox.h"
 #include "SDL_shape.h"
 #include "SDL_thread.h"
 
+#include "SDL_vulkan_internal.h"
+
 /* The SDL video driver */
 
 typedef struct SDL_WindowShaper SDL_WindowShaper;
@@ -163,6 +165,11 @@ struct SDL_VideoDevice
      */
     void (*VideoQuit) (_THIS);
 
+    /*
+     * Reinitialize the touch devices -- called if an unknown touch ID occurs.
+     */
+    void (*ResetTouch) (_THIS);
+
     /* * * */
     /*
      * Display functions
@@ -200,8 +207,8 @@ struct SDL_VideoDevice
     /*
      * Window functions
      */
-    int (*CreateWindow) (_THIS, SDL_Window * window);
-    int (*CreateWindowFrom) (_THIS, SDL_Window * window, const void *data);
+    int (*CreateSDLWindow) (_THIS, SDL_Window * window);
+    int (*CreateSDLWindowFrom) (_THIS, SDL_Window * window, const void *data);
     void (*SetWindowTitle) (_THIS, SDL_Window * window);
     void (*SetWindowIcon) (_THIS, SDL_Window * window, SDL_Surface * icon);
     void (*SetWindowPosition) (_THIS, SDL_Window * window);
@@ -252,8 +259,19 @@ struct SDL_VideoDevice
     void (*GL_GetDrawableSize) (_THIS, SDL_Window * window, int *w, int *h);
     int (*GL_SetSwapInterval) (_THIS, int interval);
     int (*GL_GetSwapInterval) (_THIS);
-    void (*GL_SwapWindow) (_THIS, SDL_Window * window);
+    int (*GL_SwapWindow) (_THIS, SDL_Window * window);
     void (*GL_DeleteContext) (_THIS, SDL_GLContext context);
+    void (*GL_DefaultProfileConfig) (_THIS, int *mask, int *major, int *minor);
+
+    /* * * */
+    /*
+     * Vulkan support
+     */
+    int (*Vulkan_LoadLibrary) (_THIS, const char *path);
+    void (*Vulkan_UnloadLibrary) (_THIS);
+    SDL_bool (*Vulkan_GetInstanceExtensions) (_THIS, SDL_Window *window, unsigned *count, const char **names);
+    SDL_bool (*Vulkan_CreateSurface) (_THIS, SDL_Window *window, VkInstance instance, VkSurfaceKHR *surface);
+    void (*Vulkan_GetDrawableSize) (_THIS, SDL_Window * window, int *w, int *h);
 
     /* * * */
     /*
@@ -288,6 +306,7 @@ struct SDL_VideoDevice
 
     /* * * */
     /* Data common to all drivers */
+    SDL_bool is_dummy;
     SDL_bool suspend_screensaver;
     int num_displays;
     SDL_VideoDisplay *displays;
@@ -295,7 +314,7 @@ struct SDL_VideoDevice
     SDL_Window *grabbed_window;
     Uint8 window_magic;
     Uint32 next_object_id;
-    char * clipboard_text;
+    char *clipboard_text;
 
     /* * * */
     /* Data used by the GL drivers */
@@ -323,7 +342,9 @@ struct SDL_VideoDevice
         int profile_mask;
         int share_with_current_context;
         int release_behavior;
+        int reset_notification;
         int framebuffer_srgb_capable;
+        int no_error;
         int retained_backing;
         int driver_loaded;
         char driver_path[256];
@@ -341,6 +362,17 @@ struct SDL_VideoDevice
     SDL_TLSID current_glctx_tls;
 
     /* * * */
+    /* Data used by the Vulkan drivers */
+    struct
+    {
+        void *vkGetInstanceProcAddr;
+        void *vkEnumerateInstanceExtensionProperties;
+        int loader_loaded;
+        char loader_path[256];
+        void *loader_handle;
+    } vulkan_config;
+
+    /* * * */
     /* Data private to this driver */
     void *driverdata;
     struct SDL_GLDriverData *gl_data;
@@ -366,57 +398,26 @@ typedef struct VideoBootStrap
     SDL_VideoDevice *(*create) (int devindex);
 } VideoBootStrap;
 
-#if SDL_VIDEO_DRIVER_COCOA
+/* Not all of these are available in a given build. Use #ifdefs, etc. */
 extern VideoBootStrap COCOA_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_X11
 extern VideoBootStrap X11_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_MIR
 extern VideoBootStrap MIR_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_DIRECTFB
 extern VideoBootStrap DirectFB_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_WINDOWS
 extern VideoBootStrap WINDOWS_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_WINRT
 extern VideoBootStrap WINRT_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_HAIKU
 extern VideoBootStrap HAIKU_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_PANDORA
 extern VideoBootStrap PND_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_UIKIT
 extern VideoBootStrap UIKIT_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_ANDROID
 extern VideoBootStrap Android_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_PSP
 extern VideoBootStrap PSP_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_RPI
 extern VideoBootStrap RPI_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_DUMMY
+extern VideoBootStrap KMSDRM_bootstrap;
 extern VideoBootStrap DUMMY_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_WAYLAND
 extern VideoBootStrap Wayland_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_NACL
 extern VideoBootStrap NACL_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_VIVANTE
 extern VideoBootStrap VIVANTE_bootstrap;
-#endif
-#if SDL_VIDEO_DRIVER_EMSCRIPTEN
 extern VideoBootStrap Emscripten_bootstrap;
-#endif
+extern VideoBootStrap QNX_bootstrap;
 
 extern SDL_VideoDevice *SDL_GetVideoDevice(void);
 extern int SDL_AddBasicVideoDisplay(const SDL_DisplayMode * desktop_mode);
@@ -425,7 +426,10 @@ extern SDL_bool SDL_AddDisplayMode(SDL_VideoDisplay *display, const SDL_DisplayM
 extern SDL_VideoDisplay *SDL_GetDisplayForWindow(SDL_Window *window);
 extern void *SDL_GetDisplayDriverData( int displayIndex );
 
+extern void SDL_GL_DeduceMaxSupportedESProfile(int* major, int* minor);
+
 extern int SDL_RecreateWindow(SDL_Window * window, Uint32 flags);
+extern SDL_bool SDL_HasWindows(void);
 
 extern void SDL_OnWindowShown(SDL_Window * window);
 extern void SDL_OnWindowHidden(SDL_Window * window);
@@ -443,6 +447,13 @@ extern SDL_bool SDL_ShouldAllowTopmost(void);
 
 extern float SDL_ComputeDiagonalDPI(int hpix, int vpix, float hinches, float vinches);
 
-#endif /* _SDL_sysvideo_h */
+extern void SDL_OnApplicationWillTerminate(void);
+extern void SDL_OnApplicationDidReceiveMemoryWarning(void);
+extern void SDL_OnApplicationWillResignActive(void);
+extern void SDL_OnApplicationDidEnterBackground(void);
+extern void SDL_OnApplicationWillEnterForeground(void);
+extern void SDL_OnApplicationDidBecomeActive(void);
+
+#endif /* SDL_sysvideo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/SDL_video.c b/src/video/SDL_video.c
index 0a21ef5..60b2147 100644
--- a/src/video/SDL_video.c
+++ b/src/video/SDL_video.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -46,13 +46,10 @@
 #include "SDL_opengles2.h"
 #endif /* SDL_VIDEO_OPENGL_ES2 && !SDL_VIDEO_OPENGL */
 
+#if !SDL_VIDEO_OPENGL
 #ifndef GL_CONTEXT_RELEASE_BEHAVIOR_KHR
 #define GL_CONTEXT_RELEASE_BEHAVIOR_KHR 0x82FB
 #endif
-
-/* On Windows, windows.h defines CreateWindow */
-#ifdef CreateWindow
-#undef CreateWindow
 #endif
 
 #ifdef __EMSCRIPTEN__
@@ -103,12 +100,18 @@ static VideoBootStrap *bootstrap[] = {
 #if SDL_VIDEO_DRIVER_RPI
     &RPI_bootstrap,
 #endif 
+#if SDL_VIDEO_DRIVER_KMSDRM
+    &KMSDRM_bootstrap,
+#endif
 #if SDL_VIDEO_DRIVER_NACL
     &NACL_bootstrap,
 #endif
 #if SDL_VIDEO_DRIVER_EMSCRIPTEN
     &Emscripten_bootstrap,
 #endif
+#if SDL_VIDEO_DRIVER_QNX
+    &QNX_bootstrap,
+#endif
 #if SDL_VIDEO_DRIVER_DUMMY
     &DUMMY_bootstrap,
 #endif
@@ -122,6 +125,7 @@ static SDL_VideoDevice *_this = NULL;
         SDL_UninitializedVideo(); \
         return retval; \
     } \
+    SDL_assert(window && window->magic == &_this->window_magic); \
     if (!window || window->magic != &_this->window_magic) { \
         SDL_SetError("Invalid window"); \
         return retval; \
@@ -133,6 +137,7 @@ static SDL_VideoDevice *_this = NULL;
         return retval; \
     } \
     SDL_assert(_this->displays != NULL); \
+    SDL_assert(displayIndex >= 0 && displayIndex < _this->num_displays); \
     if (displayIndex < 0 || displayIndex >= _this->num_displays) { \
         SDL_SetError("displayIndex must be in the range 0 - %d", \
                      _this->num_displays - 1); \
@@ -170,6 +175,11 @@ ShouldUseTextureFramebuffer()
         return SDL_TRUE;
     }
 
+    /* If this is the dummy driver there is no texture support */
+    if (_this->is_dummy) {
+        return SDL_FALSE;
+    }
+
     /* If the user has specified a software renderer we can't use a
        texture framebuffer, or renderer creation will go recursive.
      */
@@ -195,7 +205,7 @@ ShouldUseTextureFramebuffer()
     return SDL_FALSE;
 
 #elif defined(__MACOSX__)
-    /* Mac OS X uses OpenGL as the native fast path */
+    /* Mac OS X uses OpenGL as the native fast path (for cocoa and X11) */
     return SDL_TRUE;
 
 #elif defined(__LINUX__)
@@ -336,9 +346,14 @@ SDL_CreateWindowTexture(SDL_VideoDevice *unused, SDL_Window * window, Uint32 * f
     /* Create framebuffer data */
     data->bytes_per_pixel = SDL_BYTESPERPIXEL(*format);
     data->pitch = (((window->w * data->bytes_per_pixel) + 3) & ~3);
-    data->pixels = SDL_malloc(window->h * data->pitch);
-    if (!data->pixels) {
-        return SDL_OutOfMemory();
+
+    {
+        /* Make static analysis happy about potential malloc(0) calls. */
+        const size_t allocsize = window->h * data->pitch;
+        data->pixels = SDL_malloc((allocsize > 0) ? allocsize : 1);
+        if (!data->pixels) {
+            return SDL_OutOfMemory();
+        }
     }
 
     *pixels = data->pixels;
@@ -707,21 +722,21 @@ int SDL_GetDisplayUsableBounds(int displayIndex, SDL_Rect * rect)
 int
 SDL_GetDisplayDPI(int displayIndex, float * ddpi, float * hdpi, float * vdpi)
 {
-	SDL_VideoDisplay *display;
+    SDL_VideoDisplay *display;
 
     CHECK_DISPLAY_INDEX(displayIndex, -1);
 
     display = &_this->displays[displayIndex];
 
-	if (_this->GetDisplayDPI) {
-		if (_this->GetDisplayDPI(_this, display, ddpi, hdpi, vdpi) == 0) {
-			return 0;
-		}
+    if (_this->GetDisplayDPI) {
+        if (_this->GetDisplayDPI(_this, display, ddpi, hdpi, vdpi) == 0) {
+            return 0;
+        }
     } else {
         return SDL_Unsupported();
     }
 
-	return -1;
+    return -1;
 }
 
 SDL_bool
@@ -1157,35 +1172,38 @@ SDL_UpdateFullscreenMode(SDL_Window * window, SDL_bool fullscreen)
     CHECK_WINDOW_MAGIC(window,-1);
 
     /* if we are in the process of hiding don't go back to fullscreen */
-    if ( window->is_hiding && fullscreen )
+    if (window->is_hiding && fullscreen) {
         return 0;
+    }
 
 #ifdef __MACOSX__
     /* if the window is going away and no resolution change is necessary,
-     do nothing, or else we may trigger an ugly double-transition
+       do nothing, or else we may trigger an ugly double-transition
      */
-    if (window->is_destroying && (window->last_fullscreen_flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN_DESKTOP)
-        return 0;
+    if (SDL_strcmp(_this->name, "cocoa") == 0) {  /* don't do this for X11, etc */
+        if (window->is_destroying && (window->last_fullscreen_flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN_DESKTOP)
+            return 0;
     
-    /* If we're switching between a fullscreen Space and "normal" fullscreen, we need to get back to normal first. */
-    if (fullscreen && ((window->last_fullscreen_flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN_DESKTOP) && ((window->flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN)) {
-        if (!Cocoa_SetWindowFullscreenSpace(window, SDL_FALSE)) {
-            return -1;
-        }
-    } else if (fullscreen && ((window->last_fullscreen_flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN) && ((window->flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN_DESKTOP)) {
-        display = SDL_GetDisplayForWindow(window);
-        SDL_SetDisplayModeForDisplay(display, NULL);
-        if (_this->SetWindowFullscreen) {
-            _this->SetWindowFullscreen(_this, window, display, SDL_FALSE);
+        /* If we're switching between a fullscreen Space and "normal" fullscreen, we need to get back to normal first. */
+        if (fullscreen && ((window->last_fullscreen_flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN_DESKTOP) && ((window->flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN)) {
+            if (!Cocoa_SetWindowFullscreenSpace(window, SDL_FALSE)) {
+                return -1;
+            }
+        } else if (fullscreen && ((window->last_fullscreen_flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN) && ((window->flags & FULLSCREEN_MASK) == SDL_WINDOW_FULLSCREEN_DESKTOP)) {
+            display = SDL_GetDisplayForWindow(window);
+            SDL_SetDisplayModeForDisplay(display, NULL);
+            if (_this->SetWindowFullscreen) {
+                _this->SetWindowFullscreen(_this, window, display, SDL_FALSE);
+            }
         }
-    }
 
-    if (Cocoa_SetWindowFullscreenSpace(window, fullscreen)) {
-        if (Cocoa_IsWindowInFullscreenSpace(window) != fullscreen) {
-            return -1;
+        if (Cocoa_SetWindowFullscreenSpace(window, fullscreen)) {
+            if (Cocoa_IsWindowInFullscreenSpace(window) != fullscreen) {
+                return -1;
+            }
+            window->last_fullscreen_flags = window->flags;
+            return 0;
         }
-        window->last_fullscreen_flags = window->flags;
-        return 0;
     }
 #elif __WINRT__ && (NTDDI_VERSION < NTDDI_WIN10)
     /* HACK: WinRT 8.x apps can't choose whether or not they are fullscreen
@@ -1304,7 +1322,7 @@ SDL_UpdateFullscreenMode(SDL_Window * window, SDL_bool fullscreen)
 }
 
 #define CREATE_FLAGS \
-    (SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_ALWAYS_ON_TOP | SDL_WINDOW_SKIP_TASKBAR | SDL_WINDOW_POPUP_MENU | SDL_WINDOW_UTILITY | SDL_WINDOW_TOOLTIP)
+    (SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_ALWAYS_ON_TOP | SDL_WINDOW_SKIP_TASKBAR | SDL_WINDOW_POPUP_MENU | SDL_WINDOW_UTILITY | SDL_WINDOW_TOOLTIP | SDL_WINDOW_VULKAN)
 
 static void
 SDL_FinishWindowCreation(SDL_Window *window, Uint32 flags)
@@ -1338,7 +1356,7 @@ SDL_CreateWindow(const char *title, int x, int y, int w, int h, Uint32 flags)
         }
     }
 
-    if ( (((flags & SDL_WINDOW_UTILITY) != 0) + ((flags & SDL_WINDOW_TOOLTIP) != 0) + ((flags & SDL_WINDOW_POPUP_MENU) != 0)) > 1 ) {
+    if ((((flags & SDL_WINDOW_UTILITY) != 0) + ((flags & SDL_WINDOW_TOOLTIP) != 0) + ((flags & SDL_WINDOW_POPUP_MENU) != 0)) > 1) {
         SDL_SetError("Conflicting window flags specified");
         return NULL;
     }
@@ -1359,7 +1377,7 @@ SDL_CreateWindow(const char *title, int x, int y, int w, int h, Uint32 flags)
 
     /* Some platforms have OpenGL enabled by default */
 #if (SDL_VIDEO_OPENGL && __MACOSX__) || __IPHONEOS__ || __ANDROID__ || __NACL__
-    if (SDL_strcmp(_this->name, "dummy") != 0) {
+    if (!_this->is_dummy && !(flags & SDL_WINDOW_VULKAN)) {
         flags |= SDL_WINDOW_OPENGL;
     }
 #endif
@@ -1373,6 +1391,21 @@ SDL_CreateWindow(const char *title, int x, int y, int w, int h, Uint32 flags)
         }
     }
 
+    if (flags & SDL_WINDOW_VULKAN) {
+        if (!_this->Vulkan_CreateSurface) {
+            SDL_SetError("Vulkan support is either not configured in SDL "
+                         "or not available in video driver");
+            return NULL;
+        }
+        if (flags & SDL_WINDOW_OPENGL) {
+            SDL_SetError("Vulkan and OpenGL not supported on same window");
+            return NULL;
+        }
+        if (SDL_Vulkan_LoadLibrary(NULL) < 0) {
+            return NULL;
+        }
+    }
+
     /* Unless the user has specified the high-DPI disabling hint, respect the
      * SDL_WINDOW_ALLOW_HIGHDPI flag.
      */
@@ -1439,7 +1472,7 @@ SDL_CreateWindow(const char *title, int x, int y, int w, int h, Uint32 flags)
     }
     _this->windows = window;
 
-    if (_this->CreateWindow && _this->CreateWindow(_this, window) < 0) {
+    if (_this->CreateSDLWindow && _this->CreateSDLWindow(_this, window) < 0) {
         SDL_DestroyWindow(window);
         return NULL;
     }
@@ -1476,7 +1509,7 @@ SDL_CreateWindowFrom(const void *data)
         SDL_UninitializedVideo();
         return NULL;
     }
-    if (!_this->CreateWindowFrom) {
+    if (!_this->CreateSDLWindowFrom) {
         SDL_Unsupported();
         return NULL;
     }
@@ -1498,7 +1531,7 @@ SDL_CreateWindowFrom(const void *data)
     }
     _this->windows = window;
 
-    if (_this->CreateWindowFrom(_this, window, data) < 0) {
+    if (_this->CreateSDLWindowFrom(_this, window, data) < 0) {
         SDL_DestroyWindow(window);
         return NULL;
     }
@@ -1548,12 +1581,22 @@ SDL_RecreateWindow(SDL_Window * window, Uint32 flags)
         }
     }
 
+    if ((window->flags & SDL_WINDOW_VULKAN) != (flags & SDL_WINDOW_VULKAN)) {
+        SDL_SetError("Can't change SDL_WINDOW_VULKAN window flag");
+        return -1;
+    }
+
+    if ((window->flags & SDL_WINDOW_VULKAN) && (flags & SDL_WINDOW_OPENGL)) {
+        SDL_SetError("Vulkan and OpenGL not supported on same window");
+        return -1;
+    }
+
     window->flags = ((flags & CREATE_FLAGS) | SDL_WINDOW_HIDDEN);
     window->last_fullscreen_flags = window->flags;
     window->is_destroying = SDL_FALSE;
 
-    if (_this->CreateWindow && !(flags & SDL_WINDOW_FOREIGN)) {
-        if (_this->CreateWindow(_this, window) < 0) {
+    if (_this->CreateSDLWindow && !(flags & SDL_WINDOW_FOREIGN)) {
+        if (_this->CreateSDLWindow(_this, window) < 0) {
             if (loaded_opengl) {
                 SDL_GL_UnloadLibrary();
                 window->flags &= ~SDL_WINDOW_OPENGL;
@@ -1583,6 +1626,12 @@ SDL_RecreateWindow(SDL_Window * window, Uint32 flags)
     return 0;
 }
 
+SDL_bool
+SDL_HasWindows(void)
+{
+    return (_this && _this->windows != NULL);
+}
+
 Uint32
 SDL_GetWindowID(SDL_Window * window)
 {
@@ -1738,7 +1787,7 @@ SDL_SetWindowPosition(SDL_Window * window, int x, int y)
     if (SDL_WINDOWPOS_ISCENTERED(x) || SDL_WINDOWPOS_ISCENTERED(y)) {
         int displayIndex = (x & 0xFFFF);
         SDL_Rect bounds;
-        if (displayIndex > _this->num_displays) {
+        if (displayIndex >= _this->num_displays) {
             displayIndex = 0;
         }
 
@@ -1867,20 +1916,16 @@ SDL_SetWindowSize(SDL_Window * window, int w, int h)
     }
 
     /* Make sure we don't exceed any window size limits */
-    if (window->min_w && w < window->min_w)
-    {
+    if (window->min_w && w < window->min_w) {
         w = window->min_w;
     }
-    if (window->max_w && w > window->max_w)
-    {
+    if (window->max_w && w > window->max_w) {
         w = window->max_w;
     }
-    if (window->min_h && h < window->min_h)
-    {
+    if (window->min_h && h < window->min_h) {
         h = window->min_h;
     }
-    if (window->max_h && h > window->max_h)
-    {
+    if (window->max_h && h > window->max_h) {
         h = window->max_h;
     }
 
@@ -1917,30 +1962,6 @@ SDL_GetWindowSize(SDL_Window * window, int *w, int *h)
     }
 }
 
-void
-SDL_SetWindowMinimumSize(SDL_Window * window, int min_w, int min_h)
-{
-    CHECK_WINDOW_MAGIC(window,);
-    if (min_w <= 0) {
-        SDL_InvalidParamError("min_w");
-        return;
-    }
-    if (min_h <= 0) {
-        SDL_InvalidParamError("min_h");
-        return;
-    }
-
-    if (!(window->flags & SDL_WINDOW_FULLSCREEN)) {
-        window->min_w = min_w;
-        window->min_h = min_h;
-        if (_this->SetWindowMinimumSize) {
-            _this->SetWindowMinimumSize(_this, window);
-        }
-        /* Ensure that window is not smaller than minimal size */
-        SDL_SetWindowSize(window, SDL_max(window->w, window->min_w), SDL_max(window->h, window->min_h));
-    }
-}
-
 int
 SDL_GetWindowBordersSize(SDL_Window * window, int *top, int *left, int *bottom, int *right)
 {
@@ -1964,6 +1985,37 @@ SDL_GetWindowBordersSize(SDL_Window * window, int *top, int *left, int *bottom,
 }
 
 void
+SDL_SetWindowMinimumSize(SDL_Window * window, int min_w, int min_h)
+{
+    CHECK_WINDOW_MAGIC(window,);
+    if (min_w <= 0) {
+        SDL_InvalidParamError("min_w");
+        return;
+    }
+    if (min_h <= 0) {
+        SDL_InvalidParamError("min_h");
+        return;
+    }
+
+    if ((window->max_w && min_w >= window->max_w) ||
+        (window->max_h && min_h >= window->max_h)) {
+        SDL_SetError("SDL_SetWindowMinimumSize(): Tried to set minimum size larger than maximum size");
+        return;
+    }
+
+    window->min_w = min_w;
+    window->min_h = min_h;
+
+    if (!(window->flags & SDL_WINDOW_FULLSCREEN)) {
+        if (_this->SetWindowMinimumSize) {
+            _this->SetWindowMinimumSize(_this, window);
+        }
+        /* Ensure that window is not smaller than minimal size */
+        SDL_SetWindowSize(window, SDL_max(window->w, window->min_w), SDL_max(window->h, window->min_h));
+    }
+}
+
+void
 SDL_GetWindowMinimumSize(SDL_Window * window, int *min_w, int *min_h)
 {
     CHECK_WINDOW_MAGIC(window,);
@@ -1988,9 +2040,15 @@ SDL_SetWindowMaximumSize(SDL_Window * window, int max_w, int max_h)
         return;
     }
 
+    if (max_w <= window->min_w || max_h <= window->min_h) {
+        SDL_SetError("SDL_SetWindowMaximumSize(): Tried to set maximum size smaller than minimum size");
+        return;
+    }
+
+    window->max_w = max_w;
+    window->max_h = max_h;
+
     if (!(window->flags & SDL_WINDOW_FULLSCREEN)) {
-        window->max_w = max_w;
-        window->max_h = max_h;
         if (_this->SetWindowMaximumSize) {
             _this->SetWindowMaximumSize(_this, window);
         }
@@ -2035,13 +2093,13 @@ SDL_HideWindow(SDL_Window * window)
         return;
     }
 
-	window->is_hiding = SDL_TRUE;
+    window->is_hiding = SDL_TRUE;
     SDL_UpdateFullscreenMode(window, SDL_FALSE);
 
     if (_this->HideWindow) {
         _this->HideWindow(_this, window);
     }
-	window->is_hiding = SDL_FALSE;
+    window->is_hiding = SDL_FALSE;
     SDL_SendWindowEvent(window, SDL_WINDOWEVENT_HIDDEN, 0, 0);
 }
 
@@ -2506,8 +2564,10 @@ ShouldMinimizeOnFocusLoss(SDL_Window * window)
     }
 
 #ifdef __MACOSX__
-    if (Cocoa_IsWindowInFullscreenSpace(window)) {
-        return SDL_FALSE;
+    if (SDL_strcmp(_this->name, "cocoa") == 0) {  /* don't do this for X11, etc */
+        if (Cocoa_IsWindowInFullscreenSpace(window)) {
+            return SDL_FALSE;
+        }
     }
 #endif
 
@@ -2586,6 +2646,9 @@ SDL_DestroyWindow(SDL_Window * window)
     if (window->flags & SDL_WINDOW_OPENGL) {
         SDL_GL_UnloadLibrary();
     }
+    if (window->flags & SDL_WINDOW_VULKAN) {
+        SDL_Vulkan_UnloadLibrary();
+    }
 
     display = SDL_GetDisplayForWindow(window);
     if (display->fullscreen_window == window) {
@@ -2777,11 +2840,13 @@ SDL_GL_UnloadLibrary(void)
     }
 }
 
+#if SDL_VIDEO_OPENGL || SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2
 static SDL_INLINE SDL_bool
 isAtLeastGL3(const char *verstr)
 {
     return (verstr && (SDL_atoi(verstr) >= 3));
 }
+#endif
 
 SDL_bool
 SDL_GL_ExtensionSupported(const char *extension)
@@ -2855,7 +2920,7 @@ SDL_GL_ExtensionSupported(const char *extension)
             break;
 
         terminator = where + SDL_strlen(extension);
-        if (where == start || *(where - 1) == ' ')
+        if (where == extensions || *(where - 1) == ' ')
             if (*terminator == ' ' || *terminator == '\0')
                 return SDL_TRUE;
 
@@ -2867,6 +2932,37 @@ SDL_GL_ExtensionSupported(const char *extension)
 #endif
 }
 
+/* Deduce supported ES profile versions from the supported
+   ARB_ES*_compatibility extensions. There is no direct query.
+   
+   This is normally only called when the OpenGL driver supports
+   {GLX,WGL}_EXT_create_context_es2_profile.
+ */
+void
+SDL_GL_DeduceMaxSupportedESProfile(int* major, int* minor)
+{
+/* THIS REQUIRES AN EXISTING GL CONTEXT THAT HAS BEEN MADE CURRENT. */
+/*  Please refer to https://bugzilla.libsdl.org/show_bug.cgi?id=3725 for discussion. */
+#if SDL_VIDEO_OPENGL || SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2
+    /* XXX This is fragile; it will break in the event of release of
+     * new versions of OpenGL ES.
+     */
+    if (SDL_GL_ExtensionSupported("GL_ARB_ES3_2_compatibility")) {
+        *major = 3;
+        *minor = 2;
+    } else if (SDL_GL_ExtensionSupported("GL_ARB_ES3_1_compatibility")) {
+        *major = 3;
+        *minor = 1;
+    } else if (SDL_GL_ExtensionSupported("GL_ARB_ES3_compatibility")) {
+        *major = 3;
+        *minor = 0;
+    } else {
+        *major = 2;
+        *minor = 0;
+    }
+#endif
+}
+
 void
 SDL_GL_ResetAttributes()
 {
@@ -2891,22 +2987,32 @@ SDL_GL_ResetAttributes()
     _this->gl_config.multisamplesamples = 0;
     _this->gl_config.retained_backing = 1;
     _this->gl_config.accelerated = -1;  /* accelerated or not, both are fine */
-    _this->gl_config.profile_mask = 0;
+
+    if (_this->GL_DefaultProfileConfig) {
+        _this->GL_DefaultProfileConfig(_this, &_this->gl_config.profile_mask,
+                                       &_this->gl_config.major_version,
+                                       &_this->gl_config.minor_version);
+    } else {
 #if SDL_VIDEO_OPENGL
-    _this->gl_config.major_version = 2;
-    _this->gl_config.minor_version = 1;
+        _this->gl_config.major_version = 2;
+        _this->gl_config.minor_version = 1;
+        _this->gl_config.profile_mask = 0;
 #elif SDL_VIDEO_OPENGL_ES2
-    _this->gl_config.major_version = 2;
-    _this->gl_config.minor_version = 0;
-    _this->gl_config.profile_mask = SDL_GL_CONTEXT_PROFILE_ES;
+        _this->gl_config.major_version = 2;
+        _this->gl_config.minor_version = 0;
+        _this->gl_config.profile_mask = SDL_GL_CONTEXT_PROFILE_ES;
 #elif SDL_VIDEO_OPENGL_ES
-    _this->gl_config.major_version = 1;
-    _this->gl_config.minor_version = 1;
-    _this->gl_config.profile_mask = SDL_GL_CONTEXT_PROFILE_ES;
+        _this->gl_config.major_version = 1;
+        _this->gl_config.minor_version = 1;
+        _this->gl_config.profile_mask = SDL_GL_CONTEXT_PROFILE_ES;
 #endif
+    }
+
     _this->gl_config.flags = 0;
     _this->gl_config.framebuffer_srgb_capable = 0;
+    _this->gl_config.no_error = 0;
     _this->gl_config.release_behavior = SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH;
+    _this->gl_config.reset_notification = SDL_GL_CONTEXT_RESET_NO_NOTIFICATION;
 
     _this->gl_config.share_with_current_context = 0;
 }
@@ -3016,6 +3122,12 @@ SDL_GL_SetAttribute(SDL_GLattr attr, int value)
     case SDL_GL_CONTEXT_RELEASE_BEHAVIOR:
         _this->gl_config.release_behavior = value;
         break;
+    case SDL_GL_CONTEXT_RESET_NOTIFICATION:
+        _this->gl_config.reset_notification = value;
+        break;
+    case SDL_GL_CONTEXT_NO_ERROR:
+        _this->gl_config.no_error = value;
+        break;
     default:
         retval = SDL_SetError("Unknown OpenGL attribute");
         break;
@@ -3047,9 +3159,17 @@ SDL_GL_GetAttribute(SDL_GLattr attr, int *value)
     GLenum attachmentattrib = 0;
 #endif
 
+    if (!value) {
+        return SDL_InvalidParamError("value");
+    }
+
     /* Clear value in any case */
     *value = 0;
 
+    if (!_this) {
+        return SDL_UninitializedVideo();
+    }
+
     switch (attr) {
     case SDL_GL_RED_SIZE:
 #if SDL_VIDEO_OPENGL
@@ -3212,6 +3332,11 @@ SDL_GL_GetAttribute(SDL_GLattr attr, int *value)
             *value = _this->gl_config.framebuffer_srgb_capable;
             return 0;
         }
+    case SDL_GL_CONTEXT_NO_ERROR:
+        {
+            *value = _this->gl_config.no_error;
+            return 0;
+        }
     default:
         return SDL_SetError("Unknown OpenGL attribute");
     }
@@ -3219,7 +3344,7 @@ SDL_GL_GetAttribute(SDL_GLattr attr, int *value)
 #if SDL_VIDEO_OPENGL
     glGetStringFunc = SDL_GL_GetProcAddress("glGetString");
     if (!glGetStringFunc) {
-        return SDL_SetError("Failed getting OpenGL glGetString entry point");
+        return -1;
     }
 
     if (attachmentattrib && isAtLeastGL3((const char *) glGetStringFunc(GL_VERSION))) {
@@ -3228,7 +3353,7 @@ SDL_GL_GetAttribute(SDL_GLattr attr, int *value)
         if (glGetFramebufferAttachmentParameterivFunc) {
             glGetFramebufferAttachmentParameterivFunc(GL_FRAMEBUFFER, attachment, attachmentattrib, (GLint *) value);
         } else {
-            return SDL_SetError("Failed getting OpenGL glGetFramebufferAttachmentParameteriv entry point");
+            return -1;
         }
     } else
 #endif
@@ -3238,13 +3363,13 @@ SDL_GL_GetAttribute(SDL_GLattr attr, int *value)
         if (glGetIntegervFunc) {
             glGetIntegervFunc(attrib, (GLint *) value);
         } else {
-            return SDL_SetError("Failed getting OpenGL glGetIntegerv entry point");
+            return -1;
         }
     }
 
     glGetErrorFunc = SDL_GL_GetProcAddress("glGetError");
     if (!glGetErrorFunc) {
-        return SDL_SetError("Failed getting OpenGL glGetError entry point");
+        return -1;
     }
 
     error = glGetErrorFunc();
@@ -3617,8 +3742,9 @@ SDL_IsScreenKeyboardShown(SDL_Window *window)
 #include "x11/SDL_x11messagebox.h"
 #endif
 
-// This function will be unused if none of the above video drivers are present.
-SDL_UNUSED static SDL_bool SDL_MessageboxValidForDriver(const SDL_MessageBoxData *messageboxdata, SDL_SYSWM_TYPE drivertype)
+
+#if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT || SDL_VIDEO_DRIVER_COCOA || SDL_VIDEO_DRIVER_UIKIT || SDL_VIDEO_DRIVER_X11
+static SDL_bool SDL_MessageboxValidForDriver(const SDL_MessageBoxData *messageboxdata, SDL_SYSWM_TYPE drivertype)
 {
     SDL_SysWMinfo info;
     SDL_Window *window = messageboxdata->window;
@@ -3634,6 +3760,7 @@ SDL_UNUSED static SDL_bool SDL_MessageboxValidForDriver(const SDL_MessageBoxData
         return (info.subsystem == drivertype);
     }
 }
+#endif
 
 int
 SDL_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
@@ -3780,15 +3907,170 @@ SDL_SetWindowHitTest(SDL_Window * window, SDL_HitTest callback, void *userdata)
     return 0;
 }
 
-float SDL_ComputeDiagonalDPI(int hpix, int vpix, float hinches, float vinches)
+float
+SDL_ComputeDiagonalDPI(int hpix, int vpix, float hinches, float vinches)
+{
+    float den2 = hinches * hinches + vinches * vinches;
+    if (den2 <= 0.0f) {
+        return 0.0f;
+    }
+
+    return (float)(SDL_sqrt((double)hpix * (double)hpix + (double)vpix * (double)vpix) /
+                   SDL_sqrt((double)den2));
+}
+
+/*
+ * Functions used by iOS application delegates
+ */
+void SDL_OnApplicationWillTerminate(void)
+{
+    SDL_SendAppEvent(SDL_APP_TERMINATING);
+}
+
+void SDL_OnApplicationDidReceiveMemoryWarning(void)
+{
+    SDL_SendAppEvent(SDL_APP_LOWMEMORY);
+}
+
+void SDL_OnApplicationWillResignActive(void)
+{
+    if (_this) {
+        SDL_Window *window;
+        for (window = _this->windows; window != NULL; window = window->next) {
+            SDL_SendWindowEvent(window, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
+            SDL_SendWindowEvent(window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
+        }
+    }
+    SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
+}
+
+void SDL_OnApplicationDidEnterBackground(void)
+{
+    SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
+}
+
+void SDL_OnApplicationWillEnterForeground(void)
+{
+    SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND);
+}
+
+void SDL_OnApplicationDidBecomeActive(void)
+{
+    SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
+
+    if (_this) {
+        SDL_Window *window;
+        for (window = _this->windows; window != NULL; window = window->next) {
+            SDL_SendWindowEvent(window, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
+            SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESTORED, 0, 0);
+        }
+    }
+}
+
+#define NOT_A_VULKAN_WINDOW "The specified window isn't a Vulkan window"
+
+int SDL_Vulkan_LoadLibrary(const char *path)
+{
+    int retval;
+    if (!_this) {
+        SDL_UninitializedVideo();
+        return -1;
+    }
+    if (_this->vulkan_config.loader_loaded) {
+        if (path && SDL_strcmp(path, _this->vulkan_config.loader_path) != 0) {
+            return SDL_SetError("Vulkan loader library already loaded");
+        }
+        retval = 0;
+    } else {
+        if (!_this->Vulkan_LoadLibrary) {
+            return SDL_SetError("No Vulkan support in video driver");
+        }
+        retval = _this->Vulkan_LoadLibrary(_this, path);
+    }
+    if (retval == 0) {
+        _this->vulkan_config.loader_loaded++;
+    }
+    return retval;
+}
+
+void *SDL_Vulkan_GetVkGetInstanceProcAddr(void)
+{
+    if (!_this) {
+        SDL_UninitializedVideo();
+        return NULL;
+    }
+    if (!_this->vulkan_config.loader_loaded) {
+        SDL_SetError("No Vulkan loader has been loaded");
+    }
+    return _this->vulkan_config.vkGetInstanceProcAddr;
+}
+
+void SDL_Vulkan_UnloadLibrary(void)
+{
+    if (!_this) {
+        SDL_UninitializedVideo();
+        return;
+    }
+    if (_this->vulkan_config.loader_loaded > 0) {
+        if (--_this->vulkan_config.loader_loaded > 0) {
+            return;
+        }
+        if (_this->Vulkan_UnloadLibrary) {
+            _this->Vulkan_UnloadLibrary(_this);
+        }
+    }
+}
+
+SDL_bool SDL_Vulkan_GetInstanceExtensions(SDL_Window *window, unsigned *count, const char **names)
 {
-	float den2 = hinches * hinches + vinches * vinches;
-	if ( den2 <= 0.0f ) {
-		return 0.0f;
-	}
-		
-	return (float)(SDL_sqrt((double)hpix * (double)hpix + (double)vpix * (double)vpix) /
-				   SDL_sqrt((double)den2));
+    CHECK_WINDOW_MAGIC(window, SDL_FALSE);
+
+    if (!(window->flags & SDL_WINDOW_VULKAN)) {
+        SDL_SetError(NOT_A_VULKAN_WINDOW);
+        return SDL_FALSE;
+    }
+
+    if (!count) {
+        SDL_InvalidParamError("count");
+        return SDL_FALSE;
+    }
+
+    return _this->Vulkan_GetInstanceExtensions(_this, window, count, names);
+}
+
+SDL_bool SDL_Vulkan_CreateSurface(SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface)
+{
+    CHECK_WINDOW_MAGIC(window, SDL_FALSE);
+
+    if (!(window->flags & SDL_WINDOW_VULKAN)) {
+        SDL_SetError(NOT_A_VULKAN_WINDOW);
+        return SDL_FALSE;
+    }
+
+    if (!instance) {
+        SDL_InvalidParamError("instance");
+        return SDL_FALSE;
+    }
+
+    if (!surface) {
+        SDL_InvalidParamError("surface");
+        return SDL_FALSE;
+    }
+
+    return _this->Vulkan_CreateSurface(_this, window, instance, surface);
+}
+
+void SDL_Vulkan_GetDrawableSize(SDL_Window * window, int *w, int *h)
+{
+    CHECK_WINDOW_MAGIC(window,);
+
+    if (_this->Vulkan_GetDrawableSize) {
+        _this->Vulkan_GetDrawableSize(_this, window, w, h);
+    } else {
+        SDL_GetWindowSize(window, w, h);
+    }
 }
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/SDL_vulkan_internal.h b/src/video/SDL_vulkan_internal.h
new file mode 100644
index 0000000..ed4d7bf
--- /dev/null
+++ b/src/video/SDL_vulkan_internal.h
@@ -0,0 +1,88 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#ifndef SDL_vulkan_internal_h_
+#define SDL_vulkan_internal_h_
+
+#include "../SDL_internal.h"
+
+#include "SDL_stdinc.h"
+
+#if defined(SDL_LOADSO_DISABLED)
+#undef SDL_VIDEO_VULKAN
+#define SDL_VIDEO_VULKAN 0
+#endif
+
+#if SDL_VIDEO_VULKAN
+
+#if SDL_VIDEO_DRIVER_ANDROID
+#define VK_USE_PLATFORM_ANDROID_KHR
+#endif
+#if SDL_VIDEO_DRIVER_COCOA
+#define VK_USE_PLATFORM_MACOS_MVK
+#endif
+#if SDL_VIDEO_DRIVER_MIR
+#define VK_USE_PLATFORM_MIR_KHR
+#endif
+#if SDL_VIDEO_DRIVER_UIKIT
+#define VK_USE_PLATFORM_IOS_MVK
+#endif
+#if SDL_VIDEO_DRIVER_WAYLAND
+#define VK_USE_PLATFORM_WAYLAND_KHR
+#include "wayland/SDL_waylanddyn.h"
+#endif
+#if SDL_VIDEO_DRIVER_WINDOWS
+#define VK_USE_PLATFORM_WIN32_KHR
+#include "../core/windows/SDL_windows.h"
+#endif
+#if SDL_VIDEO_DRIVER_X11
+#define VK_USE_PLATFORM_XLIB_KHR
+#define VK_USE_PLATFORM_XCB_KHR
+#endif
+
+#define VK_NO_PROTOTYPES
+#include "./khronos/vulkan/vulkan.h"
+
+#include "SDL_vulkan.h"
+
+
+extern const char *SDL_Vulkan_GetResultString(VkResult result);
+
+extern VkExtensionProperties *SDL_Vulkan_CreateInstanceExtensionsList(
+    PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties,
+    Uint32 *extensionCount); /* free returned list with SDL_free */
+
+/* Implements functionality of SDL_Vulkan_GetInstanceExtensions for a list of
+ * names passed in nameCount and names. */
+extern SDL_bool SDL_Vulkan_GetInstanceExtensions_Helper(unsigned *userCount,
+                                                        const char **userNames,
+                                                        unsigned nameCount,
+                                                        const char *const *names);
+
+#else
+
+/* No SDL Vulkan support, just include the header for typedefs */
+#include "SDL_vulkan.h"
+
+#endif /* SDL_VIDEO_VULKAN */
+
+#endif /* SDL_vulkan_internal_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/SDL_vulkan_utils.c b/src/video/SDL_vulkan_utils.c
new file mode 100644
index 0000000..abc6fd8
--- /dev/null
+++ b/src/video/SDL_vulkan_utils.c
@@ -0,0 +1,177 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "../SDL_internal.h"
+
+#include "SDL_vulkan_internal.h"
+#include "SDL_error.h"
+
+#if SDL_VIDEO_VULKAN
+
+const char *SDL_Vulkan_GetResultString(VkResult result)
+{
+    switch((int)result)
+    {
+    case VK_SUCCESS:
+        return "VK_SUCCESS";
+    case VK_NOT_READY:
+        return "VK_NOT_READY";
+    case VK_TIMEOUT:
+        return "VK_TIMEOUT";
+    case VK_EVENT_SET:
+        return "VK_EVENT_SET";
+    case VK_EVENT_RESET:
+        return "VK_EVENT_RESET";
+    case VK_INCOMPLETE:
+        return "VK_INCOMPLETE";
+    case VK_ERROR_OUT_OF_HOST_MEMORY:
+        return "VK_ERROR_OUT_OF_HOST_MEMORY";
+    case VK_ERROR_OUT_OF_DEVICE_MEMORY:
+        return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
+    case VK_ERROR_INITIALIZATION_FAILED:
+        return "VK_ERROR_INITIALIZATION_FAILED";
+    case VK_ERROR_DEVICE_LOST:
+        return "VK_ERROR_DEVICE_LOST";
+    case VK_ERROR_MEMORY_MAP_FAILED:
+        return "VK_ERROR_MEMORY_MAP_FAILED";
+    case VK_ERROR_LAYER_NOT_PRESENT:
+        return "VK_ERROR_LAYER_NOT_PRESENT";
+    case VK_ERROR_EXTENSION_NOT_PRESENT:
+        return "VK_ERROR_EXTENSION_NOT_PRESENT";
+    case VK_ERROR_FEATURE_NOT_PRESENT:
+        return "VK_ERROR_FEATURE_NOT_PRESENT";
+    case VK_ERROR_INCOMPATIBLE_DRIVER:
+        return "VK_ERROR_INCOMPATIBLE_DRIVER";
+    case VK_ERROR_TOO_MANY_OBJECTS:
+        return "VK_ERROR_TOO_MANY_OBJECTS";
+    case VK_ERROR_FORMAT_NOT_SUPPORTED:
+        return "VK_ERROR_FORMAT_NOT_SUPPORTED";
+    case VK_ERROR_FRAGMENTED_POOL:
+        return "VK_ERROR_FRAGMENTED_POOL";
+    case VK_ERROR_SURFACE_LOST_KHR:
+        return "VK_ERROR_SURFACE_LOST_KHR";
+    case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR:
+        return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR";
+    case VK_SUBOPTIMAL_KHR:
+        return "VK_SUBOPTIMAL_KHR";
+    case VK_ERROR_OUT_OF_DATE_KHR:
+        return "VK_ERROR_OUT_OF_DATE_KHR";
+    case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR:
+        return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR";
+    case VK_ERROR_VALIDATION_FAILED_EXT:
+        return "VK_ERROR_VALIDATION_FAILED_EXT";
+    case VK_ERROR_OUT_OF_POOL_MEMORY_KHR:
+        return "VK_ERROR_OUT_OF_POOL_MEMORY_KHR";
+    case VK_ERROR_INVALID_SHADER_NV:
+        return "VK_ERROR_INVALID_SHADER_NV";
+    case VK_RESULT_MAX_ENUM:
+    case VK_RESULT_RANGE_SIZE:
+        break;
+    }
+    if(result < 0)
+        return "VK_ERROR_<Unknown>";
+    return "VK_<Unknown>";
+}
+
+VkExtensionProperties *SDL_Vulkan_CreateInstanceExtensionsList(
+    PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties,
+    Uint32 *extensionCount)
+{
+    Uint32 count = 0;
+    VkResult result = vkEnumerateInstanceExtensionProperties(NULL, &count, NULL);
+    VkExtensionProperties *retval;
+    if(result == VK_ERROR_INCOMPATIBLE_DRIVER)
+    {
+        /* Avoid the ERR_MAX_STRLEN limit by passing part of the message
+         * as a string argument.
+         */
+        SDL_SetError(
+            "You probably don't have a working Vulkan driver installed. %s %s %s(%d)",
+            "Getting Vulkan extensions failed:",
+            "vkEnumerateInstanceExtensionProperties returned",
+            SDL_Vulkan_GetResultString(result),
+            (int)result);
+        return NULL;
+    }
+    else if(result != VK_SUCCESS)
+    {
+        SDL_SetError(
+            "Getting Vulkan extensions failed: vkEnumerateInstanceExtensionProperties returned "
+            "%s(%d)",
+            SDL_Vulkan_GetResultString(result),
+            (int)result);
+        return NULL;
+    }
+    if(count == 0)
+    {
+        retval = SDL_calloc(1, sizeof(VkExtensionProperties)); // so we can return non-null
+    }
+	else
+	{
+		retval = SDL_calloc(count, sizeof(VkExtensionProperties));
+	}
+    if(!retval)
+    {
+        SDL_OutOfMemory();
+        return NULL;
+    }
+    result = vkEnumerateInstanceExtensionProperties(NULL, &count, retval);
+    if(result != VK_SUCCESS)
+    {
+        SDL_SetError(
+            "Getting Vulkan extensions failed: vkEnumerateInstanceExtensionProperties returned "
+            "%s(%d)",
+            SDL_Vulkan_GetResultString(result),
+            (int)result);
+        SDL_free(retval);
+        return NULL;
+    }
+    *extensionCount = count;
+    return retval;
+}
+
+SDL_bool SDL_Vulkan_GetInstanceExtensions_Helper(unsigned *userCount,
+                                                 const char **userNames,
+                                                 unsigned nameCount,
+                                                 const char *const *names)
+{
+    if(userNames)
+    {
+		unsigned int i;
+
+        if(*userCount != nameCount)
+        {
+            SDL_SetError(
+                "Count doesn't match count from previous call of SDL_Vulkan_GetInstanceExtensions");
+            return SDL_FALSE;
+        }
+        for(i = 0; i < nameCount; i++)
+        {
+            userNames[i] = names[i];
+        }
+    }
+    else
+    {
+        *userCount = nameCount;
+    }
+    return SDL_TRUE;
+}
+
+#endif
diff --git a/src/video/android/SDL_androidclipboard.c b/src/video/android/SDL_androidclipboard.c
index b996e7a..d52de4f 100644
--- a/src/video/android/SDL_androidclipboard.c
+++ b/src/video/android/SDL_androidclipboard.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,7 +23,7 @@
 #if SDL_VIDEO_DRIVER_ANDROID
 
 #include "SDL_androidvideo.h"
-
+#include "SDL_androidclipboard.h"
 #include "../../core/android/SDL_android.h"
 
 int
diff --git a/src/video/android/SDL_androidclipboard.h b/src/video/android/SDL_androidclipboard.h
index a61045a..d1818b0 100644
--- a/src/video/android/SDL_androidclipboard.h
+++ b/src/video/android/SDL_androidclipboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,13 +20,13 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_androidclipboard_h
-#define _SDL_androidclipboard_h
+#ifndef SDL_androidclipboard_h_
+#define SDL_androidclipboard_h_
 
 extern int Android_SetClipboardText(_THIS, const char *text);
 extern char *Android_GetClipboardText(_THIS);
 extern SDL_bool Android_HasClipboardText(_THIS);
 
-#endif /* _SDL_androidclipboard_h */
+#endif /* SDL_androidclipboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/android/SDL_androidevents.c b/src/video/android/SDL_androidevents.c
index c3cd4cc..35c59b0 100644
--- a/src/video/android/SDL_androidevents.c
+++ b/src/video/android/SDL_androidevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -29,19 +29,12 @@
 #include "SDL_events.h"
 #include "SDL_androidwindow.h"
 
+/* Can't include sysaudio "../../audio/android/SDL_androidaudio.h"
+ * because of THIS redefinition */
+extern void ANDROIDAUDIO_ResumeDevices(void);
+extern void ANDROIDAUDIO_PauseDevices(void);
 
-void android_egl_context_backup();
-void android_egl_context_restore();
-
-#if SDL_AUDIO_DRIVER_ANDROID
-void ANDROIDAUDIO_ResumeDevices(void);
-void ANDROIDAUDIO_PauseDevices(void);
-#else
-static void ANDROIDAUDIO_ResumeDevices(void) {}
-static void ANDROIDAUDIO_PauseDevices(void) {}
-#endif
-
-void 
+static void 
 android_egl_context_restore() 
 {
     SDL_Event event;
@@ -55,7 +48,7 @@ android_egl_context_restore()
     }
 }
 
-void 
+static void 
 android_egl_context_backup() 
 {
     /* Keep a copy of the EGL Context so we can try to restore it when we resume */
diff --git a/src/video/android/SDL_androidevents.h b/src/video/android/SDL_androidevents.h
index 4a2230e..ad9100a 100644
--- a/src/video/android/SDL_androidevents.h
+++ b/src/video/android/SDL_androidevents.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/android/SDL_androidgl.c b/src/video/android/SDL_androidgl.c
index 4cfe863..783fa2a 100644
--- a/src/video/android/SDL_androidgl.c
+++ b/src/video/android/SDL_androidgl.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -29,6 +29,7 @@
 #include "SDL_androidwindow.h"
 
 #include "SDL_androidvideo.h"
+#include "SDL_androidgl.h"
 #include "../../core/android/SDL_android.h"
 
 #include <android/log.h>
@@ -38,7 +39,7 @@
 SDL_EGL_CreateContext_impl(Android)
 SDL_EGL_MakeCurrent_impl(Android)
 
-void
+int
 Android_GLES_SwapWindow(_THIS, SDL_Window * window)
 {
     /* The following two calls existed in the original Java code
@@ -48,12 +49,12 @@ Android_GLES_SwapWindow(_THIS, SDL_Window * window)
     
     /*_this->egl_data->eglWaitNative(EGL_CORE_NATIVE_ENGINE);
     _this->egl_data->eglWaitGL();*/
-    SDL_EGL_SwapBuffers(_this, ((SDL_WindowData *) window->driverdata)->egl_surface);
+    return SDL_EGL_SwapBuffers(_this, ((SDL_WindowData *) window->driverdata)->egl_surface);
 }
 
 int
 Android_GLES_LoadLibrary(_THIS, const char *path) {
-    return SDL_EGL_LoadLibrary(_this, path, (NativeDisplayType) 0);
+    return SDL_EGL_LoadLibrary(_this, path, (NativeDisplayType) 0, 0);
 }
 
 #endif /* SDL_VIDEO_DRIVER_ANDROID */
diff --git a/src/video/windows/SDL_windowsframebuffer.h b/src/video/android/SDL_androidgl.h
similarity index 70%
copy from src/video/windows/SDL_windowsframebuffer.h
copy to src/video/android/SDL_androidgl.h
index 0c825f9..5e96d2c 100644
--- a/src/video/windows/SDL_windowsframebuffer.h
+++ b/src/video/android/SDL_androidgl.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,15 @@
 */
 #include "../../SDL_internal.h"
 
-extern int WIN_CreateWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format, void ** pixels, int *pitch);
-extern int WIN_UpdateWindowFramebuffer(_THIS, SDL_Window * window, const SDL_Rect * rects, int numrects);
-extern void WIN_DestroyWindowFramebuffer(_THIS, SDL_Window * window);
+#ifndef SDL_androidgl_h_
+#define SDL_androidgl_h_
+
+SDL_GLContext Android_GLES_CreateContext(_THIS, SDL_Window * window);
+int Android_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
+int Android_GLES_SwapWindow(_THIS, SDL_Window * window);
+int Android_GLES_LoadLibrary(_THIS, const char *path);
+
+
+#endif /* SDL_androidgl_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/android/SDL_androidkeyboard.c b/src/video/android/SDL_androidkeyboard.c
index 652e0cc..888b1b1 100644
--- a/src/video/android/SDL_androidkeyboard.c
+++ b/src/video/android/SDL_androidkeyboard.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -129,8 +129,8 @@ static SDL_Scancode Android_Keycodes[] = {
     SDL_SCANCODE_AUDIOSTOP, /* AKEYCODE_MEDIA_STOP */
     SDL_SCANCODE_AUDIONEXT, /* AKEYCODE_MEDIA_NEXT */
     SDL_SCANCODE_AUDIOPREV, /* AKEYCODE_MEDIA_PREVIOUS */
-    SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_REWIND */
-    SDL_SCANCODE_UNKNOWN, /* AKEYCODE_MEDIA_FAST_FORWARD */
+    SDL_SCANCODE_AUDIOREWIND, /* AKEYCODE_MEDIA_REWIND */
+    SDL_SCANCODE_AUDIOFASTFORWARD, /* AKEYCODE_MEDIA_FAST_FORWARD */
     SDL_SCANCODE_MUTE, /* AKEYCODE_MUTE */
     SDL_SCANCODE_PAGEUP, /* AKEYCODE_PAGE_UP */
     SDL_SCANCODE_PAGEDOWN, /* AKEYCODE_PAGE_DOWN */
@@ -357,7 +357,7 @@ Android_HasScreenKeyboardSupport(_THIS)
 SDL_bool
 Android_IsScreenKeyboardShown(_THIS, SDL_Window * window)
 {
-    return SDL_IsTextInputActive();
+    return Android_JNI_IsScreenKeyboardShown();
 }
 
 void
diff --git a/src/video/android/SDL_androidkeyboard.h b/src/video/android/SDL_androidkeyboard.h
index ced9bc2..19a0ba9 100644
--- a/src/video/android/SDL_androidkeyboard.h
+++ b/src/video/android/SDL_androidkeyboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/android/SDL_androidmessagebox.c b/src/video/android/SDL_androidmessagebox.c
index 61f6763..d25261b 100644
--- a/src/video/android/SDL_androidmessagebox.c
+++ b/src/video/android/SDL_androidmessagebox.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,12 +23,12 @@
 #if SDL_VIDEO_DRIVER_ANDROID
 
 #include "SDL_messagebox.h"
+#include "SDL_androidmessagebox.h"
+#include "../../core/android/SDL_android.h"
 
 int
 Android_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
 {
-    int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid);
-
     return Android_JNI_ShowMessageBox(messageboxdata, buttonid);
 }
 
diff --git a/src/video/android/SDL_androidmessagebox.h b/src/video/android/SDL_androidmessagebox.h
index 3c680c6..87cdc6d 100644
--- a/src/video/android/SDL_androidmessagebox.h
+++ b/src/video/android/SDL_androidmessagebox.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/android/SDL_androidmouse.c b/src/video/android/SDL_androidmouse.c
index 883fa8d..16782db 100644
--- a/src/video/android/SDL_androidmouse.c
+++ b/src/video/android/SDL_androidmouse.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -30,6 +30,7 @@
 
 #include "../../core/android/SDL_android.h"
 
+/* See Android's MotionEvent class for constants */
 #define ACTION_DOWN 0
 #define ACTION_UP 1
 #define ACTION_MOVE 2
@@ -41,41 +42,59 @@
 #define BUTTON_BACK 8
 #define BUTTON_FORWARD 16
 
-static Uint8 SDLButton;
+/* Last known Android mouse button state (includes all buttons) */
+static int last_state;
 
 void
 Android_InitMouse(void)
 {
-    SDLButton = 0;
+    last_state = 0;
 }
 
-void Android_OnMouse( int androidButton, int action, float x, float y) {
+/* Translate Android mouse button state to SDL mouse button */
+static Uint8
+TranslateButton(int state)
+{
+    if (state & BUTTON_PRIMARY) {
+        return SDL_BUTTON_LEFT;
+    } else if (state & BUTTON_SECONDARY) {
+        return SDL_BUTTON_RIGHT;
+    } else if (state & BUTTON_TERTIARY) {
+        return SDL_BUTTON_MIDDLE;
+    } else if (state & BUTTON_FORWARD) {
+        return SDL_BUTTON_X1;
+    } else if (state & BUTTON_BACK) {
+        return SDL_BUTTON_X2;
+    } else {
+        return 0;
+    }
+}
+
+void
+Android_OnMouse(int state, int action, float x, float y)
+{
+    int changes;
+    Uint8 button;
+
     if (!Android_Window) {
         return;
     }
 
     switch(action) {
         case ACTION_DOWN:
-            // Determine which button originated the event, and store it for ACTION_UP
-            SDLButton = SDL_BUTTON_LEFT;
-            if (androidButton == BUTTON_SECONDARY) {
-                SDLButton = SDL_BUTTON_RIGHT;
-            } else if (androidButton == BUTTON_TERTIARY) {
-                SDLButton = SDL_BUTTON_MIDDLE;
-            } else if (androidButton == BUTTON_FORWARD) {
-                SDLButton = SDL_BUTTON_X1;
-            } else if (androidButton == BUTTON_BACK) {
-                SDLButton = SDL_BUTTON_X2;
-            }
+            changes = state & ~last_state;
+            button = TranslateButton(changes);
+            last_state = state;
             SDL_SendMouseMotion(Android_Window, 0, 0, x, y);
-            SDL_SendMouseButton(Android_Window, 0, SDL_PRESSED, SDLButton);
+            SDL_SendMouseButton(Android_Window, 0, SDL_PRESSED, button);
             break;
 
         case ACTION_UP:
-            // Android won't give us the button that originated the ACTION_DOWN event, so we'll
-            // assume it's the one we stored
+            changes = last_state & ~state;
+            button = TranslateButton(changes);
+            last_state = state;
             SDL_SendMouseMotion(Android_Window, 0, 0, x, y);
-            SDL_SendMouseButton(Android_Window, 0, SDL_RELEASED, SDLButton);
+            SDL_SendMouseButton(Android_Window, 0, SDL_RELEASED, button);
             break;
 
         case ACTION_MOVE:
diff --git a/src/video/android/SDL_androidmouse.h b/src/video/android/SDL_androidmouse.h
index a64e06d..ffee18b 100644
--- a/src/video/android/SDL_androidmouse.h
+++ b/src/video/android/SDL_androidmouse.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,14 +19,14 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_androidmouse_h
-#define _SDL_androidmouse_h
+#ifndef SDL_androidmouse_h_
+#define SDL_androidmouse_h_
 
 #include "SDL_androidvideo.h"
 
 extern void Android_InitMouse(void);
 extern void Android_OnMouse( int button, int action, float x, float y);
 
-#endif /* _SDL_androidmouse_h */
+#endif /* SDL_androidmouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/android/SDL_androidtouch.c b/src/video/android/SDL_androidtouch.c
index 0ff11ef..e0d0cd5 100644
--- a/src/video/android/SDL_androidtouch.c
+++ b/src/video/android/SDL_androidtouch.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -52,16 +52,13 @@ static void Android_GetWindowCoordinates(float x, float y,
 
 static SDL_bool separate_mouse_and_touch = SDL_FALSE;
 
-static void
+static void SDLCALL
 SeparateEventsHintWatcher(void *userdata, const char *name,
                           const char *oldValue, const char *newValue)
 {
-    jclass mActivityClass = Android_JNI_GetActivityClass();
-    JNIEnv *env = Android_JNI_GetEnv();
-    jfieldID fid = (*env)->GetStaticFieldID(env, mActivityClass, "mSeparateMouseAndTouch", "Z");
-
     separate_mouse_and_touch = (newValue && (SDL_strcmp(newValue, "1") == 0));
-    (*env)->SetStaticBooleanField(env, mActivityClass, fid, separate_mouse_and_touch ? JNI_TRUE : JNI_FALSE);
+
+    Android_JNI_SetSeparateMouseAndTouch(separate_mouse_and_touch);
 }
 
 void Android_InitTouch(void)
diff --git a/src/video/android/SDL_androidtouch.h b/src/video/android/SDL_androidtouch.h
index 2ad096c..efe6e23 100644
--- a/src/video/android/SDL_androidtouch.h
+++ b/src/video/android/SDL_androidtouch.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/android/SDL_androidvideo.c b/src/video/android/SDL_androidvideo.c
index 178a3e6..bd7b1ae 100644
--- a/src/video/android/SDL_androidvideo.c
+++ b/src/video/android/SDL_androidvideo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,12 +33,14 @@
 #include "../../events/SDL_windowevents_c.h"
 
 #include "SDL_androidvideo.h"
+#include "SDL_androidgl.h"
 #include "SDL_androidclipboard.h"
 #include "SDL_androidevents.h"
 #include "SDL_androidkeyboard.h"
 #include "SDL_androidmouse.h"
 #include "SDL_androidtouch.h"
 #include "SDL_androidwindow.h"
+#include "SDL_androidvulkan.h"
 
 #define ANDROID_VID_DRIVER_NAME "Android"
 
@@ -47,11 +49,6 @@ static int Android_VideoInit(_THIS);
 static void Android_VideoQuit(_THIS);
 
 #include "../SDL_egl_c.h"
-/* GL functions (SDL_androidgl.c) */
-extern SDL_GLContext Android_GLES_CreateContext(_THIS, SDL_Window * window);
-extern int Android_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
-extern void Android_GLES_SwapWindow(_THIS, SDL_Window * window);
-extern int Android_GLES_LoadLibrary(_THIS, const char *path);
 #define Android_GLES_GetProcAddress SDL_EGL_GetProcAddress
 #define Android_GLES_UnloadLibrary SDL_EGL_UnloadLibrary
 #define Android_GLES_SetSwapInterval SDL_EGL_SetSwapInterval
@@ -65,7 +62,7 @@ extern int Android_GLES_LoadLibrary(_THIS, const char *path);
 int Android_ScreenWidth = 0;
 int Android_ScreenHeight = 0;
 Uint32 Android_ScreenFormat = SDL_PIXELFORMAT_UNKNOWN;
-int Android_ScreenRate = 0;
+static int Android_ScreenRate = 0;
 
 SDL_sem *Android_PauseSem = NULL, *Android_ResumeSem = NULL;
 
@@ -118,7 +115,7 @@ Android_CreateDevice(int devindex)
     device->VideoQuit = Android_VideoQuit;
     device->PumpEvents = Android_PumpEvents;
 
-    device->CreateWindow = Android_CreateWindow;
+    device->CreateSDLWindow = Android_CreateWindow;
     device->SetWindowTitle = Android_SetWindowTitle;
     device->DestroyWindow = Android_DestroyWindow;
     device->GetWindowWMInfo = Android_GetWindowWMInfo;
@@ -136,6 +133,13 @@ Android_CreateDevice(int devindex)
     device->GL_SwapWindow = Android_GLES_SwapWindow;
     device->GL_DeleteContext = Android_GLES_DeleteContext;
 
+#if SDL_VIDEO_VULKAN
+    device->Vulkan_LoadLibrary = Android_Vulkan_LoadLibrary;
+    device->Vulkan_UnloadLibrary = Android_Vulkan_UnloadLibrary;
+    device->Vulkan_GetInstanceExtensions = Android_Vulkan_GetInstanceExtensions;
+    device->Vulkan_CreateSurface = Android_Vulkan_CreateSurface;
+#endif
+
     /* Screensaver */
     device->SuspendScreenSaver = Android_SuspendScreenSaver;
 
@@ -197,6 +201,8 @@ Android_VideoQuit(_THIS)
 void
 Android_SetScreenResolution(int width, int height, Uint32 format, float rate)
 {
+	SDL_VideoDevice* device;
+	SDL_VideoDisplay *display;
     Android_ScreenWidth = width;
     Android_ScreenHeight = height;
     Android_ScreenFormat = format;
@@ -208,10 +214,10 @@ Android_SetScreenResolution(int width, int height, Uint32 format, float rate)
       example happen when the Activity enters or exists immersive mode,
       which can happen after VideoInit().
     */
-    SDL_VideoDevice* device = SDL_GetVideoDevice();
+    device = SDL_GetVideoDevice();
     if (device && device->num_displays > 0)
     {
-        SDL_VideoDisplay* display = &device->displays[0];
+        display = &device->displays[0];
         display->desktop_mode.format = Android_ScreenFormat;
         display->desktop_mode.w = Android_ScreenWidth;
         display->desktop_mode.h = Android_ScreenHeight;
@@ -223,7 +229,7 @@ Android_SetScreenResolution(int width, int height, Uint32 format, float rate)
 
         /* Force the current mode to match the resize otherwise the SDL_WINDOWEVENT_RESTORED event
          * will fall back to the old mode */
-        SDL_VideoDisplay *display = SDL_GetDisplayForWindow(Android_Window);
+        display = SDL_GetDisplayForWindow(Android_Window);
 
         display->current_mode.format = format;
         display->current_mode.w = width;
diff --git a/src/video/android/SDL_androidvideo.h b/src/video/android/SDL_androidvideo.h
index 0f76a91..f061dd5 100644
--- a/src/video/android/SDL_androidvideo.h
+++ b/src/video/android/SDL_androidvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_androidvideo_h
-#define _SDL_androidvideo_h
+#ifndef SDL_androidvideo_h_
+#define SDL_androidvideo_h_
 
 #include "SDL_mutex.h"
 #include "SDL_rect.h"
@@ -44,6 +44,6 @@ extern SDL_sem *Android_PauseSem, *Android_ResumeSem;
 extern SDL_Window *Android_Window;
 
 
-#endif /* _SDL_androidvideo_h */
+#endif /* SDL_androidvideo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/android/SDL_androidvulkan.c b/src/video/android/SDL_androidvulkan.c
new file mode 100644
index 0000000..072b0f3
--- /dev/null
+++ b/src/video/android/SDL_androidvulkan.c
@@ -0,0 +1,174 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.c.
+ */
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_ANDROID
+
+#include "SDL_androidvideo.h"
+#include "SDL_androidwindow.h"
+#include "SDL_assert.h"
+
+#include "SDL_loadso.h"
+#include "SDL_androidvulkan.h"
+#include "SDL_syswm.h"
+
+int Android_Vulkan_LoadLibrary(_THIS, const char *path)
+{
+    VkExtensionProperties *extensions = NULL;
+    Uint32 i, extensionCount = 0;
+    SDL_bool hasSurfaceExtension = SDL_FALSE;
+    SDL_bool hasAndroidSurfaceExtension = SDL_FALSE;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
+    if(_this->vulkan_config.loader_handle)
+        return SDL_SetError("Vulkan already loaded");
+
+    /* Load the Vulkan loader library */
+    if(!path)
+        path = SDL_getenv("SDL_VULKAN_LIBRARY");
+    if(!path)
+        path = "libvulkan.so";
+    _this->vulkan_config.loader_handle = SDL_LoadObject(path);
+    if(!_this->vulkan_config.loader_handle)
+        return -1;
+    SDL_strlcpy(_this->vulkan_config.loader_path, path,
+                SDL_arraysize(_this->vulkan_config.loader_path));
+    vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction(
+        _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr");
+    if(!vkGetInstanceProcAddr)
+        goto fail;
+    _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr;
+    _this->vulkan_config.vkEnumerateInstanceExtensionProperties =
+        (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)(
+            VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties");
+    if(!_this->vulkan_config.vkEnumerateInstanceExtensionProperties)
+        goto fail;
+    extensions = SDL_Vulkan_CreateInstanceExtensionsList(
+        (PFN_vkEnumerateInstanceExtensionProperties)
+            _this->vulkan_config.vkEnumerateInstanceExtensionProperties,
+        &extensionCount);
+    if(!extensions)
+        goto fail;
+    for(i = 0; i < extensionCount; i++)
+    {
+        if(SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasSurfaceExtension = SDL_TRUE;
+        else if(SDL_strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasAndroidSurfaceExtension = SDL_TRUE;
+    }
+    SDL_free(extensions);
+    if(!hasSurfaceExtension)
+    {
+        SDL_SetError("Installed Vulkan doesn't implement the "
+                     VK_KHR_SURFACE_EXTENSION_NAME " extension");
+        goto fail;
+    }
+    else if(!hasAndroidSurfaceExtension)
+    {
+        SDL_SetError("Installed Vulkan doesn't implement the "
+                     VK_KHR_ANDROID_SURFACE_EXTENSION_NAME "extension");
+        goto fail;
+    }
+    return 0;
+
+fail:
+    SDL_UnloadObject(_this->vulkan_config.loader_handle);
+    _this->vulkan_config.loader_handle = NULL;
+    return -1;
+}
+
+void Android_Vulkan_UnloadLibrary(_THIS)
+{
+    if(_this->vulkan_config.loader_handle)
+    {
+        SDL_UnloadObject(_this->vulkan_config.loader_handle);
+        _this->vulkan_config.loader_handle = NULL;
+    }
+}
+
+SDL_bool Android_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names)
+{
+    static const char *const extensionsForAndroid[] = {
+        VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_ANDROID_SURFACE_EXTENSION_NAME
+    };
+    if(!_this->vulkan_config.loader_handle)
+    {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+    return SDL_Vulkan_GetInstanceExtensions_Helper(
+            count, names, SDL_arraysize(extensionsForAndroid),
+            extensionsForAndroid);
+}
+
+SDL_bool Android_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface)
+{
+    SDL_WindowData *windowData = (SDL_WindowData *)window->driverdata;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr =
+        (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr;
+    PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR =
+        (PFN_vkCreateAndroidSurfaceKHR)vkGetInstanceProcAddr(
+                                            (VkInstance)instance,
+                                            "vkCreateAndroidSurfaceKHR");
+    VkAndroidSurfaceCreateInfoKHR createInfo = {};
+    VkResult result;
+
+    if(!_this->vulkan_config.loader_handle)
+    {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+
+    if(!vkCreateAndroidSurfaceKHR)
+    {
+        SDL_SetError(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME
+                     " extension is not enabled in the Vulkan instance.");
+        return SDL_FALSE;
+    }
+    createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
+    createInfo.pNext = NULL;
+    createInfo.flags = 0;
+    createInfo.window = windowData->native_window;
+    result = vkCreateAndroidSurfaceKHR(instance, &createInfo,
+                                       NULL, surface);
+    if(result != VK_SUCCESS)
+    {
+        SDL_SetError("vkCreateAndroidSurfaceKHR failed: %s",
+                     SDL_Vulkan_GetResultString(result));
+        return SDL_FALSE;
+    }
+    return SDL_TRUE;
+}
+
+#endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/emscripten/SDL_emscriptenvideo.h b/src/video/android/SDL_androidvulkan.h
similarity index 55%
copy from src/video/emscripten/SDL_emscriptenvideo.h
copy to src/video/android/SDL_androidvulkan.h
index 7618ab6..b06fece 100644
--- a/src/video/emscripten/SDL_emscriptenvideo.h
+++ b/src/video/android/SDL_androidvulkan.h
@@ -18,37 +18,35 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../../SDL_internal.h"
-
-#ifndef _SDL_emscriptenvideo_h
-#define _SDL_emscriptenvideo_h
 
-#include "../SDL_sysvideo.h"
-#include "../../events/SDL_touch_c.h"
-#include <emscripten/emscripten.h>
-#include <emscripten/html5.h>
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.h.
+ */
 
-#include <EGL/egl.h>
+#include "../../SDL_internal.h"
 
-typedef struct SDL_WindowData
-{
-#if SDL_VIDEO_OPENGL_EGL
-    EGLSurface egl_surface;
-#endif
-    SDL_Window *window;
-    SDL_Surface *surface;
+#ifndef SDL_androidvulkan_h_
+#define SDL_androidvulkan_h_
 
-    float pixel_ratio;
+#include "../SDL_vulkan_internal.h"
+#include "../SDL_sysvideo.h"
 
-    SDL_bool external_size;
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_ANDROID
 
-    int requested_fullscreen_mode;
-    SDL_bool fullscreen_resize;
+int Android_Vulkan_LoadLibrary(_THIS, const char *path);
+void Android_Vulkan_UnloadLibrary(_THIS);
+SDL_bool Android_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names);
+SDL_bool Android_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface);
 
-    SDL_bool finger_touching;  /* for mapping touch events to mice */
-    SDL_FingerID first_finger;
-} SDL_WindowData;
+#endif
 
-#endif /* _SDL_emscriptenvideo_h */
+#endif /* SDL_androidvulkan_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/android/SDL_androidwindow.c b/src/video/android/SDL_androidwindow.c
index 37a928f..4b8ac7f 100644
--- a/src/video/android/SDL_androidwindow.c
+++ b/src/video/android/SDL_androidwindow.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -29,6 +29,7 @@
 
 #include "SDL_androidvideo.h"
 #include "SDL_androidwindow.h"
+#include "SDL_hints.h"
 
 int
 Android_CreateWindow(_THIS, SDL_Window * window)
@@ -42,6 +43,9 @@ Android_CreateWindow(_THIS, SDL_Window * window)
     Android_PauseSem = SDL_CreateSemaphore(0);
     Android_ResumeSem = SDL_CreateSemaphore(0);
 
+    /* Set orientation */
+    Android_JNI_SetOrientation(window->w, window->h, window->flags & SDL_WINDOW_RESIZABLE, SDL_GetHint(SDL_HINT_ORIENTATIONS));
+
     /* Adjust the window data to match the screen */
     window->x = 0;
     window->y = 0;
@@ -69,13 +73,17 @@ Android_CreateWindow(_THIS, SDL_Window * window)
         SDL_free(data);
         return SDL_SetError("Could not fetch native window");
     }
-    
-    data->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) data->native_window);
 
-    if (data->egl_surface == EGL_NO_SURFACE) {
-        ANativeWindow_release(data->native_window);
-        SDL_free(data);
-        return SDL_SetError("Could not create GLES window surface");
+    /* Do not create EGLSurface for Vulkan window since it will then make the window
+       incompatible with vkCreateAndroidSurfaceKHR */
+    if ((window->flags & SDL_WINDOW_VULKAN) == 0) {
+        data->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) data->native_window);
+
+        if (data->egl_surface == EGL_NO_SURFACE) {
+            ANativeWindow_release(data->native_window);
+            SDL_free(data);
+            return SDL_SetError("Could not create GLES window surface");
+        }
     }
 
     window->driverdata = data;
@@ -128,7 +136,7 @@ Android_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
         info->info.android.surface = data->egl_surface;
         return SDL_TRUE;
     } else {
-        SDL_SetError("Application not compiled with SDL %d.%d\n",
+        SDL_SetError("Application not compiled with SDL %d.%d",
                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
diff --git a/src/video/android/SDL_androidwindow.h b/src/video/android/SDL_androidwindow.h
index 3ac99f4..b3445a4 100644
--- a/src/video/android/SDL_androidwindow.h
+++ b/src/video/android/SDL_androidwindow.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_androidwindow_h
-#define _SDL_androidwindow_h
+#ifndef SDL_androidwindow_h_
+#define SDL_androidwindow_h_
 
 #include "../../core/android/SDL_android.h"
 #include "../SDL_egl_c.h"
@@ -39,6 +39,6 @@ typedef struct
     
 } SDL_WindowData;
 
-#endif /* _SDL_androidwindow_h */
+#endif /* SDL_androidwindow_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoaclipboard.h b/src/video/cocoa/SDL_cocoaclipboard.h
index 871b394..2f134b4 100644
--- a/src/video/cocoa/SDL_cocoaclipboard.h
+++ b/src/video/cocoa/SDL_cocoaclipboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_cocoaclipboard_h
-#define _SDL_cocoaclipboard_h
+#ifndef SDL_cocoaclipboard_h_
+#define SDL_cocoaclipboard_h_
 
 /* Forward declaration */
 struct SDL_VideoData;
@@ -31,6 +31,6 @@ extern char *Cocoa_GetClipboardText(_THIS);
 extern SDL_bool Cocoa_HasClipboardText(_THIS);
 extern void Cocoa_CheckClipboardUpdate(struct SDL_VideoData * data);
 
-#endif /* _SDL_cocoaclipboard_h */
+#endif /* SDL_cocoaclipboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoaclipboard.m b/src/video/cocoa/SDL_cocoaclipboard.m
index fd86809..9d578e1 100644
--- a/src/video/cocoa/SDL_cocoaclipboard.m
+++ b/src/video/cocoa/SDL_cocoaclipboard.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/cocoa/SDL_cocoaevents.h b/src/video/cocoa/SDL_cocoaevents.h
index ea40e53..73011d0 100644
--- a/src/video/cocoa/SDL_cocoaevents.h
+++ b/src/video/cocoa/SDL_cocoaevents.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,13 +20,13 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_cocoaevents_h
-#define _SDL_cocoaevents_h
+#ifndef SDL_cocoaevents_h_
+#define SDL_cocoaevents_h_
 
 extern void Cocoa_RegisterApp(void);
 extern void Cocoa_PumpEvents(_THIS);
 extern void Cocoa_SuspendScreenSaver(_THIS);
 
-#endif /* _SDL_cocoaevents_h */
+#endif /* SDL_cocoaevents_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoaevents.m b/src/video/cocoa/SDL_cocoaevents.m
index 17a3183..e428e43 100644
--- a/src/video/cocoa/SDL_cocoaevents.m
+++ b/src/video/cocoa/SDL_cocoaevents.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -55,22 +55,22 @@ static void Cocoa_DispatchEvent(NSEvent *theEvent)
     SDL_VideoDevice *_this = SDL_GetVideoDevice();
 
     switch ([theEvent type]) {
-        case NSLeftMouseDown:
-        case NSOtherMouseDown:
-        case NSRightMouseDown:
-        case NSLeftMouseUp:
-        case NSOtherMouseUp:
-        case NSRightMouseUp:
-        case NSLeftMouseDragged:
-        case NSRightMouseDragged:
-        case NSOtherMouseDragged: /* usually middle mouse dragged */
-        case NSMouseMoved:
-        case NSScrollWheel:
+        case NSEventTypeLeftMouseDown:
+        case NSEventTypeOtherMouseDown:
+        case NSEventTypeRightMouseDown:
+        case NSEventTypeLeftMouseUp:
+        case NSEventTypeOtherMouseUp:
+        case NSEventTypeRightMouseUp:
+        case NSEventTypeLeftMouseDragged:
+        case NSEventTypeRightMouseDragged:
+        case NSEventTypeOtherMouseDragged: /* usually middle mouse dragged */
+        case NSEventTypeMouseMoved:
+        case NSEventTypeScrollWheel:
             Cocoa_HandleMouseEvent(_this, theEvent);
             break;
-        case NSKeyDown:
-        case NSKeyUp:
-        case NSFlagsChanged:
+        case NSEventTypeKeyDown:
+        case NSEventTypeKeyUp:
+        case NSEventTypeFlagsChanged:
             Cocoa_HandleKeyEvent(_this, theEvent);
             break;
         default:
@@ -289,7 +289,7 @@ CreateApplicationMenus(void)
     [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
 
     menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
-    [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
+    [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
 
     [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
 
@@ -335,7 +335,7 @@ CreateApplicationMenus(void)
 
         /* Add menu items */
         menuItem = [viewMenu addItemWithTitle:@"Toggle Full Screen" action:@selector(toggleFullScreen:) keyEquivalent:@"f"];
-        [menuItem setKeyEquivalentModifierMask:NSControlKeyMask | NSCommandKeyMask];
+        [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagControl | NSEventModifierFlagCommand];
 
         /* Put menu into the menubar */
         menuItem = [[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""];
@@ -394,6 +394,7 @@ void
 Cocoa_PumpEvents(_THIS)
 { @autoreleasepool
 {
+#if MAC_OS_X_VERSION_MIN_REQUIRED < 1070
     /* Update activity every 30 seconds to prevent screensaver */
     SDL_VideoData *data = (SDL_VideoData *)_this->driverdata;
     if (_this->suspend_screensaver && !data->screensaver_use_iopm) {
@@ -404,9 +405,10 @@ Cocoa_PumpEvents(_THIS)
             data->screensaver_activity = now;
         }
     }
+#endif
 
     for ( ; ; ) {
-        NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES ];
+        NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES ];
         if ( event == nil ) {
             break;
         }
diff --git a/src/video/cocoa/SDL_cocoakeyboard.h b/src/video/cocoa/SDL_cocoakeyboard.h
index 4f9da01..1d63023 100644
--- a/src/video/cocoa/SDL_cocoakeyboard.h
+++ b/src/video/cocoa/SDL_cocoakeyboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_cocoakeyboard_h
-#define _SDL_cocoakeyboard_h
+#ifndef SDL_cocoakeyboard_h_
+#define SDL_cocoakeyboard_h_
 
 extern void Cocoa_InitKeyboard(_THIS);
 extern void Cocoa_HandleKeyEvent(_THIS, NSEvent * event);
@@ -31,6 +31,6 @@ extern void Cocoa_StartTextInput(_THIS);
 extern void Cocoa_StopTextInput(_THIS);
 extern void Cocoa_SetTextInputRect(_THIS, SDL_Rect *rect);
 
-#endif /* _SDL_cocoakeyboard_h */
+#endif /* SDL_cocoakeyboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoakeyboard.m b/src/video/cocoa/SDL_cocoakeyboard.m
index 8b2ed91..b2ce5a3 100644
--- a/src/video/cocoa/SDL_cocoakeyboard.m
+++ b/src/video/cocoa/SDL_cocoakeyboard.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -143,10 +143,13 @@
             aRange.location, aRange.length, windowHeight,
             NSStringFromRect(rect));
 
-    if ([window respondsToSelector:@selector(convertRectToScreen:)]) {
-        rect = [window convertRectToScreen:rect];
-    } else {
+#if MAC_OS_X_VERSION_MIN_REQUIRED < 1070
+    if (![window respondsToSelector:@selector(convertRectToScreen:)]) {
         rect.origin = [window convertBaseToScreen:rect.origin];
+    } else
+#endif
+    {
+        rect = [window convertRectToScreen:rect];
     }
 
     return rect;
@@ -460,7 +463,7 @@ DoSidedModifiers(unsigned short scancode,
     unsigned int i, bit;
 
     /* Iterate through the bits, testing each against the old modifiers */
-    for (i = 0, bit = NSShiftKeyMask; bit <= NSCommandKeyMask; bit <<= 1, ++i) {
+    for (i = 0, bit = NSEventModifierFlagShift; bit <= NSEventModifierFlagCommand; bit <<= 1, ++i) {
         unsigned int oldMask, newMask;
 
         oldMask = oldMods & bit;
@@ -581,7 +584,7 @@ Cocoa_InitKeyboard(_THIS)
     SDL_SetScancodeName(SDL_SCANCODE_RGUI, "Right Command");
 
     data->modifierFlags = [NSEvent modifierFlags];
-    SDL_ToggleModState(KMOD_CAPS, (data->modifierFlags & NSAlphaShiftKeyMask) != 0);
+    SDL_ToggleModState(KMOD_CAPS, (data->modifierFlags & NSEventModifierFlagCapsLock) != 0);
 
     InitHIDCallback();
 }
@@ -646,7 +649,7 @@ Cocoa_SetTextInputRect(_THIS, SDL_Rect *rect)
 void
 Cocoa_HandleKeyEvent(_THIS, NSEvent *event)
 {
-    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
+    SDL_VideoData *data = _this ? ((SDL_VideoData *) _this->driverdata) : NULL;
     if (!data) {
         return;  /* can happen when returning from fullscreen Space on shutdown */
     }
@@ -670,7 +673,7 @@ Cocoa_HandleKeyEvent(_THIS, NSEvent *event)
     }
 
     switch ([event type]) {
-    case NSKeyDown:
+    case NSEventTypeKeyDown:
         if (![event isARepeat]) {
             /* See if we need to rebuild the keyboard layout */
             UpdateKeymap(data, SDL_TRUE);
@@ -679,7 +682,7 @@ Cocoa_HandleKeyEvent(_THIS, NSEvent *event)
         SDL_SendKeyboardKey(SDL_PRESSED, code);
 #if 1
         if (code == SDL_SCANCODE_UNKNOWN) {
-            fprintf(stderr, "The key you just pressed is not recognized by SDL. To help get this fixed, report this to the SDL mailing list <sdl at libsdl.org> or to Christian Walther <cwalther at gmx.ch>. Mac virtual key code is %d.\n", scancode);
+            fprintf(stderr, "The key you just pressed is not recognized by SDL. To help get this fixed, report this to the SDL forums/mailing list <https://discourse.libsdl.org/> or to Christian Walther <cwalther at gmx.ch>. Mac virtual key code is %d.\n", scancode);
         }
 #endif
         if (SDL_EventState(SDL_TEXTINPUT, SDL_QUERY)) {
@@ -694,10 +697,10 @@ Cocoa_HandleKeyEvent(_THIS, NSEvent *event)
 #endif
         }
         break;
-    case NSKeyUp:
+    case NSEventTypeKeyUp:
         SDL_SendKeyboardKey(SDL_RELEASED, code);
         break;
-    case NSFlagsChanged:
+    case NSEventTypeFlagsChanged:
         /* FIXME CW 2007-08-14: check if this whole mess that takes up half of this file is really necessary */
         HandleModifiers(_this, scancode, [event modifierFlags]);
         break;
diff --git a/src/video/cocoa/SDL_cocoamessagebox.h b/src/video/cocoa/SDL_cocoamessagebox.h
index d1ca788..e3aa68a 100644
--- a/src/video/cocoa/SDL_cocoamessagebox.h
+++ b/src/video/cocoa/SDL_cocoamessagebox.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/cocoa/SDL_cocoamessagebox.m b/src/video/cocoa/SDL_cocoamessagebox.m
index ed59e72..ea55449 100644
--- a/src/video/cocoa/SDL_cocoamessagebox.m
+++ b/src/video/cocoa/SDL_cocoamessagebox.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -57,11 +57,24 @@
 - (void)showAlert:(NSAlert*)alert
 {
     if (nswindow) {
-        [alert beginSheetModalForWindow:nswindow modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
+#ifdef MAC_OS_X_VERSION_10_9
+        if ([alert respondsToSelector:@selector(beginSheetModalForWindow:completionHandler:)]) {
+            [alert beginSheetModalForWindow:nswindow completionHandler:^(NSModalResponse returnCode) {
+                clicked = returnCode;
+            }];
+        } else
+#endif
+        {
+#if MAC_OS_X_VERSION_MIN_REQUIRED < 1090
+            [alert beginSheetModalForWindow:nswindow modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
+#endif
+        }
+
         while (clicked < 0) {
             SDL_PumpEvents();
             SDL_Delay(100);
         }
+
         [nswindow release];
     } else {
         clicked = [alert runModal];
@@ -86,11 +99,11 @@ Cocoa_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
     NSAlert* alert = [[[NSAlert alloc] init] autorelease];
 
     if (messageboxdata->flags & SDL_MESSAGEBOX_ERROR) {
-        [alert setAlertStyle:NSCriticalAlertStyle];
+        [alert setAlertStyle:NSAlertStyleCritical];
     } else if (messageboxdata->flags & SDL_MESSAGEBOX_WARNING) {
-        [alert setAlertStyle:NSWarningAlertStyle];
+        [alert setAlertStyle:NSAlertStyleWarning];
     } else {
-        [alert setAlertStyle:NSInformationalAlertStyle];
+        [alert setAlertStyle:NSAlertStyleInformational];
     }
 
     [alert setMessageText:[NSString stringWithUTF8String:messageboxdata->title]];
diff --git a/src/video/cocoa/SDL_cocoametalview.h b/src/video/cocoa/SDL_cocoametalview.h
new file mode 100644
index 0000000..745dea3
--- /dev/null
+++ b/src/video/cocoa/SDL_cocoametalview.h
@@ -0,0 +1,65 @@
+/*
+ Simple DirectMedia Layer
+ Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+ 
+ This software is provided 'as-is', without any express or implied
+ warranty.  In no event will the authors be held liable for any damages
+ arising from the use of this software.
+ 
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+ 
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+ */
+
+/*
+ * @author Mark Callow, www.edgewise-consulting.com.
+ *
+ * Thanks to Alex Szpakowski, @slime73 on GitHub, for his gist showing
+ * how to add a CAMetalLayer backed view.
+ */
+
+#ifndef SDL_cocoametalview_h_
+#define SDL_cocoametalview_h_
+
+#import "../SDL_sysvideo.h"
+#import "SDL_cocoawindow.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_COCOA
+
+#include <Cocoa/Cocoa.h>
+#include <Metal/Metal.h>
+#include <QuartzCore/CAMetalLayer.h>
+
+#define METALVIEW_TAG 255
+
+ at interface SDL_cocoametalview : NSView {
+    NSInteger _tag;
+    bool _useHighDPI;
+}
+
+- (instancetype)initWithFrame:(NSRect)frame
+                   useHighDPI:(bool)useHighDPI;
+
+/* Override superclass tag so this class can set it. */
+ at property (assign, readonly) NSInteger tag;
+
+ at end
+
+SDL_cocoametalview* Cocoa_Mtl_AddMetalView(SDL_Window* window);
+
+void Cocoa_Mtl_GetDrawableSize(SDL_Window * window, int * w, int * h);
+
+#endif /* SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_COCOA */
+
+#endif /* SDL_cocoametalview_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
+
diff --git a/src/video/cocoa/SDL_cocoametalview.m b/src/video/cocoa/SDL_cocoametalview.m
new file mode 100644
index 0000000..562eecc
--- /dev/null
+++ b/src/video/cocoa/SDL_cocoametalview.m
@@ -0,0 +1,128 @@
+/*
+ Simple DirectMedia Layer
+ Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+ 
+ This software is provided 'as-is', without any express or implied
+ warranty.  In no event will the authors be held liable for any damages
+ arising from the use of this software.
+ 
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+ 
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+ */
+
+/*
+ * @author Mark Callow, www.edgewise-consulting.com.
+ *
+ * Thanks to Alex Szpakowski, @slime73 on GitHub, for his gist showing
+ * how to add a CAMetalLayer backed view.
+ */
+
+#import "SDL_cocoametalview.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_COCOA
+
+#include "SDL_assert.h"
+
+ at implementation SDL_cocoametalview
+
+/* The synthesized getter should be called by super's viewWithTag. */
+ at synthesize tag = _tag;
+
+/* Return a Metal-compatible layer. */
++ (Class)layerClass
+{
+	return NSClassFromString(@"CAMetalLayer");
+}
+
+/* Indicate the view wants to draw using a backing layer instead of drawRect. */
+-(BOOL) wantsUpdateLayer
+{
+    return YES;
+}
+
+/* When the wantsLayer property is set to YES, this method will be invoked to
+ * return a layer instance.
+ */
+-(CALayer*) makeBackingLayer
+{
+    return [self.class.layerClass layer];
+}
+
+- (instancetype)initWithFrame:(NSRect)frame
+                   useHighDPI:(bool)useHighDPI
+{
+	if ((self = [super initWithFrame:frame])) {
+    
+        /* Allow resize. */
+        self.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
+        _tag = METALVIEW_TAG;
+      
+        _useHighDPI = useHighDPI;
+        [self updateDrawableSize];
+	}
+  
+	return self;
+}
+
+/* Set the size of the metal drawables when the view is resized. */
+- (void)resizeSubviewsWithOldSize:(NSSize)oldSize {
+    [super resizeSubviewsWithOldSize:oldSize];
+    [self updateDrawableSize];
+}
+
+- (void)updateDrawableSize
+{
+    NSRect bounds = [self bounds];
+    if (_useHighDPI) {
+        bounds = [self convertRectToBacking:bounds];
+    }
+    ((CAMetalLayer *) self.layer).drawableSize = NSSizeToCGSize(bounds.size);
+}
+
+ at end
+
+SDL_cocoametalview*
+Cocoa_Mtl_AddMetalView(SDL_Window* window)
+{
+    SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
+    NSView *view = data->nswindow.contentView;
+
+    SDL_cocoametalview *metalview
+        = [[SDL_cocoametalview alloc] initWithFrame:view.frame
+                       useHighDPI:(window->flags & SDL_WINDOW_ALLOW_HIGHDPI)];
+    // Instantiate the CAMetalLayer
+    metalview.wantsLayer = YES;
+    [view addSubview:metalview];
+    return metalview;
+}
+
+void
+Cocoa_Mtl_GetDrawableSize(SDL_Window * window, int * w, int * h)
+{
+    SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
+    NSView *view = data->nswindow.contentView;
+    SDL_cocoametalview* metalview = [view viewWithTag:METALVIEW_TAG];
+    if (metalview) {
+        CAMetalLayer *layer = (CAMetalLayer*)metalview.layer;
+        assert(layer != NULL);
+        if (w) {
+            *w = layer.drawableSize.width;
+        }
+        if (h) {
+            *h = layer.drawableSize.height;
+        }
+    }
+}
+
+#endif /* SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_COCOA */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoamodes.h b/src/video/cocoa/SDL_cocoamodes.h
index ce8601c..f90962d 100644
--- a/src/video/cocoa/SDL_cocoamodes.h
+++ b/src/video/cocoa/SDL_cocoamodes.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_cocoamodes_h
-#define _SDL_cocoamodes_h
+#ifndef SDL_cocoamodes_h_
+#define SDL_cocoamodes_h_
 
 typedef struct
 {
@@ -41,6 +41,6 @@ extern int Cocoa_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi,
 extern int Cocoa_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode);
 extern void Cocoa_QuitModes(_THIS);
 
-#endif /* _SDL_cocoamodes_h */
+#endif /* SDL_cocoamodes_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoamodes.m b/src/video/cocoa/SDL_cocoamodes.m
index 6ae9dec..592367a 100644
--- a/src/video/cocoa/SDL_cocoamodes.m
+++ b/src/video/cocoa/SDL_cocoamodes.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -100,15 +100,47 @@ CG_SetError(const char *prefix, CGDisplayErr result)
 }
 
 static SDL_bool
-GetDisplayMode(_THIS, CGDisplayModeRef vidmode, CVDisplayLinkRef link, SDL_DisplayMode *mode)
+GetDisplayMode(_THIS, CGDisplayModeRef vidmode, CFArrayRef modelist, CVDisplayLinkRef link, SDL_DisplayMode *mode)
 {
     SDL_DisplayModeData *data;
-    int width = 0;
-    int height = 0;
+    int width = (int) CGDisplayModeGetWidth(vidmode);
+    int height = (int) CGDisplayModeGetHeight(vidmode);
     int bpp = 0;
     int refreshRate = 0;
     CFStringRef fmt;
 
+    /* Ignore this mode if it's low-dpi (@1x) and we have a high-dpi mode in the
+     * list with the same size in points.
+     */
+#ifdef MAC_OS_X_VERSION_10_8
+    if (modelist != NULL && floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) {
+        int pixelW = (int) CGDisplayModeGetPixelWidth(vidmode);
+        int pixelH = (int) CGDisplayModeGetPixelHeight(vidmode);
+
+        if (width == pixelW && height == pixelH) {
+            CFIndex modescount = CFArrayGetCount(modelist);
+
+            for (int i = 0; i < modescount; i++) {
+                CGDisplayModeRef othermode = (CGDisplayModeRef) CFArrayGetValueAtIndex(modelist, i);
+
+                if (CFEqual(vidmode, othermode)) {
+                    continue;
+                }
+
+                int otherW = (int) CGDisplayModeGetWidth(othermode);
+                int otherH = (int) CGDisplayModeGetHeight(othermode);
+
+                int otherpixelW = (int) CGDisplayModeGetPixelWidth(othermode);
+                int otherpixelH = (int) CGDisplayModeGetPixelHeight(othermode);
+
+                if (width == otherW && height == otherH && (otherpixelW != otherW || otherpixelH != otherH)) {
+                    return SDL_FALSE;
+                }
+            }
+        }
+    }
+#endif
+
     data = (SDL_DisplayModeData *) SDL_malloc(sizeof(*data));
     if (!data) {
         return SDL_FALSE;
@@ -116,8 +148,6 @@ GetDisplayMode(_THIS, CGDisplayModeRef vidmode, CVDisplayLinkRef link, SDL_Displ
     data->moderef = vidmode;
 
     fmt = CGDisplayModeCopyPixelEncoding(vidmode);
-    width = (int) CGDisplayModeGetWidth(vidmode);
-    height = (int) CGDisplayModeGetHeight(vidmode);
     refreshRate = (int) (CGDisplayModeGetRefreshRate(vidmode) + 0.5);
 
     if (CFStringCompare(fmt, CFSTR(IO32BitDirectPixels),
@@ -243,7 +273,7 @@ Cocoa_InitModes(_THIS)
             SDL_zero(display);
             /* this returns a stddup'ed string */
             display.name = (char *)Cocoa_GetDisplayName(displays[i]);
-            if (!GetDisplayMode(_this, moderef, link, &mode)) {
+            if (!GetDisplayMode(_this, moderef, NULL, link, &mode)) {
                 CVDisplayLinkRelease(link);
                 CGDisplayModeRelease(moderef);
                 SDL_free(display.name);
@@ -340,7 +370,32 @@ void
 Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
 {
     SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata;
-    CFArrayRef modes = CGDisplayCopyAllDisplayModes(data->display, NULL);
+    CFDictionaryRef dict = NULL;
+    CFArrayRef modes;
+
+    /* By default, CGDisplayCopyAllDisplayModes will only get a subset of the
+     * system's available modes. For example on a 15" 2016 MBP, users can
+     * choose 1920x1080 at 2x in System Preferences but it won't show up here,
+     * unless we specify the option below.
+     */
+#ifdef MAC_OS_X_VERSION_10_8
+    if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7) {
+        const CFStringRef dictkeys[] = {kCGDisplayShowDuplicateLowResolutionModes};
+        const CFBooleanRef dictvalues[] = {kCFBooleanTrue};
+        dict = CFDictionaryCreate(NULL,
+                                  (const void **)dictkeys,
+                                  (const void **)dictvalues,
+                                  1,
+                                  &kCFCopyStringDictionaryKeyCallBacks,
+                                  &kCFTypeDictionaryValueCallBacks);
+    }
+#endif
+
+    modes = CGDisplayCopyAllDisplayModes(data->display, dict);
+
+    if (dict != NULL) {
+        CFRelease(dict);
+    }
 
     if (modes) {
         CVDisplayLinkRef link = NULL;
@@ -352,7 +407,7 @@ Cocoa_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
         for (i = 0; i < count; i++) {
             CGDisplayModeRef moderef = (CGDisplayModeRef) CFArrayGetValueAtIndex(modes, i);
             SDL_DisplayMode mode;
-            if (GetDisplayMode(_this, moderef, link, &mode)) {
+            if (GetDisplayMode(_this, moderef, modes, link, &mode)) {
                 CGDisplayModeRetain(moderef);
                 SDL_AddDisplayMode(display, &mode);
             }
diff --git a/src/video/cocoa/SDL_cocoamouse.h b/src/video/cocoa/SDL_cocoamouse.h
index 4f60c83..8bcc68f 100644
--- a/src/video/cocoa/SDL_cocoamouse.h
+++ b/src/video/cocoa/SDL_cocoamouse.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_cocoamouse_h
-#define _SDL_cocoamouse_h
+#ifndef SDL_cocoamouse_h_
+#define SDL_cocoamouse_h_
 
 #include "SDL_cocoavideo.h"
 
@@ -47,6 +47,6 @@ typedef struct {
 + (NSCursor *)invisibleCursor;
 @end
 
-#endif /* _SDL_cocoamouse_h */
+#endif /* SDL_cocoamouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoamouse.m b/src/video/cocoa/SDL_cocoamouse.m
index 0a27549..d6fa5ff 100644
--- a/src/video/cocoa/SDL_cocoamouse.m
+++ b/src/video/cocoa/SDL_cocoamouse.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -26,6 +26,7 @@
 #include "SDL_events.h"
 #include "SDL_cocoamouse.h"
 #include "SDL_cocoamousetap.h"
+#include "SDL_cocoavideo.h"
 
 #include "../../events/SDL_mouse_c.h"
 
@@ -363,10 +364,10 @@ void
 Cocoa_HandleMouseEvent(_THIS, NSEvent *event)
 {
     switch ([event type]) {
-        case NSMouseMoved:
-        case NSLeftMouseDragged:
-        case NSRightMouseDragged:
-        case NSOtherMouseDragged:
+        case NSEventTypeMouseMoved:
+        case NSEventTypeLeftMouseDragged:
+        case NSEventTypeRightMouseDragged:
+        case NSEventTypeOtherMouseDragged:
             break;
 
         default:
@@ -431,17 +432,7 @@ Cocoa_HandleMouseWheel(SDL_Window *window, NSEvent *event)
         }
     }
 
-    if (x > 0) {
-        x = SDL_ceil(x);
-    } else if (x < 0) {
-        x = SDL_floor(x);
-    }
-    if (y > 0) {
-        y = SDL_ceil(y);
-    } else if (y < 0) {
-        y = SDL_floor(y);
-    }
-    SDL_SendMouseWheel(window, mouse->mouseID, (int)x, (int)y, direction);
+    SDL_SendMouseWheel(window, mouse->mouseID, x, y, direction);
 }
 
 void
diff --git a/src/video/cocoa/SDL_cocoamousetap.h b/src/video/cocoa/SDL_cocoamousetap.h
index af92314..f80cccb 100644
--- a/src/video/cocoa/SDL_cocoamousetap.h
+++ b/src/video/cocoa/SDL_cocoamousetap.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,14 +20,15 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_cocoamousetap_h
-#define _SDL_cocoamousetap_h
+#ifndef SDL_cocoamousetap_h_
+#define SDL_cocoamousetap_h_
 
 #include "SDL_cocoamouse.h"
 
 extern void Cocoa_InitMouseEventTap(SDL_MouseData *driverdata);
+extern void Cocoa_EnableMouseEventTap(SDL_MouseData *driverdata, SDL_bool enabled);
 extern void Cocoa_QuitMouseEventTap(SDL_MouseData *driverdata);
 
-#endif /* _SDL_cocoamousetap_h */
+#endif /* SDL_cocoamousetap_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoamousetap.m b/src/video/cocoa/SDL_cocoamousetap.m
index 48abbca..7ae564e 100644
--- a/src/video/cocoa/SDL_cocoamousetap.m
+++ b/src/video/cocoa/SDL_cocoamousetap.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -69,11 +69,14 @@ Cocoa_MouseTapCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event
 
     switch (type) {
         case kCGEventTapDisabledByTimeout:
-        case kCGEventTapDisabledByUserInput:
             {
                 CGEventTapEnable(tapdata->tap, true);
                 return NULL;
             }
+        case kCGEventTapDisabledByUserInput:
+            {
+                return NULL;
+            }
         default:
             break;
     }
@@ -142,15 +145,12 @@ Cocoa_MouseTapThread(void *data)
 {
     SDL_MouseEventTapData *tapdata = (SDL_MouseEventTapData*)data;
 
-    /* Create a tap. */
-    CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap,
-                                              kCGEventTapOptionDefault, allGrabbedEventsMask,
-                                              &Cocoa_MouseTapCallback, tapdata);
+    /* Tap was created on main thread but we own it now. */
+    CFMachPortRef eventTap = tapdata->tap;
     if (eventTap) {
         /* Try to create a runloop source we can schedule. */
         CFRunLoopSourceRef runloopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
         if  (runloopSource) {
-            tapdata->tap = eventTap;
             tapdata->runloopSource = runloopSource;
         } else {
             CFRelease(eventTap);
@@ -202,15 +202,32 @@ Cocoa_InitMouseEventTap(SDL_MouseData* driverdata)
 
     tapdata->runloopStartedSemaphore = SDL_CreateSemaphore(0);
     if (tapdata->runloopStartedSemaphore) {
-        tapdata->thread = SDL_CreateThreadInternal(&Cocoa_MouseTapThread, "Event Tap Loop", 512 * 1024, tapdata);
-        if (!tapdata->thread) {
-            SDL_DestroySemaphore(tapdata->runloopStartedSemaphore);
+        tapdata->tap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap,
+                                        kCGEventTapOptionDefault, allGrabbedEventsMask,
+                                        &Cocoa_MouseTapCallback, tapdata);
+        if (tapdata->tap) {
+            /* Tap starts disabled, until app requests mouse grab */
+            CGEventTapEnable(tapdata->tap, false);
+            tapdata->thread = SDL_CreateThreadInternal(&Cocoa_MouseTapThread, "Event Tap Loop", 512 * 1024, tapdata);
+            if (tapdata->thread) {
+                /* Success - early out. Ownership transferred to thread. */
+            	return;
+            }
+            CFRelease(tapdata->tap);
         }
+        SDL_DestroySemaphore(tapdata->runloopStartedSemaphore);
     }
+    SDL_free(driverdata->tapdata);
+    driverdata->tapdata = NULL;
+}
 
-    if (!tapdata->thread) {
-        SDL_free(driverdata->tapdata);
-        driverdata->tapdata = NULL;
+void
+Cocoa_EnableMouseEventTap(SDL_MouseData *driverdata, SDL_bool enabled)
+{
+    SDL_MouseEventTapData *tapdata = (SDL_MouseEventTapData*)driverdata->tapdata;
+    if (tapdata && tapdata->tap)
+    {
+        CGEventTapEnable(tapdata->tap, !!enabled);
     }
 }
 
@@ -246,6 +263,11 @@ Cocoa_InitMouseEventTap(SDL_MouseData *unused)
 }
 
 void
+Cocoa_EnableMouseEventTap(SDL_MouseData *driverdata, SDL_bool enabled)
+{
+}
+
+void
 Cocoa_QuitMouseEventTap(SDL_MouseData *driverdata)
 {
 }
diff --git a/src/video/cocoa/SDL_cocoaopengl.h b/src/video/cocoa/SDL_cocoaopengl.h
index 1f7bd57..d9cefd3 100644
--- a/src/video/cocoa/SDL_cocoaopengl.h
+++ b/src/video/cocoa/SDL_cocoaopengl.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_cocoaopengl_h
-#define _SDL_cocoaopengl_h
+#ifndef SDL_cocoaopengl_h_
+#define SDL_cocoaopengl_h_
 
 #if SDL_VIDEO_OPENGL_CGL
 
@@ -58,11 +58,11 @@ extern void Cocoa_GL_GetDrawableSize(_THIS, SDL_Window * window,
                                      int * w, int * h);
 extern int Cocoa_GL_SetSwapInterval(_THIS, int interval);
 extern int Cocoa_GL_GetSwapInterval(_THIS);
-extern void Cocoa_GL_SwapWindow(_THIS, SDL_Window * window);
+extern int Cocoa_GL_SwapWindow(_THIS, SDL_Window * window);
 extern void Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context);
 
 #endif /* SDL_VIDEO_OPENGL_CGL */
 
-#endif /* _SDL_cocoaopengl_h */
+#endif /* SDL_cocoaopengl_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoaopengl.m b/src/video/cocoa/SDL_cocoaopengl.m
index 645e5ba..a65f0cd 100644
--- a/src/video/cocoa/SDL_cocoaopengl.m
+++ b/src/video/cocoa/SDL_cocoaopengl.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -383,13 +383,14 @@ Cocoa_GL_GetSwapInterval(_THIS)
     return status;
 }}
 
-void
+int
 Cocoa_GL_SwapWindow(_THIS, SDL_Window * window)
 { @autoreleasepool
 {
     SDLOpenGLContext* nscontext = (SDLOpenGLContext*)SDL_GL_GetCurrentContext();
     [nscontext flushBuffer];
     [nscontext updateIfNeeded];
+    return 0;
 }}
 
 void
diff --git a/src/video/cocoa/SDL_cocoashape.h b/src/video/cocoa/SDL_cocoashape.h
index f64b591..73923ca 100644
--- a/src/video/cocoa/SDL_cocoashape.h
+++ b/src/video/cocoa/SDL_cocoashape.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_cocoashape_h
-#define _SDL_cocoashape_h
+#ifndef SDL_cocoashape_h_
+#define SDL_cocoashape_h_
 
 #include "SDL_stdinc.h"
 #include "SDL_video.h"
@@ -40,4 +40,6 @@ extern SDL_WindowShaper* Cocoa_CreateShaper(SDL_Window* window);
 extern int Cocoa_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode);
 extern int Cocoa_ResizeWindowShape(SDL_Window *window);
 
-#endif
+#endif /* SDL_cocoashape_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoashape.m b/src/video/cocoa/SDL_cocoashape.m
index fc8a277..32d4e9d 100644
--- a/src/video/cocoa/SDL_cocoashape.m
+++ b/src/video/cocoa/SDL_cocoashape.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -35,7 +35,7 @@ Cocoa_CreateShaper(SDL_Window* window)
     SDL_WindowData* windata = (SDL_WindowData*)window->driverdata;
     [windata->nswindow setOpaque:NO];
 
-    [windata->nswindow setStyleMask:NSBorderlessWindowMask];
+    [windata->nswindow setStyleMask:NSWindowStyleMaskBorderless];
 
     SDL_WindowShaper* result = result = malloc(sizeof(SDL_WindowShaper));
     result->window = window;
diff --git a/src/video/cocoa/SDL_cocoavideo.h b/src/video/cocoa/SDL_cocoavideo.h
index 498ce6c..2c5ab92 100644
--- a/src/video/cocoa/SDL_cocoavideo.h
+++ b/src/video/cocoa/SDL_cocoavideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_cocoavideo_h
-#define _SDL_cocoavideo_h
+#ifndef SDL_cocoavideo_h_
+#define SDL_cocoavideo_h_
 
 #include "SDL_opengl.h"
 
@@ -40,6 +40,59 @@
 #include "SDL_cocoaopengl.h"
 #include "SDL_cocoawindow.h"
 
+#ifndef MAC_OS_X_VERSION_10_12
+#define DECLARE_EVENT(name) static const NSEventType NSEventType##name = NS##name
+DECLARE_EVENT(LeftMouseDown);
+DECLARE_EVENT(LeftMouseUp);
+DECLARE_EVENT(RightMouseDown);
+DECLARE_EVENT(RightMouseUp);
+DECLARE_EVENT(OtherMouseDown);
+DECLARE_EVENT(OtherMouseUp);
+DECLARE_EVENT(MouseMoved);
+DECLARE_EVENT(LeftMouseDragged);
+DECLARE_EVENT(RightMouseDragged);
+DECLARE_EVENT(OtherMouseDragged);
+DECLARE_EVENT(ScrollWheel);
+DECLARE_EVENT(KeyDown);
+DECLARE_EVENT(KeyUp);
+DECLARE_EVENT(FlagsChanged);
+#undef DECLARE_EVENT
+
+static const NSEventMask NSEventMaskAny = NSAnyEventMask;
+
+#define DECLARE_MODIFIER_FLAG(name) static const NSUInteger NSEventModifierFlag##name = NS##name##KeyMask
+DECLARE_MODIFIER_FLAG(Shift);
+DECLARE_MODIFIER_FLAG(Control);
+DECLARE_MODIFIER_FLAG(Command);
+DECLARE_MODIFIER_FLAG(NumericPad);
+DECLARE_MODIFIER_FLAG(Help);
+DECLARE_MODIFIER_FLAG(Function);
+#undef DECLARE_MODIFIER_FLAG
+static const NSUInteger NSEventModifierFlagCapsLock = NSAlphaShiftKeyMask;
+static const NSUInteger NSEventModifierFlagOption = NSAlternateKeyMask;
+
+#define DECLARE_WINDOW_MASK(name) static const unsigned int NSWindowStyleMask##name = NS##name##WindowMask
+DECLARE_WINDOW_MASK(Borderless);
+DECLARE_WINDOW_MASK(Titled);
+DECLARE_WINDOW_MASK(Closable);
+DECLARE_WINDOW_MASK(Miniaturizable);
+DECLARE_WINDOW_MASK(Resizable);
+DECLARE_WINDOW_MASK(TexturedBackground);
+DECLARE_WINDOW_MASK(UnifiedTitleAndToolbar);
+DECLARE_WINDOW_MASK(FullScreen);
+/*DECLARE_WINDOW_MASK(FullSizeContentView);*/ /* Not used, fails compile on older SDKs */
+static const unsigned int NSWindowStyleMaskUtilityWindow = NSUtilityWindowMask;
+static const unsigned int NSWindowStyleMaskDocModalWindow = NSDocModalWindowMask;
+static const unsigned int NSWindowStyleMaskHUDWindow = NSHUDWindowMask;
+#undef DECLARE_WINDOW_MASK
+
+#define DECLARE_ALERT_STYLE(name) static const NSUInteger NSAlertStyle##name = NS##name##AlertStyle
+DECLARE_ALERT_STYLE(Warning);
+DECLARE_ALERT_STYLE(Informational);
+DECLARE_ALERT_STYLE(Critical);
+#undef DECLARE_ALERT_STYLE
+#endif
+
 /* Private display data */
 
 @class SDLTranslatorResponder;
@@ -60,6 +113,6 @@ typedef struct SDL_VideoData
 /* Utility functions */
 extern NSImage * Cocoa_CreateImage(SDL_Surface * surface);
 
-#endif /* _SDL_cocoavideo_h */
+#endif /* SDL_cocoavideo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoavideo.m b/src/video/cocoa/SDL_cocoavideo.m
index e436e65..872ef09 100644
--- a/src/video/cocoa/SDL_cocoavideo.m
+++ b/src/video/cocoa/SDL_cocoavideo.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -26,6 +26,7 @@
 #include "SDL_endian.h"
 #include "SDL_cocoavideo.h"
 #include "SDL_cocoashape.h"
+#include "SDL_cocoavulkan.h"
 #include "SDL_assert.h"
 
 /* Initialization/Query functions */
@@ -80,8 +81,8 @@ Cocoa_CreateDevice(int devindex)
     device->PumpEvents = Cocoa_PumpEvents;
     device->SuspendScreenSaver = Cocoa_SuspendScreenSaver;
 
-    device->CreateWindow = Cocoa_CreateWindow;
-    device->CreateWindowFrom = Cocoa_CreateWindowFrom;
+    device->CreateSDLWindow = Cocoa_CreateWindow;
+    device->CreateSDLWindowFrom = Cocoa_CreateWindowFrom;
     device->SetWindowTitle = Cocoa_SetWindowTitle;
     device->SetWindowIcon = Cocoa_SetWindowIcon;
     device->SetWindowPosition = Cocoa_SetWindowPosition;
@@ -122,6 +123,14 @@ Cocoa_CreateDevice(int devindex)
     device->GL_DeleteContext = Cocoa_GL_DeleteContext;
 #endif
 
+#if SDL_VIDEO_VULKAN
+    device->Vulkan_LoadLibrary = Cocoa_Vulkan_LoadLibrary;
+    device->Vulkan_UnloadLibrary = Cocoa_Vulkan_UnloadLibrary;
+    device->Vulkan_GetInstanceExtensions = Cocoa_Vulkan_GetInstanceExtensions;
+    device->Vulkan_CreateSurface = Cocoa_Vulkan_CreateSurface;
+    device->Vulkan_GetDrawableSize = Cocoa_Vulkan_GetDrawableSize;
+#endif
+
     device->StartTextInput = Cocoa_StartTextInput;
     device->StopTextInput = Cocoa_StopTextInput;
     device->SetTextInputRect = Cocoa_SetTextInputRect;
diff --git a/src/video/emscripten/SDL_emscriptenvideo.h b/src/video/cocoa/SDL_cocoavulkan.h
similarity index 51%
copy from src/video/emscripten/SDL_emscriptenvideo.h
copy to src/video/cocoa/SDL_cocoavulkan.h
index 7618ab6..fa523ac 100644
--- a/src/video/emscripten/SDL_emscriptenvideo.h
+++ b/src/video/cocoa/SDL_cocoavulkan.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,37 +18,38 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../../SDL_internal.h"
 
-#ifndef _SDL_emscriptenvideo_h
-#define _SDL_emscriptenvideo_h
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.h.
+ */
+
 
-#include "../SDL_sysvideo.h"
-#include "../../events/SDL_touch_c.h"
-#include <emscripten/emscripten.h>
-#include <emscripten/html5.h>
+#include "../../SDL_internal.h"
 
-#include <EGL/egl.h>
+#ifndef SDL_cocoavulkan_h_
+#define SDL_cocoavulkan_h_
 
-typedef struct SDL_WindowData
-{
-#if SDL_VIDEO_OPENGL_EGL
-    EGLSurface egl_surface;
-#endif
-    SDL_Window *window;
-    SDL_Surface *surface;
+#include "../SDL_vulkan_internal.h"
+#include "../SDL_sysvideo.h"
 
-    float pixel_ratio;
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_COCOA
 
-    SDL_bool external_size;
+int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path);
+void Cocoa_Vulkan_UnloadLibrary(_THIS);
+SDL_bool Cocoa_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names);
+SDL_bool Cocoa_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface);
 
-    int requested_fullscreen_mode;
-    SDL_bool fullscreen_resize;
+void Cocoa_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h);
 
-    SDL_bool finger_touching;  /* for mapping touch events to mice */
-    SDL_FingerID first_finger;
-} SDL_WindowData;
+#endif
 
-#endif /* _SDL_emscriptenvideo_h */
+#endif /* SDL_cocoavulkan_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoavulkan.m b/src/video/cocoa/SDL_cocoavulkan.m
new file mode 100644
index 0000000..86ded26
--- /dev/null
+++ b/src/video/cocoa/SDL_cocoavulkan.m
@@ -0,0 +1,209 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+/* 
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.c.
+ */
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_COCOA
+
+#include "SDL_cocoavideo.h"
+#include "SDL_cocoawindow.h"
+#include "SDL_assert.h"
+
+#include "SDL_loadso.h"
+#include "SDL_cocoametalview.h"
+#include "SDL_cocoavulkan.h"
+#include "SDL_syswm.h"
+
+#include <dlfcn.h>
+
+#define DEFAULT_MOLTENVK  "libMoltenVK.dylib"
+/* Since libSDL is most likely a .dylib, need RTLD_DEFAULT not RTLD_SELF. */
+#define DEFAULT_HANDLE RTLD_DEFAULT
+
+int Cocoa_Vulkan_LoadLibrary(_THIS, const char *path)
+{
+    VkExtensionProperties *extensions = NULL;
+    Uint32 extensionCount = 0;
+    SDL_bool hasSurfaceExtension = SDL_FALSE;
+    SDL_bool hasMacOSSurfaceExtension = SDL_FALSE;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
+
+    if (_this->vulkan_config.loader_handle) {
+        SDL_SetError("MoltenVK/Vulkan already loaded");
+        return -1;
+    }
+
+    /* Load the Vulkan loader library */
+    if (!path) {
+        path = SDL_getenv("SDL_VULKAN_LIBRARY");
+    }
+    if (!path) {
+        /* MoltenVK framework, currently, v0.17.0, has a static library and is
+         * the recommended way to use the package. There is likely no object to
+         * load. */
+        vkGetInstanceProcAddr =
+         (PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE,
+                                          "vkGetInstanceProcAddr");
+    }
+    
+    if (vkGetInstanceProcAddr) {
+        _this->vulkan_config.loader_handle = DEFAULT_HANDLE;
+    } else {
+        if (!path) {
+            /* Look for the .dylib packaged with the application instead. */
+            path = DEFAULT_MOLTENVK;
+        }
+        
+        _this->vulkan_config.loader_handle = SDL_LoadObject(path);
+        if (!_this->vulkan_config.loader_handle) {
+            return -1;
+        }
+        SDL_strlcpy(_this->vulkan_config.loader_path, path,
+                    SDL_arraysize(_this->vulkan_config.loader_path));
+        vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction(
+            _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr");
+    }
+
+    if (!vkGetInstanceProcAddr) {
+        SDL_SetError("Failed to find %s in either executable or %s: %s",
+                     "vkGetInstanceProcAddr",
+                     DEFAULT_MOLTENVK,
+                     (const char *) dlerror());
+        goto fail;
+    }
+
+    _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr;
+    _this->vulkan_config.vkEnumerateInstanceExtensionProperties =
+        (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)(
+            VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties");
+    if (!_this->vulkan_config.vkEnumerateInstanceExtensionProperties) {
+        goto fail;
+    }
+    extensions = SDL_Vulkan_CreateInstanceExtensionsList(
+        (PFN_vkEnumerateInstanceExtensionProperties)
+            _this->vulkan_config.vkEnumerateInstanceExtensionProperties,
+        &extensionCount);
+    if (!extensions) {
+        goto fail;
+    }
+    for (Uint32 i = 0; i < extensionCount; i++) {
+        if (SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) {
+            hasSurfaceExtension = SDL_TRUE;
+        } else if (SDL_strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) {
+            hasMacOSSurfaceExtension = SDL_TRUE;
+        }
+    }
+    SDL_free(extensions);
+    if (!hasSurfaceExtension) {
+        SDL_SetError("Installed MoltenVK/Vulkan doesn't implement the "
+                     VK_KHR_SURFACE_EXTENSION_NAME " extension");
+        goto fail;
+    } else if (!hasMacOSSurfaceExtension) {
+        SDL_SetError("Installed MoltenVK/Vulkan doesn't implement the "
+                     VK_MVK_MACOS_SURFACE_EXTENSION_NAME "extension");
+        goto fail;
+    }
+    return 0;
+
+fail:
+    SDL_UnloadObject(_this->vulkan_config.loader_handle);
+    _this->vulkan_config.loader_handle = NULL;
+    return -1;
+}
+
+void Cocoa_Vulkan_UnloadLibrary(_THIS)
+{
+    if (_this->vulkan_config.loader_handle) {
+        if (_this->vulkan_config.loader_handle != DEFAULT_HANDLE) {
+            SDL_UnloadObject(_this->vulkan_config.loader_handle);
+        }
+        _this->vulkan_config.loader_handle = NULL;
+    }
+}
+
+SDL_bool Cocoa_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names)
+{
+    static const char *const extensionsForCocoa[] = {
+        VK_KHR_SURFACE_EXTENSION_NAME, VK_MVK_MACOS_SURFACE_EXTENSION_NAME
+    };
+    if (!_this->vulkan_config.loader_handle) {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+    return SDL_Vulkan_GetInstanceExtensions_Helper(
+            count, names, SDL_arraysize(extensionsForCocoa),
+            extensionsForCocoa);
+}
+
+SDL_bool Cocoa_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface)
+{
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr =
+        (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr;
+    PFN_vkCreateMacOSSurfaceMVK vkCreateMacOSSurfaceMVK =
+        (PFN_vkCreateMacOSSurfaceMVK)vkGetInstanceProcAddr(
+                                            (VkInstance)instance,
+                                            "vkCreateMacOSSurfaceMVK");
+    VkMacOSSurfaceCreateInfoMVK createInfo = {};
+    VkResult result;
+
+    if (!_this->vulkan_config.loader_handle) {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+
+    if (!vkCreateMacOSSurfaceMVK) {
+        SDL_SetError(VK_MVK_MACOS_SURFACE_EXTENSION_NAME
+                     " extension is not enabled in the Vulkan instance.");
+        return SDL_FALSE;
+    }
+    createInfo.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
+    createInfo.pNext = NULL;
+    createInfo.flags = 0;
+    createInfo.pView = Cocoa_Mtl_AddMetalView(window);
+    result = vkCreateMacOSSurfaceMVK(instance, &createInfo,
+                                       NULL, surface);
+    if (result != VK_SUCCESS) {
+        SDL_SetError("vkCreateMacOSSurfaceMVK failed: %s",
+                     SDL_Vulkan_GetResultString(result));
+        return SDL_FALSE;
+    }
+    return SDL_TRUE;
+}
+
+void Cocoa_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h)
+{
+    Cocoa_Mtl_GetDrawableSize(window, w, h);
+}
+
+#endif
+
+/* vim: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoawindow.h b/src/video/cocoa/SDL_cocoawindow.h
index a32de83..d5502b2 100644
--- a/src/video/cocoa/SDL_cocoawindow.h
+++ b/src/video/cocoa/SDL_cocoawindow.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_cocoawindow_h
-#define _SDL_cocoawindow_h
+#ifndef SDL_cocoawindow_h_
+#define SDL_cocoawindow_h_
 
 #import <Cocoa/Cocoa.h>
 
@@ -142,6 +142,6 @@ extern void Cocoa_DestroyWindow(_THIS, SDL_Window * window);
 extern SDL_bool Cocoa_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info);
 extern int Cocoa_SetWindowHitTest(SDL_Window *window, SDL_bool enabled);
 
-#endif /* _SDL_cocoawindow_h */
+#endif /* SDL_cocoawindow_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/cocoa/SDL_cocoawindow.m b/src/video/cocoa/SDL_cocoawindow.m
index cfad548..c92590b 100644
--- a/src/video/cocoa/SDL_cocoawindow.m
+++ b/src/video/cocoa/SDL_cocoawindow.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -38,6 +38,7 @@
 #include "SDL_cocoavideo.h"
 #include "SDL_cocoashape.h"
 #include "SDL_cocoamouse.h"
+#include "SDL_cocoamousetap.h"
 #include "SDL_cocoaopengl.h"
 #include "SDL_assert.h"
 
@@ -64,10 +65,31 @@
 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;
 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
 - (BOOL)wantsPeriodicDraggingUpdates;
+- (BOOL)validateMenuItem:(NSMenuItem *)menuItem;
+
+- (SDL_Window*)findSDLWindow;
 @end
 
 @implementation SDLWindow
 
+- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
+{
+    /* Only allow using the macOS native fullscreen toggle menubar item if the
+     * window is resizable and not in a SDL fullscreen mode.
+     */
+    if ([menuItem action] == @selector(toggleFullScreen:)) {
+        SDL_Window *window = [self findSDLWindow];
+        if (window == NULL) {
+            return NO;
+        } else if ((window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_FULLSCREEN_DESKTOP)) != 0) {
+            return NO;
+        } else if ((window->flags & SDL_WINDOW_RESIZABLE) == 0) {
+            return NO;
+        }
+    }
+    return [super validateMenuItem:menuItem];
+}
+
 - (BOOL)canBecomeKeyWindow
 {
     return YES;
@@ -82,7 +104,7 @@
 {
     [super sendEvent:event];
 
-    if ([event type] != NSLeftMouseUp) {
+    if ([event type] != NSEventTypeLeftMouseUp) {
         return;
     }
 
@@ -116,11 +138,10 @@
 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
 { @autoreleasepool
 {
-    SDL_VideoDevice *_this = SDL_GetVideoDevice();
     NSPasteboard *pasteboard = [sender draggingPasteboard];
     NSArray *types = [NSArray arrayWithObject:NSFilenamesPboardType];
     NSString *desiredType = [pasteboard availableTypeFromArray:types];
-    SDL_Window *sdlwindow = nil;
+    SDL_Window *sdlwindow = [self findSDLWindow];
 
     if (desiredType == nil) {
         return NO;  /* can't accept anything that's being dropped here. */
@@ -157,16 +178,6 @@
             }
         }
 
-        /* !!! FIXME: is there a better way to do this? */
-        if (_this) {
-            for (sdlwindow = _this->windows; sdlwindow; sdlwindow = sdlwindow->next) {
-                NSWindow *nswindow = ((SDL_WindowData *) sdlwindow->driverdata)->nswindow;
-                if (nswindow == self) {
-                    break;
-                }
-            }
-        }
-
         if (!SDL_SendDropFile(sdlwindow, [[fileURL path] UTF8String])) {
             return NO;
         }
@@ -181,6 +192,24 @@
     return NO;
 }
 
+- (SDL_Window*)findSDLWindow
+{
+    SDL_Window *sdlwindow = NULL;
+    SDL_VideoDevice *_this = SDL_GetVideoDevice();
+
+    /* !!! FIXME: is there a better way to do this? */
+    if (_this) {
+        for (sdlwindow = _this->windows; sdlwindow; sdlwindow = sdlwindow->next) {
+            NSWindow *nswindow = ((SDL_WindowData *) sdlwindow->driverdata)->nswindow;
+            if (nswindow == self) {
+                break;
+            }
+        }
+    }
+
+    return sdlwindow;
+}
+
 @end
 
 
@@ -220,15 +249,15 @@ GetWindowStyle(SDL_Window * window)
     NSUInteger style = 0;
 
     if (window->flags & SDL_WINDOW_FULLSCREEN) {
-        style = NSBorderlessWindowMask;
+        style = NSWindowStyleMaskBorderless;
     } else {
         if (window->flags & SDL_WINDOW_BORDERLESS) {
-            style = NSBorderlessWindowMask;
+            style = NSWindowStyleMaskBorderless;
         } else {
-            style = (NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask);
+            style = (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable);
         }
         if (window->flags & SDL_WINDOW_RESIZABLE) {
-            style |= NSResizableWindowMask;
+            style |= NSWindowStyleMaskResizable;
         }
     }
     return style;
@@ -491,6 +520,11 @@ SetWindowStyle(SDL_Window * window, NSUInteger style)
     NSRect rect = [nswindow contentRectForFrameRect:[nswindow frame]];
     ConvertNSRect([nswindow screen], fullscreen, &rect);
 
+    if (inFullscreenTransition) {
+        /* We'll take care of this at the end of the transition */
+        return;
+    }
+
     if (s_moveHack) {
         SDL_bool blockMove = ((SDL_GetTicks() - s_moveHack) < 500);
 
@@ -594,8 +628,8 @@ SetWindowStyle(SDL_Window * window, NSUInteger style)
         [NSMenu setMenuBarVisible:NO];
     }
 
-    const unsigned int newflags = [NSEvent modifierFlags] & NSAlphaShiftKeyMask;
-    _data->videodata->modifierFlags = (_data->videodata->modifierFlags & ~NSAlphaShiftKeyMask) | newflags;
+    const unsigned int newflags = [NSEvent modifierFlags] & NSEventModifierFlagCapsLock;
+    _data->videodata->modifierFlags = (_data->videodata->modifierFlags & ~NSEventModifierFlagCapsLock) | newflags;
     SDL_ToggleModState(KMOD_CAPS, newflags != 0);
 }
 
@@ -641,7 +675,7 @@ SetWindowStyle(SDL_Window * window, NSUInteger style)
 {
     SDL_Window *window = _data->window;
 
-    SetWindowStyle(window, (NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask));
+    SetWindowStyle(window, (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable));
 
     isFullscreenSpace = YES;
     inFullscreenTransition = YES;
@@ -666,6 +700,8 @@ SetWindowStyle(SDL_Window * window, NSUInteger style)
 - (void)windowDidEnterFullScreen:(NSNotification *)aNotification
 {
     SDL_Window *window = _data->window;
+    SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
+    NSWindow *nswindow = data->nswindow;
 
     inFullscreenTransition = NO;
 
@@ -673,6 +709,11 @@ SetWindowStyle(SDL_Window * window, NSUInteger style)
         pendingWindowOperation = PENDING_OPERATION_NONE;
         [self setFullscreenSpace:NO];
     } else {
+        /* Unset the resizable flag. 
+           This is a workaround for https://bugzilla.libsdl.org/show_bug.cgi?id=3697
+         */
+        SetWindowStyle(window, [nswindow styleMask] & (~NSWindowStyleMaskResizable));
+
         if ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) {
             [NSMenu setMenuBarVisible:NO];
         }
@@ -683,6 +724,7 @@ SetWindowStyle(SDL_Window * window, NSUInteger style)
          */
         window->w = 0;
         window->h = 0;
+        [self windowDidMove:aNotification];
         [self windowDidResize:aNotification];
     }
 }
@@ -691,13 +733,13 @@ SetWindowStyle(SDL_Window * window, NSUInteger style)
 {
     SDL_Window *window = _data->window;
 
+    isFullscreenSpace = NO;
+    inFullscreenTransition = YES;
+
     /* As of OS X 10.11, the window seems to need to be resizable when exiting
        a Space, in order for it to resize back to its windowed-mode size.
      */
-    SetWindowStyle(window, GetWindowStyle(window) | NSResizableWindowMask);
-
-    isFullscreenSpace = NO;
-    inFullscreenTransition = YES;
+    SetWindowStyle(window, GetWindowStyle(window) | NSWindowStyleMaskResizable);
 }
 
 - (void)windowDidFailToExitFullScreen:(NSNotification *)aNotification
@@ -708,7 +750,7 @@ SetWindowStyle(SDL_Window * window, NSUInteger style)
         return;
     }
 
-    SetWindowStyle(window, (NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask));
+    SetWindowStyle(window, (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable));
     
     isFullscreenSpace = YES;
     inFullscreenTransition = NO;
@@ -744,11 +786,36 @@ SetWindowStyle(SDL_Window * window, NSUInteger style)
         [NSMenu setMenuBarVisible:YES];
 
         pendingWindowOperation = PENDING_OPERATION_NONE;
+
+#if 0
+/* This fixed bug 3719, which is that changing window size while fullscreen
+   doesn't take effect when leaving fullscreen, but introduces bug 3809,
+   which is that a maximized window doesn't go back to normal size when
+   restored, so this code is disabled until we can properly handle the
+   beginning and end of maximize and restore.
+ */
+        /* Restore windowed size and position in case it changed while fullscreen */
+        {
+            NSRect rect;
+            rect.origin.x = window->windowed.x;
+            rect.origin.y = window->windowed.y;
+            rect.size.width = window->windowed.w;
+            rect.size.height = window->windowed.h;
+            ConvertNSRect([nswindow screen], NO, &rect);
+
+            s_moveHack = 0;
+            [nswindow setContentSize:rect.size];
+            [nswindow setFrameOrigin:rect.origin];
+            s_moveHack = SDL_GetTicks();
+        }
+#endif /* 0 */
+
         /* Force the size change event in case it was delivered earlier
            while the window was still animating into place.
          */
         window->w = 0;
         window->h = 0;
+        [self windowDidMove:aNotification];
         [self windowDidResize:aNotification];
 
         /* FIXME: Why does the window get hidden? */
@@ -839,7 +906,7 @@ SetWindowStyle(SDL_Window * window, NSUInteger style)
 
     switch ([theEvent buttonNumber]) {
     case 0:
-        if (([theEvent modifierFlags] & NSControlKeyMask) &&
+        if (([theEvent modifierFlags] & NSEventModifierFlagControl) &&
 		    GetHintCtrlClickEmulateRightClick()) {
             wasCtrlLeft = YES;
             button = SDL_BUTTON_RIGHT;
@@ -1168,12 +1235,12 @@ SetupWindowData(_THIS, SDL_Window * window, NSWindow *nswindow, SDL_bool created
     {
         unsigned long style = [nswindow styleMask];
 
-        if (style == NSBorderlessWindowMask) {
+        if (style == NSWindowStyleMaskBorderless) {
             window->flags |= SDL_WINDOW_BORDERLESS;
         } else {
             window->flags &= ~SDL_WINDOW_BORDERLESS;
         }
-        if (style & NSResizableWindowMask) {
+        if (style & NSWindowStyleMaskResizable) {
             window->flags |= SDL_WINDOW_RESIZABLE;
         } else {
             window->flags &= ~SDL_WINDOW_RESIZABLE;
@@ -1534,7 +1601,7 @@ Cocoa_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display
             rect.origin.y += (screenRect.size.height - rect.size.height);
         }
 
-        [nswindow setStyleMask:NSBorderlessWindowMask];
+        [nswindow setStyleMask:NSWindowStyleMaskBorderless];
     } else {
         rect.origin.x = window->windowed.x;
         rect.origin.y = window->windowed.y;
@@ -1634,8 +1701,13 @@ Cocoa_GetWindowGammaRamp(_THIS, SDL_Window * window, Uint16 * ramp)
 void
 Cocoa_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed)
 {
-    /* Move the cursor to the nearest point in the window */
+    SDL_Mouse *mouse = SDL_GetMouse();
     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
+
+    /* Enable or disable the event tap as necessary */
+    Cocoa_EnableMouseEventTap(mouse->driverdata, grabbed);
+
+    /* Move the cursor to the nearest point in the window */
     if (grabbed && data && ![data->listener isMoving]) {
         int x, y;
         CGPoint cgpoint;
@@ -1700,7 +1772,7 @@ Cocoa_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
         info->info.cocoa.window = nswindow;
         return SDL_TRUE;
     } else {
-        SDL_SetError("Application not compiled with SDL %d.%d\n",
+        SDL_SetError("Application not compiled with SDL %d.%d",
                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
diff --git a/src/video/directfb/SDL_DirectFB_WM.c b/src/video/directfb/SDL_DirectFB_WM.c
index 4b979f3..41cb282 100644
--- a/src/video/directfb/SDL_DirectFB_WM.c
+++ b/src/video/directfb/SDL_DirectFB_WM.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/directfb/SDL_DirectFB_WM.h b/src/video/directfb/SDL_DirectFB_WM.h
index f5f9a46..7258c5e 100644
--- a/src/video/directfb/SDL_DirectFB_WM.h
+++ b/src/video/directfb/SDL_DirectFB_WM.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_directfb_wm_h
-#define _SDL_directfb_wm_h
+#ifndef SDL_directfb_wm_h_
+#define SDL_directfb_wm_h_
 
 #include "SDL_DirectFB_video.h"
 
@@ -51,6 +51,6 @@ extern DFBResult DirectFB_WM_GetClientSize(_THIS, SDL_Window * window,
                                            int *cw, int *ch);
 
 
-#endif /* _SDL_directfb_wm_h */
+#endif /* SDL_directfb_wm_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/directfb/SDL_DirectFB_dyn.c b/src/video/directfb/SDL_DirectFB_dyn.c
index 52a4b53..d2d3071 100644
--- a/src/video/directfb/SDL_DirectFB_dyn.c
+++ b/src/video/directfb/SDL_DirectFB_dyn.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/directfb/SDL_DirectFB_dyn.h b/src/video/directfb/SDL_DirectFB_dyn.h
index bd99a3f..87af6de 100644
--- a/src/video/directfb/SDL_DirectFB_dyn.h
+++ b/src/video/directfb/SDL_DirectFB_dyn.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_DirectFB_dyn_h
-#define _SDL_DirectFB_dyn_h
+#ifndef SDL_DirectFB_dyn_h_
+#define SDL_DirectFB_dyn_h_
 
 #define DFB_SYMS \
     DFB_SYM(DFBResult, DirectFBError, (const char *msg, DFBResult result), (msg, result), return) \
@@ -36,4 +36,6 @@
 int SDL_DirectFB_LoadLibrary(void);
 void SDL_DirectFB_UnLoadLibrary(void);
 
-#endif
+#endif /* SDL_DirectFB_dyn_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/directfb/SDL_DirectFB_events.c b/src/video/directfb/SDL_DirectFB_events.c
index 0bf9fdb..16d1c57 100644
--- a/src/video/directfb/SDL_DirectFB_events.c
+++ b/src/video/directfb/SDL_DirectFB_events.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -743,9 +743,6 @@ void
 DirectFB_QuitKeyboard(_THIS)
 {
     /* SDL_DFB_DEVICEDATA(_this); */
-
-    SDL_KeyboardQuit();
-
 }
 
 #endif /* SDL_VIDEO_DRIVER_DIRECTFB */
diff --git a/src/video/directfb/SDL_DirectFB_events.h b/src/video/directfb/SDL_DirectFB_events.h
index 2931ad2..e4ff390 100644
--- a/src/video/directfb/SDL_DirectFB_events.h
+++ b/src/video/directfb/SDL_DirectFB_events.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_DirectFB_events_h
-#define _SDL_DirectFB_events_h
+#ifndef SDL_DirectFB_events_h_
+#define SDL_DirectFB_events_h_
 
 #include "../SDL_sysvideo.h"
 
@@ -29,4 +29,6 @@ extern void DirectFB_InitKeyboard(_THIS);
 extern void DirectFB_QuitKeyboard(_THIS);
 extern void DirectFB_PumpEventsWindow(_THIS);
 
-#endif
+#endif /* SDL_DirectFB_events_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/directfb/SDL_DirectFB_modes.c b/src/video/directfb/SDL_DirectFB_modes.c
index 9d0abf5..76f41a5 100644
--- a/src/video/directfb/SDL_DirectFB_modes.c
+++ b/src/video/directfb/SDL_DirectFB_modes.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/directfb/SDL_DirectFB_modes.h b/src/video/directfb/SDL_DirectFB_modes.h
index 9911eff..6c310c9 100644
--- a/src/video/directfb/SDL_DirectFB_modes.h
+++ b/src/video/directfb/SDL_DirectFB_modes.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_directfb_modes_h
-#define _SDL_directfb_modes_h
+#ifndef SDL_directfb_modes_h_
+#define SDL_directfb_modes_h_
 
 #include <directfb.h>
 
@@ -54,6 +54,6 @@ extern void DirectFB_QuitModes(_THIS);
 
 extern void DirectFB_SetContext(_THIS, SDL_Window *window);
 
-#endif /* _SDL_directfb_modes_h */
+#endif /* SDL_directfb_modes_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/directfb/SDL_DirectFB_mouse.c b/src/video/directfb/SDL_DirectFB_mouse.c
index 0657d2f..6fea8d3 100644
--- a/src/video/directfb/SDL_DirectFB_mouse.c
+++ b/src/video/directfb/SDL_DirectFB_mouse.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -36,10 +36,8 @@ static SDL_Cursor *DirectFB_CreateDefaultCursor(void);
 static SDL_Cursor *DirectFB_CreateCursor(SDL_Surface * surface,
                                          int hot_x, int hot_y);
 static int DirectFB_ShowCursor(SDL_Cursor * cursor);
-static void DirectFB_MoveCursor(SDL_Cursor * cursor);
 static void DirectFB_FreeCursor(SDL_Cursor * cursor);
 static void DirectFB_WarpMouse(SDL_Window * window, int x, int y);
-static void DirectFB_FreeMouse(SDL_Mouse * mouse);
 
 static const char *arrow[] = {
     /* pixels */
@@ -84,11 +82,9 @@ DirectFB_CreateDefaultCursor(void)
 
     SDL_DFB_DEVICEDATA(dev);
     DFB_CursorData *curdata;
-    DFBResult ret;
     DFBSurfaceDescription dsc;
     SDL_Cursor *cursor;
     Uint32 *dest;
-    Uint32 *p;
     int pitch, i, j;
 
     SDL_DFB_ALLOC_CLEAR( cursor, sizeof(*cursor));
@@ -139,7 +135,6 @@ DirectFB_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y)
 
     SDL_DFB_DEVICEDATA(dev);
     DFB_CursorData *curdata;
-    DFBResult ret;
     DFBSurfaceDescription dsc;
     SDL_Cursor *cursor;
     Uint32 *dest;
@@ -184,7 +179,6 @@ static int
 DirectFB_ShowCursor(SDL_Cursor * cursor)
 {
     SDL_DFB_CURSORDATA(cursor);
-    DFBResult ret;
     SDL_Window *window;
 
     window = SDL_GetFocusWindow();
@@ -239,7 +233,6 @@ DirectFB_WarpMouse(SDL_Window * window, int x, int y)
     SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
     DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata;
     DFB_WindowData *windata = (DFB_WindowData *) window->driverdata;
-    DFBResult ret;
     int cx, cy;
 
     SDL_DFB_CHECKERR(windata->dfbwin->GetPosition(windata->dfbwin, &cx, &cy));
@@ -253,8 +246,10 @@ DirectFB_WarpMouse(SDL_Window * window, int x, int y)
 
 #if USE_MULTI_API
 
+static void DirectFB_MoveCursor(SDL_Cursor * cursor);
 static void DirectFB_WarpMouse(SDL_Mouse * mouse, SDL_Window * window,
                                int x, int y);
+static void DirectFB_FreeMouse(SDL_Mouse * mouse);
 
 static int id_mask;
 
diff --git a/src/video/directfb/SDL_DirectFB_mouse.h b/src/video/directfb/SDL_DirectFB_mouse.h
index 4e2f27a..c793c22 100644
--- a/src/video/directfb/SDL_DirectFB_mouse.h
+++ b/src/video/directfb/SDL_DirectFB_mouse.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_DirectFB_mouse_h
-#define _SDL_DirectFB_mouse_h
+#ifndef SDL_DirectFB_mouse_h_
+#define SDL_DirectFB_mouse_h_
 
 #include <directfb.h>
 
@@ -39,6 +39,6 @@ struct _DFB_CursorData
 extern void DirectFB_InitMouse(_THIS);
 extern void DirectFB_QuitMouse(_THIS);
 
-#endif /* _SDL_DirectFB_mouse_h */
+#endif /* SDL_DirectFB_mouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/directfb/SDL_DirectFB_opengl.c b/src/video/directfb/SDL_DirectFB_opengl.c
index 065854a..b05e7b2 100644
--- a/src/video/directfb/SDL_DirectFB_opengl.c
+++ b/src/video/directfb/SDL_DirectFB_opengl.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -117,9 +117,9 @@ DirectFB_GL_LoadLibrary(_THIS, const char *path)
 
 
     if (path == NULL) {
-        path = SDL_getenv("SDL_VIDEO_GL_DRIVER");
+        path = SDL_getenv("SDL_OPENGL_LIBRARY");
         if (path == NULL) {
-            path = "libGL.so";
+            path = "libGL.so.1";
         }
     }
 
@@ -133,7 +133,6 @@ DirectFB_GL_LoadLibrary(_THIS, const char *path)
     SDL_DFB_DEBUG("Loaded library: %s\n", path);
 
     _this->gl_config.dll_handle = handle;
-    _this->gl_config.driver_loaded = 1;
     if (path) {
         SDL_strlcpy(_this->gl_config.driver_path, path,
                     SDL_arraysize(_this->gl_config.driver_path));
@@ -151,16 +150,10 @@ static void
 DirectFB_GL_UnloadLibrary(_THIS)
 {
  #if 0
-    int ret;
-
-    if (_this->gl_config.driver_loaded) {
-
-        ret = GL_UnloadObject(_this->gl_config.dll_handle);
-        if (ret)
-            SDL_DFB_ERR("Error #%d trying to unload library.\n", ret);
-        _this->gl_config.dll_handle = NULL;
-        _this->gl_config.driver_loaded = 0;
-    }
+    int ret = GL_UnloadObject(_this->gl_config.dll_handle);
+    if (ret)
+        SDL_DFB_ERR("Error #%d trying to unload library.\n", ret);
+    _this->gl_config.dll_handle = NULL;
 #endif
     /* Free OpenGL memory */
     SDL_free(_this->gl_data);
@@ -246,18 +239,12 @@ DirectFB_GL_GetSwapInterval(_THIS)
     return 0;
 }
 
-void
+int
 DirectFB_GL_SwapWindow(_THIS, SDL_Window * window)
 {
     SDL_DFB_WINDOWDATA(window);
-    DFBRegion region;
     DirectFB_GLContext *p;
 
-    region.x1 = 0;
-    region.y1 = 0;
-    region.x2 = window->w;
-    region.y2 = window->h;
-
 #if 0
     if (devdata->glFinish)
         devdata->glFinish();
@@ -273,9 +260,9 @@ DirectFB_GL_SwapWindow(_THIS, SDL_Window * window)
         }
 
     SDL_DFB_CHECKERR(windata->window_surface->Flip(windata->window_surface,NULL,  DSFLIP_PIPELINE |DSFLIP_BLIT | DSFLIP_ONSYNC ));
-    return;
+    return 0;
   error:
-    return;
+    return -1;
 }
 
 void
diff --git a/src/video/directfb/SDL_DirectFB_opengl.h b/src/video/directfb/SDL_DirectFB_opengl.h
index 6391ee4..c074bc6 100644
--- a/src/video/directfb/SDL_DirectFB_opengl.h
+++ b/src/video/directfb/SDL_DirectFB_opengl.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 
 
-#ifndef _SDL_directfb_opengl_h
-#define _SDL_directfb_opengl_h
+#ifndef SDL_directfb_opengl_h_
+#define SDL_directfb_opengl_h_
 
 #include "SDL_DirectFB_video.h"
 
@@ -50,7 +50,7 @@ extern int DirectFB_GL_MakeCurrent(_THIS, SDL_Window * window,
                                    SDL_GLContext context);
 extern int DirectFB_GL_SetSwapInterval(_THIS, int interval);
 extern int DirectFB_GL_GetSwapInterval(_THIS);
-extern void DirectFB_GL_SwapWindow(_THIS, SDL_Window * window);
+extern int DirectFB_GL_SwapWindow(_THIS, SDL_Window * window);
 extern void DirectFB_GL_DeleteContext(_THIS, SDL_GLContext context);
 
 extern void DirectFB_GL_FreeWindowContexts(_THIS, SDL_Window * window);
@@ -59,6 +59,6 @@ extern void DirectFB_GL_DestroyWindowContexts(_THIS, SDL_Window * window);
 
 #endif /* SDL_DIRECTFB_OPENGL */
 
-#endif /* _SDL_directfb_opengl_h */
+#endif /* SDL_directfb_opengl_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/directfb/SDL_DirectFB_render.c b/src/video/directfb/SDL_DirectFB_render.c
index 4a1bf46..4280d04 100644
--- a/src/video/directfb/SDL_DirectFB_render.c
+++ b/src/video/directfb/SDL_DirectFB_render.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -217,7 +217,9 @@ static SDL_INLINE IDirectFBSurface *get_dfb_surface(SDL_Window *window)
     SDL_memset(&wm_info, 0, sizeof(SDL_SysWMinfo));
 
     SDL_VERSION(&wm_info.version);
-    SDL_GetWindowWMInfo(window, &wm_info);
+    if (!SDL_GetWindowWMInfo(window, &wm_info)) {
+        return NULL;
+    }
 
     return wm_info.info.dfb.surface;
 }
@@ -228,7 +230,9 @@ static SDL_INLINE IDirectFBWindow *get_dfb_window(SDL_Window *window)
     SDL_memset(&wm_info, 0, sizeof(SDL_SysWMinfo));
 
     SDL_VERSION(&wm_info.version);
-    SDL_GetWindowWMInfo(window, &wm_info);
+    if (!SDL_GetWindowWMInfo(window, &wm_info)) {
+        return NULL;
+    }
 
     return wm_info.info.dfb.window;
 }
@@ -332,7 +336,7 @@ DirectFB_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event)
    }
 }
 
-int
+static int
 DirectFB_RenderClear(SDL_Renderer * renderer)
 {
     DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata;
@@ -344,7 +348,6 @@ DirectFB_RenderClear(SDL_Renderer * renderer)
 
     destsurf->Clear(destsurf, renderer->r, renderer->g, renderer->b, renderer->a);
 
-
     return 0;
 }
 
@@ -357,6 +360,10 @@ DirectFB_CreateRenderer(SDL_Window * window, Uint32 flags)
     DirectFB_RenderData *data = NULL;
     DFBSurfaceCapabilities scaps;
 
+    if (!winsurf) {
+        return NULL;
+    }
+
     SDL_DFB_ALLOC_CLEAR(renderer, sizeof(*renderer));
     SDL_DFB_ALLOC_CLEAR(data, sizeof(*data));
 
@@ -530,7 +537,7 @@ DirectFB_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
     /* find the right pixelformat */
     pixelformat = DirectFB_SDLToDFBPixelFormat(texture->format);
     if (pixelformat == DSPF_UNKNOWN) {
-        SDL_SetError("Unknown pixel format %d\n", data->format);
+        SDL_SetError("Unknown pixel format %d", data->format);
         goto error;
     }
 
@@ -1273,7 +1280,7 @@ DirectFB_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
                      Uint32 format, void * pixels, int pitch)
 {
     Uint32 sdl_format;
-    void * laypixels;
+    unsigned char* laypixels;
     int laypitch;
     DFBSurfacePixelFormat dfb_format;
     DirectFB_RenderData *data = (DirectFB_RenderData *) renderer->driverdata;
@@ -1303,7 +1310,7 @@ DirectFB_RenderWritePixels(SDL_Renderer * renderer, const SDL_Rect * rect,
     SDL_Window *window = renderer->window;
     SDL_DFB_WINDOWDATA(window);
     Uint32 sdl_format;
-    void * laypixels;
+    unsigned char* laypixels;
     int laypitch;
     DFBSurfacePixelFormat dfb_format;
 
diff --git a/src/video/directfb/SDL_DirectFB_render.h b/src/video/directfb/SDL_DirectFB_render.h
index be016b0..2f85c1e 100644
--- a/src/video/directfb/SDL_DirectFB_render.h
+++ b/src/video/directfb/SDL_DirectFB_render.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/directfb/SDL_DirectFB_shape.c b/src/video/directfb/SDL_DirectFB_shape.c
index 3239e30..7ebdbd2 100644
--- a/src/video/directfb/SDL_DirectFB_shape.c
+++ b/src/video/directfb/SDL_DirectFB_shape.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -29,25 +29,22 @@
 
 #include "../SDL_shape_internals.h"
 
-SDL_Window*
-DirectFB_CreateShapedWindow(const char *title,unsigned int x,unsigned int y,unsigned int w,unsigned int h,Uint32 flags) {
-    return SDL_CreateWindow(title,x,y,w,h,flags /* | SDL_DFB_WINDOW_SHAPED */);
-}
-
 SDL_WindowShaper*
 DirectFB_CreateShaper(SDL_Window* window) {
     SDL_WindowShaper* result = NULL;
+    SDL_ShapeData* data;
+    int resized_properly;
 
     result = malloc(sizeof(SDL_WindowShaper));
     result->window = window;
     result->mode.mode = ShapeModeDefault;
     result->mode.parameters.binarizationCutoff = 1;
     result->userx = result->usery = 0;
-    SDL_ShapeData* data = SDL_malloc(sizeof(SDL_ShapeData));
+    data = SDL_malloc(sizeof(SDL_ShapeData));
     result->driverdata = data;
     data->surface = NULL;
     window->shaper = result;
-    int resized_properly = DirectFB_ResizeWindowShape(window);
+    resized_properly = DirectFB_ResizeWindowShape(window);
     SDL_assert(resized_properly == 0);
 
     return result;
diff --git a/src/video/directfb/SDL_DirectFB_shape.h b/src/video/directfb/SDL_DirectFB_shape.h
index 46be39f..9da5aef 100644
--- a/src/video/directfb/SDL_DirectFB_shape.h
+++ b/src/video/directfb/SDL_DirectFB_shape.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_DirectFB_shape_h
-#define _SDL_DirectFB_shape_h
+#ifndef SDL_DirectFB_shape_h_
+#define SDL_DirectFB_shape_h_
 
 #include <directfb.h>
 
@@ -31,9 +31,8 @@ typedef struct {
     IDirectFBSurface *surface;
 } SDL_ShapeData;
 
-extern SDL_Window* DirectFB_CreateShapedWindow(const char *title,unsigned int x,unsigned int y,unsigned int w,unsigned int h,Uint32 flags);
 extern SDL_WindowShaper* DirectFB_CreateShaper(SDL_Window* window);
 extern int DirectFB_ResizeWindowShape(SDL_Window* window);
 extern int DirectFB_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shapeMode);
 
-#endif /* _SDL_DirectFB_shape_h */
+#endif /* SDL_DirectFB_shape_h_ */
diff --git a/src/video/directfb/SDL_DirectFB_video.c b/src/video/directfb/SDL_DirectFB_video.c
index d339dd7..4271509 100644
--- a/src/video/directfb/SDL_DirectFB_video.c
+++ b/src/video/directfb/SDL_DirectFB_video.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,14 +22,10 @@
 
 #if SDL_VIDEO_DRIVER_DIRECTFB
 
-#include "SDL_DirectFB_video.h"
-
-#include "SDL_DirectFB_events.h"
 /*
  * #include "SDL_DirectFB_keyboard.h"
  */
 #include "SDL_DirectFB_modes.h"
-#include "SDL_DirectFB_mouse.h"
 #include "SDL_DirectFB_opengl.h"
 #include "SDL_DirectFB_window.h"
 #include "SDL_DirectFB_WM.h"
@@ -108,15 +104,13 @@ DirectFB_CreateDevice(int devindex)
     SDL_DFB_ALLOC_CLEAR(device, sizeof(SDL_VideoDevice));
 
     /* Set the function pointers */
-
-    /* Set the function pointers */
     device->VideoInit = DirectFB_VideoInit;
     device->VideoQuit = DirectFB_VideoQuit;
     device->GetDisplayModes = DirectFB_GetDisplayModes;
     device->SetDisplayMode = DirectFB_SetDisplayMode;
     device->PumpEvents = DirectFB_PumpEventsWindow;
-    device->CreateWindow = DirectFB_CreateWindow;
-    device->CreateWindowFrom = DirectFB_CreateWindowFrom;
+    device->CreateSDLWindow = DirectFB_CreateWindow;
+    device->CreateSDLWindowFrom = DirectFB_CreateWindowFrom;
     device->SetWindowTitle = DirectFB_SetWindowTitle;
     device->SetWindowIcon = DirectFB_SetWindowIcon;
     device->SetWindowPosition = DirectFB_SetWindowPosition;
@@ -178,7 +172,7 @@ DirectFB_DeviceInformation(IDirectFB * dfb)
     SDL_DFB_LOG( "Driver Version: %d.%d", desc.driver.major,
             desc.driver.minor);
 
-    SDL_DFB_LOG( "Video memoory:  %d", desc.video_memory);
+    SDL_DFB_LOG( "Video memory:   %d", desc.video_memory);
 
     SDL_DFB_LOG( "Blitting flags:");
     for (n = 0; blitting_flags[n].flag; n++) {
@@ -234,8 +228,7 @@ DirectFB_VideoInit(_THIS)
             DirectFBSetOption("disable-module", "x11input");
     }
 
-    /* FIXME: Reenable as default once multi kbd/mouse interface is sorted out */
-    devdata->use_linux_input = readBoolEnv(DFBENV_USE_LINUX_INPUT, 0);       /* default: on */
+    devdata->use_linux_input = readBoolEnv(DFBENV_USE_LINUX_INPUT, 1);       /* default: on */
 
     if (!devdata->use_linux_input)
     {
diff --git a/src/video/directfb/SDL_DirectFB_video.h b/src/video/directfb/SDL_DirectFB_video.h
index b36ace0..d40f856 100644
--- a/src/video/directfb/SDL_DirectFB_video.h
+++ b/src/video/directfb/SDL_DirectFB_video.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_DirectFB_video_h
-#define _SDL_DirectFB_video_h
+#ifndef SDL_DirectFB_video_h_
+#define SDL_DirectFB_video_h_
 
 #include <directfb.h>
 #include <directfb_version.h>
@@ -167,4 +167,4 @@ DFBSurfacePixelFormat DirectFB_SDLToDFBPixelFormat(Uint32 format);
 void DirectFB_SetSupportedPixelFormats(SDL_RendererInfo *ri);
 
 
-#endif /* _SDL_DirectFB_video_h */
+#endif /* SDL_DirectFB_video_h_ */
diff --git a/src/video/directfb/SDL_DirectFB_window.c b/src/video/directfb/SDL_DirectFB_window.c
index 40bbe6a..e657b96 100644
--- a/src/video/directfb/SDL_DirectFB_window.c
+++ b/src/video/directfb/SDL_DirectFB_window.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -458,9 +458,29 @@ SDL_bool
 DirectFB_GetWindowWMInfo(_THIS, SDL_Window * window,
                          struct SDL_SysWMinfo * info)
 {
+    const Uint32 version = ((((Uint32) info->version.major) * 1000000) +
+                            (((Uint32) info->version.minor) * 10000) +
+                            (((Uint32) info->version.patch)));
+
     SDL_DFB_DEVICEDATA(_this);
     SDL_DFB_WINDOWDATA(window);
 
+    /* Before 2.0.6, it was possible to build an SDL with DirectFB support
+       (SDL_SysWMinfo will be large enough to hold DirectFB info), but build
+       your app against SDL headers that didn't have DirectFB support
+       (SDL_SysWMinfo could be smaller than DirectFB needs. This would lead
+       to an app properly using SDL_GetWindowWMInfo() but we'd accidentally
+       overflow memory on the stack or heap. To protect against this, we've
+       padded out the struct unconditionally in the headers and DirectFB will
+       just return an error for older apps using this function. Those apps
+       will need to be recompiled against newer headers or not use DirectFB,
+       maybe by forcing SDL_VIDEODRIVER=x11. */
+    if (version < 2000006) {
+        info->subsystem = SDL_SYSWM_UNKNOWN;
+        SDL_SetError("Version must be 2.0.6 or newer");
+        return SDL_FALSE;
+    }
+
     if (info->version.major == SDL_MAJOR_VERSION &&
         info->version.minor == SDL_MINOR_VERSION) {
         info->subsystem = SDL_SYSWM_DIRECTFB;
@@ -469,7 +489,7 @@ DirectFB_GetWindowWMInfo(_THIS, SDL_Window * window,
         info->info.dfb.surface = windata->surface;
         return SDL_TRUE;
     } else {
-        SDL_SetError("Application not compiled with SDL %d.%d\n",
+        SDL_SetError("Application not compiled with SDL %d.%d",
                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
diff --git a/src/video/directfb/SDL_DirectFB_window.h b/src/video/directfb/SDL_DirectFB_window.h
index 4b99708..248c7e8 100644
--- a/src/video/directfb/SDL_DirectFB_window.h
+++ b/src/video/directfb/SDL_DirectFB_window.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_directfb_window_h
-#define _SDL_directfb_window_h
+#ifndef SDL_directfb_window_h_
+#define SDL_directfb_window_h_
 
 #include "SDL_DirectFB_video.h"
 #include "SDL_DirectFB_WM.h"
@@ -77,6 +77,6 @@ extern SDL_bool DirectFB_GetWindowWMInfo(_THIS, SDL_Window * window,
 extern void DirectFB_AdjustWindowSurface(SDL_Window * window);
 extern int DirectFB_SetWindowOpacity(_THIS, SDL_Window * window, float opacity);
 
-#endif /* _SDL_directfb_window_h */
+#endif /* SDL_directfb_window_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/dummy/SDL_nullevents.c b/src/video/dummy/SDL_nullevents.c
index a5a9443..67e491a 100644
--- a/src/video/dummy/SDL_nullevents.c
+++ b/src/video/dummy/SDL_nullevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/dummy/SDL_nullevents_c.h b/src/video/dummy/SDL_nullevents_c.h
index d2f7869..b18884c 100644
--- a/src/video/dummy/SDL_nullevents_c.h
+++ b/src/video/dummy/SDL_nullevents_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/dummy/SDL_nullframebuffer.c b/src/video/dummy/SDL_nullframebuffer.c
index 01c8a5a..ed109a4 100644
--- a/src/video/dummy/SDL_nullframebuffer.c
+++ b/src/video/dummy/SDL_nullframebuffer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/dummy/SDL_nullframebuffer_c.h b/src/video/dummy/SDL_nullframebuffer_c.h
index 37d198f..108c5f2 100644
--- a/src/video/dummy/SDL_nullframebuffer_c.h
+++ b/src/video/dummy/SDL_nullframebuffer_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/dummy/SDL_nullvideo.c b/src/video/dummy/SDL_nullvideo.c
index 96f4781..915dd3f 100644
--- a/src/video/dummy/SDL_nullvideo.c
+++ b/src/video/dummy/SDL_nullvideo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -84,6 +84,7 @@ DUMMY_CreateDevice(int devindex)
         SDL_OutOfMemory();
         return (0);
     }
+    device->is_dummy = SDL_TRUE;
 
     /* Set the function pointers */
     device->VideoInit = DUMMY_VideoInit;
diff --git a/src/video/dummy/SDL_nullvideo.h b/src/video/dummy/SDL_nullvideo.h
index 0126ba1..d73470b 100644
--- a/src/video/dummy/SDL_nullvideo.h
+++ b/src/video/dummy/SDL_nullvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,11 +20,11 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_nullvideo_h
-#define _SDL_nullvideo_h
+#ifndef SDL_nullvideo_h_
+#define SDL_nullvideo_h_
 
 #include "../SDL_sysvideo.h"
 
-#endif /* _SDL_nullvideo_h */
+#endif /* SDL_nullvideo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/emscripten/SDL_emscriptenevents.c b/src/video/emscripten/SDL_emscriptenevents.c
index a4720e4..4ba8453 100644
--- a/src/video/emscripten/SDL_emscriptenevents.c
+++ b/src/video/emscripten/SDL_emscriptenevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -270,7 +270,7 @@ static const SDL_Scancode emscripten_scancode_table[] = {
 
 
 /* "borrowed" from SDL_windowsevents.c */
-int
+static int
 Emscripten_ConvertUTF32toUTF8(Uint32 codepoint, char * text)
 {
     if (codepoint <= 0x7F) {
@@ -297,13 +297,23 @@ Emscripten_ConvertUTF32toUTF8(Uint32 codepoint, char * text)
     return SDL_TRUE;
 }
 
-EM_BOOL
+static EM_BOOL
+Emscripten_HandlePointerLockChange(int eventType, const EmscriptenPointerlockChangeEvent *changeEvent, void *userData)
+{
+    SDL_WindowData *window_data = (SDL_WindowData *) userData;
+    /* keep track of lock losses, so we can regrab if/when appropriate. */
+    window_data->has_pointer_lock = changeEvent->isActive;
+    return 0;
+}
+
+
+static EM_BOOL
 Emscripten_HandleMouseMove(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
 {
     SDL_WindowData *window_data = userData;
+    const int isPointerLocked = window_data->has_pointer_lock;
     int mx, my;
     static double residualx = 0, residualy = 0;
-    EmscriptenPointerlockChangeEvent pointerlock_status;
 
     /* rescale (in case canvas is being scaled)*/
     double client_w, client_h, xscale, yscale;
@@ -311,10 +321,6 @@ Emscripten_HandleMouseMove(int eventType, const EmscriptenMouseEvent *mouseEvent
     xscale = window_data->window->w / client_w;
     yscale = window_data->window->h / client_h;
 
-    /* check for pointer lock */
-    int isPointerLockSupported = emscripten_get_pointerlock_status(&pointerlock_status);
-    int isPointerLocked = isPointerLockSupported == EMSCRIPTEN_RESULT_SUCCESS  ? pointerlock_status.isActive : SDL_FALSE;
-
     if (isPointerLocked) {
         residualx += mouseEvent->movementX * xscale;
         residualy += mouseEvent->movementY * yscale;
@@ -332,11 +338,14 @@ Emscripten_HandleMouseMove(int eventType, const EmscriptenMouseEvent *mouseEvent
     return 0;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_HandleMouseButton(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
 {
     SDL_WindowData *window_data = userData;
-    uint32_t sdl_button;
+    Uint8 sdl_button;
+    Uint8 sdl_button_state;
+    SDL_EventType sdl_event_type;
+
     switch (mouseEvent->button) {
         case 0:
             sdl_button = SDL_BUTTON_LEFT;
@@ -351,22 +360,27 @@ Emscripten_HandleMouseButton(int eventType, const EmscriptenMouseEvent *mouseEve
             return 0;
     }
 
-    SDL_EventType sdl_event_type = (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN ? SDL_PRESSED : SDL_RELEASED);
-    SDL_SendMouseButton(window_data->window, 0, sdl_event_type, sdl_button);
+    if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN) {
+        if (SDL_GetMouse()->relative_mode && !window_data->has_pointer_lock) {
+            emscripten_request_pointerlock(NULL, 0);  /* try to regrab lost pointer lock. */
+        }
+        sdl_button_state = SDL_PRESSED;
+        sdl_event_type = SDL_MOUSEBUTTONDOWN;
+    } else {
+        sdl_button_state = SDL_RELEASED;
+        sdl_event_type = SDL_MOUSEBUTTONUP;
+    }
+    SDL_SendMouseButton(window_data->window, 0, sdl_button_state, sdl_button);
     return SDL_GetEventState(sdl_event_type) == SDL_ENABLE;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_HandleMouseFocus(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
 {
     SDL_WindowData *window_data = userData;
 
     int mx = mouseEvent->canvasX, my = mouseEvent->canvasY;
-    EmscriptenPointerlockChangeEvent pointerlock_status;
-
-    /* check for pointer lock */
-    int isPointerLockSupported = emscripten_get_pointerlock_status(&pointerlock_status);
-    int isPointerLocked = isPointerLockSupported == EMSCRIPTEN_RESULT_SUCCESS  ? pointerlock_status.isActive : SDL_FALSE;
+    const int isPointerLocked = window_data->has_pointer_lock;
 
     if (!isPointerLocked) {
         /* rescale (in case canvas is being scaled)*/
@@ -382,15 +396,15 @@ Emscripten_HandleMouseFocus(int eventType, const EmscriptenMouseEvent *mouseEven
     return SDL_GetEventState(SDL_WINDOWEVENT) == SDL_ENABLE;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_HandleWheel(int eventType, const EmscriptenWheelEvent *wheelEvent, void *userData)
 {
     SDL_WindowData *window_data = userData;
-    SDL_SendMouseWheel(window_data->window, 0, wheelEvent->deltaX, -wheelEvent->deltaY, SDL_MOUSEWHEEL_NORMAL);
+    SDL_SendMouseWheel(window_data->window, 0, (float)wheelEvent->deltaX, (float)-wheelEvent->deltaY, SDL_MOUSEWHEEL_NORMAL);
     return SDL_GetEventState(SDL_MOUSEWHEEL) == SDL_ENABLE;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_HandleFocus(int eventType, const EmscriptenFocusEvent *wheelEvent, void *userData)
 {
     SDL_WindowData *window_data = userData;
@@ -405,7 +419,7 @@ Emscripten_HandleFocus(int eventType, const EmscriptenFocusEvent *wheelEvent, vo
     return SDL_GetEventState(SDL_WINDOWEVENT) == SDL_ENABLE;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_HandleTouch(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData)
 {
     SDL_WindowData *window_data = userData;
@@ -423,6 +437,7 @@ Emscripten_HandleTouch(int eventType, const EmscriptenTouchEvent *touchEvent, vo
     for (i = 0; i < touchEvent->numTouches; i++) {
         SDL_FingerID id;
         float x, y;
+        int mx, my;
 
         if (!touchEvent->touches[i].isChanged)
             continue;
@@ -431,11 +446,14 @@ Emscripten_HandleTouch(int eventType, const EmscriptenTouchEvent *touchEvent, vo
         x = touchEvent->touches[i].canvasX / client_w;
         y = touchEvent->touches[i].canvasY / client_h;
 
+        mx = x * window_data->window->w;
+        my = y * window_data->window->h;
+
         if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART) {
             if (!window_data->finger_touching) {
                 window_data->finger_touching = SDL_TRUE;
                 window_data->first_finger = id;
-                SDL_SendMouseMotion(window_data->window, SDL_TOUCH_MOUSEID, 0, x, y);
+                SDL_SendMouseMotion(window_data->window, SDL_TOUCH_MOUSEID, 0, mx, my);
                 SDL_SendMouseButton(window_data->window, SDL_TOUCH_MOUSEID, SDL_PRESSED, SDL_BUTTON_LEFT);
             }
             SDL_SendTouch(deviceId, id, SDL_TRUE, x, y, 1.0f);
@@ -445,7 +463,7 @@ Emscripten_HandleTouch(int eventType, const EmscriptenTouchEvent *touchEvent, vo
             }
         } else if (eventType == EMSCRIPTEN_EVENT_TOUCHMOVE) {
             if ((window_data->finger_touching) && (window_data->first_finger == id)) {
-                SDL_SendMouseMotion(window_data->window, SDL_TOUCH_MOUSEID, 0, x, y);
+                SDL_SendMouseMotion(window_data->window, SDL_TOUCH_MOUSEID, 0, mx, my);
             }
             SDL_SendTouchMotion(deviceId, id, x, y, 1.0f);
 
@@ -468,10 +486,12 @@ Emscripten_HandleTouch(int eventType, const EmscriptenTouchEvent *touchEvent, vo
     return preventDefault;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_HandleKey(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData)
 {
     Uint32 scancode;
+    SDL_bool prevent_default;
+    SDL_bool is_nav_key;
 
     /* .keyCode is deprecated, but still the most reliable way to get keys */
     if (keyEvent->keyCode < SDL_arraysize(emscripten_scancode_table)) {
@@ -499,18 +519,25 @@ Emscripten_HandleKey(int eventType, const EmscriptenKeyboardEvent *keyEvent, voi
         }
     }
 
-    SDL_bool prevent_default = SDL_GetEventState(eventType == EMSCRIPTEN_EVENT_KEYDOWN ? SDL_KEYDOWN : SDL_KEYUP) == SDL_ENABLE;
+    prevent_default = SDL_GetEventState(eventType == EMSCRIPTEN_EVENT_KEYDOWN ? SDL_KEYDOWN : SDL_KEYUP) == SDL_ENABLE;
 
     /* if TEXTINPUT events are enabled we can't prevent keydown or we won't get keypress
      * we need to ALWAYS prevent backspace and tab otherwise chrome takes action and does bad navigation UX
      */
-    if (eventType == EMSCRIPTEN_EVENT_KEYDOWN && SDL_GetEventState(SDL_TEXTINPUT) == SDL_ENABLE && keyEvent->keyCode != 8 /* backspace */ && keyEvent->keyCode != 9 /* tab */)
+    is_nav_key = keyEvent->keyCode == 8 /* backspace */ ||
+                 keyEvent->keyCode == 9 /* tab */ ||
+                 keyEvent->keyCode == 37 /* left */ ||
+                 keyEvent->keyCode == 38 /* up */ ||
+                 keyEvent->keyCode == 39 /* right */ ||
+                 keyEvent->keyCode == 40 /* down */;
+
+    if (eventType == EMSCRIPTEN_EVENT_KEYDOWN && SDL_GetEventState(SDL_TEXTINPUT) == SDL_ENABLE && !is_nav_key)
         prevent_default = SDL_FALSE;
 
     return prevent_default;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_HandleKeyPress(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData)
 {
     char text[5];
@@ -520,7 +547,7 @@ Emscripten_HandleKeyPress(int eventType, const EmscriptenKeyboardEvent *keyEvent
     return SDL_GetEventState(SDL_TEXTINPUT) == SDL_ENABLE;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_HandleFullscreenChange(int eventType, const EmscriptenFullscreenChangeEvent *fullscreenChangeEvent, void *userData)
 {
     SDL_WindowData *window_data = userData;
@@ -541,13 +568,15 @@ Emscripten_HandleFullscreenChange(int eventType, const EmscriptenFullscreenChang
     return 0;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_HandleResize(int eventType, const EmscriptenUiEvent *uiEvent, void *userData)
 {
     SDL_WindowData *window_data = userData;
 
     /* update pixel ratio */
-    window_data->pixel_ratio = emscripten_get_device_pixel_ratio();
+    if (window_data->window->flags & SDL_WINDOW_ALLOW_HIGHDPI) {
+        window_data->pixel_ratio = emscripten_get_device_pixel_ratio();
+    }
 
     if(!(window_data->window->flags & FULLSCREEN_MASK))
     {
@@ -591,7 +620,7 @@ Emscripten_HandleCanvasResize(int eventType, const void *reserved, void *userDat
     return 0;
 }
 
-EM_BOOL
+static EM_BOOL
 Emscripten_HandleVisibilityChange(int eventType, const EmscriptenVisibilityChangeEvent *visEvent, void *userData)
 {
     SDL_WindowData *window_data = userData;
@@ -602,6 +631,8 @@ Emscripten_HandleVisibilityChange(int eventType, const EmscriptenVisibilityChang
 void
 Emscripten_RegisterEventHandlers(SDL_WindowData *data)
 {
+    const char *keyElement;
+
     /* There is only one window and that window is the canvas */
     emscripten_set_mousemove_callback("#canvas", data, 0, Emscripten_HandleMouseMove);
 
@@ -621,8 +652,10 @@ Emscripten_RegisterEventHandlers(SDL_WindowData *data)
     emscripten_set_touchmove_callback("#canvas", data, 0, Emscripten_HandleTouch);
     emscripten_set_touchcancel_callback("#canvas", data, 0, Emscripten_HandleTouch);
 
+    emscripten_set_pointerlockchange_callback("#document", data, 0, Emscripten_HandlePointerLockChange);
+
     /* Keyboard events are awkward */
-    const char *keyElement = SDL_GetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT);
+    keyElement = SDL_GetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT);
     if (!keyElement) keyElement = "#window";
 
     emscripten_set_keydown_callback(keyElement, data, 0, Emscripten_HandleKey);
@@ -639,6 +672,8 @@ Emscripten_RegisterEventHandlers(SDL_WindowData *data)
 void
 Emscripten_UnregisterEventHandlers(SDL_WindowData *data)
 {
+    const char *target;
+
     /* only works due to having one window */
     emscripten_set_mousemove_callback("#canvas", NULL, 0, NULL);
 
@@ -658,14 +693,15 @@ Emscripten_UnregisterEventHandlers(SDL_WindowData *data)
     emscripten_set_touchmove_callback("#canvas", NULL, 0, NULL);
     emscripten_set_touchcancel_callback("#canvas", NULL, 0, NULL);
 
-    const char *target = SDL_GetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT);
+    emscripten_set_pointerlockchange_callback("#document", NULL, 0, NULL);
+
+    target = SDL_GetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT);
     if (!target) {
         target = "#window";
     }
 
     emscripten_set_keydown_callback(target, NULL, 0, NULL);
     emscripten_set_keyup_callback(target, NULL, 0, NULL);
-
     emscripten_set_keypress_callback(target, NULL, 0, NULL);
 
     emscripten_set_fullscreenchange_callback("#document", NULL, 0, NULL);
diff --git a/src/video/emscripten/SDL_emscriptenevents.h b/src/video/emscripten/SDL_emscriptenevents.h
index 089ff60..4179f4e 100644
--- a/src/video/emscripten/SDL_emscriptenevents.h
+++ b/src/video/emscripten/SDL_emscriptenevents.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 
 
-#ifndef _SDL_emscriptenevents_h
-#define _SDL_emscriptenevents_h
+#ifndef SDL_emscriptenevents_h_
+#define SDL_emscriptenevents_h_
 
 #include "SDL_emscriptenvideo.h"
 
@@ -31,9 +31,10 @@ Emscripten_RegisterEventHandlers(SDL_WindowData *data);
 extern void
 Emscripten_UnregisterEventHandlers(SDL_WindowData *data);
 
-extern int
+extern EM_BOOL
 Emscripten_HandleCanvasResize(int eventType, const void *reserved, void *userData);
-#endif /* _SDL_emscriptenevents_h */
+
+#endif /* SDL_emscriptenevents_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
 
diff --git a/src/video/emscripten/SDL_emscriptenframebuffer.c b/src/video/emscripten/SDL_emscriptenframebuffer.c
index 8a6a465..2aca71e 100644
--- a/src/video/emscripten/SDL_emscriptenframebuffer.c
+++ b/src/video/emscripten/SDL_emscriptenframebuffer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/emscripten/SDL_emscriptenframebuffer.h b/src/video/emscripten/SDL_emscriptenframebuffer.h
index b2a6d3b..1ecb279 100644
--- a/src/video/emscripten/SDL_emscriptenframebuffer.h
+++ b/src/video/emscripten/SDL_emscriptenframebuffer.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,13 +20,13 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_emscriptenframebuffer_h
-#define _SDL_emscriptenframebuffer_h
+#ifndef SDL_emscriptenframebuffer_h_
+#define SDL_emscriptenframebuffer_h_
 
 extern int Emscripten_CreateWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format, void ** pixels, int *pitch);
 extern int Emscripten_UpdateWindowFramebuffer(_THIS, SDL_Window * window, const SDL_Rect * rects, int numrects);
 extern void Emscripten_DestroyWindowFramebuffer(_THIS, SDL_Window * window);
 
-#endif /* _SDL_emscriptenframebuffer_h */
+#endif /* SDL_emscriptenframebuffer_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/emscripten/SDL_emscriptenmouse.c b/src/video/emscripten/SDL_emscriptenmouse.c
index 512ad22..8232dac 100644
--- a/src/video/emscripten/SDL_emscriptenmouse.c
+++ b/src/video/emscripten/SDL_emscriptenmouse.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -32,9 +32,8 @@
 #include "../../events/SDL_mouse_c.h"
 #include "SDL_assert.h"
 
-
 static SDL_Cursor*
-Emscripten_CreateDefaultCursor()
+Emscripten_CreateCursorFromString(const char* cursor_str, SDL_bool is_custom)
 {
     SDL_Cursor* cursor;
     Emscripten_CursorData *curdata;
@@ -48,7 +47,8 @@ Emscripten_CreateDefaultCursor()
             return NULL;
         }
 
-        curdata->system_cursor = "default";
+        curdata->system_cursor = cursor_str;
+        curdata->is_custom = is_custom;
         cursor->driverdata = curdata;
     }
     else {
@@ -58,19 +58,78 @@ Emscripten_CreateDefaultCursor()
     return cursor;
 }
 
-/*
 static SDL_Cursor*
-Emscripten_CreateCursor(SDL_Surface* sruface, int hot_x, int hot_y)
+Emscripten_CreateDefaultCursor()
 {
-    return Emscripten_CreateDefaultCursor();
+    return Emscripten_CreateCursorFromString("default", SDL_FALSE);
+}
+
+static SDL_Cursor*
+Emscripten_CreateCursor(SDL_Surface* surface, int hot_x, int hot_y)
+{
+    const char *cursor_url = NULL;
+    SDL_Surface *conv_surf;
+
+    conv_surf = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_ABGR8888, 0);
+
+    if (!conv_surf) {
+        return NULL;
+    }
+
+    cursor_url = (const char *)EM_ASM_INT({
+        var w = $0;
+        var h = $1;
+        var pixels = $2;
+
+        var canvas = document.createElement("canvas");
+        canvas.width = w;
+        canvas.height = h;
+
+        var ctx = canvas.getContext("2d");
+
+        var image = ctx.createImageData(w, h);
+        var data = image.data;
+        var src = pixels >> 2;
+        var dst = 0;
+        var num;
+        if (typeof CanvasPixelArray !== 'undefined' && data instanceof CanvasPixelArray) {
+            // IE10/IE11: ImageData objects are backed by the deprecated CanvasPixelArray,
+            // not UInt8ClampedArray. These don't have buffers, so we need to revert
+            // to copying a byte at a time. We do the undefined check because modern
+            // browsers do not define CanvasPixelArray anymore.
+            num = data.length;
+            while (dst < num) {
+                var val = HEAP32[src]; // This is optimized. Instead, we could do {{{ makeGetValue('buffer', 'dst', 'i32') }}};
+                data[dst  ] = val & 0xff;
+                data[dst+1] = (val >> 8) & 0xff;
+                data[dst+2] = (val >> 16) & 0xff;
+                data[dst+3] = (val >> 24) & 0xff;
+                src++;
+                dst += 4;
+            }
+        } else {
+            var data32 = new Int32Array(data.buffer);
+            num = data32.length;
+            data32.set(HEAP32.subarray(src, src + num));
+        }
+
+        ctx.putImageData(image, 0, 0);
+        var url = "url(" + canvas.toDataURL() + "), auto";
+
+        var urlBuf = _malloc(url.length + 1);
+        stringToUTF8(url, urlBuf, url.length + 1);
+
+        return urlBuf;
+    }, surface->w, surface->h, conv_surf->pixels);
+
+    SDL_FreeSurface(conv_surf);
+
+    return Emscripten_CreateCursorFromString(cursor_url, SDL_TRUE);
 }
-*/
 
 static SDL_Cursor*
 Emscripten_CreateSystemCursor(SDL_SystemCursor id)
 {
-    SDL_Cursor *cursor;
-    Emscripten_CursorData *curdata;
     const char *cursor_name = NULL;
 
     switch(id) {
@@ -114,22 +173,7 @@ Emscripten_CreateSystemCursor(SDL_SystemCursor id)
             return NULL;
     }
 
-    cursor = (SDL_Cursor *) SDL_calloc(1, sizeof(*cursor));
-    if (!cursor) {
-        SDL_OutOfMemory();
-        return NULL;
-    }
-    curdata = (Emscripten_CursorData *) SDL_calloc(1, sizeof(*curdata));
-    if (!curdata) {
-        SDL_OutOfMemory();
-        SDL_free(cursor);
-        return NULL;
-    }
-
-    curdata->system_cursor = cursor_name;
-    cursor->driverdata = curdata;
-
-    return cursor;
+    return Emscripten_CreateCursorFromString(cursor_name, SDL_FALSE);
 }
 
 static void
@@ -140,6 +184,9 @@ Emscripten_FreeCursor(SDL_Cursor* cursor)
         curdata = (Emscripten_CursorData *) cursor->driverdata;
 
         if (curdata != NULL) {
+            if (curdata->is_custom) {
+                SDL_free((char *)curdata->system_cursor);
+            }
             SDL_free(cursor->driverdata);
         }
 
@@ -202,9 +249,7 @@ Emscripten_InitMouse()
 {
     SDL_Mouse* mouse = SDL_GetMouse();
 
-/*
     mouse->CreateCursor         = Emscripten_CreateCursor;
-*/ 
     mouse->ShowCursor           = Emscripten_ShowCursor;
     mouse->FreeCursor           = Emscripten_FreeCursor;
     mouse->WarpMouse            = Emscripten_WarpMouse;
@@ -217,17 +262,6 @@ Emscripten_InitMouse()
 void
 Emscripten_FiniMouse()
 {
-    SDL_Mouse* mouse = SDL_GetMouse();
-
-    Emscripten_FreeCursor(mouse->def_cursor);
-    mouse->def_cursor = NULL;
-
-    mouse->CreateCursor         = NULL;
-    mouse->ShowCursor           = NULL;
-    mouse->FreeCursor           = NULL;
-    mouse->WarpMouse            = NULL;
-    mouse->CreateSystemCursor   = NULL;
-    mouse->SetRelativeMouseMode = NULL;
 }
 
 #endif /* SDL_VIDEO_DRIVER_EMSCRIPTEN */
diff --git a/src/video/emscripten/SDL_emscriptenmouse.h b/src/video/emscripten/SDL_emscriptenmouse.h
index 76ea849..2f075ee 100644
--- a/src/video/emscripten/SDL_emscriptenmouse.h
+++ b/src/video/emscripten/SDL_emscriptenmouse.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,12 +20,15 @@
 */
 
 
-#ifndef _SDL_emscriptenmouse_h
-#define _SDL_emscriptenmouse_h
+#ifndef SDL_emscriptenmouse_h_
+#define SDL_emscriptenmouse_h_
+
+#include "SDL_stdinc.h"
 
 typedef struct _Emscripten_CursorData
 {
     const char *system_cursor;
+    SDL_bool is_custom;
 } Emscripten_CursorData;
 
 extern void
@@ -34,6 +37,6 @@ Emscripten_InitMouse();
 extern void
 Emscripten_FiniMouse();
 
-#endif /* _SDL_emscriptenmouse_h */
+#endif /* SDL_emscriptenmouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/emscripten/SDL_emscriptenopengles.c b/src/video/emscripten/SDL_emscriptenopengles.c
index 12a37c6..2d9c1dd 100644
--- a/src/video/emscripten/SDL_emscriptenopengles.c
+++ b/src/video/emscripten/SDL_emscriptenopengles.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -39,11 +39,15 @@ Emscripten_GLES_LoadLibrary(_THIS, const char *path) {
     if (!_this->egl_data) {
         return SDL_OutOfMemory();
     }
-    
+
+    /* Emscripten forces you to manually cast eglGetProcAddress to the real
+       function type; grep for "__eglMustCastToProperFunctionPointerType" in
+       Emscripten's egl.h for details. */
+    _this->egl_data->eglGetProcAddress = (void *(EGLAPIENTRY *)(const char *)) eglGetProcAddress;
+
     LOAD_FUNC(eglGetDisplay);
     LOAD_FUNC(eglInitialize);
     LOAD_FUNC(eglTerminate);
-    LOAD_FUNC(eglGetProcAddress);
     LOAD_FUNC(eglChooseConfig);
     LOAD_FUNC(eglGetConfigAttrib);
     LOAD_FUNC(eglCreateContext);
@@ -66,8 +70,6 @@ Emscripten_GLES_LoadLibrary(_THIS, const char *path) {
         return SDL_SetError("Could not initialize EGL");
     }
 
-    _this->gl_config.driver_loaded = 1;
-
     if (path) {
         SDL_strlcpy(_this->gl_config.driver_path, path, sizeof(_this->gl_config.driver_path) - 1);
     } else {
diff --git a/src/video/emscripten/SDL_emscriptenopengles.h b/src/video/emscripten/SDL_emscriptenopengles.h
index edafed8..e77efde 100644
--- a/src/video/emscripten/SDL_emscriptenopengles.h
+++ b/src/video/emscripten/SDL_emscriptenopengles.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_emscriptenopengles_h
-#define _SDL_emscriptenopengles_h
+#ifndef SDL_emscriptenopengles_h_
+#define SDL_emscriptenopengles_h_
 
 #if SDL_VIDEO_DRIVER_EMSCRIPTEN && SDL_VIDEO_OPENGL_EGL
 
@@ -38,12 +38,12 @@
 extern int Emscripten_GLES_LoadLibrary(_THIS, const char *path);
 extern void Emscripten_GLES_DeleteContext(_THIS, SDL_GLContext context);
 extern SDL_GLContext Emscripten_GLES_CreateContext(_THIS, SDL_Window * window);
-extern void Emscripten_GLES_SwapWindow(_THIS, SDL_Window * window);
+extern int Emscripten_GLES_SwapWindow(_THIS, SDL_Window * window);
 extern int Emscripten_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 extern void Emscripten_GLES_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h);
 
 #endif /* SDL_VIDEO_DRIVER_EMSCRIPTEN && SDL_VIDEO_OPENGL_EGL */
 
-#endif /* _SDL_emscriptenopengles_h */
+#endif /* SDL_emscriptenopengles_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/emscripten/SDL_emscriptenvideo.c b/src/video/emscripten/SDL_emscriptenvideo.c
index 847bb4c..897d470 100644
--- a/src/video/emscripten/SDL_emscriptenvideo.c
+++ b/src/video/emscripten/SDL_emscriptenvideo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -91,8 +91,7 @@ Emscripten_CreateDevice(int devindex)
 
     device->PumpEvents = Emscripten_PumpEvents;
 
-    device->CreateWindow = Emscripten_CreateWindow;
-    /*device->CreateWindowFrom = Emscripten_CreateWindowFrom;*/
+    device->CreateSDLWindow = Emscripten_CreateWindow;
     device->SetWindowTitle = Emscripten_SetWindowTitle;
     /*device->SetWindowIcon = Emscripten_SetWindowIcon;
     device->SetWindowPosition = Emscripten_SetWindowPosition;*/
@@ -111,6 +110,7 @@ Emscripten_CreateDevice(int devindex)
     device->UpdateWindowFramebuffer = Emscripten_UpdateWindowFramebuffer;
     device->DestroyWindowFramebuffer = Emscripten_DestroyWindowFramebuffer;
 
+#if SDL_VIDEO_OPENGL_EGL
     device->GL_LoadLibrary = Emscripten_GLES_LoadLibrary;
     device->GL_GetProcAddress = Emscripten_GLES_GetProcAddress;
     device->GL_UnloadLibrary = Emscripten_GLES_UnloadLibrary;
@@ -121,6 +121,7 @@ Emscripten_CreateDevice(int devindex)
     device->GL_SwapWindow = Emscripten_GLES_SwapWindow;
     device->GL_DeleteContext = Emscripten_GLES_DeleteContext;
     device->GL_GetDrawableSize = Emscripten_GLES_GetDrawableSize;
+#endif
 
     device->free = Emscripten_DeleteDevice;
 
@@ -228,6 +229,7 @@ Emscripten_CreateWindow(_THIS, SDL_Window * window)
         }
     }
 
+#if SDL_VIDEO_OPENGL_EGL
     if (window->flags & SDL_WINDOW_OPENGL) {
         if (!_this->egl_data) {
             if (SDL_GL_LoadLibrary(NULL) < 0) {
@@ -240,6 +242,7 @@ Emscripten_CreateWindow(_THIS, SDL_Window * window)
             return SDL_SetError("Could not create GLES window surface");
         }
     }
+#endif
 
     wdata->window = window;
 
@@ -263,7 +266,9 @@ static void Emscripten_SetWindowSize(_THIS, SDL_Window * window)
     if (window->driverdata) {
         data = (SDL_WindowData *) window->driverdata;
         /* update pixel ratio */
-        data->pixel_ratio = emscripten_get_device_pixel_ratio();
+        if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) {
+            data->pixel_ratio = emscripten_get_device_pixel_ratio();
+        }
         emscripten_set_canvas_size(window->w * data->pixel_ratio, window->h * data->pixel_ratio);
 
         /*scale canvas down*/
@@ -282,10 +287,12 @@ Emscripten_DestroyWindow(_THIS, SDL_Window * window)
         data = (SDL_WindowData *) window->driverdata;
 
         Emscripten_UnregisterEventHandlers(data);
+#if SDL_VIDEO_OPENGL_EGL
         if (data->egl_surface != EGL_NO_SURFACE) {
             SDL_EGL_DestroySurface(_this, data->egl_surface);
             data->egl_surface = EGL_NO_SURFACE;
         }
+#endif
         SDL_free(window->driverdata);
         window->driverdata = NULL;
     }
diff --git a/src/video/emscripten/SDL_emscriptenvideo.h b/src/video/emscripten/SDL_emscriptenvideo.h
index 7618ab6..394df09 100644
--- a/src/video/emscripten/SDL_emscriptenvideo.h
+++ b/src/video/emscripten/SDL_emscriptenvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,15 +20,17 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_emscriptenvideo_h
-#define _SDL_emscriptenvideo_h
+#ifndef SDL_emscriptenvideo_h_
+#define SDL_emscriptenvideo_h_
 
 #include "../SDL_sysvideo.h"
 #include "../../events/SDL_touch_c.h"
 #include <emscripten/emscripten.h>
 #include <emscripten/html5.h>
 
+#if SDL_VIDEO_OPENGL_EGL
 #include <EGL/egl.h>
+#endif
 
 typedef struct SDL_WindowData
 {
@@ -47,8 +49,10 @@ typedef struct SDL_WindowData
 
     SDL_bool finger_touching;  /* for mapping touch events to mice */
     SDL_FingerID first_finger;
+
+    SDL_bool has_pointer_lock;
 } SDL_WindowData;
 
-#endif /* _SDL_emscriptenvideo_h */
+#endif /* SDL_emscriptenvideo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_BWin.h b/src/video/haiku/SDL_BWin.h
index a353e1a..a20147a 100644
--- a/src/video/haiku/SDL_BWin.h
+++ b/src/video/haiku/SDL_BWin.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_BWin_h
-#define _SDL_BWin_h
+#ifndef SDL_BWin_h_
+#define SDL_BWin_h_
 
 #ifdef __cplusplus
 extern "C" {
@@ -38,9 +38,9 @@ extern "C" {
 #include <stdio.h>
 #include <AppKit.h>
 #include <InterfaceKit.h>
-#include <be/game/DirectWindow.h>
+#include <game/DirectWindow.h>
 #if SDL_VIDEO_OPENGL
-#include <be/opengl/GLView.h>
+#include <opengl/GLView.h>
 #endif
 #include "SDL_events.h"
 #include "../../main/haiku/SDL_BApp.h"
@@ -72,6 +72,7 @@ class SDL_BWin:public BDirectWindow
 
 #if SDL_VIDEO_OPENGL
         _SDL_GLView = NULL;
+        _gl_type = 0;
 #endif
         _shown = false;
         _inhibit_resize = false;
@@ -114,6 +115,8 @@ class SDL_BWin:public BDirectWindow
         }
 #endif
 
+        delete _prev_frame;
+
         /* Clean up framebuffer stuff */
         _buffer_locker->Lock();
 #ifdef DRAWTHREAD
@@ -133,6 +136,7 @@ class SDL_BWin:public BDirectWindow
                                      B_FOLLOW_ALL_SIDES,
                                      (B_WILL_DRAW | B_FRAME_EVENTS),
                                      gl_flags);
+            _gl_type = gl_flags;
         }
         AddChild(_SDL_GLView);
         _SDL_GLView->EnableDirectMode(true);
@@ -250,6 +254,7 @@ class SDL_BWin:public BDirectWindow
 
     virtual void WindowActivated(bool active) {
         BMessage msg(BAPP_KEYBOARD_FOCUS);  /* Mouse focus sold separately */
+        msg.AddBool("focusGained", active);
         _PostWindowEvent(msg);
     }
 
@@ -442,6 +447,7 @@ class SDL_BWin:public BDirectWindow
     BBitmap *GetBitmap() { return _bitmap; }
 #if SDL_VIDEO_OPENGL
     BGLView *GetGLView() { return _SDL_GLView; }
+    Uint32 GetGLType() { return _gl_type; }
 #endif
 
     /* Setter methods */
@@ -585,7 +591,7 @@ private:
         if(msg->FindBool("window-border", &bEnabled) != B_OK) {
             return;
         }
-        SetLook(bEnabled ? B_BORDERED_WINDOW_LOOK : B_NO_BORDER_WINDOW_LOOK);
+        SetLook(bEnabled ? B_TITLED_WINDOW_LOOK : B_NO_BORDER_WINDOW_LOOK);
     }
 
     void _SetResizable(BMessage *msg) {
@@ -624,6 +630,7 @@ private:
     /* Members */
 #if SDL_VIDEO_OPENGL
     BGLView * _SDL_GLView;
+    Uint32 _gl_type;
 #endif
 
     int32 _last_buttons;
@@ -667,4 +674,6 @@ private:
  *                         through a draw cycle.  Occurs when the previous
  *                         buffer provided by DirectConnected() is invalidated.
  */
-#endif
+#endif /* SDL_BWin_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bclipboard.cc b/src/video/haiku/SDL_bclipboard.cc
index fcd1caa..1cc2951 100644
--- a/src/video/haiku/SDL_bclipboard.cc
+++ b/src/video/haiku/SDL_bclipboard.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,7 +22,7 @@
 
 #if SDL_VIDEO_DRIVER_HAIKU
 
-/* BWindow based framebuffer implementation */
+/* BWindow based clipboard implementation */
 
 #include <unistd.h>
 #include <TypeConstants.h>
@@ -43,7 +43,7 @@ int BE_SetClipboardText(_THIS, const char *text) {
 			/* Presumably the string of characters is ascii-format */
 			ssize_t asciiLength = 0;
 			for(; text[asciiLength] != 0; ++asciiLength) {}
-			clip->AddData("text/plain", B_MIME_TYPE, &text, asciiLength);
+			clip->AddData("text/plain", B_MIME_TYPE, text, asciiLength);
 			be_clipboard->Commit();
 		}
 		be_clipboard->Unlock();
@@ -61,8 +61,6 @@ char *BE_GetClipboardText(_THIS) {
 			/* Presumably the string of characters is ascii-format */
 			clip->FindData("text/plain", B_MIME_TYPE, (const void**)&text,
 				&length);
-		} else {
-			be_clipboard->Unlock();
 		}
 		be_clipboard->Unlock();
 	} 
@@ -71,8 +69,8 @@ char *BE_GetClipboardText(_THIS) {
 		result = SDL_strdup("");
 	} else {
 		/* Copy the data and pass on to SDL */
-		result = (char*)SDL_calloc(1, sizeof(char*)*length);
-		SDL_strlcpy(result, text, length);
+		result = (char *)SDL_malloc((length + 1) * sizeof(char));
+		SDL_strlcpy(result, text, length + 1);
 	}
 	
 	return result;
@@ -93,3 +91,5 @@ SDL_bool BE_HasClipboardText(_THIS) {
 #endif
 
 #endif /* SDL_VIDEO_DRIVER_HAIKU */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bclipboard.h b/src/video/haiku/SDL_bclipboard.h
index dd31f19..1578a70 100644
--- a/src/video/haiku/SDL_bclipboard.h
+++ b/src/video/haiku/SDL_bclipboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -29,3 +29,5 @@ extern char *BE_GetClipboardText(_THIS);
 extern SDL_bool BE_HasClipboardText(_THIS);
 
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bevents.cc b/src/video/haiku/SDL_bevents.cc
index 36513a3..e3b38e7 100644
--- a/src/video/haiku/SDL_bevents.cc
+++ b/src/video/haiku/SDL_bevents.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -37,3 +37,5 @@ void BE_PumpEvents(_THIS) {
 #endif
 
 #endif /* SDL_VIDEO_DRIVER_HAIKU */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bevents.h b/src/video/haiku/SDL_bevents.h
index cb756c9..fea8c54 100644
--- a/src/video/haiku/SDL_bevents.h
+++ b/src/video/haiku/SDL_bevents.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -35,3 +35,5 @@ extern void BE_PumpEvents(_THIS);
 #endif
 
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bframebuffer.cc b/src/video/haiku/SDL_bframebuffer.cc
index 5e6a300..6a1adea 100644
--- a/src/video/haiku/SDL_bframebuffer.cc
+++ b/src/video/haiku/SDL_bframebuffer.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -35,7 +35,9 @@
 extern "C" {
 #endif
 
-int32 BE_UpdateOnce(SDL_Window *window);
+#ifndef DRAWTHREAD
+static int32 BE_UpdateOnce(SDL_Window *window);
+#endif
 
 static SDL_INLINE SDL_BWin *_ToBeWin(SDL_Window *window) {
 	return ((SDL_BWin*)(window->driverdata));
@@ -76,7 +78,8 @@ int BE_CreateWindowFramebuffer(_THIS, SDL_Window * window,
 			true);	/* Contiguous memory required */
 			
 	if(bitmap->InitCheck() != B_OK) {
-		return SDL_SetError("Could not initialize back buffer!\n");
+		delete bitmap;
+		return SDL_SetError("Could not initialize back buffer!");
 	}
 
 
@@ -143,7 +146,6 @@ int32 BE_DrawThread(void *data) {
 			/* Blit each clipping rectangle */
 			bscreen.WaitForRetrace();
 			for(i = 0; i < numClips; ++i) {
-				clipping_rect rc = clips[i];
 				/* Get addresses of the start of each clipping rectangle */
 				int32 width = clips[i].right - clips[i].left + 1;
 				int32 height = clips[i].bottom - clips[i].top + 1;
@@ -199,7 +201,8 @@ void BE_DestroyWindowFramebuffer(_THIS, SDL_Window * window) {
  * The specific issues have since become rare enough that they may have been
  * solved, but I doubt it- they were pretty sporadic before now.
  */
-int32 BE_UpdateOnce(SDL_Window *window) {
+#ifndef DRAWTHREAD
+static int32 BE_UpdateOnce(SDL_Window *window) {
 	SDL_BWin *bwin = _ToBeWin(window);
 	BScreen bscreen;
 	if(!bscreen.IsValid()) {
@@ -224,7 +227,6 @@ int32 BE_UpdateOnce(SDL_Window *window) {
 		/* Blit each clipping rectangle */
 		bscreen.WaitForRetrace();
 		for(i = 0; i < numClips; ++i) {
-			clipping_rect rc = clips[i];
 			/* Get addresses of the start of each clipping rectangle */
 			int32 width = clips[i].right - clips[i].left + 1;
 			int32 height = clips[i].bottom - clips[i].top + 1;
@@ -246,9 +248,12 @@ int32 BE_UpdateOnce(SDL_Window *window) {
 	}
 	return 0;
 }
+#endif
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif /* SDL_VIDEO_DRIVER_HAIKU */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bframebuffer.h b/src/video/haiku/SDL_bframebuffer.h
index d6be21f..93f600a 100644
--- a/src/video/haiku/SDL_bframebuffer.h
+++ b/src/video/haiku/SDL_bframebuffer.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -43,3 +43,5 @@ extern int32 BE_DrawThread(void *data);
 #endif
 
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bkeyboard.cc b/src/video/haiku/SDL_bkeyboard.cc
index 0ae3d3f..5be6d92 100644
--- a/src/video/haiku/SDL_bkeyboard.cc
+++ b/src/video/haiku/SDL_bkeyboard.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -41,7 +41,7 @@ extern "C" {
 static SDL_Scancode keymap[KEYMAP_SIZE];
 static int8 keystate[KEYMAP_SIZE];
 
-void BE_InitOSKeymap() {
+void BE_InitOSKeymap(void) {
 		for( uint i = 0; i < SDL_TABLESIZE(keymap); ++i ) {
 			keymap[i] = SDL_SCANCODE_UNKNOWN;
 		}
@@ -186,3 +186,5 @@ void BE_SetKeyState(int32 bkey, int8 state) {
 #endif
 
 #endif /* SDL_VIDEO_DRIVER_HAIKU */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bkeyboard.h b/src/video/haiku/SDL_bkeyboard.h
index 6327994..ca21af4 100644
--- a/src/video/haiku/SDL_bkeyboard.h
+++ b/src/video/haiku/SDL_bkeyboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -30,7 +30,7 @@ extern "C" {
 
 #include "../../../include/SDL_keyboard.h"
 
-extern void BE_InitOSKeymap();
+extern void BE_InitOSKeymap(void);
 extern SDL_Scancode BE_GetScancodeFromBeKey(int32 bkey);
 extern int8 BE_GetKeyState(int32 bkey);
 extern void BE_SetKeyState(int32 bkey, int8 state);
@@ -40,3 +40,5 @@ extern void BE_SetKeyState(int32 bkey, int8 state);
 #endif
 
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bmodes.cc b/src/video/haiku/SDL_bmodes.cc
index 84aeb1f..b4f508c 100644
--- a/src/video/haiku/SDL_bmodes.cc
+++ b/src/video/haiku/SDL_bmodes.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -43,7 +43,7 @@ extern "C" {
 #if WRAP_BMODE
 /* This wrapper is here so that the driverdata can be freed without freeing
    the display_mode structure */
-typedef struct SDL_DisplayModeData {
+struct SDL_DisplayModeData {
 	display_mode *bmode;
 };
 #endif
@@ -310,7 +310,7 @@ int BE_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode){
 	}
 
 	if(bscreen.SetMode(bmode) != B_OK) {
-		return SDL_SetError("Bad video mode\n");
+		return SDL_SetError("Bad video mode");
 	}
 	
 	free(bmode_list);
@@ -329,3 +329,5 @@ int BE_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode){
 #endif
 
 #endif /* SDL_VIDEO_DRIVER_HAIKU */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bmodes.h b/src/video/haiku/SDL_bmodes.h
index c3882ba..04d1af3 100644
--- a/src/video/haiku/SDL_bmodes.h
+++ b/src/video/haiku/SDL_bmodes.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -44,3 +44,5 @@ extern int BE_SetDisplayMode(_THIS, SDL_VideoDisplay *display,
 #endif
 
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bopengl.cc b/src/video/haiku/SDL_bopengl.cc
index 15454f1..6bf7a17 100644
--- a/src/video/haiku/SDL_bopengl.cc
+++ b/src/video/haiku/SDL_bopengl.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,7 +20,7 @@
 */
 #include "../../SDL_internal.h"
 
-#if SDL_VIDEO_DRIVER_HAIKU
+#if SDL_VIDEO_DRIVER_HAIKU && SDL_VIDEO_OPENGL
 
 #include "SDL_bopengl.h"
 
@@ -35,43 +35,41 @@ extern "C" {
 #endif
 
 
-#define BGL_FLAGS BGL_RGB | BGL_DOUBLE
-
 static SDL_INLINE SDL_BWin *_ToBeWin(SDL_Window *window) {
-	return ((SDL_BWin*)(window->driverdata));
+    return ((SDL_BWin*)(window->driverdata));
 }
 
 static SDL_INLINE SDL_BApp *_GetBeApp() {
-	return ((SDL_BApp*)be_app);
+    return ((SDL_BApp*)be_app);
 }
 
 /* Passing a NULL path means load pointers from the application */
 int BE_GL_LoadLibrary(_THIS, const char *path)
 {
 /* FIXME: Is this working correctly? */
-	image_info info;
-			int32 cookie = 0;
-	while (get_next_image_info(0, &cookie, &info) == B_OK) {
-		void *location = NULL;
-		if( get_image_symbol(info.id, "glBegin", B_SYMBOL_TYPE_ANY,
-				&location) == B_OK) {
-
-			_this->gl_config.dll_handle = (void *) info.id;
-			_this->gl_config.driver_loaded = 1;
-			SDL_strlcpy(_this->gl_config.driver_path, "libGL.so",
-					SDL_arraysize(_this->gl_config.driver_path));
-		}
-	}
-	return 0;
+    image_info info;
+            int32 cookie = 0;
+    while (get_next_image_info(0, &cookie, &info) == B_OK) {
+        void *location = NULL;
+        if( get_image_symbol(info.id, "glBegin", B_SYMBOL_TYPE_ANY,
+                &location) == B_OK) {
+
+            _this->gl_config.dll_handle = (void *) (size_t) info.id;
+            _this->gl_config.driver_loaded = 1;
+            SDL_strlcpy(_this->gl_config.driver_path, "libGL.so",
+                    SDL_arraysize(_this->gl_config.driver_path));
+        }
+    }
+    return 0;
 }
 
 void *BE_GL_GetProcAddress(_THIS, const char *proc)
 {
-	if (_this->gl_config.dll_handle != NULL) {
-		void *location = NULL;
-		status_t err;
-		if ((err =
-			get_image_symbol((image_id) _this->gl_config.dll_handle,
+    if (_this->gl_config.dll_handle != NULL) {
+        void *location = NULL;
+        status_t err;
+        if ((err =
+            get_image_symbol((image_id) (size_t) _this->gl_config.dll_handle,
                               proc, B_SYMBOL_TYPE_ANY,
                               &location)) == B_OK) {
             return location;
@@ -79,52 +77,75 @@ void *BE_GL_GetProcAddress(_THIS, const char *proc)
                 SDL_SetError("Couldn't find OpenGL symbol");
                 return NULL;
         }
-	} else {
-		SDL_SetError("OpenGL library not loaded");
-		return NULL;
-	}
+    } else {
+        SDL_SetError("OpenGL library not loaded");
+        return NULL;
+    }
 }
 
 
 
 
-void BE_GL_SwapWindow(_THIS, SDL_Window * window) {
+int BE_GL_SwapWindow(_THIS, SDL_Window * window) {
     _ToBeWin(window)->SwapBuffers();
+    return 0;
 }
 
 int BE_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context) {
-	_GetBeApp()->SetCurrentContext(((SDL_BWin*)context)->GetGLView());
-	return 0;
+    SDL_BWin* win = (SDL_BWin*)context;
+    _GetBeApp()->SetCurrentContext(win ? win->GetGLView() : NULL);
+    return 0;
 }
 
 
 SDL_GLContext BE_GL_CreateContext(_THIS, SDL_Window * window) {
-	/* FIXME: Not sure what flags should be included here; may want to have
-	   most of them */
-	SDL_BWin *bwin = _ToBeWin(window);
-	bwin->CreateGLView(BGL_FLAGS);
-	return (SDL_GLContext)(bwin);
+    /* FIXME: Not sure what flags should be included here; may want to have
+       most of them */
+    SDL_BWin *bwin = _ToBeWin(window);
+    Uint32 gl_flags = BGL_RGB;
+    if (_this->gl_config.alpha_size) {
+        gl_flags |= BGL_ALPHA;
+    }
+    if (_this->gl_config.depth_size) {
+        gl_flags |= BGL_DEPTH;
+    }
+    if (_this->gl_config.stencil_size) {
+        gl_flags |= BGL_STENCIL;
+    }
+    if (_this->gl_config.double_buffer) {
+        gl_flags |= BGL_DOUBLE;
+    } else {
+        gl_flags |= BGL_SINGLE;
+    }
+    if (_this->gl_config.accum_red_size ||
+            _this->gl_config.accum_green_size ||
+            _this->gl_config.accum_blue_size ||
+            _this->gl_config.accum_alpha_size) {
+        gl_flags |= BGL_ACCUM;
+    }
+    bwin->CreateGLView(gl_flags);
+    return (SDL_GLContext)(bwin);
 }
 
 void BE_GL_DeleteContext(_THIS, SDL_GLContext context) {
-	/* Currently, automatically unlocks the view */
-	((SDL_BWin*)context)->RemoveGLView();
+    /* Currently, automatically unlocks the view */
+    ((SDL_BWin*)context)->RemoveGLView();
 }
 
 
 int BE_GL_SetSwapInterval(_THIS, int interval) {
-	/* TODO: Implement this, if necessary? */
-	return 0;
+    /* TODO: Implement this, if necessary? */
+    return SDL_Unsupported();
 }
 
 int BE_GL_GetSwapInterval(_THIS) {
-	/* TODO: Implement this, if necessary? */
-	return 0;
+    /* TODO: Implement this, if necessary? */
+    return 0;
 }
 
 
 void BE_GL_UnloadLibrary(_THIS) {
-	/* TODO: Implement this, if necessary? */
+    /* TODO: Implement this, if necessary? */
 }
 
 
@@ -132,88 +153,24 @@ void BE_GL_UnloadLibrary(_THIS) {
    mode changes (see SDL_bmodes.cc), but it doesn't seem to help, and is not
    currently in use. */
 void BE_GL_RebootContexts(_THIS) {
-	SDL_Window *window = _this->windows;
-	while(window) {
-		SDL_BWin *bwin = _ToBeWin(window);
-		if(bwin->GetGLView()) {
-			bwin->LockLooper();
-			bwin->RemoveGLView();
-			bwin->CreateGLView(BGL_FLAGS);
-			bwin->UnlockLooper();
-		}
-		window = window->next;
-	}
-}
-
-
-#if 0 /* Functions from 1.2 that do not appear to be used in 1.3 */
-
-    int BE_GL_GetAttribute(_THIS, SDL_GLattr attrib, int *value)
-    {
-        /*
-           FIXME? Right now BE_GL_GetAttribute shouldn't be called between glBegin() and glEnd() - it doesn't use "cached" values
-         */
-        switch (attrib) {
-        case SDL_GL_RED_SIZE:
-            glGetIntegerv(GL_RED_BITS, (GLint *) value);
-            break;
-        case SDL_GL_GREEN_SIZE:
-            glGetIntegerv(GL_GREEN_BITS, (GLint *) value);
-            break;
-        case SDL_GL_BLUE_SIZE:
-            glGetIntegerv(GL_BLUE_BITS, (GLint *) value);
-            break;
-        case SDL_GL_ALPHA_SIZE:
-            glGetIntegerv(GL_ALPHA_BITS, (GLint *) value);
-            break;
-        case SDL_GL_DOUBLEBUFFER:
-            glGetBooleanv(GL_DOUBLEBUFFER, (GLboolean *) value);
-            break;
-        case SDL_GL_BUFFER_SIZE:
-            int v;
-            glGetIntegerv(GL_RED_BITS, (GLint *) & v);
-            *value = v;
-            glGetIntegerv(GL_GREEN_BITS, (GLint *) & v);
-            *value += v;
-            glGetIntegerv(GL_BLUE_BITS, (GLint *) & v);
-            *value += v;
-            glGetIntegerv(GL_ALPHA_BITS, (GLint *) & v);
-            *value += v;
-            break;
-        case SDL_GL_DEPTH_SIZE:
-            glGetIntegerv(GL_DEPTH_BITS, (GLint *) value);      /* Mesa creates 16 only? r5 always 32 */
-            break;
-        case SDL_GL_STENCIL_SIZE:
-            glGetIntegerv(GL_STENCIL_BITS, (GLint *) value);
-            break;
-        case SDL_GL_ACCUM_RED_SIZE:
-            glGetIntegerv(GL_ACCUM_RED_BITS, (GLint *) value);
-            break;
-        case SDL_GL_ACCUM_GREEN_SIZE:
-            glGetIntegerv(GL_ACCUM_GREEN_BITS, (GLint *) value);
-            break;
-        case SDL_GL_ACCUM_BLUE_SIZE:
-            glGetIntegerv(GL_ACCUM_BLUE_BITS, (GLint *) value);
-            break;
-        case SDL_GL_ACCUM_ALPHA_SIZE:
-            glGetIntegerv(GL_ACCUM_ALPHA_BITS, (GLint *) value);
-            break;
-        case SDL_GL_STEREO:
-        case SDL_GL_MULTISAMPLEBUFFERS:
-        case SDL_GL_MULTISAMPLESAMPLES:
-        default:
-            *value = 0;
-            return (-1);
+    SDL_Window *window = _this->windows;
+    while(window) {
+        SDL_BWin *bwin = _ToBeWin(window);
+        if(bwin->GetGLView()) {
+            bwin->LockLooper();
+            bwin->RemoveGLView();
+            bwin->CreateGLView(bwin->GetGLType());
+            bwin->UnlockLooper();
         }
-        return 0;
+        window = window->next;
     }
-
-#endif
-
+}
 
 
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* SDL_VIDEO_DRIVER_HAIKU */
+#endif /* SDL_VIDEO_DRIVER_HAIKU && SDL_VIDEO_OPENGL */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bopengl.h b/src/video/haiku/SDL_bopengl.h
index e7d475d..a8d2346 100644
--- a/src/video/haiku/SDL_bopengl.h
+++ b/src/video/haiku/SDL_bopengl.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,6 +22,8 @@
 #ifndef SDL_BOPENGL_H
 #define SDL_BOPENGL_H
 
+#if SDL_VIDEO_DRIVER_HAIKU && SDL_VIDEO_OPENGL
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -36,7 +38,7 @@ extern int BE_GL_MakeCurrent(_THIS, SDL_Window * window,
                               SDL_GLContext context);
 extern int BE_GL_SetSwapInterval(_THIS, int interval);                  /* TODO */
 extern int BE_GL_GetSwapInterval(_THIS);                                /* TODO */
-extern void BE_GL_SwapWindow(_THIS, SDL_Window * window);
+extern int BE_GL_SwapWindow(_THIS, SDL_Window * window);
 extern SDL_GLContext BE_GL_CreateContext(_THIS, SDL_Window * window);
 extern void BE_GL_DeleteContext(_THIS, SDL_GLContext context);
 
@@ -46,4 +48,8 @@ extern void BE_GL_RebootContexts(_THIS);
 }
 #endif
 
+#endif /* SDL_VIDEO_DRIVER_HAIKU && SDL_VIDEO_OPENGL */
+
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bvideo.cc b/src/video/haiku/SDL_bvideo.cc
index 8986c60..74f1274 100644
--- a/src/video/haiku/SDL_bvideo.cc
+++ b/src/video/haiku/SDL_bvideo.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -68,8 +68,8 @@ BE_CreateDevice(int devindex)
     device->SetDisplayMode = BE_SetDisplayMode;
     device->PumpEvents = BE_PumpEvents;
 
-    device->CreateWindow = BE_CreateWindow;
-    device->CreateWindowFrom = BE_CreateWindowFrom;
+    device->CreateSDLWindow = BE_CreateWindow;
+    device->CreateSDLWindowFrom = BE_CreateWindowFrom;
     device->SetWindowTitle = BE_SetWindowTitle;
     device->SetWindowIcon = BE_SetWindowIcon;
     device->SetWindowPosition = BE_SetWindowPosition;
@@ -96,7 +96,7 @@ BE_CreateDevice(int devindex)
     device->shape_driver.SetWindowShape = NULL;
     device->shape_driver.ResizeWindowShape = NULL;
 
-
+#if SDL_VIDEO_OPENGL
     device->GL_LoadLibrary = BE_GL_LoadLibrary;
     device->GL_GetProcAddress = BE_GL_GetProcAddress;
     device->GL_UnloadLibrary = BE_GL_UnloadLibrary;
@@ -106,6 +106,7 @@ BE_CreateDevice(int devindex)
     device->GL_GetSwapInterval = BE_GL_GetSwapInterval;
     device->GL_SwapWindow = BE_GL_SwapWindow;
     device->GL_DeleteContext = BE_GL_DeleteContext;
+#endif
 
     device->StartTextInput = BE_StartTextInput;
     device->StopTextInput = BE_StopTextInput;
@@ -173,3 +174,5 @@ void BE_VideoQuit(_THIS)
 #endif
 
 #endif /* SDL_VIDEO_DRIVER_HAIKU */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bvideo.h b/src/video/haiku/SDL_bvideo.h
index ef5c740..5972cb0 100644
--- a/src/video/haiku/SDL_bvideo.h
+++ b/src/video/haiku/SDL_bvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -40,3 +40,5 @@ extern int BE_Available(void);
 #endif
 
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bwindow.cc b/src/video/haiku/SDL_bwindow.cc
index a35471d..a2e9616 100644
--- a/src/video/haiku/SDL_bwindow.cc
+++ b/src/video/haiku/SDL_bwindow.cc
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -41,7 +41,7 @@ static SDL_INLINE SDL_BApp *_GetBeApp() {
 
 static int _InitWindow(_THIS, SDL_Window *window) {
 	uint32 flags = 0;
-	window_look look = B_BORDERED_WINDOW_LOOK;
+	window_look look = B_TITLED_WINDOW_LOOK;
 
 	BRect bounds(
         window->x,
@@ -66,7 +66,7 @@ static int _InitWindow(_THIS, SDL_Window *window) {
 
     SDL_BWin *bwin = new(std::nothrow) SDL_BWin(bounds, look, flags);
     if(bwin == NULL)
-    	return ENOMEM;
+        return -1;
 
     window->driverdata = bwin;
     int32 winID = _GetBeApp()->GetID(window);
@@ -76,8 +76,9 @@ static int _InitWindow(_THIS, SDL_Window *window) {
 }
 
 int BE_CreateWindow(_THIS, SDL_Window *window) {
-	if(_InitWindow(_this, window) == ENOMEM)
-		return ENOMEM;
+    if (_InitWindow(_this, window) < 0) {
+        return -1;
+    }
 	
 	/* Start window loop */
     _ToBeWin(window)->Show();
@@ -102,8 +103,9 @@ int BE_CreateWindowFrom(_THIS, SDL_Window * window, const void *data) {
 	}
 	
 	/* If we are out of memory, return the error code */
-	if(_InitWindow(_this, window) == ENOMEM)
-		return ENOMEM;
+    if (_InitWindow(_this, window) < 0) {
+        return -1;
+    }
 	
 	/* TODO: Add any other SDL-supported window attributes here */
     _ToBeWin(window)->SetTitle(otherBWin->Title());
@@ -227,3 +229,5 @@ SDL_bool BE_GetWindowWMInfo(_THIS, SDL_Window * window,
 #endif
 
 #endif /* SDL_VIDEO_DRIVER_HAIKU */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/haiku/SDL_bwindow.h b/src/video/haiku/SDL_bwindow.h
index 388443d..1a26af8 100644
--- a/src/video/haiku/SDL_bwindow.h
+++ b/src/video/haiku/SDL_bwindow.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -52,3 +52,4 @@ extern SDL_bool BE_GetWindowWMInfo(_THIS, SDL_Window * window,
 
 #endif
 
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/khronos/EGL/egl.h b/src/video/khronos/EGL/egl.h
new file mode 100644
index 0000000..93a2187
--- /dev/null
+++ b/src/video/khronos/EGL/egl.h
@@ -0,0 +1,303 @@
+#ifndef __egl_h_
+#define __egl_h_ 1
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** Copyright (c) 2013-2017 The Khronos Group Inc.
+**
+** Permission is hereby granted, free of charge, to any person obtaining a
+** copy of this software and/or associated documentation files (the
+** "Materials"), to deal in the Materials without restriction, including
+** without limitation the rights to use, copy, modify, merge, publish,
+** distribute, sublicense, and/or sell copies of the Materials, and to
+** permit persons to whom the Materials are 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 Materials.
+**
+** THE MATERIALS ARE 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
+** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
+*/
+/*
+** This header is generated from the Khronos OpenGL / OpenGL ES XML
+** API Registry. The current version of the Registry, generator scripts
+** used to make the header, and the header can be found at
+**   http://www.khronos.org/registry/egl
+**
+** Khronos $Git commit SHA1: a732b061e7 $ on $Git commit date: 2017-06-17 23:27:53 +0100 $
+*/
+
+#include <EGL/eglplatform.h>
+
+/* Generated on date 20170627 */
+
+/* Generated C header for:
+ * API: egl
+ * Versions considered: .*
+ * Versions emitted: .*
+ * Default extensions included: None
+ * Additional extensions included: _nomatch_^
+ * Extensions removed: _nomatch_^
+ */
+
+#ifndef EGL_VERSION_1_0
+#define EGL_VERSION_1_0 1
+typedef unsigned int EGLBoolean;
+typedef void *EGLDisplay;
+#include <KHR/khrplatform.h>
+#include <EGL/eglplatform.h>
+typedef void *EGLConfig;
+typedef void *EGLSurface;
+typedef void *EGLContext;
+typedef void (*__eglMustCastToProperFunctionPointerType)(void);
+#define EGL_ALPHA_SIZE                    0x3021
+#define EGL_BAD_ACCESS                    0x3002
+#define EGL_BAD_ALLOC                     0x3003
+#define EGL_BAD_ATTRIBUTE                 0x3004
+#define EGL_BAD_CONFIG                    0x3005
+#define EGL_BAD_CONTEXT                   0x3006
+#define EGL_BAD_CURRENT_SURFACE           0x3007
+#define EGL_BAD_DISPLAY                   0x3008
+#define EGL_BAD_MATCH                     0x3009
+#define EGL_BAD_NATIVE_PIXMAP             0x300A
+#define EGL_BAD_NATIVE_WINDOW             0x300B
+#define EGL_BAD_PARAMETER                 0x300C
+#define EGL_BAD_SURFACE                   0x300D
+#define EGL_BLUE_SIZE                     0x3022
+#define EGL_BUFFER_SIZE                   0x3020
+#define EGL_CONFIG_CAVEAT                 0x3027
+#define EGL_CONFIG_ID                     0x3028
+#define EGL_CORE_NATIVE_ENGINE            0x305B
+#define EGL_DEPTH_SIZE                    0x3025
+#define EGL_DONT_CARE                     EGL_CAST(EGLint,-1)
+#define EGL_DRAW                          0x3059
+#define EGL_EXTENSIONS                    0x3055
+#define EGL_FALSE                         0
+#define EGL_GREEN_SIZE                    0x3023
+#define EGL_HEIGHT                        0x3056
+#define EGL_LARGEST_PBUFFER               0x3058
+#define EGL_LEVEL                         0x3029
+#define EGL_MAX_PBUFFER_HEIGHT            0x302A
+#define EGL_MAX_PBUFFER_PIXELS            0x302B
+#define EGL_MAX_PBUFFER_WIDTH             0x302C
+#define EGL_NATIVE_RENDERABLE             0x302D
+#define EGL_NATIVE_VISUAL_ID              0x302E
+#define EGL_NATIVE_VISUAL_TYPE            0x302F
+#define EGL_NONE                          0x3038
+#define EGL_NON_CONFORMANT_CONFIG         0x3051
+#define EGL_NOT_INITIALIZED               0x3001
+#define EGL_NO_CONTEXT                    EGL_CAST(EGLContext,0)
+#define EGL_NO_DISPLAY                    EGL_CAST(EGLDisplay,0)
+#define EGL_NO_SURFACE                    EGL_CAST(EGLSurface,0)
+#define EGL_PBUFFER_BIT                   0x0001
+#define EGL_PIXMAP_BIT                    0x0002
+#define EGL_READ                          0x305A
+#define EGL_RED_SIZE                      0x3024
+#define EGL_SAMPLES                       0x3031
+#define EGL_SAMPLE_BUFFERS                0x3032
+#define EGL_SLOW_CONFIG                   0x3050
+#define EGL_STENCIL_SIZE                  0x3026
+#define EGL_SUCCESS                       0x3000
+#define EGL_SURFACE_TYPE                  0x3033
+#define EGL_TRANSPARENT_BLUE_VALUE        0x3035
+#define EGL_TRANSPARENT_GREEN_VALUE       0x3036
+#define EGL_TRANSPARENT_RED_VALUE         0x3037
+#define EGL_TRANSPARENT_RGB               0x3052
+#define EGL_TRANSPARENT_TYPE              0x3034
+#define EGL_TRUE                          1
+#define EGL_VENDOR                        0x3053
+#define EGL_VERSION                       0x3054
+#define EGL_WIDTH                         0x3057
+#define EGL_WINDOW_BIT                    0x0004
+EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig (EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config);
+EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers (EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target);
+EGLAPI EGLContext EGLAPIENTRY eglCreateContext (EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list);
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface (EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list);
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurface (EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list);
+EGLAPI EGLSurface EGLAPIENTRY eglCreateWindowSurface (EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroyContext (EGLDisplay dpy, EGLContext ctx);
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroySurface (EGLDisplay dpy, EGLSurface surface);
+EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigAttrib (EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value);
+EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigs (EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config);
+EGLAPI EGLDisplay EGLAPIENTRY eglGetCurrentDisplay (void);
+EGLAPI EGLSurface EGLAPIENTRY eglGetCurrentSurface (EGLint readdraw);
+EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay (EGLNativeDisplayType display_id);
+EGLAPI EGLint EGLAPIENTRY eglGetError (void);
+EGLAPI __eglMustCastToProperFunctionPointerType EGLAPIENTRY eglGetProcAddress (const char *procname);
+EGLAPI EGLBoolean EGLAPIENTRY eglInitialize (EGLDisplay dpy, EGLint *major, EGLint *minor);
+EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent (EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryContext (EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint *value);
+EGLAPI const char *EGLAPIENTRY eglQueryString (EGLDisplay dpy, EGLint name);
+EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value);
+EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers (EGLDisplay dpy, EGLSurface surface);
+EGLAPI EGLBoolean EGLAPIENTRY eglTerminate (EGLDisplay dpy);
+EGLAPI EGLBoolean EGLAPIENTRY eglWaitGL (void);
+EGLAPI EGLBoolean EGLAPIENTRY eglWaitNative (EGLint engine);
+#endif /* EGL_VERSION_1_0 */
+
+#ifndef EGL_VERSION_1_1
+#define EGL_VERSION_1_1 1
+#define EGL_BACK_BUFFER                   0x3084
+#define EGL_BIND_TO_TEXTURE_RGB           0x3039
+#define EGL_BIND_TO_TEXTURE_RGBA          0x303A
+#define EGL_CONTEXT_LOST                  0x300E
+#define EGL_MIN_SWAP_INTERVAL             0x303B
+#define EGL_MAX_SWAP_INTERVAL             0x303C
+#define EGL_MIPMAP_TEXTURE                0x3082
+#define EGL_MIPMAP_LEVEL                  0x3083
+#define EGL_NO_TEXTURE                    0x305C
+#define EGL_TEXTURE_2D                    0x305F
+#define EGL_TEXTURE_FORMAT                0x3080
+#define EGL_TEXTURE_RGB                   0x305D
+#define EGL_TEXTURE_RGBA                  0x305E
+#define EGL_TEXTURE_TARGET                0x3081
+EGLAPI EGLBoolean EGLAPIENTRY eglBindTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer);
+EGLAPI EGLBoolean EGLAPIENTRY eglReleaseTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer);
+EGLAPI EGLBoolean EGLAPIENTRY eglSurfaceAttrib (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value);
+EGLAPI EGLBoolean EGLAPIENTRY eglSwapInterval (EGLDisplay dpy, EGLint interval);
+#endif /* EGL_VERSION_1_1 */
+
+#ifndef EGL_VERSION_1_2
+#define EGL_VERSION_1_2 1
+typedef unsigned int EGLenum;
+typedef void *EGLClientBuffer;
+#define EGL_ALPHA_FORMAT                  0x3088
+#define EGL_ALPHA_FORMAT_NONPRE           0x308B
+#define EGL_ALPHA_FORMAT_PRE              0x308C
+#define EGL_ALPHA_MASK_SIZE               0x303E
+#define EGL_BUFFER_PRESERVED              0x3094
+#define EGL_BUFFER_DESTROYED              0x3095
+#define EGL_CLIENT_APIS                   0x308D
+#define EGL_COLORSPACE                    0x3087
+#define EGL_COLORSPACE_sRGB               0x3089
+#define EGL_COLORSPACE_LINEAR             0x308A
+#define EGL_COLOR_BUFFER_TYPE             0x303F
+#define EGL_CONTEXT_CLIENT_TYPE           0x3097
+#define EGL_DISPLAY_SCALING               10000
+#define EGL_HORIZONTAL_RESOLUTION         0x3090
+#define EGL_LUMINANCE_BUFFER              0x308F
+#define EGL_LUMINANCE_SIZE                0x303D
+#define EGL_OPENGL_ES_BIT                 0x0001
+#define EGL_OPENVG_BIT                    0x0002
+#define EGL_OPENGL_ES_API                 0x30A0
+#define EGL_OPENVG_API                    0x30A1
+#define EGL_OPENVG_IMAGE                  0x3096
+#define EGL_PIXEL_ASPECT_RATIO            0x3092
+#define EGL_RENDERABLE_TYPE               0x3040
+#define EGL_RENDER_BUFFER                 0x3086
+#define EGL_RGB_BUFFER                    0x308E
+#define EGL_SINGLE_BUFFER                 0x3085
+#define EGL_SWAP_BEHAVIOR                 0x3093
+#define EGL_UNKNOWN                       EGL_CAST(EGLint,-1)
+#define EGL_VERTICAL_RESOLUTION           0x3091
+EGLAPI EGLBoolean EGLAPIENTRY eglBindAPI (EGLenum api);
+EGLAPI EGLenum EGLAPIENTRY eglQueryAPI (void);
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer (EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglReleaseThread (void);
+EGLAPI EGLBoolean EGLAPIENTRY eglWaitClient (void);
+#endif /* EGL_VERSION_1_2 */
+
+#ifndef EGL_VERSION_1_3
+#define EGL_VERSION_1_3 1
+#define EGL_CONFORMANT                    0x3042
+#define EGL_CONTEXT_CLIENT_VERSION        0x3098
+#define EGL_MATCH_NATIVE_PIXMAP           0x3041
+#define EGL_OPENGL_ES2_BIT                0x0004
+#define EGL_VG_ALPHA_FORMAT               0x3088
+#define EGL_VG_ALPHA_FORMAT_NONPRE        0x308B
+#define EGL_VG_ALPHA_FORMAT_PRE           0x308C
+#define EGL_VG_ALPHA_FORMAT_PRE_BIT       0x0040
+#define EGL_VG_COLORSPACE                 0x3087
+#define EGL_VG_COLORSPACE_sRGB            0x3089
+#define EGL_VG_COLORSPACE_LINEAR          0x308A
+#define EGL_VG_COLORSPACE_LINEAR_BIT      0x0020
+#endif /* EGL_VERSION_1_3 */
+
+#ifndef EGL_VERSION_1_4
+#define EGL_VERSION_1_4 1
+#define EGL_DEFAULT_DISPLAY               EGL_CAST(EGLNativeDisplayType,0)
+#define EGL_MULTISAMPLE_RESOLVE_BOX_BIT   0x0200
+#define EGL_MULTISAMPLE_RESOLVE           0x3099
+#define EGL_MULTISAMPLE_RESOLVE_DEFAULT   0x309A
+#define EGL_MULTISAMPLE_RESOLVE_BOX       0x309B
+#define EGL_OPENGL_API                    0x30A2
+#define EGL_OPENGL_BIT                    0x0008
+#define EGL_SWAP_BEHAVIOR_PRESERVED_BIT   0x0400
+EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext (void);
+#endif /* EGL_VERSION_1_4 */
+
+#ifndef EGL_VERSION_1_5
+#define EGL_VERSION_1_5 1
+typedef void *EGLSync;
+typedef intptr_t EGLAttrib;
+typedef khronos_utime_nanoseconds_t EGLTime;
+typedef void *EGLImage;
+#define EGL_CONTEXT_MAJOR_VERSION         0x3098
+#define EGL_CONTEXT_MINOR_VERSION         0x30FB
+#define EGL_CONTEXT_OPENGL_PROFILE_MASK   0x30FD
+#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY 0x31BD
+#define EGL_NO_RESET_NOTIFICATION         0x31BE
+#define EGL_LOSE_CONTEXT_ON_RESET         0x31BF
+#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT 0x00000001
+#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT 0x00000002
+#define EGL_CONTEXT_OPENGL_DEBUG          0x31B0
+#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE 0x31B1
+#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS  0x31B2
+#define EGL_OPENGL_ES3_BIT                0x00000040
+#define EGL_CL_EVENT_HANDLE               0x309C
+#define EGL_SYNC_CL_EVENT                 0x30FE
+#define EGL_SYNC_CL_EVENT_COMPLETE        0x30FF
+#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE  0x30F0
+#define EGL_SYNC_TYPE                     0x30F7
+#define EGL_SYNC_STATUS                   0x30F1
+#define EGL_SYNC_CONDITION                0x30F8
+#define EGL_SIGNALED                      0x30F2
+#define EGL_UNSIGNALED                    0x30F3
+#define EGL_SYNC_FLUSH_COMMANDS_BIT       0x0001
+#define EGL_FOREVER                       0xFFFFFFFFFFFFFFFFull
+#define EGL_TIMEOUT_EXPIRED               0x30F5
+#define EGL_CONDITION_SATISFIED           0x30F6
+#define EGL_NO_SYNC                       EGL_CAST(EGLSync,0)
+#define EGL_SYNC_FENCE                    0x30F9
+#define EGL_GL_COLORSPACE                 0x309D
+#define EGL_GL_COLORSPACE_SRGB            0x3089
+#define EGL_GL_COLORSPACE_LINEAR          0x308A
+#define EGL_GL_RENDERBUFFER               0x30B9
+#define EGL_GL_TEXTURE_2D                 0x30B1
+#define EGL_GL_TEXTURE_LEVEL              0x30BC
+#define EGL_GL_TEXTURE_3D                 0x30B2
+#define EGL_GL_TEXTURE_ZOFFSET            0x30BD
+#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x30B3
+#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x30B4
+#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x30B5
+#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x30B6
+#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x30B7
+#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x30B8
+#define EGL_IMAGE_PRESERVED               0x30D2
+#define EGL_NO_IMAGE                      EGL_CAST(EGLImage,0)
+EGLAPI EGLSync EGLAPIENTRY eglCreateSync (EGLDisplay dpy, EGLenum type, const EGLAttrib *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroySync (EGLDisplay dpy, EGLSync sync);
+EGLAPI EGLint EGLAPIENTRY eglClientWaitSync (EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout);
+EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttrib (EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib *value);
+EGLAPI EGLImage EGLAPIENTRY eglCreateImage (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLAttrib *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImage (EGLDisplay dpy, EGLImage image);
+EGLAPI EGLDisplay EGLAPIENTRY eglGetPlatformDisplay (EGLenum platform, void *native_display, const EGLAttrib *attrib_list);
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformWindowSurface (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLAttrib *attrib_list);
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformPixmapSurface (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLAttrib *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglWaitSync (EGLDisplay dpy, EGLSync sync, EGLint flags);
+#endif /* EGL_VERSION_1_5 */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/SDL_egl.h b/src/video/khronos/EGL/eglext.h
similarity index 55%
copy from include/SDL_egl.h
copy to src/video/khronos/EGL/eglext.h
index bea2a6c..d2def03 100644
--- a/include/SDL_egl.h
+++ b/src/video/khronos/EGL/eglext.h
@@ -1,787 +1,3 @@
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
-
-  This software is provided 'as-is', without any express or implied
-  warranty.  In no event will the authors be held liable for any damages
-  arising from the use of this software.
-
-  Permission is granted to anyone to use this software for any purpose,
-  including commercial applications, and to alter it and redistribute it
-  freely, subject to the following restrictions:
-
-  1. The origin of this software must not be misrepresented; you must not
-     claim that you wrote the original software. If you use this software
-     in a product, an acknowledgment in the product documentation would be
-     appreciated but is not required.
-  2. Altered source versions must be plainly marked as such, and must not be
-     misrepresented as being the original software.
-  3. This notice may not be removed or altered from any source distribution.
-*/
-
-/**
- *  \file SDL_egl.h
- *
- *  This is a simple file to encapsulate the EGL API headers.
- */
-#ifndef _MSC_VER
-
-#include <EGL/egl.h>
-#include <EGL/eglext.h>
-
-#else /* _MSC_VER */
-
-/* EGL headers for Visual Studio */
-
-#ifndef __khrplatform_h_
-#define __khrplatform_h_
-
-/*
-** Copyright (c) 2008-2009 The Khronos Group Inc.
-**
-** Permission is hereby granted, free of charge, to any person obtaining a
-** copy of this software and/or associated documentation files (the
-** "Materials"), to deal in the Materials without restriction, including
-** without limitation the rights to use, copy, modify, merge, publish,
-** distribute, sublicense, and/or sell copies of the Materials, and to
-** permit persons to whom the Materials are 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 Materials.
-**
-** THE MATERIALS ARE 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
-** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
-*/
-
-/* Khronos platform-specific types and definitions.
-*
-* $Revision: 23298 $ on $Date: 2013-09-30 17:07:13 -0700 (Mon, 30 Sep 2013) $
-*
-* Adopters may modify this file to suit their platform. Adopters are
-* encouraged to submit platform specific modifications to the Khronos
-* group so that they can be included in future versions of this file.
-* Please submit changes by sending them to the public Khronos Bugzilla
-* (http://khronos.org/bugzilla) by filing a bug against product
-* "Khronos (general)" component "Registry".
-*
-* A predefined template which fills in some of the bug fields can be
-* reached using http://tinyurl.com/khrplatform-h-bugreport, but you
-* must create a Bugzilla login first.
-*
-*
-* See the Implementer's Guidelines for information about where this file
-* should be located on your system and for more details of its use:
-*    http://www.khronos.org/registry/implementers_guide.pdf
-*
-* This file should be included as
-*        #include <KHR/khrplatform.h>
-* by Khronos client API header files that use its types and defines.
-*
-* The types in khrplatform.h should only be used to define API-specific types.
-*
-* Types defined in khrplatform.h:
-*    khronos_int8_t              signed   8  bit
-*    khronos_uint8_t             unsigned 8  bit
-*    khronos_int16_t             signed   16 bit
-*    khronos_uint16_t            unsigned 16 bit
-*    khronos_int32_t             signed   32 bit
-*    khronos_uint32_t            unsigned 32 bit
-*    khronos_int64_t             signed   64 bit
-*    khronos_uint64_t            unsigned 64 bit
-*    khronos_intptr_t            signed   same number of bits as a pointer
-*    khronos_uintptr_t           unsigned same number of bits as a pointer
-*    khronos_ssize_t             signed   size
-*    khronos_usize_t             unsigned size
-*    khronos_float_t             signed   32 bit floating point
-*    khronos_time_ns_t           unsigned 64 bit time in nanoseconds
-*    khronos_utime_nanoseconds_t unsigned time interval or absolute time in
-*                                         nanoseconds
-*    khronos_stime_nanoseconds_t signed time interval in nanoseconds
-*    khronos_boolean_enum_t      enumerated boolean type. This should
-*      only be used as a base type when a client API's boolean type is
-*      an enum. Client APIs which use an integer or other type for
-*      booleans cannot use this as the base type for their boolean.
-*
-* Tokens defined in khrplatform.h:
-*
-*    KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
-*
-*    KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
-*    KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
-*
-* Calling convention macros defined in this file:
-*    KHRONOS_APICALL
-*    KHRONOS_APIENTRY
-*    KHRONOS_APIATTRIBUTES
-*
-* These may be used in function prototypes as:
-*
-*      KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
-*                                  int arg1,
-*                                  int arg2) KHRONOS_APIATTRIBUTES;
-*/
-
-/*-------------------------------------------------------------------------
-* Definition of KHRONOS_APICALL
-*-------------------------------------------------------------------------
-* This precedes the return type of the function in the function prototype.
-*/
-#if defined(_WIN32) && !defined(__SCITECH_SNAP__)
-#   define KHRONOS_APICALL __declspec(dllimport)
-#elif defined (__SYMBIAN32__)
-#   define KHRONOS_APICALL IMPORT_C
-#else
-#   define KHRONOS_APICALL
-#endif
-
-/*-------------------------------------------------------------------------
-* Definition of KHRONOS_APIENTRY
-*-------------------------------------------------------------------------
-* This follows the return type of the function  and precedes the function
-* name in the function prototype.
-*/
-#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
-/* Win32 but not WinCE */
-#   define KHRONOS_APIENTRY __stdcall
-#else
-#   define KHRONOS_APIENTRY
-#endif
-
-/*-------------------------------------------------------------------------
-* Definition of KHRONOS_APIATTRIBUTES
-*-------------------------------------------------------------------------
-* This follows the closing parenthesis of the function prototype arguments.
-*/
-#if defined (__ARMCC_2__)
-#define KHRONOS_APIATTRIBUTES __softfp
-#else
-#define KHRONOS_APIATTRIBUTES
-#endif
-
-/*-------------------------------------------------------------------------
-* basic type definitions
-*-----------------------------------------------------------------------*/
-#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
-
-
-/*
-* Using <stdint.h>
-*/
-#include <stdint.h>
-typedef int32_t                 khronos_int32_t;
-typedef uint32_t                khronos_uint32_t;
-typedef int64_t                 khronos_int64_t;
-typedef uint64_t                khronos_uint64_t;
-#define KHRONOS_SUPPORT_INT64   1
-#define KHRONOS_SUPPORT_FLOAT   1
-
-#elif defined(__VMS ) || defined(__sgi)
-
-/*
-* Using <inttypes.h>
-*/
-#include <inttypes.h>
-typedef int32_t                 khronos_int32_t;
-typedef uint32_t                khronos_uint32_t;
-typedef int64_t                 khronos_int64_t;
-typedef uint64_t                khronos_uint64_t;
-#define KHRONOS_SUPPORT_INT64   1
-#define KHRONOS_SUPPORT_FLOAT   1
-
-#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
-
-/*
-* Win32
-*/
-typedef __int32                 khronos_int32_t;
-typedef unsigned __int32        khronos_uint32_t;
-typedef __int64                 khronos_int64_t;
-typedef unsigned __int64        khronos_uint64_t;
-#define KHRONOS_SUPPORT_INT64   1
-#define KHRONOS_SUPPORT_FLOAT   1
-
-#elif defined(__sun__) || defined(__digital__)
-
-/*
-* Sun or Digital
-*/
-typedef int                     khronos_int32_t;
-typedef unsigned int            khronos_uint32_t;
-#if defined(__arch64__) || defined(_LP64)
-typedef long int                khronos_int64_t;
-typedef unsigned long int       khronos_uint64_t;
-#else
-typedef long long int           khronos_int64_t;
-typedef unsigned long long int  khronos_uint64_t;
-#endif /* __arch64__ */
-#define KHRONOS_SUPPORT_INT64   1
-#define KHRONOS_SUPPORT_FLOAT   1
-
-#elif 0
-
-/*
-* Hypothetical platform with no float or int64 support
-*/
-typedef int                     khronos_int32_t;
-typedef unsigned int            khronos_uint32_t;
-#define KHRONOS_SUPPORT_INT64   0
-#define KHRONOS_SUPPORT_FLOAT   0
-
-#else
-
-/*
-* Generic fallback
-*/
-#include <stdint.h>
-typedef int32_t                 khronos_int32_t;
-typedef uint32_t                khronos_uint32_t;
-typedef int64_t                 khronos_int64_t;
-typedef uint64_t                khronos_uint64_t;
-#define KHRONOS_SUPPORT_INT64   1
-#define KHRONOS_SUPPORT_FLOAT   1
-
-#endif
-
-
-/*
-* Types that are (so far) the same on all platforms
-*/
-typedef signed   char          khronos_int8_t;
-typedef unsigned char          khronos_uint8_t;
-typedef signed   short int     khronos_int16_t;
-typedef unsigned short int     khronos_uint16_t;
-
-/*
-* Types that differ between LLP64 and LP64 architectures - in LLP64,
-* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
-* to be the only LLP64 architecture in current use.
-*/
-#ifdef _WIN64
-typedef signed   long long int khronos_intptr_t;
-typedef unsigned long long int khronos_uintptr_t;
-typedef signed   long long int khronos_ssize_t;
-typedef unsigned long long int khronos_usize_t;
-#else
-typedef signed   long  int     khronos_intptr_t;
-typedef unsigned long  int     khronos_uintptr_t;
-typedef signed   long  int     khronos_ssize_t;
-typedef unsigned long  int     khronos_usize_t;
-#endif
-
-#if KHRONOS_SUPPORT_FLOAT
-/*
-* Float type
-*/
-typedef          float         khronos_float_t;
-#endif
-
-#if KHRONOS_SUPPORT_INT64
-/* Time types
-*
-* These types can be used to represent a time interval in nanoseconds or
-* an absolute Unadjusted System Time.  Unadjusted System Time is the number
-* of nanoseconds since some arbitrary system event (e.g. since the last
-* time the system booted).  The Unadjusted System Time is an unsigned
-* 64 bit value that wraps back to 0 every 584 years.  Time intervals
-* may be either signed or unsigned.
-*/
-typedef khronos_uint64_t       khronos_utime_nanoseconds_t;
-typedef khronos_int64_t        khronos_stime_nanoseconds_t;
-#endif
-
-/*
-* Dummy value used to pad enum types to 32 bits.
-*/
-#ifndef KHRONOS_MAX_ENUM
-#define KHRONOS_MAX_ENUM 0x7FFFFFFF
-#endif
-
-/*
-* Enumerated boolean type
-*
-* Values other than zero should be considered to be true.  Therefore
-* comparisons should not be made against KHRONOS_TRUE.
-*/
-typedef enum {
-    KHRONOS_FALSE = 0,
-    KHRONOS_TRUE = 1,
-    KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
-} khronos_boolean_enum_t;
-
-#endif /* __khrplatform_h_ */
-
-
-#ifndef __eglplatform_h_
-#define __eglplatform_h_
-
-/*
-** Copyright (c) 2007-2009 The Khronos Group Inc.
-**
-** Permission is hereby granted, free of charge, to any person obtaining a
-** copy of this software and/or associated documentation files (the
-** "Materials"), to deal in the Materials without restriction, including
-** without limitation the rights to use, copy, modify, merge, publish,
-** distribute, sublicense, and/or sell copies of the Materials, and to
-** permit persons to whom the Materials are 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 Materials.
-**
-** THE MATERIALS ARE 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
-** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
-*/
-
-/* Platform-specific types and definitions for egl.h
-* $Revision: 12306 $ on $Date: 2010-08-25 09:51:28 -0700 (Wed, 25 Aug 2010) $
-*
-* Adopters may modify khrplatform.h and this file to suit their platform.
-* You are encouraged to submit all modifications to the Khronos group so that
-* they can be included in future versions of this file.  Please submit changes
-* by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla)
-* by filing a bug against product "EGL" component "Registry".
-*/
-
-/*#include <KHR/khrplatform.h>*/
-
-/* Macros used in EGL function prototype declarations.
-*
-* EGL functions should be prototyped as:
-*
-* EGLAPI return-type EGLAPIENTRY eglFunction(arguments);
-* typedef return-type (EXPAPIENTRYP PFNEGLFUNCTIONPROC) (arguments);
-*
-* KHRONOS_APICALL and KHRONOS_APIENTRY are defined in KHR/khrplatform.h
-*/
-
-#ifndef EGLAPI
-#define EGLAPI KHRONOS_APICALL
-#endif
-
-#ifndef EGLAPIENTRY
-#define EGLAPIENTRY  KHRONOS_APIENTRY
-#endif
-#define EGLAPIENTRYP EGLAPIENTRY*
-
-/* The types NativeDisplayType, NativeWindowType, and NativePixmapType
-* are aliases of window-system-dependent types, such as X Display * or
-* Windows Device Context. They must be defined in platform-specific
-* code below. The EGL-prefixed versions of Native*Type are the same
-* types, renamed in EGL 1.3 so all types in the API start with "EGL".
-*
-* Khronos STRONGLY RECOMMENDS that you use the default definitions
-* provided below, since these changes affect both binary and source
-* portability of applications using EGL running on different EGL
-* implementations.
-*/
-
-#if defined(_WIN32) || defined(__VC32__) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) /* Win32 and WinCE */
-#ifndef WIN32_LEAN_AND_MEAN
-#define WIN32_LEAN_AND_MEAN 1
-#endif
-#include <windows.h>
-
-#if __WINRT__
-#include <Unknwn.h>
-typedef IUnknown * EGLNativeWindowType;
-typedef IUnknown * EGLNativePixmapType;
-typedef IUnknown * EGLNativeDisplayType;
-#else
-typedef HDC     EGLNativeDisplayType;
-typedef HBITMAP EGLNativePixmapType;
-typedef HWND    EGLNativeWindowType;
-#endif
-
-#elif defined(__WINSCW__) || defined(__SYMBIAN32__)  /* Symbian */
-
-typedef int   EGLNativeDisplayType;
-typedef void *EGLNativeWindowType;
-typedef void *EGLNativePixmapType;
-
-#elif defined(WL_EGL_PLATFORM)
-
-typedef struct wl_display     *EGLNativeDisplayType;
-typedef struct wl_egl_pixmap  *EGLNativePixmapType;
-typedef struct wl_egl_window  *EGLNativeWindowType;
-
-#elif defined(__GBM__)
-
-typedef struct gbm_device  *EGLNativeDisplayType;
-typedef struct gbm_bo      *EGLNativePixmapType;
-typedef void               *EGLNativeWindowType;
-
-#elif defined(__ANDROID__) /* Android */
-
-struct ANativeWindow;
-struct egl_native_pixmap_t;
-
-typedef struct ANativeWindow        *EGLNativeWindowType;
-typedef struct egl_native_pixmap_t  *EGLNativePixmapType;
-typedef void                        *EGLNativeDisplayType;
-
-#elif defined(MIR_EGL_PLATFORM)
-
-#include <mir_toolkit/mir_client_library.h>
-typedef MirEGLNativeDisplayType EGLNativeDisplayType;
-typedef void                   *EGLNativePixmapType;
-typedef MirEGLNativeWindowType  EGLNativeWindowType;
-
-#elif defined(__unix__)
-
-#ifdef MESA_EGL_NO_X11_HEADERS
-
-typedef void            *EGLNativeDisplayType;
-typedef khronos_uintptr_t EGLNativePixmapType;
-typedef khronos_uintptr_t EGLNativeWindowType;
-
-#else
-
-/* X11 (tentative)  */
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-
-typedef Display *EGLNativeDisplayType;
-typedef Pixmap   EGLNativePixmapType;
-typedef Window   EGLNativeWindowType;
-
-#endif /* MESA_EGL_NO_X11_HEADERS */
-
-#else
-#error "Platform not recognized"
-#endif
-
-/* EGL 1.2 types, renamed for consistency in EGL 1.3 */
-typedef EGLNativeDisplayType NativeDisplayType;
-typedef EGLNativePixmapType  NativePixmapType;
-typedef EGLNativeWindowType  NativeWindowType;
-
-
-/* Define EGLint. This must be a signed integral type large enough to contain
-* all legal attribute names and values passed into and out of EGL, whether
-* their type is boolean, bitmask, enumerant (symbolic constant), integer,
-* handle, or other.  While in general a 32-bit integer will suffice, if
-* handles are 64 bit types, then EGLint should be defined as a signed 64-bit
-* integer type.
-*/
-typedef khronos_int32_t EGLint;
-
-#endif /* __eglplatform_h */
-
-#ifndef __egl_h_
-#define __egl_h_ 1
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
-** Copyright (c) 2013-2015 The Khronos Group Inc.
-**
-** Permission is hereby granted, free of charge, to any person obtaining a
-** copy of this software and/or associated documentation files (the
-** "Materials"), to deal in the Materials without restriction, including
-** without limitation the rights to use, copy, modify, merge, publish,
-** distribute, sublicense, and/or sell copies of the Materials, and to
-** permit persons to whom the Materials are 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 Materials.
-**
-** THE MATERIALS ARE 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
-** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
-*/
-/*
-** This header is generated from the Khronos OpenGL / OpenGL ES XML
-** API Registry. The current version of the Registry, generator scripts
-** used to make the header, and the header can be found at
-**   http://www.opengl.org/registry/
-**
-** Khronos $Revision: 31566 $ on $Date: 2015-06-23 08:48:48 -0700 (Tue, 23 Jun 2015) $
-*/
-
-/*#include <EGL/eglplatform.h>*/
-
-/* Generated on date 20150623 */
-
-/* Generated C header for:
- * API: egl
- * Versions considered: .*
- * Versions emitted: .*
- * Default extensions included: None
- * Additional extensions included: _nomatch_^
- * Extensions removed: _nomatch_^
- */
-
-#ifndef EGL_VERSION_1_0
-#define EGL_VERSION_1_0 1
-typedef unsigned int EGLBoolean;
-typedef void *EGLDisplay;
-typedef void *EGLConfig;
-typedef void *EGLSurface;
-typedef void *EGLContext;
-typedef void (*__eglMustCastToProperFunctionPointerType)(void);
-#define EGL_ALPHA_SIZE                    0x3021
-#define EGL_BAD_ACCESS                    0x3002
-#define EGL_BAD_ALLOC                     0x3003
-#define EGL_BAD_ATTRIBUTE                 0x3004
-#define EGL_BAD_CONFIG                    0x3005
-#define EGL_BAD_CONTEXT                   0x3006
-#define EGL_BAD_CURRENT_SURFACE           0x3007
-#define EGL_BAD_DISPLAY                   0x3008
-#define EGL_BAD_MATCH                     0x3009
-#define EGL_BAD_NATIVE_PIXMAP             0x300A
-#define EGL_BAD_NATIVE_WINDOW             0x300B
-#define EGL_BAD_PARAMETER                 0x300C
-#define EGL_BAD_SURFACE                   0x300D
-#define EGL_BLUE_SIZE                     0x3022
-#define EGL_BUFFER_SIZE                   0x3020
-#define EGL_CONFIG_CAVEAT                 0x3027
-#define EGL_CONFIG_ID                     0x3028
-#define EGL_CORE_NATIVE_ENGINE            0x305B
-#define EGL_DEPTH_SIZE                    0x3025
-#define EGL_DONT_CARE                     ((EGLint)-1)
-#define EGL_DRAW                          0x3059
-#define EGL_EXTENSIONS                    0x3055
-#define EGL_FALSE                         0
-#define EGL_GREEN_SIZE                    0x3023
-#define EGL_HEIGHT                        0x3056
-#define EGL_LARGEST_PBUFFER               0x3058
-#define EGL_LEVEL                         0x3029
-#define EGL_MAX_PBUFFER_HEIGHT            0x302A
-#define EGL_MAX_PBUFFER_PIXELS            0x302B
-#define EGL_MAX_PBUFFER_WIDTH             0x302C
-#define EGL_NATIVE_RENDERABLE             0x302D
-#define EGL_NATIVE_VISUAL_ID              0x302E
-#define EGL_NATIVE_VISUAL_TYPE            0x302F
-#define EGL_NONE                          0x3038
-#define EGL_NON_CONFORMANT_CONFIG         0x3051
-#define EGL_NOT_INITIALIZED               0x3001
-#define EGL_NO_CONTEXT                    ((EGLContext)0)
-#define EGL_NO_DISPLAY                    ((EGLDisplay)0)
-#define EGL_NO_SURFACE                    ((EGLSurface)0)
-#define EGL_PBUFFER_BIT                   0x0001
-#define EGL_PIXMAP_BIT                    0x0002
-#define EGL_READ                          0x305A
-#define EGL_RED_SIZE                      0x3024
-#define EGL_SAMPLES                       0x3031
-#define EGL_SAMPLE_BUFFERS                0x3032
-#define EGL_SLOW_CONFIG                   0x3050
-#define EGL_STENCIL_SIZE                  0x3026
-#define EGL_SUCCESS                       0x3000
-#define EGL_SURFACE_TYPE                  0x3033
-#define EGL_TRANSPARENT_BLUE_VALUE        0x3035
-#define EGL_TRANSPARENT_GREEN_VALUE       0x3036
-#define EGL_TRANSPARENT_RED_VALUE         0x3037
-#define EGL_TRANSPARENT_RGB               0x3052
-#define EGL_TRANSPARENT_TYPE              0x3034
-#define EGL_TRUE                          1
-#define EGL_VENDOR                        0x3053
-#define EGL_VERSION                       0x3054
-#define EGL_WIDTH                         0x3057
-#define EGL_WINDOW_BIT                    0x0004
-EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig (EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config);
-EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers (EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target);
-EGLAPI EGLContext EGLAPIENTRY eglCreateContext (EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list);
-EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface (EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list);
-EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurface (EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list);
-EGLAPI EGLSurface EGLAPIENTRY eglCreateWindowSurface (EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list);
-EGLAPI EGLBoolean EGLAPIENTRY eglDestroyContext (EGLDisplay dpy, EGLContext ctx);
-EGLAPI EGLBoolean EGLAPIENTRY eglDestroySurface (EGLDisplay dpy, EGLSurface surface);
-EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigAttrib (EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value);
-EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigs (EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config);
-EGLAPI EGLDisplay EGLAPIENTRY eglGetCurrentDisplay (void);
-EGLAPI EGLSurface EGLAPIENTRY eglGetCurrentSurface (EGLint readdraw);
-EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay (EGLNativeDisplayType display_id);
-EGLAPI EGLint EGLAPIENTRY eglGetError (void);
-EGLAPI __eglMustCastToProperFunctionPointerType EGLAPIENTRY eglGetProcAddress (const char *procname);
-EGLAPI EGLBoolean EGLAPIENTRY eglInitialize (EGLDisplay dpy, EGLint *major, EGLint *minor);
-EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent (EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx);
-EGLAPI EGLBoolean EGLAPIENTRY eglQueryContext (EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint *value);
-EGLAPI const char *EGLAPIENTRY eglQueryString (EGLDisplay dpy, EGLint name);
-EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value);
-EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers (EGLDisplay dpy, EGLSurface surface);
-EGLAPI EGLBoolean EGLAPIENTRY eglTerminate (EGLDisplay dpy);
-EGLAPI EGLBoolean EGLAPIENTRY eglWaitGL (void);
-EGLAPI EGLBoolean EGLAPIENTRY eglWaitNative (EGLint engine);
-#endif /* EGL_VERSION_1_0 */
-
-#ifndef EGL_VERSION_1_1
-#define EGL_VERSION_1_1 1
-#define EGL_BACK_BUFFER                   0x3084
-#define EGL_BIND_TO_TEXTURE_RGB           0x3039
-#define EGL_BIND_TO_TEXTURE_RGBA          0x303A
-#define EGL_CONTEXT_LOST                  0x300E
-#define EGL_MIN_SWAP_INTERVAL             0x303B
-#define EGL_MAX_SWAP_INTERVAL             0x303C
-#define EGL_MIPMAP_TEXTURE                0x3082
-#define EGL_MIPMAP_LEVEL                  0x3083
-#define EGL_NO_TEXTURE                    0x305C
-#define EGL_TEXTURE_2D                    0x305F
-#define EGL_TEXTURE_FORMAT                0x3080
-#define EGL_TEXTURE_RGB                   0x305D
-#define EGL_TEXTURE_RGBA                  0x305E
-#define EGL_TEXTURE_TARGET                0x3081
-EGLAPI EGLBoolean EGLAPIENTRY eglBindTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer);
-EGLAPI EGLBoolean EGLAPIENTRY eglReleaseTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer);
-EGLAPI EGLBoolean EGLAPIENTRY eglSurfaceAttrib (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value);
-EGLAPI EGLBoolean EGLAPIENTRY eglSwapInterval (EGLDisplay dpy, EGLint interval);
-#endif /* EGL_VERSION_1_1 */
-
-#ifndef EGL_VERSION_1_2
-#define EGL_VERSION_1_2 1
-typedef unsigned int EGLenum;
-typedef void *EGLClientBuffer;
-#define EGL_ALPHA_FORMAT                  0x3088
-#define EGL_ALPHA_FORMAT_NONPRE           0x308B
-#define EGL_ALPHA_FORMAT_PRE              0x308C
-#define EGL_ALPHA_MASK_SIZE               0x303E
-#define EGL_BUFFER_PRESERVED              0x3094
-#define EGL_BUFFER_DESTROYED              0x3095
-#define EGL_CLIENT_APIS                   0x308D
-#define EGL_COLORSPACE                    0x3087
-#define EGL_COLORSPACE_sRGB               0x3089
-#define EGL_COLORSPACE_LINEAR             0x308A
-#define EGL_COLOR_BUFFER_TYPE             0x303F
-#define EGL_CONTEXT_CLIENT_TYPE           0x3097
-#define EGL_DISPLAY_SCALING               10000
-#define EGL_HORIZONTAL_RESOLUTION         0x3090
-#define EGL_LUMINANCE_BUFFER              0x308F
-#define EGL_LUMINANCE_SIZE                0x303D
-#define EGL_OPENGL_ES_BIT                 0x0001
-#define EGL_OPENVG_BIT                    0x0002
-#define EGL_OPENGL_ES_API                 0x30A0
-#define EGL_OPENVG_API                    0x30A1
-#define EGL_OPENVG_IMAGE                  0x3096
-#define EGL_PIXEL_ASPECT_RATIO            0x3092
-#define EGL_RENDERABLE_TYPE               0x3040
-#define EGL_RENDER_BUFFER                 0x3086
-#define EGL_RGB_BUFFER                    0x308E
-#define EGL_SINGLE_BUFFER                 0x3085
-#define EGL_SWAP_BEHAVIOR                 0x3093
-#define EGL_UNKNOWN                       ((EGLint)-1)
-#define EGL_VERTICAL_RESOLUTION           0x3091
-EGLAPI EGLBoolean EGLAPIENTRY eglBindAPI (EGLenum api);
-EGLAPI EGLenum EGLAPIENTRY eglQueryAPI (void);
-EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer (EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list);
-EGLAPI EGLBoolean EGLAPIENTRY eglReleaseThread (void);
-EGLAPI EGLBoolean EGLAPIENTRY eglWaitClient (void);
-#endif /* EGL_VERSION_1_2 */
-
-#ifndef EGL_VERSION_1_3
-#define EGL_VERSION_1_3 1
-#define EGL_CONFORMANT                    0x3042
-#define EGL_CONTEXT_CLIENT_VERSION        0x3098
-#define EGL_MATCH_NATIVE_PIXMAP           0x3041
-#define EGL_OPENGL_ES2_BIT                0x0004
-#define EGL_VG_ALPHA_FORMAT               0x3088
-#define EGL_VG_ALPHA_FORMAT_NONPRE        0x308B
-#define EGL_VG_ALPHA_FORMAT_PRE           0x308C
-#define EGL_VG_ALPHA_FORMAT_PRE_BIT       0x0040
-#define EGL_VG_COLORSPACE                 0x3087
-#define EGL_VG_COLORSPACE_sRGB            0x3089
-#define EGL_VG_COLORSPACE_LINEAR          0x308A
-#define EGL_VG_COLORSPACE_LINEAR_BIT      0x0020
-#endif /* EGL_VERSION_1_3 */
-
-#ifndef EGL_VERSION_1_4
-#define EGL_VERSION_1_4 1
-#define EGL_DEFAULT_DISPLAY               ((EGLNativeDisplayType)0)
-#define EGL_MULTISAMPLE_RESOLVE_BOX_BIT   0x0200
-#define EGL_MULTISAMPLE_RESOLVE           0x3099
-#define EGL_MULTISAMPLE_RESOLVE_DEFAULT   0x309A
-#define EGL_MULTISAMPLE_RESOLVE_BOX       0x309B
-#define EGL_OPENGL_API                    0x30A2
-#define EGL_OPENGL_BIT                    0x0008
-#define EGL_SWAP_BEHAVIOR_PRESERVED_BIT   0x0400
-EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext (void);
-#endif /* EGL_VERSION_1_4 */
-
-#ifndef EGL_VERSION_1_5
-#define EGL_VERSION_1_5 1
-typedef void *EGLSync;
-typedef intptr_t EGLAttrib;
-typedef khronos_utime_nanoseconds_t EGLTime;
-typedef void *EGLImage;
-#define EGL_CONTEXT_MAJOR_VERSION         0x3098
-#define EGL_CONTEXT_MINOR_VERSION         0x30FB
-#define EGL_CONTEXT_OPENGL_PROFILE_MASK   0x30FD
-#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY 0x31BD
-#define EGL_NO_RESET_NOTIFICATION         0x31BE
-#define EGL_LOSE_CONTEXT_ON_RESET         0x31BF
-#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT 0x00000001
-#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT 0x00000002
-#define EGL_CONTEXT_OPENGL_DEBUG          0x31B0
-#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE 0x31B1
-#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS  0x31B2
-#define EGL_OPENGL_ES3_BIT                0x00000040
-#define EGL_CL_EVENT_HANDLE               0x309C
-#define EGL_SYNC_CL_EVENT                 0x30FE
-#define EGL_SYNC_CL_EVENT_COMPLETE        0x30FF
-#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE  0x30F0
-#define EGL_SYNC_TYPE                     0x30F7
-#define EGL_SYNC_STATUS                   0x30F1
-#define EGL_SYNC_CONDITION                0x30F8
-#define EGL_SIGNALED                      0x30F2
-#define EGL_UNSIGNALED                    0x30F3
-#define EGL_SYNC_FLUSH_COMMANDS_BIT       0x0001
-#define EGL_FOREVER                       0xFFFFFFFFFFFFFFFFull
-#define EGL_TIMEOUT_EXPIRED               0x30F5
-#define EGL_CONDITION_SATISFIED           0x30F6
-#define EGL_NO_SYNC                       ((EGLSync)0)
-#define EGL_SYNC_FENCE                    0x30F9
-#define EGL_GL_COLORSPACE                 0x309D
-#define EGL_GL_COLORSPACE_SRGB            0x3089
-#define EGL_GL_COLORSPACE_LINEAR          0x308A
-#define EGL_GL_RENDERBUFFER               0x30B9
-#define EGL_GL_TEXTURE_2D                 0x30B1
-#define EGL_GL_TEXTURE_LEVEL              0x30BC
-#define EGL_GL_TEXTURE_3D                 0x30B2
-#define EGL_GL_TEXTURE_ZOFFSET            0x30BD
-#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x30B3
-#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x30B4
-#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x30B5
-#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x30B6
-#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x30B7
-#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x30B8
-#define EGL_IMAGE_PRESERVED               0x30D2
-#define EGL_NO_IMAGE                      ((EGLImage)0)
-EGLAPI EGLSync EGLAPIENTRY eglCreateSync (EGLDisplay dpy, EGLenum type, const EGLAttrib *attrib_list);
-EGLAPI EGLBoolean EGLAPIENTRY eglDestroySync (EGLDisplay dpy, EGLSync sync);
-EGLAPI EGLint EGLAPIENTRY eglClientWaitSync (EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout);
-EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttrib (EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib *value);
-EGLAPI EGLImage EGLAPIENTRY eglCreateImage (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLAttrib *attrib_list);
-EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImage (EGLDisplay dpy, EGLImage image);
-EGLAPI EGLDisplay EGLAPIENTRY eglGetPlatformDisplay (EGLenum platform, void *native_display, const EGLAttrib *attrib_list);
-EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformWindowSurface (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLAttrib *attrib_list);
-EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformPixmapSurface (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLAttrib *attrib_list);
-EGLAPI EGLBoolean EGLAPIENTRY eglWaitSync (EGLDisplay dpy, EGLSync sync, EGLint flags);
-#endif /* EGL_VERSION_1_5 */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __egl_h_ */
-
-
-
 #ifndef __eglext_h_
 #define __eglext_h_ 1
 
@@ -790,7 +6,7 @@ extern "C" {
 #endif
 
 /*
-** Copyright (c) 2013-2015 The Khronos Group Inc.
+** Copyright (c) 2013-2017 The Khronos Group Inc.
 **
 ** Permission is hereby granted, free of charge, to any person obtaining a
 ** copy of this software and/or associated documentation files (the
@@ -815,14 +31,14 @@ extern "C" {
 ** This header is generated from the Khronos OpenGL / OpenGL ES XML
 ** API Registry. The current version of the Registry, generator scripts
 ** used to make the header, and the header can be found at
-**   http://www.opengl.org/registry/
+**   http://www.khronos.org/registry/egl
 **
-** Khronos $Revision: 31566 $ on $Date: 2015-06-23 08:48:48 -0700 (Tue, 23 Jun 2015) $
+** Khronos $Git commit SHA1: a732b061e7 $ on $Git commit date: 2017-06-17 23:27:53 +0100 $
 */
 
-/*#include <EGL/eglplatform.h>*/
+#include <EGL/eglplatform.h>
 
-#define EGL_EGLEXT_VERSION 20150623
+#define EGL_EGLEXT_VERSION 20170627
 
 /* Generated C header for:
  * API: egl
@@ -861,6 +77,13 @@ EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSync64KHR (EGLDisplay dpy, EGLenum type,
 #define EGL_VG_ALPHA_FORMAT_PRE_BIT_KHR   0x0040
 #endif /* EGL_KHR_config_attribs */
 
+#ifndef EGL_KHR_context_flush_control
+#define EGL_KHR_context_flush_control 1
+#define EGL_CONTEXT_RELEASE_BEHAVIOR_NONE_KHR 0
+#define EGL_CONTEXT_RELEASE_BEHAVIOR_KHR  0x2097
+#define EGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR 0x2098
+#endif /* EGL_KHR_context_flush_control */
+
 #ifndef EGL_KHR_create_context
 #define EGL_KHR_create_context 1
 #define EGL_CONTEXT_MAJOR_VERSION_KHR     0x3098
@@ -883,6 +106,42 @@ EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSync64KHR (EGLDisplay dpy, EGLenum type,
 #define EGL_CONTEXT_OPENGL_NO_ERROR_KHR   0x31B3
 #endif /* EGL_KHR_create_context_no_error */
 
+#ifndef EGL_KHR_debug
+#define EGL_KHR_debug 1
+typedef void *EGLLabelKHR;
+typedef void *EGLObjectKHR;
+typedef void (EGLAPIENTRY  *EGLDEBUGPROCKHR)(EGLenum error,const char *command,EGLint messageType,EGLLabelKHR threadLabel,EGLLabelKHR objectLabel,const char* message);
+#define EGL_OBJECT_THREAD_KHR             0x33B0
+#define EGL_OBJECT_DISPLAY_KHR            0x33B1
+#define EGL_OBJECT_CONTEXT_KHR            0x33B2
+#define EGL_OBJECT_SURFACE_KHR            0x33B3
+#define EGL_OBJECT_IMAGE_KHR              0x33B4
+#define EGL_OBJECT_SYNC_KHR               0x33B5
+#define EGL_OBJECT_STREAM_KHR             0x33B6
+#define EGL_DEBUG_MSG_CRITICAL_KHR        0x33B9
+#define EGL_DEBUG_MSG_ERROR_KHR           0x33BA
+#define EGL_DEBUG_MSG_WARN_KHR            0x33BB
+#define EGL_DEBUG_MSG_INFO_KHR            0x33BC
+#define EGL_DEBUG_CALLBACK_KHR            0x33B8
+typedef EGLint (EGLAPIENTRYP PFNEGLDEBUGMESSAGECONTROLKHRPROC) (EGLDEBUGPROCKHR callback, const EGLAttrib *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDEBUGKHRPROC) (EGLint attribute, EGLAttrib *value);
+typedef EGLint (EGLAPIENTRYP PFNEGLLABELOBJECTKHRPROC) (EGLDisplay display, EGLenum objectType, EGLObjectKHR object, EGLLabelKHR label);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLint EGLAPIENTRY eglDebugMessageControlKHR (EGLDEBUGPROCKHR callback, const EGLAttrib *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryDebugKHR (EGLint attribute, EGLAttrib *value);
+EGLAPI EGLint EGLAPIENTRY eglLabelObjectKHR (EGLDisplay display, EGLenum objectType, EGLObjectKHR object, EGLLabelKHR label);
+#endif
+#endif /* EGL_KHR_debug */
+
+#ifndef EGL_KHR_display_reference
+#define EGL_KHR_display_reference 1
+#define EGL_TRACK_REFERENCES_KHR          0x3352
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDISPLAYATTRIBKHRPROC) (EGLDisplay dpy, EGLint name, EGLAttrib *value);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryDisplayAttribKHR (EGLDisplay dpy, EGLint name, EGLAttrib *value);
+#endif
+#endif /* EGL_KHR_display_reference */
+
 #ifndef EGL_KHR_fence_sync
 #define EGL_KHR_fence_sync 1
 typedef khronos_utime_nanoseconds_t EGLTimeKHR;
@@ -945,7 +204,7 @@ EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttribKHR (EGLDisplay dpy, EGLSyncKHR sy
 #define EGL_KHR_image 1
 typedef void *EGLImageKHR;
 #define EGL_NATIVE_PIXMAP_KHR             0x30B0
-#define EGL_NO_IMAGE_KHR                  ((EGLImageKHR)0)
+#define EGL_NO_IMAGE_KHR                  EGL_CAST(EGLImageKHR,0)
 typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
 typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image);
 #ifdef EGL_EGLEXT_PROTOTYPES
@@ -1007,6 +266,16 @@ EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface64KHR (EGLDisplay dpy, EGLSurface s
 #endif
 #endif /* EGL_KHR_lock_surface3 */
 
+#ifndef EGL_KHR_mutable_render_buffer
+#define EGL_KHR_mutable_render_buffer 1
+#define EGL_MUTABLE_RENDER_BUFFER_BIT_KHR 0x1000
+#endif /* EGL_KHR_mutable_render_buffer */
+
+#ifndef EGL_KHR_no_config_context
+#define EGL_KHR_no_config_context 1
+#define EGL_NO_CONFIG_KHR                 EGL_CAST(EGLConfig,0)
+#endif /* EGL_KHR_no_config_context */
+
 #ifndef EGL_KHR_partial_update
 #define EGL_KHR_partial_update 1
 #define EGL_BUFFER_AGE_KHR                0x313D
@@ -1049,7 +318,7 @@ EGLAPI EGLBoolean EGLAPIENTRY eglSetDamageRegionKHR (EGLDisplay dpy, EGLSurface
 #define EGL_SYNC_REUSABLE_KHR             0x30FA
 #define EGL_SYNC_FLUSH_COMMANDS_BIT_KHR   0x0001
 #define EGL_FOREVER_KHR                   0xFFFFFFFFFFFFFFFFull
-#define EGL_NO_SYNC_KHR                   ((EGLSyncKHR)0)
+#define EGL_NO_SYNC_KHR                   EGL_CAST(EGLSyncKHR,0)
 typedef EGLBoolean (EGLAPIENTRYP PFNEGLSIGNALSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode);
 #ifdef EGL_EGLEXT_PROTOTYPES
 EGLAPI EGLBoolean EGLAPIENTRY eglSignalSyncKHR (EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode);
@@ -1062,7 +331,7 @@ EGLAPI EGLBoolean EGLAPIENTRY eglSignalSyncKHR (EGLDisplay dpy, EGLSyncKHR sync,
 typedef void *EGLStreamKHR;
 typedef khronos_uint64_t EGLuint64KHR;
 #ifdef KHRONOS_SUPPORT_INT64
-#define EGL_NO_STREAM_KHR                 ((EGLStreamKHR)0)
+#define EGL_NO_STREAM_KHR                 EGL_CAST(EGLStreamKHR,0)
 #define EGL_CONSUMER_LATENCY_USEC_KHR     0x3210
 #define EGL_PRODUCER_FRAME_KHR            0x3212
 #define EGL_CONSUMER_FRAME_KHR            0x3213
@@ -1090,6 +359,24 @@ EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamu64KHR (EGLDisplay dpy, EGLStreamKHR
 #endif /* KHRONOS_SUPPORT_INT64 */
 #endif /* EGL_KHR_stream */
 
+#ifndef EGL_KHR_stream_attrib
+#define EGL_KHR_stream_attrib 1
+#ifdef KHRONOS_SUPPORT_INT64
+typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMATTRIBKHRPROC) (EGLDisplay dpy, const EGLAttrib *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSETSTREAMATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib value);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib *value);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERACQUIREATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLStreamKHR EGLAPIENTRY eglCreateStreamAttribKHR (EGLDisplay dpy, const EGLAttrib *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglSetStreamAttribKHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib value);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamAttribKHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib *value);
+EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerAcquireAttribKHR (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerReleaseAttribKHR (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list);
+#endif
+#endif /* KHRONOS_SUPPORT_INT64 */
+#endif /* EGL_KHR_stream_attrib */
+
 #ifndef EGL_KHR_stream_consumer_gltexture
 #define EGL_KHR_stream_consumer_gltexture 1
 #ifdef EGL_KHR_stream
@@ -1109,7 +396,7 @@ EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerReleaseKHR (EGLDisplay dpy, EGLSt
 #define EGL_KHR_stream_cross_process_fd 1
 typedef int EGLNativeFileDescriptorKHR;
 #ifdef EGL_KHR_stream
-#define EGL_NO_FILE_DESCRIPTOR_KHR        ((EGLNativeFileDescriptorKHR)(-1))
+#define EGL_NO_FILE_DESCRIPTOR_KHR        EGL_CAST(EGLNativeFileDescriptorKHR,-1)
 typedef EGLNativeFileDescriptorKHR (EGLAPIENTRYP PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream);
 typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMFROMFILEDESCRIPTORKHRPROC) (EGLDisplay dpy, EGLNativeFileDescriptorKHR file_descriptor);
 #ifdef EGL_EGLEXT_PROTOTYPES
@@ -1186,11 +473,28 @@ EGLAPI void EGLAPIENTRY eglSetBlobCacheFuncsANDROID (EGLDisplay dpy, EGLSetBlobF
 #endif
 #endif /* EGL_ANDROID_blob_cache */
 
+#ifndef EGL_ANDROID_create_native_client_buffer
+#define EGL_ANDROID_create_native_client_buffer 1
+#define EGL_NATIVE_BUFFER_USAGE_ANDROID   0x3143
+#define EGL_NATIVE_BUFFER_USAGE_PROTECTED_BIT_ANDROID 0x00000001
+#define EGL_NATIVE_BUFFER_USAGE_RENDERBUFFER_BIT_ANDROID 0x00000002
+#define EGL_NATIVE_BUFFER_USAGE_TEXTURE_BIT_ANDROID 0x00000004
+typedef EGLClientBuffer (EGLAPIENTRYP PFNEGLCREATENATIVECLIENTBUFFERANDROIDPROC) (const EGLint *attrib_list);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLClientBuffer EGLAPIENTRY eglCreateNativeClientBufferANDROID (const EGLint *attrib_list);
+#endif
+#endif /* EGL_ANDROID_create_native_client_buffer */
+
 #ifndef EGL_ANDROID_framebuffer_target
 #define EGL_ANDROID_framebuffer_target 1
 #define EGL_FRAMEBUFFER_TARGET_ANDROID    0x3147
 #endif /* EGL_ANDROID_framebuffer_target */
 
+#ifndef EGL_ANDROID_front_buffer_auto_refresh
+#define EGL_ANDROID_front_buffer_auto_refresh 1
+#define EGL_FRONT_BUFFER_AUTO_REFRESH_ANDROID 0x314C
+#endif /* EGL_ANDROID_front_buffer_auto_refresh */
+
 #ifndef EGL_ANDROID_image_native_buffer
 #define EGL_ANDROID_image_native_buffer 1
 #define EGL_NATIVE_BUFFER_ANDROID         0x3140
@@ -1208,6 +512,15 @@ EGLAPI EGLint EGLAPIENTRY eglDupNativeFenceFDANDROID (EGLDisplay dpy, EGLSyncKHR
 #endif
 #endif /* EGL_ANDROID_native_fence_sync */
 
+#ifndef EGL_ANDROID_presentation_time
+#define EGL_ANDROID_presentation_time 1
+typedef khronos_stime_nanoseconds_t EGLnsecsANDROID;
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLPRESENTATIONTIMEANDROIDPROC) (EGLDisplay dpy, EGLSurface surface, EGLnsecsANDROID time);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglPresentationTimeANDROID (EGLDisplay dpy, EGLSurface surface, EGLnsecsANDROID time);
+#endif
+#endif /* EGL_ANDROID_presentation_time */
+
 #ifndef EGL_ANDROID_recordable
 #define EGL_ANDROID_recordable 1
 #define EGL_RECORDABLE_ANDROID            0x3142
@@ -1241,11 +554,21 @@ EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurfacePointerANGLE (EGLDisplay dpy, EGLSu
 #define EGL_FIXED_SIZE_ANGLE              0x3201
 #endif /* EGL_ANGLE_window_fixed_size */
 
+#ifndef EGL_ARM_implicit_external_sync
+#define EGL_ARM_implicit_external_sync 1
+#define EGL_SYNC_PRIOR_COMMANDS_IMPLICIT_EXTERNAL_ARM 0x328A
+#endif /* EGL_ARM_implicit_external_sync */
+
 #ifndef EGL_ARM_pixmap_multisample_discard
 #define EGL_ARM_pixmap_multisample_discard 1
 #define EGL_DISCARD_SAMPLES_ARM           0x3286
 #endif /* EGL_ARM_pixmap_multisample_discard */
 
+#ifndef EGL_EXT_bind_to_front
+#define EGL_EXT_bind_to_front 1
+#define EGL_FRONT_BUFFER_EXT              0x3464
+#endif /* EGL_EXT_bind_to_front */
+
 #ifndef EGL_EXT_buffer_age
 #define EGL_EXT_buffer_age 1
 #define EGL_BUFFER_AGE_EXT                0x313D
@@ -1255,6 +578,30 @@ EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurfacePointerANGLE (EGLDisplay dpy, EGLSu
 #define EGL_EXT_client_extensions 1
 #endif /* EGL_EXT_client_extensions */
 
+#ifndef EGL_EXT_compositor
+#define EGL_EXT_compositor 1
+#define EGL_PRIMARY_COMPOSITOR_CONTEXT_EXT 0x3460
+#define EGL_EXTERNAL_REF_ID_EXT           0x3461
+#define EGL_COMPOSITOR_DROP_NEWEST_FRAME_EXT 0x3462
+#define EGL_COMPOSITOR_KEEP_NEWEST_FRAME_EXT 0x3463
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSETCONTEXTLISTEXTPROC) (const EGLint *external_ref_ids, EGLint num_entries);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSETCONTEXTATTRIBUTESEXTPROC) (EGLint external_ref_id, const EGLint *context_attributes, EGLint num_entries);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSETWINDOWLISTEXTPROC) (EGLint external_ref_id, const EGLint *external_win_ids, EGLint num_entries);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSETWINDOWATTRIBUTESEXTPROC) (EGLint external_win_id, const EGLint *window_attributes, EGLint num_entries);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORBINDTEXWINDOWEXTPROC) (EGLint external_win_id);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSETSIZEEXTPROC) (EGLint external_win_id, EGLint width, EGLint height);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSWAPPOLICYEXTPROC) (EGLint external_win_id, EGLint policy);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSetContextListEXT (const EGLint *external_ref_ids, EGLint num_entries);
+EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSetContextAttributesEXT (EGLint external_ref_id, const EGLint *context_attributes, EGLint num_entries);
+EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSetWindowListEXT (EGLint external_ref_id, const EGLint *external_win_ids, EGLint num_entries);
+EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSetWindowAttributesEXT (EGLint external_win_id, const EGLint *window_attributes, EGLint num_entries);
+EGLAPI EGLBoolean EGLAPIENTRY eglCompositorBindTexWindowEXT (EGLint external_win_id);
+EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSetSizeEXT (EGLint external_win_id, EGLint width, EGLint height);
+EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSwapPolicyEXT (EGLint external_win_id, EGLint policy);
+#endif
+#endif /* EGL_EXT_compositor */
+
 #ifndef EGL_EXT_create_context_robustness
 #define EGL_EXT_create_context_robustness 1
 #define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT 0x30BF
@@ -1266,7 +613,7 @@ EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurfacePointerANGLE (EGLDisplay dpy, EGLSu
 #ifndef EGL_EXT_device_base
 #define EGL_EXT_device_base 1
 typedef void *EGLDeviceEXT;
-#define EGL_NO_DEVICE_EXT                 ((EGLDeviceEXT)(0))
+#define EGL_NO_DEVICE_EXT                 EGL_CAST(EGLDeviceEXT,0)
 #define EGL_BAD_DEVICE_EXT                0x322B
 #define EGL_DEVICE_EXT                    0x322C
 typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDEVICEATTRIBEXTPROC) (EGLDeviceEXT device, EGLint attribute, EGLAttrib *value);
@@ -1299,6 +646,36 @@ EGLAPI EGLBoolean EGLAPIENTRY eglQueryDisplayAttribEXT (EGLDisplay dpy, EGLint a
 #define EGL_EXT_device_query 1
 #endif /* EGL_EXT_device_query */
 
+#ifndef EGL_EXT_gl_colorspace_bt2020_linear
+#define EGL_EXT_gl_colorspace_bt2020_linear 1
+#define EGL_GL_COLORSPACE_BT2020_LINEAR_EXT 0x333F
+#endif /* EGL_EXT_gl_colorspace_bt2020_linear */
+
+#ifndef EGL_EXT_gl_colorspace_bt2020_pq
+#define EGL_EXT_gl_colorspace_bt2020_pq 1
+#define EGL_GL_COLORSPACE_BT2020_PQ_EXT   0x3340
+#endif /* EGL_EXT_gl_colorspace_bt2020_pq */
+
+#ifndef EGL_EXT_gl_colorspace_display_p3
+#define EGL_EXT_gl_colorspace_display_p3 1
+#define EGL_GL_COLORSPACE_DISPLAY_P3_EXT  0x3363
+#endif /* EGL_EXT_gl_colorspace_display_p3 */
+
+#ifndef EGL_EXT_gl_colorspace_display_p3_linear
+#define EGL_EXT_gl_colorspace_display_p3_linear 1
+#define EGL_GL_COLORSPACE_DISPLAY_P3_LINEAR_EXT 0x3362
+#endif /* EGL_EXT_gl_colorspace_display_p3_linear */
+
+#ifndef EGL_EXT_gl_colorspace_scrgb
+#define EGL_EXT_gl_colorspace_scrgb 1
+#define EGL_GL_COLORSPACE_SCRGB_EXT       0x3351
+#endif /* EGL_EXT_gl_colorspace_scrgb */
+
+#ifndef EGL_EXT_gl_colorspace_scrgb_linear
+#define EGL_EXT_gl_colorspace_scrgb_linear 1
+#define EGL_GL_COLORSPACE_SCRGB_LINEAR_EXT 0x3350
+#endif /* EGL_EXT_gl_colorspace_scrgb_linear */
+
 #ifndef EGL_EXT_image_dma_buf_import
 #define EGL_EXT_image_dma_buf_import 1
 #define EGL_LINUX_DMA_BUF_EXT             0x3270
@@ -1325,6 +702,34 @@ EGLAPI EGLBoolean EGLAPIENTRY eglQueryDisplayAttribEXT (EGLDisplay dpy, EGLint a
 #define EGL_YUV_CHROMA_SITING_0_5_EXT     0x3285
 #endif /* EGL_EXT_image_dma_buf_import */
 
+#ifndef EGL_EXT_image_dma_buf_import_modifiers
+#define EGL_EXT_image_dma_buf_import_modifiers 1
+#define EGL_DMA_BUF_PLANE3_FD_EXT         0x3440
+#define EGL_DMA_BUF_PLANE3_OFFSET_EXT     0x3441
+#define EGL_DMA_BUF_PLANE3_PITCH_EXT      0x3442
+#define EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT 0x3443
+#define EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT 0x3444
+#define EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT 0x3445
+#define EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT 0x3446
+#define EGL_DMA_BUF_PLANE2_MODIFIER_LO_EXT 0x3447
+#define EGL_DMA_BUF_PLANE2_MODIFIER_HI_EXT 0x3448
+#define EGL_DMA_BUF_PLANE3_MODIFIER_LO_EXT 0x3449
+#define EGL_DMA_BUF_PLANE3_MODIFIER_HI_EXT 0x344A
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDMABUFFORMATSEXTPROC) (EGLDisplay dpy, EGLint max_formats, EGLint *formats, EGLint *num_formats);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDMABUFMODIFIERSEXTPROC) (EGLDisplay dpy, EGLint format, EGLint max_modifiers, EGLuint64KHR *modifiers, EGLBoolean *external_only, EGLint *num_modifiers);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryDmaBufFormatsEXT (EGLDisplay dpy, EGLint max_formats, EGLint *formats, EGLint *num_formats);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryDmaBufModifiersEXT (EGLDisplay dpy, EGLint format, EGLint max_modifiers, EGLuint64KHR *modifiers, EGLBoolean *external_only, EGLint *num_modifiers);
+#endif
+#endif /* EGL_EXT_image_dma_buf_import_modifiers */
+
+#ifndef EGL_EXT_image_implicit_sync_control
+#define EGL_EXT_image_implicit_sync_control 1
+#define EGL_IMPORT_SYNC_TYPE_EXT          0x3470
+#define EGL_IMPORT_IMPLICIT_SYNC_EXT      0x3471
+#define EGL_IMPORT_EXPLICIT_SYNC_EXT      0x3472
+#endif /* EGL_EXT_image_implicit_sync_control */
+
 #ifndef EGL_EXT_multiview_window
 #define EGL_EXT_multiview_window 1
 #define EGL_MULTIVIEW_VIEW_COUNT_EXT      0x3134
@@ -1334,8 +739,8 @@ EGLAPI EGLBoolean EGLAPIENTRY eglQueryDisplayAttribEXT (EGLDisplay dpy, EGLint a
 #define EGL_EXT_output_base 1
 typedef void *EGLOutputLayerEXT;
 typedef void *EGLOutputPortEXT;
-#define EGL_NO_OUTPUT_LAYER_EXT           ((EGLOutputLayerEXT)0)
-#define EGL_NO_OUTPUT_PORT_EXT            ((EGLOutputPortEXT)0)
+#define EGL_NO_OUTPUT_LAYER_EXT           EGL_CAST(EGLOutputLayerEXT,0)
+#define EGL_NO_OUTPUT_PORT_EXT            EGL_CAST(EGLOutputPortEXT,0)
 #define EGL_BAD_OUTPUT_LAYER_EXT          0x322D
 #define EGL_BAD_OUTPUT_PORT_EXT           0x322E
 #define EGL_SWAP_INTERVAL_EXT             0x322F
@@ -1372,6 +777,13 @@ EGLAPI const char *EGLAPIENTRY eglQueryOutputPortStringEXT (EGLDisplay dpy, EGLO
 #define EGL_OPENWF_PORT_ID_EXT            0x3239
 #endif /* EGL_EXT_output_openwf */
 
+#ifndef EGL_EXT_pixel_format_float
+#define EGL_EXT_pixel_format_float 1
+#define EGL_COLOR_COMPONENT_TYPE_EXT      0x3339
+#define EGL_COLOR_COMPONENT_TYPE_FIXED_EXT 0x333A
+#define EGL_COLOR_COMPONENT_TYPE_FLOAT_EXT 0x333B
+#endif /* EGL_EXT_pixel_format_float */
+
 #ifndef EGL_EXT_platform_base
 #define EGL_EXT_platform_base 1
 typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETPLATFORMDISPLAYEXTPROC) (EGLenum platform, void *native_display, const EGLint *attrib_list);
@@ -1400,9 +812,13 @@ EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformPixmapSurfaceEXT (EGLDisplay dpy,
 #define EGL_PLATFORM_X11_SCREEN_EXT       0x31D6
 #endif /* EGL_EXT_platform_x11 */
 
+#ifndef EGL_EXT_protected_content
+#define EGL_EXT_protected_content 1
+#define EGL_PROTECTED_CONTENT_EXT         0x32C0
+#endif /* EGL_EXT_protected_content */
+
 #ifndef EGL_EXT_protected_surface
 #define EGL_EXT_protected_surface 1
-#define EGL_PROTECTED_CONTENT_EXT         0x32C0
 #endif /* EGL_EXT_protected_surface */
 
 #ifndef EGL_EXT_stream_consumer_egloutput
@@ -1413,6 +829,27 @@ EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerOutputEXT (EGLDisplay dpy, EGLStr
 #endif
 #endif /* EGL_EXT_stream_consumer_egloutput */
 
+#ifndef EGL_EXT_surface_CTA861_3_metadata
+#define EGL_EXT_surface_CTA861_3_metadata 1
+#define EGL_CTA861_3_MAX_CONTENT_LIGHT_LEVEL_EXT 0x3360
+#define EGL_CTA861_3_MAX_FRAME_AVERAGE_LEVEL_EXT 0x3361
+#endif /* EGL_EXT_surface_CTA861_3_metadata */
+
+#ifndef EGL_EXT_surface_SMPTE2086_metadata
+#define EGL_EXT_surface_SMPTE2086_metadata 1
+#define EGL_SMPTE2086_DISPLAY_PRIMARY_RX_EXT 0x3341
+#define EGL_SMPTE2086_DISPLAY_PRIMARY_RY_EXT 0x3342
+#define EGL_SMPTE2086_DISPLAY_PRIMARY_GX_EXT 0x3343
+#define EGL_SMPTE2086_DISPLAY_PRIMARY_GY_EXT 0x3344
+#define EGL_SMPTE2086_DISPLAY_PRIMARY_BX_EXT 0x3345
+#define EGL_SMPTE2086_DISPLAY_PRIMARY_BY_EXT 0x3346
+#define EGL_SMPTE2086_WHITE_POINT_X_EXT   0x3347
+#define EGL_SMPTE2086_WHITE_POINT_Y_EXT   0x3348
+#define EGL_SMPTE2086_MAX_LUMINANCE_EXT   0x3349
+#define EGL_SMPTE2086_MIN_LUMINANCE_EXT   0x334A
+#define EGL_METADATA_SCALING_EXT          50000
+#endif /* EGL_EXT_surface_SMPTE2086_metadata */
+
 #ifndef EGL_EXT_swap_buffers_with_damage
 #define EGL_EXT_swap_buffers_with_damage 1
 typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC) (EGLDisplay dpy, EGLSurface surface, EGLint *rects, EGLint n_rects);
@@ -1481,6 +918,12 @@ EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurfaceHI (EGLDisplay dpy, EGLConfi
 #define EGL_CONTEXT_PRIORITY_LOW_IMG      0x3103
 #endif /* EGL_IMG_context_priority */
 
+#ifndef EGL_IMG_image_plane_attribs
+#define EGL_IMG_image_plane_attribs 1
+#define EGL_NATIVE_BUFFER_MULTIPLANE_SEPARATE_IMG 0x3105
+#define EGL_NATIVE_BUFFER_PLANE_OFFSET_IMG 0x3106
+#endif /* EGL_IMG_image_plane_attribs */
+
 #ifndef EGL_MESA_drm_image
 #define EGL_MESA_drm_image 1
 #define EGL_DRM_BUFFER_FORMAT_MESA        0x31D0
@@ -1513,6 +956,11 @@ EGLAPI EGLBoolean EGLAPIENTRY eglExportDMABUFImageMESA (EGLDisplay dpy, EGLImage
 #define EGL_PLATFORM_GBM_MESA             0x31D7
 #endif /* EGL_MESA_platform_gbm */
 
+#ifndef EGL_MESA_platform_surfaceless
+#define EGL_MESA_platform_surfaceless 1
+#define EGL_PLATFORM_SURFACELESS_MESA     0x31DD
+#endif /* EGL_MESA_platform_surfaceless */
+
 #ifndef EGL_NOK_swap_region
 #define EGL_NOK_swap_region 1
 typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSREGIONNOKPROC) (EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint *rects);
@@ -1596,6 +1044,129 @@ EGLAPI EGLBoolean EGLAPIENTRY eglPostSubBufferNV (EGLDisplay dpy, EGLSurface sur
 #endif
 #endif /* EGL_NV_post_sub_buffer */
 
+#ifndef EGL_NV_robustness_video_memory_purge
+#define EGL_NV_robustness_video_memory_purge 1
+#define EGL_GENERATE_RESET_ON_VIDEO_MEMORY_PURGE_NV 0x334C
+#endif /* EGL_NV_robustness_video_memory_purge */
+
+#ifndef EGL_NV_stream_consumer_gltexture_yuv
+#define EGL_NV_stream_consumer_gltexture_yuv 1
+#define EGL_YUV_PLANE0_TEXTURE_UNIT_NV    0x332C
+#define EGL_YUV_PLANE1_TEXTURE_UNIT_NV    0x332D
+#define EGL_YUV_PLANE2_TEXTURE_UNIT_NV    0x332E
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALATTRIBSNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLAttrib *attrib_list);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerGLTextureExternalAttribsNV (EGLDisplay dpy, EGLStreamKHR stream, EGLAttrib *attrib_list);
+#endif
+#endif /* EGL_NV_stream_consumer_gltexture_yuv */
+
+#ifndef EGL_NV_stream_cross_display
+#define EGL_NV_stream_cross_display 1
+#define EGL_STREAM_CROSS_DISPLAY_NV       0x334E
+#endif /* EGL_NV_stream_cross_display */
+
+#ifndef EGL_NV_stream_cross_object
+#define EGL_NV_stream_cross_object 1
+#define EGL_STREAM_CROSS_OBJECT_NV        0x334D
+#endif /* EGL_NV_stream_cross_object */
+
+#ifndef EGL_NV_stream_cross_partition
+#define EGL_NV_stream_cross_partition 1
+#define EGL_STREAM_CROSS_PARTITION_NV     0x323F
+#endif /* EGL_NV_stream_cross_partition */
+
+#ifndef EGL_NV_stream_cross_process
+#define EGL_NV_stream_cross_process 1
+#define EGL_STREAM_CROSS_PROCESS_NV       0x3245
+#endif /* EGL_NV_stream_cross_process */
+
+#ifndef EGL_NV_stream_cross_system
+#define EGL_NV_stream_cross_system 1
+#define EGL_STREAM_CROSS_SYSTEM_NV        0x334F
+#endif /* EGL_NV_stream_cross_system */
+
+#ifndef EGL_NV_stream_fifo_next
+#define EGL_NV_stream_fifo_next 1
+#define EGL_PENDING_FRAME_NV              0x3329
+#define EGL_STREAM_TIME_PENDING_NV        0x332A
+#endif /* EGL_NV_stream_fifo_next */
+
+#ifndef EGL_NV_stream_fifo_synchronous
+#define EGL_NV_stream_fifo_synchronous 1
+#define EGL_STREAM_FIFO_SYNCHRONOUS_NV    0x3336
+#endif /* EGL_NV_stream_fifo_synchronous */
+
+#ifndef EGL_NV_stream_frame_limits
+#define EGL_NV_stream_frame_limits 1
+#define EGL_PRODUCER_MAX_FRAME_HINT_NV    0x3337
+#define EGL_CONSUMER_MAX_FRAME_HINT_NV    0x3338
+#endif /* EGL_NV_stream_frame_limits */
+
+#ifndef EGL_NV_stream_metadata
+#define EGL_NV_stream_metadata 1
+#define EGL_MAX_STREAM_METADATA_BLOCKS_NV 0x3250
+#define EGL_MAX_STREAM_METADATA_BLOCK_SIZE_NV 0x3251
+#define EGL_MAX_STREAM_METADATA_TOTAL_SIZE_NV 0x3252
+#define EGL_PRODUCER_METADATA_NV          0x3253
+#define EGL_CONSUMER_METADATA_NV          0x3254
+#define EGL_PENDING_METADATA_NV           0x3328
+#define EGL_METADATA0_SIZE_NV             0x3255
+#define EGL_METADATA1_SIZE_NV             0x3256
+#define EGL_METADATA2_SIZE_NV             0x3257
+#define EGL_METADATA3_SIZE_NV             0x3258
+#define EGL_METADATA0_TYPE_NV             0x3259
+#define EGL_METADATA1_TYPE_NV             0x325A
+#define EGL_METADATA2_TYPE_NV             0x325B
+#define EGL_METADATA3_TYPE_NV             0x325C
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDISPLAYATTRIBNVPROC) (EGLDisplay dpy, EGLint attribute, EGLAttrib *value);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSETSTREAMMETADATANVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLint n, EGLint offset, EGLint size, const void *data);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMMETADATANVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum name, EGLint n, EGLint offset, EGLint size, void *data);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryDisplayAttribNV (EGLDisplay dpy, EGLint attribute, EGLAttrib *value);
+EGLAPI EGLBoolean EGLAPIENTRY eglSetStreamMetadataNV (EGLDisplay dpy, EGLStreamKHR stream, EGLint n, EGLint offset, EGLint size, const void *data);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamMetadataNV (EGLDisplay dpy, EGLStreamKHR stream, EGLenum name, EGLint n, EGLint offset, EGLint size, void *data);
+#endif
+#endif /* EGL_NV_stream_metadata */
+
+#ifndef EGL_NV_stream_remote
+#define EGL_NV_stream_remote 1
+#define EGL_STREAM_STATE_INITIALIZING_NV  0x3240
+#define EGL_STREAM_TYPE_NV                0x3241
+#define EGL_STREAM_PROTOCOL_NV            0x3242
+#define EGL_STREAM_ENDPOINT_NV            0x3243
+#define EGL_STREAM_LOCAL_NV               0x3244
+#define EGL_STREAM_PRODUCER_NV            0x3247
+#define EGL_STREAM_CONSUMER_NV            0x3248
+#define EGL_STREAM_PROTOCOL_FD_NV         0x3246
+#endif /* EGL_NV_stream_remote */
+
+#ifndef EGL_NV_stream_reset
+#define EGL_NV_stream_reset 1
+#define EGL_SUPPORT_RESET_NV              0x3334
+#define EGL_SUPPORT_REUSE_NV              0x3335
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLRESETSTREAMNVPROC) (EGLDisplay dpy, EGLStreamKHR stream);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglResetStreamNV (EGLDisplay dpy, EGLStreamKHR stream);
+#endif
+#endif /* EGL_NV_stream_reset */
+
+#ifndef EGL_NV_stream_socket
+#define EGL_NV_stream_socket 1
+#define EGL_STREAM_PROTOCOL_SOCKET_NV     0x324B
+#define EGL_SOCKET_HANDLE_NV              0x324C
+#define EGL_SOCKET_TYPE_NV                0x324D
+#endif /* EGL_NV_stream_socket */
+
+#ifndef EGL_NV_stream_socket_inet
+#define EGL_NV_stream_socket_inet 1
+#define EGL_SOCKET_TYPE_INET_NV           0x324F
+#endif /* EGL_NV_stream_socket_inet */
+
+#ifndef EGL_NV_stream_socket_unix
+#define EGL_NV_stream_socket_unix 1
+#define EGL_SOCKET_TYPE_UNIX_NV           0x324E
+#endif /* EGL_NV_stream_socket_unix */
+
 #ifndef EGL_NV_stream_sync
 #define EGL_NV_stream_sync 1
 #define EGL_SYNC_NEW_FRAME_NV             0x321F
@@ -1622,7 +1193,7 @@ typedef khronos_utime_nanoseconds_t EGLTimeNV;
 #define EGL_SYNC_TYPE_NV                  0x30ED
 #define EGL_SYNC_CONDITION_NV             0x30EE
 #define EGL_SYNC_FENCE_NV                 0x30EF
-#define EGL_NO_SYNC_NV                    ((EGLSyncNV)0)
+#define EGL_NO_SYNC_NV                    EGL_CAST(EGLSyncNV,0)
 typedef EGLSyncNV (EGLAPIENTRYP PFNEGLCREATEFENCESYNCNVPROC) (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list);
 typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCNVPROC) (EGLSyncNV sync);
 typedef EGLBoolean (EGLAPIENTRYP PFNEGLFENCENVPROC) (EGLSyncNV sync);
@@ -1667,7 +1238,4 @@ EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeNV (void);
 }
 #endif
 
-#endif /* __eglext_h_ */
-
-
-#endif /* _MSC_VER */
+#endif
diff --git a/src/video/khronos/EGL/eglplatform.h b/src/video/khronos/EGL/eglplatform.h
new file mode 100644
index 0000000..c77c333
--- /dev/null
+++ b/src/video/khronos/EGL/eglplatform.h
@@ -0,0 +1,132 @@
+#ifndef __eglplatform_h_
+#define __eglplatform_h_
+
+/*
+** Copyright (c) 2007-2016 The Khronos Group Inc.
+**
+** Permission is hereby granted, free of charge, to any person obtaining a
+** copy of this software and/or associated documentation files (the
+** "Materials"), to deal in the Materials without restriction, including
+** without limitation the rights to use, copy, modify, merge, publish,
+** distribute, sublicense, and/or sell copies of the Materials, and to
+** permit persons to whom the Materials are 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 Materials.
+**
+** THE MATERIALS ARE 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
+** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
+*/
+
+/* Platform-specific types and definitions for egl.h
+ * $Revision: 30994 $ on $Date: 2015-04-30 13:36:48 -0700 (Thu, 30 Apr 2015) $
+ *
+ * Adopters may modify khrplatform.h and this file to suit their platform.
+ * You are encouraged to submit all modifications to the Khronos group so that
+ * they can be included in future versions of this file.  Please submit changes
+ * by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla)
+ * by filing a bug against product "EGL" component "Registry".
+ */
+
+#include <KHR/khrplatform.h>
+
+/* Macros used in EGL function prototype declarations.
+ *
+ * EGL functions should be prototyped as:
+ *
+ * EGLAPI return-type EGLAPIENTRY eglFunction(arguments);
+ * typedef return-type (EXPAPIENTRYP PFNEGLFUNCTIONPROC) (arguments);
+ *
+ * KHRONOS_APICALL and KHRONOS_APIENTRY are defined in KHR/khrplatform.h
+ */
+
+#ifndef EGLAPI
+#define EGLAPI KHRONOS_APICALL
+#endif
+
+#ifndef EGLAPIENTRY
+#define EGLAPIENTRY  KHRONOS_APIENTRY
+#endif
+#define EGLAPIENTRYP EGLAPIENTRY*
+
+/* The types NativeDisplayType, NativeWindowType, and NativePixmapType
+ * are aliases of window-system-dependent types, such as X Display * or
+ * Windows Device Context. They must be defined in platform-specific
+ * code below. The EGL-prefixed versions of Native*Type are the same
+ * types, renamed in EGL 1.3 so all types in the API start with "EGL".
+ *
+ * Khronos STRONGLY RECOMMENDS that you use the default definitions
+ * provided below, since these changes affect both binary and source
+ * portability of applications using EGL running on different EGL
+ * implementations.
+ */
+
+#if defined(_WIN32) || defined(__VC32__) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) /* Win32 and WinCE */
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif
+#include <windows.h>
+
+typedef HDC     EGLNativeDisplayType;
+typedef HBITMAP EGLNativePixmapType;
+typedef HWND    EGLNativeWindowType;
+
+#elif defined(__APPLE__) || defined(__WINSCW__) || defined(__SYMBIAN32__)  /* Symbian */
+
+typedef int   EGLNativeDisplayType;
+typedef void *EGLNativeWindowType;
+typedef void *EGLNativePixmapType;
+
+#elif defined(__ANDROID__) || defined(ANDROID)
+
+struct ANativeWindow;
+struct egl_native_pixmap_t;
+
+typedef struct ANativeWindow*           EGLNativeWindowType;
+typedef struct egl_native_pixmap_t*     EGLNativePixmapType;
+typedef void*                           EGLNativeDisplayType;
+
+#elif defined(__unix__)
+
+/* X11 (tentative)  */
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+
+typedef Display *EGLNativeDisplayType;
+typedef Pixmap   EGLNativePixmapType;
+typedef Window   EGLNativeWindowType;
+
+#else
+#error "Platform not recognized"
+#endif
+
+/* EGL 1.2 types, renamed for consistency in EGL 1.3 */
+typedef EGLNativeDisplayType NativeDisplayType;
+typedef EGLNativePixmapType  NativePixmapType;
+typedef EGLNativeWindowType  NativeWindowType;
+
+
+/* Define EGLint. This must be a signed integral type large enough to contain
+ * all legal attribute names and values passed into and out of EGL, whether
+ * their type is boolean, bitmask, enumerant (symbolic constant), integer,
+ * handle, or other.  While in general a 32-bit integer will suffice, if
+ * handles are 64 bit types, then EGLint should be defined as a signed 64-bit
+ * integer type.
+ */
+typedef khronos_int32_t EGLint;
+
+
+/* C++ / C typecast macros for special EGL handle values */
+#if defined(__cplusplus)
+#define EGL_CAST(type, value) (static_cast<type>(value))
+#else
+#define EGL_CAST(type, value) ((type) (value))
+#endif
+
+#endif /* __eglplatform_h */
diff --git a/src/video/khronos/GLES2/gl2.h b/src/video/khronos/GLES2/gl2.h
new file mode 100644
index 0000000..8ba1642
--- /dev/null
+++ b/src/video/khronos/GLES2/gl2.h
@@ -0,0 +1,675 @@
+#ifndef __gl2_h_
+#define __gl2_h_ 1
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** Copyright (c) 2013-2017 The Khronos Group Inc.
+**
+** Permission is hereby granted, free of charge, to any person obtaining a
+** copy of this software and/or associated documentation files (the
+** "Materials"), to deal in the Materials without restriction, including
+** without limitation the rights to use, copy, modify, merge, publish,
+** distribute, sublicense, and/or sell copies of the Materials, and to
+** permit persons to whom the Materials are 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 Materials.
+**
+** THE MATERIALS ARE 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
+** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
+*/
+/*
+** This header is generated from the Khronos OpenGL / OpenGL ES XML
+** API Registry. The current version of the Registry, generator scripts
+** used to make the header, and the header can be found at
+**   https://github.com/KhronosGroup/OpenGL-Registry
+*/
+
+#include <GLES2/gl2platform.h>
+
+#ifndef GL_APIENTRYP
+#define GL_APIENTRYP GL_APIENTRY*
+#endif
+
+#ifndef GL_GLES_PROTOTYPES
+#define GL_GLES_PROTOTYPES 1
+#endif
+
+/* Generated on date 20170817 */
+
+/* Generated C header for:
+ * API: gles2
+ * Profile: common
+ * Versions considered: 2\.[0-9]
+ * Versions emitted: .*
+ * Default extensions included: None
+ * Additional extensions included: _nomatch_^
+ * Extensions removed: _nomatch_^
+ */
+
+#ifndef GL_ES_VERSION_2_0
+#define GL_ES_VERSION_2_0 1
+#include <KHR/khrplatform.h>
+typedef khronos_int8_t GLbyte;
+typedef khronos_float_t GLclampf;
+typedef khronos_int32_t GLfixed;
+typedef short GLshort;
+typedef unsigned short GLushort;
+typedef void GLvoid;
+typedef struct __GLsync *GLsync;
+typedef khronos_int64_t GLint64;
+typedef khronos_uint64_t GLuint64;
+typedef unsigned int GLenum;
+typedef unsigned int GLuint;
+typedef char GLchar;
+typedef khronos_float_t GLfloat;
+typedef khronos_ssize_t GLsizeiptr;
+typedef khronos_intptr_t GLintptr;
+typedef unsigned int GLbitfield;
+typedef int GLint;
+typedef unsigned char GLboolean;
+typedef int GLsizei;
+typedef khronos_uint8_t GLubyte;
+#define GL_DEPTH_BUFFER_BIT               0x00000100
+#define GL_STENCIL_BUFFER_BIT             0x00000400
+#define GL_COLOR_BUFFER_BIT               0x00004000
+#define GL_FALSE                          0
+#define GL_TRUE                           1
+#define GL_POINTS                         0x0000
+#define GL_LINES                          0x0001
+#define GL_LINE_LOOP                      0x0002
+#define GL_LINE_STRIP                     0x0003
+#define GL_TRIANGLES                      0x0004
+#define GL_TRIANGLE_STRIP                 0x0005
+#define GL_TRIANGLE_FAN                   0x0006
+#define GL_ZERO                           0
+#define GL_ONE                            1
+#define GL_SRC_COLOR                      0x0300
+#define GL_ONE_MINUS_SRC_COLOR            0x0301
+#define GL_SRC_ALPHA                      0x0302
+#define GL_ONE_MINUS_SRC_ALPHA            0x0303
+#define GL_DST_ALPHA                      0x0304
+#define GL_ONE_MINUS_DST_ALPHA            0x0305
+#define GL_DST_COLOR                      0x0306
+#define GL_ONE_MINUS_DST_COLOR            0x0307
+#define GL_SRC_ALPHA_SATURATE             0x0308
+#define GL_FUNC_ADD                       0x8006
+#define GL_BLEND_EQUATION                 0x8009
+#define GL_BLEND_EQUATION_RGB             0x8009
+#define GL_BLEND_EQUATION_ALPHA           0x883D
+#define GL_FUNC_SUBTRACT                  0x800A
+#define GL_FUNC_REVERSE_SUBTRACT          0x800B
+#define GL_BLEND_DST_RGB                  0x80C8
+#define GL_BLEND_SRC_RGB                  0x80C9
+#define GL_BLEND_DST_ALPHA                0x80CA
+#define GL_BLEND_SRC_ALPHA                0x80CB
+#define GL_CONSTANT_COLOR                 0x8001
+#define GL_ONE_MINUS_CONSTANT_COLOR       0x8002
+#define GL_CONSTANT_ALPHA                 0x8003
+#define GL_ONE_MINUS_CONSTANT_ALPHA       0x8004
+#define GL_BLEND_COLOR                    0x8005
+#define GL_ARRAY_BUFFER                   0x8892
+#define GL_ELEMENT_ARRAY_BUFFER           0x8893
+#define GL_ARRAY_BUFFER_BINDING           0x8894
+#define GL_ELEMENT_ARRAY_BUFFER_BINDING   0x8895
+#define GL_STREAM_DRAW                    0x88E0
+#define GL_STATIC_DRAW                    0x88E4
+#define GL_DYNAMIC_DRAW                   0x88E8
+#define GL_BUFFER_SIZE                    0x8764
+#define GL_BUFFER_USAGE                   0x8765
+#define GL_CURRENT_VERTEX_ATTRIB          0x8626
+#define GL_FRONT                          0x0404
+#define GL_BACK                           0x0405
+#define GL_FRONT_AND_BACK                 0x0408
+#define GL_TEXTURE_2D                     0x0DE1
+#define GL_CULL_FACE                      0x0B44
+#define GL_BLEND                          0x0BE2
+#define GL_DITHER                         0x0BD0
+#define GL_STENCIL_TEST                   0x0B90
+#define GL_DEPTH_TEST                     0x0B71
+#define GL_SCISSOR_TEST                   0x0C11
+#define GL_POLYGON_OFFSET_FILL            0x8037
+#define GL_SAMPLE_ALPHA_TO_COVERAGE       0x809E
+#define GL_SAMPLE_COVERAGE                0x80A0
+#define GL_NO_ERROR                       0
+#define GL_INVALID_ENUM                   0x0500
+#define GL_INVALID_VALUE                  0x0501
+#define GL_INVALID_OPERATION              0x0502
+#define GL_OUT_OF_MEMORY                  0x0505
+#define GL_CW                             0x0900
+#define GL_CCW                            0x0901
+#define GL_LINE_WIDTH                     0x0B21
+#define GL_ALIASED_POINT_SIZE_RANGE       0x846D
+#define GL_ALIASED_LINE_WIDTH_RANGE       0x846E
+#define GL_CULL_FACE_MODE                 0x0B45
+#define GL_FRONT_FACE                     0x0B46
+#define GL_DEPTH_RANGE                    0x0B70
+#define GL_DEPTH_WRITEMASK                0x0B72
+#define GL_DEPTH_CLEAR_VALUE              0x0B73
+#define GL_DEPTH_FUNC                     0x0B74
+#define GL_STENCIL_CLEAR_VALUE            0x0B91
+#define GL_STENCIL_FUNC                   0x0B92
+#define GL_STENCIL_FAIL                   0x0B94
+#define GL_STENCIL_PASS_DEPTH_FAIL        0x0B95
+#define GL_STENCIL_PASS_DEPTH_PASS        0x0B96
+#define GL_STENCIL_REF                    0x0B97
+#define GL_STENCIL_VALUE_MASK             0x0B93
+#define GL_STENCIL_WRITEMASK              0x0B98
+#define GL_STENCIL_BACK_FUNC              0x8800
+#define GL_STENCIL_BACK_FAIL              0x8801
+#define GL_STENCIL_BACK_PASS_DEPTH_FAIL   0x8802
+#define GL_STENCIL_BACK_PASS_DEPTH_PASS   0x8803
+#define GL_STENCIL_BACK_REF               0x8CA3
+#define GL_STENCIL_BACK_VALUE_MASK        0x8CA4
+#define GL_STENCIL_BACK_WRITEMASK         0x8CA5
+#define GL_VIEWPORT                       0x0BA2
+#define GL_SCISSOR_BOX                    0x0C10
+#define GL_COLOR_CLEAR_VALUE              0x0C22
+#define GL_COLOR_WRITEMASK                0x0C23
+#define GL_UNPACK_ALIGNMENT               0x0CF5
+#define GL_PACK_ALIGNMENT                 0x0D05
+#define GL_MAX_TEXTURE_SIZE               0x0D33
+#define GL_MAX_VIEWPORT_DIMS              0x0D3A
+#define GL_SUBPIXEL_BITS                  0x0D50
+#define GL_RED_BITS                       0x0D52
+#define GL_GREEN_BITS                     0x0D53
+#define GL_BLUE_BITS                      0x0D54
+#define GL_ALPHA_BITS                     0x0D55
+#define GL_DEPTH_BITS                     0x0D56
+#define GL_STENCIL_BITS                   0x0D57
+#define GL_POLYGON_OFFSET_UNITS           0x2A00
+#define GL_POLYGON_OFFSET_FACTOR          0x8038
+#define GL_TEXTURE_BINDING_2D             0x8069
+#define GL_SAMPLE_BUFFERS                 0x80A8
+#define GL_SAMPLES                        0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE          0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT         0x80AB
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS     0x86A3
+#define GL_DONT_CARE                      0x1100
+#define GL_FASTEST                        0x1101
+#define GL_NICEST                         0x1102
+#define GL_GENERATE_MIPMAP_HINT           0x8192
+#define GL_BYTE                           0x1400
+#define GL_UNSIGNED_BYTE                  0x1401
+#define GL_SHORT                          0x1402
+#define GL_UNSIGNED_SHORT                 0x1403
+#define GL_INT                            0x1404
+#define GL_UNSIGNED_INT                   0x1405
+#define GL_FLOAT                          0x1406
+#define GL_FIXED                          0x140C
+#define GL_DEPTH_COMPONENT                0x1902
+#define GL_ALPHA                          0x1906
+#define GL_RGB                            0x1907
+#define GL_RGBA                           0x1908
+#define GL_LUMINANCE                      0x1909
+#define GL_LUMINANCE_ALPHA                0x190A
+#define GL_UNSIGNED_SHORT_4_4_4_4         0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1         0x8034
+#define GL_UNSIGNED_SHORT_5_6_5           0x8363
+#define GL_FRAGMENT_SHADER                0x8B30
+#define GL_VERTEX_SHADER                  0x8B31
+#define GL_MAX_VERTEX_ATTRIBS             0x8869
+#define GL_MAX_VERTEX_UNIFORM_VECTORS     0x8DFB
+#define GL_MAX_VARYING_VECTORS            0x8DFC
+#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
+#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C
+#define GL_MAX_TEXTURE_IMAGE_UNITS        0x8872
+#define GL_MAX_FRAGMENT_UNIFORM_VECTORS   0x8DFD
+#define GL_SHADER_TYPE                    0x8B4F
+#define GL_DELETE_STATUS                  0x8B80
+#define GL_LINK_STATUS                    0x8B82
+#define GL_VALIDATE_STATUS                0x8B83
+#define GL_ATTACHED_SHADERS               0x8B85
+#define GL_ACTIVE_UNIFORMS                0x8B86
+#define GL_ACTIVE_UNIFORM_MAX_LENGTH      0x8B87
+#define GL_ACTIVE_ATTRIBUTES              0x8B89
+#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH    0x8B8A
+#define GL_SHADING_LANGUAGE_VERSION       0x8B8C
+#define GL_CURRENT_PROGRAM                0x8B8D
+#define GL_NEVER                          0x0200
+#define GL_LESS                           0x0201
+#define GL_EQUAL                          0x0202
+#define GL_LEQUAL                         0x0203
+#define GL_GREATER                        0x0204
+#define GL_NOTEQUAL                       0x0205
+#define GL_GEQUAL                         0x0206
+#define GL_ALWAYS                         0x0207
+#define GL_KEEP                           0x1E00
+#define GL_REPLACE                        0x1E01
+#define GL_INCR                           0x1E02
+#define GL_DECR                           0x1E03
+#define GL_INVERT                         0x150A
+#define GL_INCR_WRAP                      0x8507
+#define GL_DECR_WRAP                      0x8508
+#define GL_VENDOR                         0x1F00
+#define GL_RENDERER                       0x1F01
+#define GL_VERSION                        0x1F02
+#define GL_EXTENSIONS                     0x1F03
+#define GL_NEAREST                        0x2600
+#define GL_LINEAR                         0x2601
+#define GL_NEAREST_MIPMAP_NEAREST         0x2700
+#define GL_LINEAR_MIPMAP_NEAREST          0x2701
+#define GL_NEAREST_MIPMAP_LINEAR          0x2702
+#define GL_LINEAR_MIPMAP_LINEAR           0x2703
+#define GL_TEXTURE_MAG_FILTER             0x2800
+#define GL_TEXTURE_MIN_FILTER             0x2801
+#define GL_TEXTURE_WRAP_S                 0x2802
+#define GL_TEXTURE_WRAP_T                 0x2803
+#define GL_TEXTURE                        0x1702
+#define GL_TEXTURE_CUBE_MAP               0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP       0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X    0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X    0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y    0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y    0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z    0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z    0x851A
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE      0x851C
+#define GL_TEXTURE0                       0x84C0
+#define GL_TEXTURE1                       0x84C1
+#define GL_TEXTURE2                       0x84C2
+#define GL_TEXTURE3                       0x84C3
+#define GL_TEXTURE4                       0x84C4
+#define GL_TEXTURE5                       0x84C5
+#define GL_TEXTURE6                       0x84C6
+#define GL_TEXTURE7                       0x84C7
+#define GL_TEXTURE8                       0x84C8
+#define GL_TEXTURE9                       0x84C9
+#define GL_TEXTURE10                      0x84CA
+#define GL_TEXTURE11                      0x84CB
+#define GL_TEXTURE12                      0x84CC
+#define GL_TEXTURE13                      0x84CD
+#define GL_TEXTURE14                      0x84CE
+#define GL_TEXTURE15                      0x84CF
+#define GL_TEXTURE16                      0x84D0
+#define GL_TEXTURE17                      0x84D1
+#define GL_TEXTURE18                      0x84D2
+#define GL_TEXTURE19                      0x84D3
+#define GL_TEXTURE20                      0x84D4
+#define GL_TEXTURE21                      0x84D5
+#define GL_TEXTURE22                      0x84D6
+#define GL_TEXTURE23                      0x84D7
+#define GL_TEXTURE24                      0x84D8
+#define GL_TEXTURE25                      0x84D9
+#define GL_TEXTURE26                      0x84DA
+#define GL_TEXTURE27                      0x84DB
+#define GL_TEXTURE28                      0x84DC
+#define GL_TEXTURE29                      0x84DD
+#define GL_TEXTURE30                      0x84DE
+#define GL_TEXTURE31                      0x84DF
+#define GL_ACTIVE_TEXTURE                 0x84E0
+#define GL_REPEAT                         0x2901
+#define GL_CLAMP_TO_EDGE                  0x812F
+#define GL_MIRRORED_REPEAT                0x8370
+#define GL_FLOAT_VEC2                     0x8B50
+#define GL_FLOAT_VEC3                     0x8B51
+#define GL_FLOAT_VEC4                     0x8B52
+#define GL_INT_VEC2                       0x8B53
+#define GL_INT_VEC3                       0x8B54
+#define GL_INT_VEC4                       0x8B55
+#define GL_BOOL                           0x8B56
+#define GL_BOOL_VEC2                      0x8B57
+#define GL_BOOL_VEC3                      0x8B58
+#define GL_BOOL_VEC4                      0x8B59
+#define GL_FLOAT_MAT2                     0x8B5A
+#define GL_FLOAT_MAT3                     0x8B5B
+#define GL_FLOAT_MAT4                     0x8B5C
+#define GL_SAMPLER_2D                     0x8B5E
+#define GL_SAMPLER_CUBE                   0x8B60
+#define GL_VERTEX_ATTRIB_ARRAY_ENABLED    0x8622
+#define GL_VERTEX_ATTRIB_ARRAY_SIZE       0x8623
+#define GL_VERTEX_ATTRIB_ARRAY_STRIDE     0x8624
+#define GL_VERTEX_ATTRIB_ARRAY_TYPE       0x8625
+#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
+#define GL_VERTEX_ATTRIB_ARRAY_POINTER    0x8645
+#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
+#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A
+#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B
+#define GL_COMPILE_STATUS                 0x8B81
+#define GL_INFO_LOG_LENGTH                0x8B84
+#define GL_SHADER_SOURCE_LENGTH           0x8B88
+#define GL_SHADER_COMPILER                0x8DFA
+#define GL_SHADER_BINARY_FORMATS          0x8DF8
+#define GL_NUM_SHADER_BINARY_FORMATS      0x8DF9
+#define GL_LOW_FLOAT                      0x8DF0
+#define GL_MEDIUM_FLOAT                   0x8DF1
+#define GL_HIGH_FLOAT                     0x8DF2
+#define GL_LOW_INT                        0x8DF3
+#define GL_MEDIUM_INT                     0x8DF4
+#define GL_HIGH_INT                       0x8DF5
+#define GL_FRAMEBUFFER                    0x8D40
+#define GL_RENDERBUFFER                   0x8D41
+#define GL_RGBA4                          0x8056
+#define GL_RGB5_A1                        0x8057
+#define GL_RGB565                         0x8D62
+#define GL_DEPTH_COMPONENT16              0x81A5
+#define GL_STENCIL_INDEX8                 0x8D48
+#define GL_RENDERBUFFER_WIDTH             0x8D42
+#define GL_RENDERBUFFER_HEIGHT            0x8D43
+#define GL_RENDERBUFFER_INTERNAL_FORMAT   0x8D44
+#define GL_RENDERBUFFER_RED_SIZE          0x8D50
+#define GL_RENDERBUFFER_GREEN_SIZE        0x8D51
+#define GL_RENDERBUFFER_BLUE_SIZE         0x8D52
+#define GL_RENDERBUFFER_ALPHA_SIZE        0x8D53
+#define GL_RENDERBUFFER_DEPTH_SIZE        0x8D54
+#define GL_RENDERBUFFER_STENCIL_SIZE      0x8D55
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3
+#define GL_COLOR_ATTACHMENT0              0x8CE0
+#define GL_DEPTH_ATTACHMENT               0x8D00
+#define GL_STENCIL_ATTACHMENT             0x8D20
+#define GL_NONE                           0
+#define GL_FRAMEBUFFER_COMPLETE           0x8CD5
+#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6
+#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
+#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9
+#define GL_FRAMEBUFFER_UNSUPPORTED        0x8CDD
+#define GL_FRAMEBUFFER_BINDING            0x8CA6
+#define GL_RENDERBUFFER_BINDING           0x8CA7
+#define GL_MAX_RENDERBUFFER_SIZE          0x84E8
+#define GL_INVALID_FRAMEBUFFER_OPERATION  0x0506
+typedef void (GL_APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
+typedef void (GL_APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
+typedef void (GL_APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name);
+typedef void (GL_APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
+typedef void (GL_APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer);
+typedef void (GL_APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer);
+typedef void (GL_APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture);
+typedef void (GL_APIENTRYP PFNGLBLENDCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
+typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
+typedef void (GL_APIENTRYP PFNGLBLENDFUNCPROC) (GLenum sfactor, GLenum dfactor);
+typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+typedef void (GL_APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
+typedef void (GL_APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
+typedef GLenum (GL_APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target);
+typedef void (GL_APIENTRYP PFNGLCLEARPROC) (GLbitfield mask);
+typedef void (GL_APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+typedef void (GL_APIENTRYP PFNGLCLEARDEPTHFPROC) (GLfloat d);
+typedef void (GL_APIENTRYP PFNGLCLEARSTENCILPROC) (GLint s);
+typedef void (GL_APIENTRYP PFNGLCOLORMASKPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+typedef void (GL_APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
+typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data);
+typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data);
+typedef void (GL_APIENTRYP PFNGLCOPYTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef GLuint (GL_APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
+typedef GLuint (GL_APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
+typedef void (GL_APIENTRYP PFNGLCULLFACEPROC) (GLenum mode);
+typedef void (GL_APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
+typedef void (GL_APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers);
+typedef void (GL_APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
+typedef void (GL_APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers);
+typedef void (GL_APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
+typedef void (GL_APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures);
+typedef void (GL_APIENTRYP PFNGLDEPTHFUNCPROC) (GLenum func);
+typedef void (GL_APIENTRYP PFNGLDEPTHMASKPROC) (GLboolean flag);
+typedef void (GL_APIENTRYP PFNGLDEPTHRANGEFPROC) (GLfloat n, GLfloat f);
+typedef void (GL_APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
+typedef void (GL_APIENTRYP PFNGLDISABLEPROC) (GLenum cap);
+typedef void (GL_APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
+typedef void (GL_APIENTRYP PFNGLDRAWARRAYSPROC) (GLenum mode, GLint first, GLsizei count);
+typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices);
+typedef void (GL_APIENTRYP PFNGLENABLEPROC) (GLenum cap);
+typedef void (GL_APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
+typedef void (GL_APIENTRYP PFNGLFINISHPROC) (void);
+typedef void (GL_APIENTRYP PFNGLFLUSHPROC) (void);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+typedef void (GL_APIENTRYP PFNGLFRONTFACEPROC) (GLenum mode);
+typedef void (GL_APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
+typedef void (GL_APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target);
+typedef void (GL_APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers);
+typedef void (GL_APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers);
+typedef void (GL_APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures);
+typedef void (GL_APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
+typedef void (GL_APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
+typedef void (GL_APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders);
+typedef GLint (GL_APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
+typedef void (GL_APIENTRYP PFNGLGETBOOLEANVPROC) (GLenum pname, GLboolean *data);
+typedef void (GL_APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef GLenum (GL_APIENTRYP PFNGLGETERRORPROC) (void);
+typedef void (GL_APIENTRYP PFNGLGETFLOATVPROC) (GLenum pname, GLfloat *data);
+typedef void (GL_APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data);
+typedef void (GL_APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+typedef void (GL_APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+typedef void (GL_APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision);
+typedef void (GL_APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source);
+typedef const GLubyte *(GL_APIENTRYP PFNGLGETSTRINGPROC) (GLenum name);
+typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params);
+typedef void (GL_APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params);
+typedef GLint (GL_APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
+typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params);
+typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer);
+typedef void (GL_APIENTRYP PFNGLHINTPROC) (GLenum target, GLenum mode);
+typedef GLboolean (GL_APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer);
+typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDPROC) (GLenum cap);
+typedef GLboolean (GL_APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer);
+typedef GLboolean (GL_APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
+typedef GLboolean (GL_APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer);
+typedef GLboolean (GL_APIENTRYP PFNGLISSHADERPROC) (GLuint shader);
+typedef GLboolean (GL_APIENTRYP PFNGLISTEXTUREPROC) (GLuint texture);
+typedef void (GL_APIENTRYP PFNGLLINEWIDTHPROC) (GLfloat width);
+typedef void (GL_APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
+typedef void (GL_APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param);
+typedef void (GL_APIENTRYP PFNGLPOLYGONOFFSETPROC) (GLfloat factor, GLfloat units);
+typedef void (GL_APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
+typedef void (GL_APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void);
+typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLfloat value, GLboolean invert);
+typedef void (GL_APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length);
+typedef void (GL_APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
+typedef void (GL_APIENTRYP PFNGLSTENCILFUNCPROC) (GLenum func, GLint ref, GLuint mask);
+typedef void (GL_APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask);
+typedef void (GL_APIENTRYP PFNGLSTENCILMASKPROC) (GLuint mask);
+typedef void (GL_APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask);
+typedef void (GL_APIENTRYP PFNGLSTENCILOPPROC) (GLenum fail, GLenum zfail, GLenum zpass);
+typedef void (GL_APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
+typedef void (GL_APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
+typedef void (GL_APIENTRYP PFNGLTEXPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat param);
+typedef void (GL_APIENTRYP PFNGLTEXPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);
+typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);
+typedef void (GL_APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0);
+typedef void (GL_APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
+typedef void (GL_APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1);
+typedef void (GL_APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1);
+typedef void (GL_APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+typedef void (GL_APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2);
+typedef void (GL_APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+typedef void (GL_APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+typedef void (GL_APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
+typedef void (GL_APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program);
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x);
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y);
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
+typedef void (GL_APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
+#if GL_GLES_PROTOTYPES
+GL_APICALL void GL_APIENTRY glActiveTexture (GLenum texture);
+GL_APICALL void GL_APIENTRY glAttachShader (GLuint program, GLuint shader);
+GL_APICALL void GL_APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar *name);
+GL_APICALL void GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer);
+GL_APICALL void GL_APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer);
+GL_APICALL void GL_APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer);
+GL_APICALL void GL_APIENTRY glBindTexture (GLenum target, GLuint texture);
+GL_APICALL void GL_APIENTRY glBlendColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+GL_APICALL void GL_APIENTRY glBlendEquation (GLenum mode);
+GL_APICALL void GL_APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
+GL_APICALL void GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor);
+GL_APICALL void GL_APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+GL_APICALL void GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
+GL_APICALL void GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
+GL_APICALL GLenum GL_APIENTRY glCheckFramebufferStatus (GLenum target);
+GL_APICALL void GL_APIENTRY glClear (GLbitfield mask);
+GL_APICALL void GL_APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+GL_APICALL void GL_APIENTRY glClearDepthf (GLfloat d);
+GL_APICALL void GL_APIENTRY glClearStencil (GLint s);
+GL_APICALL void GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+GL_APICALL void GL_APIENTRY glCompileShader (GLuint shader);
+GL_APICALL void GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data);
+GL_APICALL void GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data);
+GL_APICALL void GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+GL_APICALL void GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GL_APICALL GLuint GL_APIENTRY glCreateProgram (void);
+GL_APICALL GLuint GL_APIENTRY glCreateShader (GLenum type);
+GL_APICALL void GL_APIENTRY glCullFace (GLenum mode);
+GL_APICALL void GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);
+GL_APICALL void GL_APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint *framebuffers);
+GL_APICALL void GL_APIENTRY glDeleteProgram (GLuint program);
+GL_APICALL void GL_APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint *renderbuffers);
+GL_APICALL void GL_APIENTRY glDeleteShader (GLuint shader);
+GL_APICALL void GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
+GL_APICALL void GL_APIENTRY glDepthFunc (GLenum func);
+GL_APICALL void GL_APIENTRY glDepthMask (GLboolean flag);
+GL_APICALL void GL_APIENTRY glDepthRangef (GLfloat n, GLfloat f);
+GL_APICALL void GL_APIENTRY glDetachShader (GLuint program, GLuint shader);
+GL_APICALL void GL_APIENTRY glDisable (GLenum cap);
+GL_APICALL void GL_APIENTRY glDisableVertexAttribArray (GLuint index);
+GL_APICALL void GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count);
+GL_APICALL void GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices);
+GL_APICALL void GL_APIENTRY glEnable (GLenum cap);
+GL_APICALL void GL_APIENTRY glEnableVertexAttribArray (GLuint index);
+GL_APICALL void GL_APIENTRY glFinish (void);
+GL_APICALL void GL_APIENTRY glFlush (void);
+GL_APICALL void GL_APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+GL_APICALL void GL_APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+GL_APICALL void GL_APIENTRY glFrontFace (GLenum mode);
+GL_APICALL void GL_APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);
+GL_APICALL void GL_APIENTRY glGenerateMipmap (GLenum target);
+GL_APICALL void GL_APIENTRY glGenFramebuffers (GLsizei n, GLuint *framebuffers);
+GL_APICALL void GL_APIENTRY glGenRenderbuffers (GLsizei n, GLuint *renderbuffers);
+GL_APICALL void GL_APIENTRY glGenTextures (GLsizei n, GLuint *textures);
+GL_APICALL void GL_APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
+GL_APICALL void GL_APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
+GL_APICALL void GL_APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders);
+GL_APICALL GLint GL_APIENTRY glGetAttribLocation (GLuint program, const GLchar *name);
+GL_APICALL void GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean *data);
+GL_APICALL void GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params);
+GL_APICALL GLenum GL_APIENTRY glGetError (void);
+GL_APICALL void GL_APIENTRY glGetFloatv (GLenum pname, GLfloat *data);
+GL_APICALL void GL_APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetIntegerv (GLenum pname, GLint *data);
+GL_APICALL void GL_APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+GL_APICALL void GL_APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+GL_APICALL void GL_APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision);
+GL_APICALL void GL_APIENTRY glGetShaderSource (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source);
+GL_APICALL const GLubyte *GL_APIENTRY glGetString (GLenum name);
+GL_APICALL void GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat *params);
+GL_APICALL void GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat *params);
+GL_APICALL void GL_APIENTRY glGetUniformiv (GLuint program, GLint location, GLint *params);
+GL_APICALL GLint GL_APIENTRY glGetUniformLocation (GLuint program, const GLchar *name);
+GL_APICALL void GL_APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat *params);
+GL_APICALL void GL_APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer);
+GL_APICALL void GL_APIENTRY glHint (GLenum target, GLenum mode);
+GL_APICALL GLboolean GL_APIENTRY glIsBuffer (GLuint buffer);
+GL_APICALL GLboolean GL_APIENTRY glIsEnabled (GLenum cap);
+GL_APICALL GLboolean GL_APIENTRY glIsFramebuffer (GLuint framebuffer);
+GL_APICALL GLboolean GL_APIENTRY glIsProgram (GLuint program);
+GL_APICALL GLboolean GL_APIENTRY glIsRenderbuffer (GLuint renderbuffer);
+GL_APICALL GLboolean GL_APIENTRY glIsShader (GLuint shader);
+GL_APICALL GLboolean GL_APIENTRY glIsTexture (GLuint texture);
+GL_APICALL void GL_APIENTRY glLineWidth (GLfloat width);
+GL_APICALL void GL_APIENTRY glLinkProgram (GLuint program);
+GL_APICALL void GL_APIENTRY glPixelStorei (GLenum pname, GLint param);
+GL_APICALL void GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units);
+GL_APICALL void GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
+GL_APICALL void GL_APIENTRY glReleaseShaderCompiler (void);
+GL_APICALL void GL_APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glSampleCoverage (GLfloat value, GLboolean invert);
+GL_APICALL void GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length);
+GL_APICALL void GL_APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
+GL_APICALL void GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask);
+GL_APICALL void GL_APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask);
+GL_APICALL void GL_APIENTRY glStencilMask (GLuint mask);
+GL_APICALL void GL_APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask);
+GL_APICALL void GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass);
+GL_APICALL void GL_APIENTRY glStencilOpSeparate (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
+GL_APICALL void GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
+GL_APICALL void GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param);
+GL_APICALL void GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat *params);
+GL_APICALL void GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
+GL_APICALL void GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint *params);
+GL_APICALL void GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels);
+GL_APICALL void GL_APIENTRY glUniform1f (GLint location, GLfloat v0);
+GL_APICALL void GL_APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniform1i (GLint location, GLint v0);
+GL_APICALL void GL_APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glUniform2f (GLint location, GLfloat v0, GLfloat v1);
+GL_APICALL void GL_APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniform2i (GLint location, GLint v0, GLint v1);
+GL_APICALL void GL_APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glUniform3f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+GL_APICALL void GL_APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniform3i (GLint location, GLint v0, GLint v1, GLint v2);
+GL_APICALL void GL_APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glUniform4f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+GL_APICALL void GL_APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniform4i (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+GL_APICALL void GL_APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUseProgram (GLuint program);
+GL_APICALL void GL_APIENTRY glValidateProgram (GLuint program);
+GL_APICALL void GL_APIENTRY glVertexAttrib1f (GLuint index, GLfloat x);
+GL_APICALL void GL_APIENTRY glVertexAttrib1fv (GLuint index, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glVertexAttrib2f (GLuint index, GLfloat x, GLfloat y);
+GL_APICALL void GL_APIENTRY glVertexAttrib2fv (GLuint index, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glVertexAttrib3f (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+GL_APICALL void GL_APIENTRY glVertexAttrib3fv (GLuint index, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glVertexAttrib4f (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GL_APICALL void GL_APIENTRY glVertexAttrib4fv (GLuint index, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
+GL_APICALL void GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
+#endif
+#endif /* GL_ES_VERSION_2_0 */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/video/khronos/GLES2/gl2ext.h b/src/video/khronos/GLES2/gl2ext.h
new file mode 100644
index 0000000..4e1488c
--- /dev/null
+++ b/src/video/khronos/GLES2/gl2ext.h
@@ -0,0 +1,3505 @@
+#ifndef __gl2ext_h_
+#define __gl2ext_h_ 1
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** Copyright (c) 2013-2017 The Khronos Group Inc.
+**
+** Permission is hereby granted, free of charge, to any person obtaining a
+** copy of this software and/or associated documentation files (the
+** "Materials"), to deal in the Materials without restriction, including
+** without limitation the rights to use, copy, modify, merge, publish,
+** distribute, sublicense, and/or sell copies of the Materials, and to
+** permit persons to whom the Materials are 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 Materials.
+**
+** THE MATERIALS ARE 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
+** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
+*/
+/*
+** This header is generated from the Khronos OpenGL / OpenGL ES XML
+** API Registry. The current version of the Registry, generator scripts
+** used to make the header, and the header can be found at
+**   https://github.com/KhronosGroup/OpenGL-Registry
+*/
+
+#ifndef GL_APIENTRYP
+#define GL_APIENTRYP GL_APIENTRY*
+#endif
+
+/* Generated on date 20170817 */
+
+/* Generated C header for:
+ * API: gles2
+ * Profile: common
+ * Versions considered: 2\.[0-9]
+ * Versions emitted: _nomatch_^
+ * Default extensions included: gles2
+ * Additional extensions included: _nomatch_^
+ * Extensions removed: _nomatch_^
+ */
+
+#ifndef GL_KHR_blend_equation_advanced
+#define GL_KHR_blend_equation_advanced 1
+#define GL_MULTIPLY_KHR                   0x9294
+#define GL_SCREEN_KHR                     0x9295
+#define GL_OVERLAY_KHR                    0x9296
+#define GL_DARKEN_KHR                     0x9297
+#define GL_LIGHTEN_KHR                    0x9298
+#define GL_COLORDODGE_KHR                 0x9299
+#define GL_COLORBURN_KHR                  0x929A
+#define GL_HARDLIGHT_KHR                  0x929B
+#define GL_SOFTLIGHT_KHR                  0x929C
+#define GL_DIFFERENCE_KHR                 0x929E
+#define GL_EXCLUSION_KHR                  0x92A0
+#define GL_HSL_HUE_KHR                    0x92AD
+#define GL_HSL_SATURATION_KHR             0x92AE
+#define GL_HSL_COLOR_KHR                  0x92AF
+#define GL_HSL_LUMINOSITY_KHR             0x92B0
+typedef void (GL_APIENTRYP PFNGLBLENDBARRIERKHRPROC) (void);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glBlendBarrierKHR (void);
+#endif
+#endif /* GL_KHR_blend_equation_advanced */
+
+#ifndef GL_KHR_blend_equation_advanced_coherent
+#define GL_KHR_blend_equation_advanced_coherent 1
+#define GL_BLEND_ADVANCED_COHERENT_KHR    0x9285
+#endif /* GL_KHR_blend_equation_advanced_coherent */
+
+#ifndef GL_KHR_context_flush_control
+#define GL_KHR_context_flush_control 1
+#define GL_CONTEXT_RELEASE_BEHAVIOR_KHR   0x82FB
+#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR 0x82FC
+#endif /* GL_KHR_context_flush_control */
+
+#ifndef GL_KHR_debug
+#define GL_KHR_debug 1
+typedef void (GL_APIENTRY  *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
+#define GL_SAMPLER                        0x82E6
+#define GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR   0x8242
+#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_KHR 0x8243
+#define GL_DEBUG_CALLBACK_FUNCTION_KHR    0x8244
+#define GL_DEBUG_CALLBACK_USER_PARAM_KHR  0x8245
+#define GL_DEBUG_SOURCE_API_KHR           0x8246
+#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR 0x8247
+#define GL_DEBUG_SOURCE_SHADER_COMPILER_KHR 0x8248
+#define GL_DEBUG_SOURCE_THIRD_PARTY_KHR   0x8249
+#define GL_DEBUG_SOURCE_APPLICATION_KHR   0x824A
+#define GL_DEBUG_SOURCE_OTHER_KHR         0x824B
+#define GL_DEBUG_TYPE_ERROR_KHR           0x824C
+#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR 0x824D
+#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR 0x824E
+#define GL_DEBUG_TYPE_PORTABILITY_KHR     0x824F
+#define GL_DEBUG_TYPE_PERFORMANCE_KHR     0x8250
+#define GL_DEBUG_TYPE_OTHER_KHR           0x8251
+#define GL_DEBUG_TYPE_MARKER_KHR          0x8268
+#define GL_DEBUG_TYPE_PUSH_GROUP_KHR      0x8269
+#define GL_DEBUG_TYPE_POP_GROUP_KHR       0x826A
+#define GL_DEBUG_SEVERITY_NOTIFICATION_KHR 0x826B
+#define GL_MAX_DEBUG_GROUP_STACK_DEPTH_KHR 0x826C
+#define GL_DEBUG_GROUP_STACK_DEPTH_KHR    0x826D
+#define GL_BUFFER_KHR                     0x82E0
+#define GL_SHADER_KHR                     0x82E1
+#define GL_PROGRAM_KHR                    0x82E2
+#define GL_VERTEX_ARRAY_KHR               0x8074
+#define GL_QUERY_KHR                      0x82E3
+#define GL_PROGRAM_PIPELINE_KHR           0x82E4
+#define GL_SAMPLER_KHR                    0x82E6
+#define GL_MAX_LABEL_LENGTH_KHR           0x82E8
+#define GL_MAX_DEBUG_MESSAGE_LENGTH_KHR   0x9143
+#define GL_MAX_DEBUG_LOGGED_MESSAGES_KHR  0x9144
+#define GL_DEBUG_LOGGED_MESSAGES_KHR      0x9145
+#define GL_DEBUG_SEVERITY_HIGH_KHR        0x9146
+#define GL_DEBUG_SEVERITY_MEDIUM_KHR      0x9147
+#define GL_DEBUG_SEVERITY_LOW_KHR         0x9148
+#define GL_DEBUG_OUTPUT_KHR               0x92E0
+#define GL_CONTEXT_FLAG_DEBUG_BIT_KHR     0x00000002
+#define GL_STACK_OVERFLOW_KHR             0x0503
+#define GL_STACK_UNDERFLOW_KHR            0x0504
+typedef void (GL_APIENTRYP PFNGLDEBUGMESSAGECONTROLKHRPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);
+typedef void (GL_APIENTRYP PFNGLDEBUGMESSAGEINSERTKHRPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf);
+typedef void (GL_APIENTRYP PFNGLDEBUGMESSAGECALLBACKKHRPROC) (GLDEBUGPROCKHR callback, const void *userParam);
+typedef GLuint (GL_APIENTRYP PFNGLGETDEBUGMESSAGELOGKHRPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog);
+typedef void (GL_APIENTRYP PFNGLPUSHDEBUGGROUPKHRPROC) (GLenum source, GLuint id, GLsizei length, const GLchar *message);
+typedef void (GL_APIENTRYP PFNGLPOPDEBUGGROUPKHRPROC) (void);
+typedef void (GL_APIENTRYP PFNGLOBJECTLABELKHRPROC) (GLenum identifier, GLuint name, GLsizei length, const GLchar *label);
+typedef void (GL_APIENTRYP PFNGLGETOBJECTLABELKHRPROC) (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label);
+typedef void (GL_APIENTRYP PFNGLOBJECTPTRLABELKHRPROC) (const void *ptr, GLsizei length, const GLchar *label);
+typedef void (GL_APIENTRYP PFNGLGETOBJECTPTRLABELKHRPROC) (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label);
+typedef void (GL_APIENTRYP PFNGLGETPOINTERVKHRPROC) (GLenum pname, void **params);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDebugMessageControlKHR (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);
+GL_APICALL void GL_APIENTRY glDebugMessageInsertKHR (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf);
+GL_APICALL void GL_APIENTRY glDebugMessageCallbackKHR (GLDEBUGPROCKHR callback, const void *userParam);
+GL_APICALL GLuint GL_APIENTRY glGetDebugMessageLogKHR (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog);
+GL_APICALL void GL_APIENTRY glPushDebugGroupKHR (GLenum source, GLuint id, GLsizei length, const GLchar *message);
+GL_APICALL void GL_APIENTRY glPopDebugGroupKHR (void);
+GL_APICALL void GL_APIENTRY glObjectLabelKHR (GLenum identifier, GLuint name, GLsizei length, const GLchar *label);
+GL_APICALL void GL_APIENTRY glGetObjectLabelKHR (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label);
+GL_APICALL void GL_APIENTRY glObjectPtrLabelKHR (const void *ptr, GLsizei length, const GLchar *label);
+GL_APICALL void GL_APIENTRY glGetObjectPtrLabelKHR (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label);
+GL_APICALL void GL_APIENTRY glGetPointervKHR (GLenum pname, void **params);
+#endif
+#endif /* GL_KHR_debug */
+
+#ifndef GL_KHR_no_error
+#define GL_KHR_no_error 1
+#define GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR  0x00000008
+#endif /* GL_KHR_no_error */
+
+#ifndef GL_KHR_parallel_shader_compile
+#define GL_KHR_parallel_shader_compile 1
+#define GL_MAX_SHADER_COMPILER_THREADS_KHR 0x91B0
+#define GL_COMPLETION_STATUS_KHR          0x91B1
+typedef void (GL_APIENTRYP PFNGLMAXSHADERCOMPILERTHREADSKHRPROC) (GLuint count);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glMaxShaderCompilerThreadsKHR (GLuint count);
+#endif
+#endif /* GL_KHR_parallel_shader_compile */
+
+#ifndef GL_KHR_robust_buffer_access_behavior
+#define GL_KHR_robust_buffer_access_behavior 1
+#endif /* GL_KHR_robust_buffer_access_behavior */
+
+#ifndef GL_KHR_robustness
+#define GL_KHR_robustness 1
+#define GL_CONTEXT_ROBUST_ACCESS_KHR      0x90F3
+#define GL_LOSE_CONTEXT_ON_RESET_KHR      0x8252
+#define GL_GUILTY_CONTEXT_RESET_KHR       0x8253
+#define GL_INNOCENT_CONTEXT_RESET_KHR     0x8254
+#define GL_UNKNOWN_CONTEXT_RESET_KHR      0x8255
+#define GL_RESET_NOTIFICATION_STRATEGY_KHR 0x8256
+#define GL_NO_RESET_NOTIFICATION_KHR      0x8261
+#define GL_CONTEXT_LOST_KHR               0x0507
+typedef GLenum (GL_APIENTRYP PFNGLGETGRAPHICSRESETSTATUSKHRPROC) (void);
+typedef void (GL_APIENTRYP PFNGLREADNPIXELSKHRPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);
+typedef void (GL_APIENTRYP PFNGLGETNUNIFORMFVKHRPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params);
+typedef void (GL_APIENTRYP PFNGLGETNUNIFORMIVKHRPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETNUNIFORMUIVKHRPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL GLenum GL_APIENTRY glGetGraphicsResetStatusKHR (void);
+GL_APICALL void GL_APIENTRY glReadnPixelsKHR (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);
+GL_APICALL void GL_APIENTRY glGetnUniformfvKHR (GLuint program, GLint location, GLsizei bufSize, GLfloat *params);
+GL_APICALL void GL_APIENTRY glGetnUniformivKHR (GLuint program, GLint location, GLsizei bufSize, GLint *params);
+GL_APICALL void GL_APIENTRY glGetnUniformuivKHR (GLuint program, GLint location, GLsizei bufSize, GLuint *params);
+#endif
+#endif /* GL_KHR_robustness */
+
+#ifndef GL_KHR_texture_compression_astc_hdr
+#define GL_KHR_texture_compression_astc_hdr 1
+#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR   0x93B0
+#define GL_COMPRESSED_RGBA_ASTC_5x4_KHR   0x93B1
+#define GL_COMPRESSED_RGBA_ASTC_5x5_KHR   0x93B2
+#define GL_COMPRESSED_RGBA_ASTC_6x5_KHR   0x93B3
+#define GL_COMPRESSED_RGBA_ASTC_6x6_KHR   0x93B4
+#define GL_COMPRESSED_RGBA_ASTC_8x5_KHR   0x93B5
+#define GL_COMPRESSED_RGBA_ASTC_8x6_KHR   0x93B6
+#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR   0x93B7
+#define GL_COMPRESSED_RGBA_ASTC_10x5_KHR  0x93B8
+#define GL_COMPRESSED_RGBA_ASTC_10x6_KHR  0x93B9
+#define GL_COMPRESSED_RGBA_ASTC_10x8_KHR  0x93BA
+#define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB
+#define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC
+#define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD
+#endif /* GL_KHR_texture_compression_astc_hdr */
+
+#ifndef GL_KHR_texture_compression_astc_ldr
+#define GL_KHR_texture_compression_astc_ldr 1
+#endif /* GL_KHR_texture_compression_astc_ldr */
+
+#ifndef GL_KHR_texture_compression_astc_sliced_3d
+#define GL_KHR_texture_compression_astc_sliced_3d 1
+#endif /* GL_KHR_texture_compression_astc_sliced_3d */
+
+#ifndef GL_OES_EGL_image
+#define GL_OES_EGL_image 1
+typedef void *GLeglImageOES;
+typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);
+typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glEGLImageTargetTexture2DOES (GLenum target, GLeglImageOES image);
+GL_APICALL void GL_APIENTRY glEGLImageTargetRenderbufferStorageOES (GLenum target, GLeglImageOES image);
+#endif
+#endif /* GL_OES_EGL_image */
+
+#ifndef GL_OES_EGL_image_external
+#define GL_OES_EGL_image_external 1
+#define GL_TEXTURE_EXTERNAL_OES           0x8D65
+#define GL_TEXTURE_BINDING_EXTERNAL_OES   0x8D67
+#define GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES 0x8D68
+#define GL_SAMPLER_EXTERNAL_OES           0x8D66
+#endif /* GL_OES_EGL_image_external */
+
+#ifndef GL_OES_EGL_image_external_essl3
+#define GL_OES_EGL_image_external_essl3 1
+#endif /* GL_OES_EGL_image_external_essl3 */
+
+#ifndef GL_OES_compressed_ETC1_RGB8_sub_texture
+#define GL_OES_compressed_ETC1_RGB8_sub_texture 1
+#endif /* GL_OES_compressed_ETC1_RGB8_sub_texture */
+
+#ifndef GL_OES_compressed_ETC1_RGB8_texture
+#define GL_OES_compressed_ETC1_RGB8_texture 1
+#define GL_ETC1_RGB8_OES                  0x8D64
+#endif /* GL_OES_compressed_ETC1_RGB8_texture */
+
+#ifndef GL_OES_compressed_paletted_texture
+#define GL_OES_compressed_paletted_texture 1
+#define GL_PALETTE4_RGB8_OES              0x8B90
+#define GL_PALETTE4_RGBA8_OES             0x8B91
+#define GL_PALETTE4_R5_G6_B5_OES          0x8B92
+#define GL_PALETTE4_RGBA4_OES             0x8B93
+#define GL_PALETTE4_RGB5_A1_OES           0x8B94
+#define GL_PALETTE8_RGB8_OES              0x8B95
+#define GL_PALETTE8_RGBA8_OES             0x8B96
+#define GL_PALETTE8_R5_G6_B5_OES          0x8B97
+#define GL_PALETTE8_RGBA4_OES             0x8B98
+#define GL_PALETTE8_RGB5_A1_OES           0x8B99
+#endif /* GL_OES_compressed_paletted_texture */
+
+#ifndef GL_OES_copy_image
+#define GL_OES_copy_image 1
+typedef void (GL_APIENTRYP PFNGLCOPYIMAGESUBDATAOESPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glCopyImageSubDataOES (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth);
+#endif
+#endif /* GL_OES_copy_image */
+
+#ifndef GL_OES_depth24
+#define GL_OES_depth24 1
+#define GL_DEPTH_COMPONENT24_OES          0x81A6
+#endif /* GL_OES_depth24 */
+
+#ifndef GL_OES_depth32
+#define GL_OES_depth32 1
+#define GL_DEPTH_COMPONENT32_OES          0x81A7
+#endif /* GL_OES_depth32 */
+
+#ifndef GL_OES_depth_texture
+#define GL_OES_depth_texture 1
+#endif /* GL_OES_depth_texture */
+
+#ifndef GL_OES_draw_buffers_indexed
+#define GL_OES_draw_buffers_indexed 1
+#define GL_MIN                            0x8007
+#define GL_MAX                            0x8008
+typedef void (GL_APIENTRYP PFNGLENABLEIOESPROC) (GLenum target, GLuint index);
+typedef void (GL_APIENTRYP PFNGLDISABLEIOESPROC) (GLenum target, GLuint index);
+typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONIOESPROC) (GLuint buf, GLenum mode);
+typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEIOESPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+typedef void (GL_APIENTRYP PFNGLBLENDFUNCIOESPROC) (GLuint buf, GLenum src, GLenum dst);
+typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEIOESPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+typedef void (GL_APIENTRYP PFNGLCOLORMASKIOESPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
+typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDIOESPROC) (GLenum target, GLuint index);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glEnableiOES (GLenum target, GLuint index);
+GL_APICALL void GL_APIENTRY glDisableiOES (GLenum target, GLuint index);
+GL_APICALL void GL_APIENTRY glBlendEquationiOES (GLuint buf, GLenum mode);
+GL_APICALL void GL_APIENTRY glBlendEquationSeparateiOES (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+GL_APICALL void GL_APIENTRY glBlendFunciOES (GLuint buf, GLenum src, GLenum dst);
+GL_APICALL void GL_APIENTRY glBlendFuncSeparateiOES (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+GL_APICALL void GL_APIENTRY glColorMaskiOES (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
+GL_APICALL GLboolean GL_APIENTRY glIsEnablediOES (GLenum target, GLuint index);
+#endif
+#endif /* GL_OES_draw_buffers_indexed */
+
+#ifndef GL_OES_draw_elements_base_vertex
+#define GL_OES_draw_elements_base_vertex 1
+typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXOESPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
+typedef void (GL_APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXOESPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex);
+typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXOESPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex);
+typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, const GLint *basevertex);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawElementsBaseVertexOES (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
+GL_APICALL void GL_APIENTRY glDrawRangeElementsBaseVertexOES (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex);
+GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseVertexOES (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex);
+GL_APICALL void GL_APIENTRY glMultiDrawElementsBaseVertexEXT (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, const GLint *basevertex);
+#endif
+#endif /* GL_OES_draw_elements_base_vertex */
+
+#ifndef GL_OES_element_index_uint
+#define GL_OES_element_index_uint 1
+#endif /* GL_OES_element_index_uint */
+
+#ifndef GL_OES_fbo_render_mipmap
+#define GL_OES_fbo_render_mipmap 1
+#endif /* GL_OES_fbo_render_mipmap */
+
+#ifndef GL_OES_fragment_precision_high
+#define GL_OES_fragment_precision_high 1
+#endif /* GL_OES_fragment_precision_high */
+
+#ifndef GL_OES_geometry_point_size
+#define GL_OES_geometry_point_size 1
+#endif /* GL_OES_geometry_point_size */
+
+#ifndef GL_OES_geometry_shader
+#define GL_OES_geometry_shader 1
+#define GL_GEOMETRY_SHADER_OES            0x8DD9
+#define GL_GEOMETRY_SHADER_BIT_OES        0x00000004
+#define GL_GEOMETRY_LINKED_VERTICES_OUT_OES 0x8916
+#define GL_GEOMETRY_LINKED_INPUT_TYPE_OES 0x8917
+#define GL_GEOMETRY_LINKED_OUTPUT_TYPE_OES 0x8918
+#define GL_GEOMETRY_SHADER_INVOCATIONS_OES 0x887F
+#define GL_LAYER_PROVOKING_VERTEX_OES     0x825E
+#define GL_LINES_ADJACENCY_OES            0x000A
+#define GL_LINE_STRIP_ADJACENCY_OES       0x000B
+#define GL_TRIANGLES_ADJACENCY_OES        0x000C
+#define GL_TRIANGLE_STRIP_ADJACENCY_OES   0x000D
+#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_OES 0x8DDF
+#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS_OES 0x8A2C
+#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS_OES 0x8A32
+#define GL_MAX_GEOMETRY_INPUT_COMPONENTS_OES 0x9123
+#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS_OES 0x9124
+#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_OES 0x8DE0
+#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_OES 0x8DE1
+#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS_OES 0x8E5A
+#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_OES 0x8C29
+#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS_OES 0x92CF
+#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS_OES 0x92D5
+#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS_OES 0x90CD
+#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS_OES 0x90D7
+#define GL_FIRST_VERTEX_CONVENTION_OES    0x8E4D
+#define GL_LAST_VERTEX_CONVENTION_OES     0x8E4E
+#define GL_UNDEFINED_VERTEX_OES           0x8260
+#define GL_PRIMITIVES_GENERATED_OES       0x8C87
+#define GL_FRAMEBUFFER_DEFAULT_LAYERS_OES 0x9312
+#define GL_MAX_FRAMEBUFFER_LAYERS_OES     0x9317
+#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_OES 0x8DA8
+#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_OES 0x8DA7
+#define GL_REFERENCED_BY_GEOMETRY_SHADER_OES 0x9309
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREOESPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glFramebufferTextureOES (GLenum target, GLenum attachment, GLuint texture, GLint level);
+#endif
+#endif /* GL_OES_geometry_shader */
+
+#ifndef GL_OES_get_program_binary
+#define GL_OES_get_program_binary 1
+#define GL_PROGRAM_BINARY_LENGTH_OES      0x8741
+#define GL_NUM_PROGRAM_BINARY_FORMATS_OES 0x87FE
+#define GL_PROGRAM_BINARY_FORMATS_OES     0x87FF
+typedef void (GL_APIENTRYP PFNGLGETPROGRAMBINARYOESPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);
+typedef void (GL_APIENTRYP PFNGLPROGRAMBINARYOESPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLint length);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetProgramBinaryOES (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);
+GL_APICALL void GL_APIENTRY glProgramBinaryOES (GLuint program, GLenum binaryFormat, const void *binary, GLint length);
+#endif
+#endif /* GL_OES_get_program_binary */
+
+#ifndef GL_OES_gpu_shader5
+#define GL_OES_gpu_shader5 1
+#endif /* GL_OES_gpu_shader5 */
+
+#ifndef GL_OES_mapbuffer
+#define GL_OES_mapbuffer 1
+#define GL_WRITE_ONLY_OES                 0x88B9
+#define GL_BUFFER_ACCESS_OES              0x88BB
+#define GL_BUFFER_MAPPED_OES              0x88BC
+#define GL_BUFFER_MAP_POINTER_OES         0x88BD
+typedef void *(GL_APIENTRYP PFNGLMAPBUFFEROESPROC) (GLenum target, GLenum access);
+typedef GLboolean (GL_APIENTRYP PFNGLUNMAPBUFFEROESPROC) (GLenum target);
+typedef void (GL_APIENTRYP PFNGLGETBUFFERPOINTERVOESPROC) (GLenum target, GLenum pname, void **params);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void *GL_APIENTRY glMapBufferOES (GLenum target, GLenum access);
+GL_APICALL GLboolean GL_APIENTRY glUnmapBufferOES (GLenum target);
+GL_APICALL void GL_APIENTRY glGetBufferPointervOES (GLenum target, GLenum pname, void **params);
+#endif
+#endif /* GL_OES_mapbuffer */
+
+#ifndef GL_OES_packed_depth_stencil
+#define GL_OES_packed_depth_stencil 1
+#define GL_DEPTH_STENCIL_OES              0x84F9
+#define GL_UNSIGNED_INT_24_8_OES          0x84FA
+#define GL_DEPTH24_STENCIL8_OES           0x88F0
+#endif /* GL_OES_packed_depth_stencil */
+
+#ifndef GL_OES_primitive_bounding_box
+#define GL_OES_primitive_bounding_box 1
+#define GL_PRIMITIVE_BOUNDING_BOX_OES     0x92BE
+typedef void (GL_APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXOESPROC) (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glPrimitiveBoundingBoxOES (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW);
+#endif
+#endif /* GL_OES_primitive_bounding_box */
+
+#ifndef GL_OES_required_internalformat
+#define GL_OES_required_internalformat 1
+#define GL_ALPHA8_OES                     0x803C
+#define GL_DEPTH_COMPONENT16_OES          0x81A5
+#define GL_LUMINANCE4_ALPHA4_OES          0x8043
+#define GL_LUMINANCE8_ALPHA8_OES          0x8045
+#define GL_LUMINANCE8_OES                 0x8040
+#define GL_RGBA4_OES                      0x8056
+#define GL_RGB5_A1_OES                    0x8057
+#define GL_RGB565_OES                     0x8D62
+#define GL_RGB8_OES                       0x8051
+#define GL_RGBA8_OES                      0x8058
+#define GL_RGB10_EXT                      0x8052
+#define GL_RGB10_A2_EXT                   0x8059
+#endif /* GL_OES_required_internalformat */
+
+#ifndef GL_OES_rgb8_rgba8
+#define GL_OES_rgb8_rgba8 1
+#endif /* GL_OES_rgb8_rgba8 */
+
+#ifndef GL_OES_sample_shading
+#define GL_OES_sample_shading 1
+#define GL_SAMPLE_SHADING_OES             0x8C36
+#define GL_MIN_SAMPLE_SHADING_VALUE_OES   0x8C37
+typedef void (GL_APIENTRYP PFNGLMINSAMPLESHADINGOESPROC) (GLfloat value);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glMinSampleShadingOES (GLfloat value);
+#endif
+#endif /* GL_OES_sample_shading */
+
+#ifndef GL_OES_sample_variables
+#define GL_OES_sample_variables 1
+#endif /* GL_OES_sample_variables */
+
+#ifndef GL_OES_shader_image_atomic
+#define GL_OES_shader_image_atomic 1
+#endif /* GL_OES_shader_image_atomic */
+
+#ifndef GL_OES_shader_io_blocks
+#define GL_OES_shader_io_blocks 1
+#endif /* GL_OES_shader_io_blocks */
+
+#ifndef GL_OES_shader_multisample_interpolation
+#define GL_OES_shader_multisample_interpolation 1
+#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_OES 0x8E5B
+#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_OES 0x8E5C
+#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS_OES 0x8E5D
+#endif /* GL_OES_shader_multisample_interpolation */
+
+#ifndef GL_OES_standard_derivatives
+#define GL_OES_standard_derivatives 1
+#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES 0x8B8B
+#endif /* GL_OES_standard_derivatives */
+
+#ifndef GL_OES_stencil1
+#define GL_OES_stencil1 1
+#define GL_STENCIL_INDEX1_OES             0x8D46
+#endif /* GL_OES_stencil1 */
+
+#ifndef GL_OES_stencil4
+#define GL_OES_stencil4 1
+#define GL_STENCIL_INDEX4_OES             0x8D47
+#endif /* GL_OES_stencil4 */
+
+#ifndef GL_OES_surfaceless_context
+#define GL_OES_surfaceless_context 1
+#define GL_FRAMEBUFFER_UNDEFINED_OES      0x8219
+#endif /* GL_OES_surfaceless_context */
+
+#ifndef GL_OES_tessellation_point_size
+#define GL_OES_tessellation_point_size 1
+#endif /* GL_OES_tessellation_point_size */
+
+#ifndef GL_OES_tessellation_shader
+#define GL_OES_tessellation_shader 1
+#define GL_PATCHES_OES                    0x000E
+#define GL_PATCH_VERTICES_OES             0x8E72
+#define GL_TESS_CONTROL_OUTPUT_VERTICES_OES 0x8E75
+#define GL_TESS_GEN_MODE_OES              0x8E76
+#define GL_TESS_GEN_SPACING_OES           0x8E77
+#define GL_TESS_GEN_VERTEX_ORDER_OES      0x8E78
+#define GL_TESS_GEN_POINT_MODE_OES        0x8E79
+#define GL_ISOLINES_OES                   0x8E7A
+#define GL_QUADS_OES                      0x0007
+#define GL_FRACTIONAL_ODD_OES             0x8E7B
+#define GL_FRACTIONAL_EVEN_OES            0x8E7C
+#define GL_MAX_PATCH_VERTICES_OES         0x8E7D
+#define GL_MAX_TESS_GEN_LEVEL_OES         0x8E7E
+#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS_OES 0x8E7F
+#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS_OES 0x8E80
+#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS_OES 0x8E81
+#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS_OES 0x8E82
+#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS_OES 0x8E83
+#define GL_MAX_TESS_PATCH_COMPONENTS_OES  0x8E84
+#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS_OES 0x8E85
+#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS_OES 0x8E86
+#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS_OES 0x8E89
+#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS_OES 0x8E8A
+#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS_OES 0x886C
+#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS_OES 0x886D
+#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS_OES 0x8E1E
+#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS_OES 0x8E1F
+#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS_OES 0x92CD
+#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS_OES 0x92CE
+#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS_OES 0x92D3
+#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS_OES 0x92D4
+#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS_OES 0x90CB
+#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS_OES 0x90CC
+#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS_OES 0x90D8
+#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS_OES 0x90D9
+#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED_OES 0x8221
+#define GL_IS_PER_PATCH_OES               0x92E7
+#define GL_REFERENCED_BY_TESS_CONTROL_SHADER_OES 0x9307
+#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER_OES 0x9308
+#define GL_TESS_CONTROL_SHADER_OES        0x8E88
+#define GL_TESS_EVALUATION_SHADER_OES     0x8E87
+#define GL_TESS_CONTROL_SHADER_BIT_OES    0x00000008
+#define GL_TESS_EVALUATION_SHADER_BIT_OES 0x00000010
+typedef void (GL_APIENTRYP PFNGLPATCHPARAMETERIOESPROC) (GLenum pname, GLint value);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glPatchParameteriOES (GLenum pname, GLint value);
+#endif
+#endif /* GL_OES_tessellation_shader */
+
+#ifndef GL_OES_texture_3D
+#define GL_OES_texture_3D 1
+#define GL_TEXTURE_WRAP_R_OES             0x8072
+#define GL_TEXTURE_3D_OES                 0x806F
+#define GL_TEXTURE_BINDING_3D_OES         0x806A
+#define GL_MAX_3D_TEXTURE_SIZE_OES        0x8073
+#define GL_SAMPLER_3D_OES                 0x8B5F
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES 0x8CD4
+typedef void (GL_APIENTRYP PFNGLTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);
+typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);
+typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data);
+typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DOESPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels);
+GL_APICALL void GL_APIENTRY glTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels);
+GL_APICALL void GL_APIENTRY glCopyTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glCompressedTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data);
+GL_APICALL void GL_APIENTRY glCompressedTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data);
+GL_APICALL void GL_APIENTRY glFramebufferTexture3DOES (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+#endif
+#endif /* GL_OES_texture_3D */
+
+#ifndef GL_OES_texture_border_clamp
+#define GL_OES_texture_border_clamp 1
+#define GL_TEXTURE_BORDER_COLOR_OES       0x1004
+#define GL_CLAMP_TO_BORDER_OES            0x812D
+typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIIVOESPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIUIVOESPROC) (GLenum target, GLenum pname, const GLuint *params);
+typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIIVOESPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIUIVOESPROC) (GLenum target, GLenum pname, GLuint *params);
+typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIIVOESPROC) (GLuint sampler, GLenum pname, const GLint *param);
+typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIUIVOESPROC) (GLuint sampler, GLenum pname, const GLuint *param);
+typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIIVOESPROC) (GLuint sampler, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVOESPROC) (GLuint sampler, GLenum pname, GLuint *params);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexParameterIivOES (GLenum target, GLenum pname, const GLint *params);
+GL_APICALL void GL_APIENTRY glTexParameterIuivOES (GLenum target, GLenum pname, const GLuint *params);
+GL_APICALL void GL_APIENTRY glGetTexParameterIivOES (GLenum target, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetTexParameterIuivOES (GLenum target, GLenum pname, GLuint *params);
+GL_APICALL void GL_APIENTRY glSamplerParameterIivOES (GLuint sampler, GLenum pname, const GLint *param);
+GL_APICALL void GL_APIENTRY glSamplerParameterIuivOES (GLuint sampler, GLenum pname, const GLuint *param);
+GL_APICALL void GL_APIENTRY glGetSamplerParameterIivOES (GLuint sampler, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetSamplerParameterIuivOES (GLuint sampler, GLenum pname, GLuint *params);
+#endif
+#endif /* GL_OES_texture_border_clamp */
+
+#ifndef GL_OES_texture_buffer
+#define GL_OES_texture_buffer 1
+#define GL_TEXTURE_BUFFER_OES             0x8C2A
+#define GL_TEXTURE_BUFFER_BINDING_OES     0x8C2A
+#define GL_MAX_TEXTURE_BUFFER_SIZE_OES    0x8C2B
+#define GL_TEXTURE_BINDING_BUFFER_OES     0x8C2C
+#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_OES 0x8C2D
+#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT_OES 0x919F
+#define GL_SAMPLER_BUFFER_OES             0x8DC2
+#define GL_INT_SAMPLER_BUFFER_OES         0x8DD0
+#define GL_UNSIGNED_INT_SAMPLER_BUFFER_OES 0x8DD8
+#define GL_IMAGE_BUFFER_OES               0x9051
+#define GL_INT_IMAGE_BUFFER_OES           0x905C
+#define GL_UNSIGNED_INT_IMAGE_BUFFER_OES  0x9067
+#define GL_TEXTURE_BUFFER_OFFSET_OES      0x919D
+#define GL_TEXTURE_BUFFER_SIZE_OES        0x919E
+typedef void (GL_APIENTRYP PFNGLTEXBUFFEROESPROC) (GLenum target, GLenum internalformat, GLuint buffer);
+typedef void (GL_APIENTRYP PFNGLTEXBUFFERRANGEOESPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexBufferOES (GLenum target, GLenum internalformat, GLuint buffer);
+GL_APICALL void GL_APIENTRY glTexBufferRangeOES (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);
+#endif
+#endif /* GL_OES_texture_buffer */
+
+#ifndef GL_OES_texture_compression_astc
+#define GL_OES_texture_compression_astc 1
+#define GL_COMPRESSED_RGBA_ASTC_3x3x3_OES 0x93C0
+#define GL_COMPRESSED_RGBA_ASTC_4x3x3_OES 0x93C1
+#define GL_COMPRESSED_RGBA_ASTC_4x4x3_OES 0x93C2
+#define GL_COMPRESSED_RGBA_ASTC_4x4x4_OES 0x93C3
+#define GL_COMPRESSED_RGBA_ASTC_5x4x4_OES 0x93C4
+#define GL_COMPRESSED_RGBA_ASTC_5x5x4_OES 0x93C5
+#define GL_COMPRESSED_RGBA_ASTC_5x5x5_OES 0x93C6
+#define GL_COMPRESSED_RGBA_ASTC_6x5x5_OES 0x93C7
+#define GL_COMPRESSED_RGBA_ASTC_6x6x5_OES 0x93C8
+#define GL_COMPRESSED_RGBA_ASTC_6x6x6_OES 0x93C9
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_3x3x3_OES 0x93E0
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x3x3_OES 0x93E1
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x3_OES 0x93E2
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x4_OES 0x93E3
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4x4_OES 0x93E4
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x4_OES 0x93E5
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x5_OES 0x93E6
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5x5_OES 0x93E7
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x5_OES 0x93E8
+#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x6_OES 0x93E9
+#endif /* GL_OES_texture_compression_astc */
+
+#ifndef GL_OES_texture_cube_map_array
+#define GL_OES_texture_cube_map_array 1
+#define GL_TEXTURE_CUBE_MAP_ARRAY_OES     0x9009
+#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_OES 0x900A
+#define GL_SAMPLER_CUBE_MAP_ARRAY_OES     0x900C
+#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_OES 0x900D
+#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_OES 0x900E
+#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_OES 0x900F
+#define GL_IMAGE_CUBE_MAP_ARRAY_OES       0x9054
+#define GL_INT_IMAGE_CUBE_MAP_ARRAY_OES   0x905F
+#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_OES 0x906A
+#endif /* GL_OES_texture_cube_map_array */
+
+#ifndef GL_OES_texture_float
+#define GL_OES_texture_float 1
+#endif /* GL_OES_texture_float */
+
+#ifndef GL_OES_texture_float_linear
+#define GL_OES_texture_float_linear 1
+#endif /* GL_OES_texture_float_linear */
+
+#ifndef GL_OES_texture_half_float
+#define GL_OES_texture_half_float 1
+#define GL_HALF_FLOAT_OES                 0x8D61
+#endif /* GL_OES_texture_half_float */
+
+#ifndef GL_OES_texture_half_float_linear
+#define GL_OES_texture_half_float_linear 1
+#endif /* GL_OES_texture_half_float_linear */
+
+#ifndef GL_OES_texture_npot
+#define GL_OES_texture_npot 1
+#endif /* GL_OES_texture_npot */
+
+#ifndef GL_OES_texture_stencil8
+#define GL_OES_texture_stencil8 1
+#define GL_STENCIL_INDEX_OES              0x1901
+#define GL_STENCIL_INDEX8_OES             0x8D48
+#endif /* GL_OES_texture_stencil8 */
+
+#ifndef GL_OES_texture_storage_multisample_2d_array
+#define GL_OES_texture_storage_multisample_2d_array 1
+#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY_OES 0x9102
+#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY_OES 0x9105
+#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY_OES 0x910B
+#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY_OES 0x910C
+#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY_OES 0x910D
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEOESPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexStorage3DMultisampleOES (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
+#endif
+#endif /* GL_OES_texture_storage_multisample_2d_array */
+
+#ifndef GL_OES_texture_view
+#define GL_OES_texture_view 1
+#define GL_TEXTURE_VIEW_MIN_LEVEL_OES     0x82DB
+#define GL_TEXTURE_VIEW_NUM_LEVELS_OES    0x82DC
+#define GL_TEXTURE_VIEW_MIN_LAYER_OES     0x82DD
+#define GL_TEXTURE_VIEW_NUM_LAYERS_OES    0x82DE
+#define GL_TEXTURE_IMMUTABLE_LEVELS       0x82DF
+typedef void (GL_APIENTRYP PFNGLTEXTUREVIEWOESPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTextureViewOES (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers);
+#endif
+#endif /* GL_OES_texture_view */
+
+#ifndef GL_OES_vertex_array_object
+#define GL_OES_vertex_array_object 1
+#define GL_VERTEX_ARRAY_BINDING_OES       0x85B5
+typedef void (GL_APIENTRYP PFNGLBINDVERTEXARRAYOESPROC) (GLuint array);
+typedef void (GL_APIENTRYP PFNGLDELETEVERTEXARRAYSOESPROC) (GLsizei n, const GLuint *arrays);
+typedef void (GL_APIENTRYP PFNGLGENVERTEXARRAYSOESPROC) (GLsizei n, GLuint *arrays);
+typedef GLboolean (GL_APIENTRYP PFNGLISVERTEXARRAYOESPROC) (GLuint array);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glBindVertexArrayOES (GLuint array);
+GL_APICALL void GL_APIENTRY glDeleteVertexArraysOES (GLsizei n, const GLuint *arrays);
+GL_APICALL void GL_APIENTRY glGenVertexArraysOES (GLsizei n, GLuint *arrays);
+GL_APICALL GLboolean GL_APIENTRY glIsVertexArrayOES (GLuint array);
+#endif
+#endif /* GL_OES_vertex_array_object */
+
+#ifndef GL_OES_vertex_half_float
+#define GL_OES_vertex_half_float 1
+#endif /* GL_OES_vertex_half_float */
+
+#ifndef GL_OES_vertex_type_10_10_10_2
+#define GL_OES_vertex_type_10_10_10_2 1
+#define GL_UNSIGNED_INT_10_10_10_2_OES    0x8DF6
+#define GL_INT_10_10_10_2_OES             0x8DF7
+#endif /* GL_OES_vertex_type_10_10_10_2 */
+
+#ifndef GL_OES_viewport_array
+#define GL_OES_viewport_array 1
+#define GL_MAX_VIEWPORTS_OES              0x825B
+#define GL_VIEWPORT_SUBPIXEL_BITS_OES     0x825C
+#define GL_VIEWPORT_BOUNDS_RANGE_OES      0x825D
+#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX_OES 0x825F
+typedef void (GL_APIENTRYP PFNGLVIEWPORTARRAYVOESPROC) (GLuint first, GLsizei count, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLVIEWPORTINDEXEDFOESPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h);
+typedef void (GL_APIENTRYP PFNGLVIEWPORTINDEXEDFVOESPROC) (GLuint index, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLSCISSORARRAYVOESPROC) (GLuint first, GLsizei count, const GLint *v);
+typedef void (GL_APIENTRYP PFNGLSCISSORINDEXEDOESPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLSCISSORINDEXEDVOESPROC) (GLuint index, const GLint *v);
+typedef void (GL_APIENTRYP PFNGLDEPTHRANGEARRAYFVOESPROC) (GLuint first, GLsizei count, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLDEPTHRANGEINDEXEDFOESPROC) (GLuint index, GLfloat n, GLfloat f);
+typedef void (GL_APIENTRYP PFNGLGETFLOATI_VOESPROC) (GLenum target, GLuint index, GLfloat *data);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glViewportArrayvOES (GLuint first, GLsizei count, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glViewportIndexedfOES (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h);
+GL_APICALL void GL_APIENTRY glViewportIndexedfvOES (GLuint index, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glScissorArrayvOES (GLuint first, GLsizei count, const GLint *v);
+GL_APICALL void GL_APIENTRY glScissorIndexedOES (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glScissorIndexedvOES (GLuint index, const GLint *v);
+GL_APICALL void GL_APIENTRY glDepthRangeArrayfvOES (GLuint first, GLsizei count, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glDepthRangeIndexedfOES (GLuint index, GLfloat n, GLfloat f);
+GL_APICALL void GL_APIENTRY glGetFloati_vOES (GLenum target, GLuint index, GLfloat *data);
+#endif
+#endif /* GL_OES_viewport_array */
+
+#ifndef GL_AMD_compressed_3DC_texture
+#define GL_AMD_compressed_3DC_texture 1
+#define GL_3DC_X_AMD                      0x87F9
+#define GL_3DC_XY_AMD                     0x87FA
+#endif /* GL_AMD_compressed_3DC_texture */
+
+#ifndef GL_AMD_compressed_ATC_texture
+#define GL_AMD_compressed_ATC_texture 1
+#define GL_ATC_RGB_AMD                    0x8C92
+#define GL_ATC_RGBA_EXPLICIT_ALPHA_AMD    0x8C93
+#define GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
+#endif /* GL_AMD_compressed_ATC_texture */
+
+#ifndef GL_AMD_performance_monitor
+#define GL_AMD_performance_monitor 1
+#define GL_COUNTER_TYPE_AMD               0x8BC0
+#define GL_COUNTER_RANGE_AMD              0x8BC1
+#define GL_UNSIGNED_INT64_AMD             0x8BC2
+#define GL_PERCENTAGE_AMD                 0x8BC3
+#define GL_PERFMON_RESULT_AVAILABLE_AMD   0x8BC4
+#define GL_PERFMON_RESULT_SIZE_AMD        0x8BC5
+#define GL_PERFMON_RESULT_AMD             0x8BC6
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void *data);
+typedef void (GL_APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);
+typedef void (GL_APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);
+typedef void (GL_APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList);
+typedef void (GL_APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor);
+typedef void (GL_APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, void *data);
+GL_APICALL void GL_APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors);
+GL_APICALL void GL_APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors);
+GL_APICALL void GL_APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList);
+GL_APICALL void GL_APIENTRY glBeginPerfMonitorAMD (GLuint monitor);
+GL_APICALL void GL_APIENTRY glEndPerfMonitorAMD (GLuint monitor);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);
+#endif
+#endif /* GL_AMD_performance_monitor */
+
+#ifndef GL_AMD_program_binary_Z400
+#define GL_AMD_program_binary_Z400 1
+#define GL_Z400_BINARY_AMD                0x8740
+#endif /* GL_AMD_program_binary_Z400 */
+
+#ifndef GL_ANDROID_extension_pack_es31a
+#define GL_ANDROID_extension_pack_es31a 1
+#endif /* GL_ANDROID_extension_pack_es31a */
+
+#ifndef GL_ANGLE_depth_texture
+#define GL_ANGLE_depth_texture 1
+#endif /* GL_ANGLE_depth_texture */
+
+#ifndef GL_ANGLE_framebuffer_blit
+#define GL_ANGLE_framebuffer_blit 1
+#define GL_READ_FRAMEBUFFER_ANGLE         0x8CA8
+#define GL_DRAW_FRAMEBUFFER_ANGLE         0x8CA9
+#define GL_DRAW_FRAMEBUFFER_BINDING_ANGLE 0x8CA6
+#define GL_READ_FRAMEBUFFER_BINDING_ANGLE 0x8CAA
+typedef void (GL_APIENTRYP PFNGLBLITFRAMEBUFFERANGLEPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glBlitFramebufferANGLE (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+#endif
+#endif /* GL_ANGLE_framebuffer_blit */
+
+#ifndef GL_ANGLE_framebuffer_multisample
+#define GL_ANGLE_framebuffer_multisample 1
+#define GL_RENDERBUFFER_SAMPLES_ANGLE     0x8CAB
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE 0x8D56
+#define GL_MAX_SAMPLES_ANGLE              0x8D57
+typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEANGLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleANGLE (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+#endif
+#endif /* GL_ANGLE_framebuffer_multisample */
+
+#ifndef GL_ANGLE_instanced_arrays
+#define GL_ANGLE_instanced_arrays 1
+#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE 0x88FE
+typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDANGLEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
+typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDANGLEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISORANGLEPROC) (GLuint index, GLuint divisor);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawArraysInstancedANGLE (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
+GL_APICALL void GL_APIENTRY glDrawElementsInstancedANGLE (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);
+GL_APICALL void GL_APIENTRY glVertexAttribDivisorANGLE (GLuint index, GLuint divisor);
+#endif
+#endif /* GL_ANGLE_instanced_arrays */
+
+#ifndef GL_ANGLE_pack_reverse_row_order
+#define GL_ANGLE_pack_reverse_row_order 1
+#define GL_PACK_REVERSE_ROW_ORDER_ANGLE   0x93A4
+#endif /* GL_ANGLE_pack_reverse_row_order */
+
+#ifndef GL_ANGLE_program_binary
+#define GL_ANGLE_program_binary 1
+#define GL_PROGRAM_BINARY_ANGLE           0x93A6
+#endif /* GL_ANGLE_program_binary */
+
+#ifndef GL_ANGLE_texture_compression_dxt3
+#define GL_ANGLE_texture_compression_dxt3 1
+#define GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE 0x83F2
+#endif /* GL_ANGLE_texture_compression_dxt3 */
+
+#ifndef GL_ANGLE_texture_compression_dxt5
+#define GL_ANGLE_texture_compression_dxt5 1
+#define GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE 0x83F3
+#endif /* GL_ANGLE_texture_compression_dxt5 */
+
+#ifndef GL_ANGLE_texture_usage
+#define GL_ANGLE_texture_usage 1
+#define GL_TEXTURE_USAGE_ANGLE            0x93A2
+#define GL_FRAMEBUFFER_ATTACHMENT_ANGLE   0x93A3
+#endif /* GL_ANGLE_texture_usage */
+
+#ifndef GL_ANGLE_translated_shader_source
+#define GL_ANGLE_translated_shader_source 1
+#define GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE 0x93A0
+typedef void (GL_APIENTRYP PFNGLGETTRANSLATEDSHADERSOURCEANGLEPROC) (GLuint shader, GLsizei bufsize, GLsizei *length, GLchar *source);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetTranslatedShaderSourceANGLE (GLuint shader, GLsizei bufsize, GLsizei *length, GLchar *source);
+#endif
+#endif /* GL_ANGLE_translated_shader_source */
+
+#ifndef GL_APPLE_clip_distance
+#define GL_APPLE_clip_distance 1
+#define GL_MAX_CLIP_DISTANCES_APPLE       0x0D32
+#define GL_CLIP_DISTANCE0_APPLE           0x3000
+#define GL_CLIP_DISTANCE1_APPLE           0x3001
+#define GL_CLIP_DISTANCE2_APPLE           0x3002
+#define GL_CLIP_DISTANCE3_APPLE           0x3003
+#define GL_CLIP_DISTANCE4_APPLE           0x3004
+#define GL_CLIP_DISTANCE5_APPLE           0x3005
+#define GL_CLIP_DISTANCE6_APPLE           0x3006
+#define GL_CLIP_DISTANCE7_APPLE           0x3007
+#endif /* GL_APPLE_clip_distance */
+
+#ifndef GL_APPLE_color_buffer_packed_float
+#define GL_APPLE_color_buffer_packed_float 1
+#endif /* GL_APPLE_color_buffer_packed_float */
+
+#ifndef GL_APPLE_copy_texture_levels
+#define GL_APPLE_copy_texture_levels 1
+typedef void (GL_APIENTRYP PFNGLCOPYTEXTURELEVELSAPPLEPROC) (GLuint destinationTexture, GLuint sourceTexture, GLint sourceBaseLevel, GLsizei sourceLevelCount);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glCopyTextureLevelsAPPLE (GLuint destinationTexture, GLuint sourceTexture, GLint sourceBaseLevel, GLsizei sourceLevelCount);
+#endif
+#endif /* GL_APPLE_copy_texture_levels */
+
+#ifndef GL_APPLE_framebuffer_multisample
+#define GL_APPLE_framebuffer_multisample 1
+#define GL_RENDERBUFFER_SAMPLES_APPLE     0x8CAB
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE 0x8D56
+#define GL_MAX_SAMPLES_APPLE              0x8D57
+#define GL_READ_FRAMEBUFFER_APPLE         0x8CA8
+#define GL_DRAW_FRAMEBUFFER_APPLE         0x8CA9
+#define GL_DRAW_FRAMEBUFFER_BINDING_APPLE 0x8CA6
+#define GL_READ_FRAMEBUFFER_BINDING_APPLE 0x8CAA
+typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEAPPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC) (void);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleAPPLE (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glResolveMultisampleFramebufferAPPLE (void);
+#endif
+#endif /* GL_APPLE_framebuffer_multisample */
+
+#ifndef GL_APPLE_rgb_422
+#define GL_APPLE_rgb_422 1
+#define GL_RGB_422_APPLE                  0x8A1F
+#define GL_UNSIGNED_SHORT_8_8_APPLE       0x85BA
+#define GL_UNSIGNED_SHORT_8_8_REV_APPLE   0x85BB
+#define GL_RGB_RAW_422_APPLE              0x8A51
+#endif /* GL_APPLE_rgb_422 */
+
+#ifndef GL_APPLE_sync
+#define GL_APPLE_sync 1
+#define GL_SYNC_OBJECT_APPLE              0x8A53
+#define GL_MAX_SERVER_WAIT_TIMEOUT_APPLE  0x9111
+#define GL_OBJECT_TYPE_APPLE              0x9112
+#define GL_SYNC_CONDITION_APPLE           0x9113
+#define GL_SYNC_STATUS_APPLE              0x9114
+#define GL_SYNC_FLAGS_APPLE               0x9115
+#define GL_SYNC_FENCE_APPLE               0x9116
+#define GL_SYNC_GPU_COMMANDS_COMPLETE_APPLE 0x9117
+#define GL_UNSIGNALED_APPLE               0x9118
+#define GL_SIGNALED_APPLE                 0x9119
+#define GL_ALREADY_SIGNALED_APPLE         0x911A
+#define GL_TIMEOUT_EXPIRED_APPLE          0x911B
+#define GL_CONDITION_SATISFIED_APPLE      0x911C
+#define GL_WAIT_FAILED_APPLE              0x911D
+#define GL_SYNC_FLUSH_COMMANDS_BIT_APPLE  0x00000001
+#define GL_TIMEOUT_IGNORED_APPLE          0xFFFFFFFFFFFFFFFFull
+typedef GLsync (GL_APIENTRYP PFNGLFENCESYNCAPPLEPROC) (GLenum condition, GLbitfield flags);
+typedef GLboolean (GL_APIENTRYP PFNGLISSYNCAPPLEPROC) (GLsync sync);
+typedef void (GL_APIENTRYP PFNGLDELETESYNCAPPLEPROC) (GLsync sync);
+typedef GLenum (GL_APIENTRYP PFNGLCLIENTWAITSYNCAPPLEPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout);
+typedef void (GL_APIENTRYP PFNGLWAITSYNCAPPLEPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout);
+typedef void (GL_APIENTRYP PFNGLGETINTEGER64VAPPLEPROC) (GLenum pname, GLint64 *params);
+typedef void (GL_APIENTRYP PFNGLGETSYNCIVAPPLEPROC) (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL GLsync GL_APIENTRY glFenceSyncAPPLE (GLenum condition, GLbitfield flags);
+GL_APICALL GLboolean GL_APIENTRY glIsSyncAPPLE (GLsync sync);
+GL_APICALL void GL_APIENTRY glDeleteSyncAPPLE (GLsync sync);
+GL_APICALL GLenum GL_APIENTRY glClientWaitSyncAPPLE (GLsync sync, GLbitfield flags, GLuint64 timeout);
+GL_APICALL void GL_APIENTRY glWaitSyncAPPLE (GLsync sync, GLbitfield flags, GLuint64 timeout);
+GL_APICALL void GL_APIENTRY glGetInteger64vAPPLE (GLenum pname, GLint64 *params);
+GL_APICALL void GL_APIENTRY glGetSyncivAPPLE (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
+#endif
+#endif /* GL_APPLE_sync */
+
+#ifndef GL_APPLE_texture_format_BGRA8888
+#define GL_APPLE_texture_format_BGRA8888 1
+#define GL_BGRA_EXT                       0x80E1
+#define GL_BGRA8_EXT                      0x93A1
+#endif /* GL_APPLE_texture_format_BGRA8888 */
+
+#ifndef GL_APPLE_texture_max_level
+#define GL_APPLE_texture_max_level 1
+#define GL_TEXTURE_MAX_LEVEL_APPLE        0x813D
+#endif /* GL_APPLE_texture_max_level */
+
+#ifndef GL_APPLE_texture_packed_float
+#define GL_APPLE_texture_packed_float 1
+#define GL_UNSIGNED_INT_10F_11F_11F_REV_APPLE 0x8C3B
+#define GL_UNSIGNED_INT_5_9_9_9_REV_APPLE 0x8C3E
+#define GL_R11F_G11F_B10F_APPLE           0x8C3A
+#define GL_RGB9_E5_APPLE                  0x8C3D
+#endif /* GL_APPLE_texture_packed_float */
+
+#ifndef GL_ARM_mali_program_binary
+#define GL_ARM_mali_program_binary 1
+#define GL_MALI_PROGRAM_BINARY_ARM        0x8F61
+#endif /* GL_ARM_mali_program_binary */
+
+#ifndef GL_ARM_mali_shader_binary
+#define GL_ARM_mali_shader_binary 1
+#define GL_MALI_SHADER_BINARY_ARM         0x8F60
+#endif /* GL_ARM_mali_shader_binary */
+
+#ifndef GL_ARM_rgba8
+#define GL_ARM_rgba8 1
+#endif /* GL_ARM_rgba8 */
+
+#ifndef GL_ARM_shader_framebuffer_fetch
+#define GL_ARM_shader_framebuffer_fetch 1
+#define GL_FETCH_PER_SAMPLE_ARM           0x8F65
+#define GL_FRAGMENT_SHADER_FRAMEBUFFER_FETCH_MRT_ARM 0x8F66
+#endif /* GL_ARM_shader_framebuffer_fetch */
+
+#ifndef GL_ARM_shader_framebuffer_fetch_depth_stencil
+#define GL_ARM_shader_framebuffer_fetch_depth_stencil 1
+#endif /* GL_ARM_shader_framebuffer_fetch_depth_stencil */
+
+#ifndef GL_DMP_program_binary
+#define GL_DMP_program_binary 1
+#define GL_SMAPHS30_PROGRAM_BINARY_DMP    0x9251
+#define GL_SMAPHS_PROGRAM_BINARY_DMP      0x9252
+#define GL_DMP_PROGRAM_BINARY_DMP         0x9253
+#endif /* GL_DMP_program_binary */
+
+#ifndef GL_DMP_shader_binary
+#define GL_DMP_shader_binary 1
+#define GL_SHADER_BINARY_DMP              0x9250
+#endif /* GL_DMP_shader_binary */
+
+#ifndef GL_EXT_EGL_image_array
+#define GL_EXT_EGL_image_array 1
+#endif /* GL_EXT_EGL_image_array */
+
+#ifndef GL_EXT_YUV_target
+#define GL_EXT_YUV_target 1
+#define GL_SAMPLER_EXTERNAL_2D_Y2Y_EXT    0x8BE7
+#endif /* GL_EXT_YUV_target */
+
+#ifndef GL_EXT_base_instance
+#define GL_EXT_base_instance 1
+typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEEXTPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance);
+typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance);
+typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawArraysInstancedBaseInstanceEXT (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance);
+GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseInstanceEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance);
+GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseVertexBaseInstanceEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance);
+#endif
+#endif /* GL_EXT_base_instance */
+
+#ifndef GL_EXT_blend_func_extended
+#define GL_EXT_blend_func_extended 1
+#define GL_SRC1_COLOR_EXT                 0x88F9
+#define GL_SRC1_ALPHA_EXT                 0x8589
+#define GL_ONE_MINUS_SRC1_COLOR_EXT       0x88FA
+#define GL_ONE_MINUS_SRC1_ALPHA_EXT       0x88FB
+#define GL_SRC_ALPHA_SATURATE_EXT         0x0308
+#define GL_LOCATION_INDEX_EXT             0x930F
+#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT 0x88FC
+typedef void (GL_APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDEXTPROC) (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name);
+typedef void (GL_APIENTRYP PFNGLBINDFRAGDATALOCATIONEXTPROC) (GLuint program, GLuint color, const GLchar *name);
+typedef GLint (GL_APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXEXTPROC) (GLuint program, GLenum programInterface, const GLchar *name);
+typedef GLint (GL_APIENTRYP PFNGLGETFRAGDATAINDEXEXTPROC) (GLuint program, const GLchar *name);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glBindFragDataLocationIndexedEXT (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name);
+GL_APICALL void GL_APIENTRY glBindFragDataLocationEXT (GLuint program, GLuint color, const GLchar *name);
+GL_APICALL GLint GL_APIENTRY glGetProgramResourceLocationIndexEXT (GLuint program, GLenum programInterface, const GLchar *name);
+GL_APICALL GLint GL_APIENTRY glGetFragDataIndexEXT (GLuint program, const GLchar *name);
+#endif
+#endif /* GL_EXT_blend_func_extended */
+
+#ifndef GL_EXT_blend_minmax
+#define GL_EXT_blend_minmax 1
+#define GL_MIN_EXT                        0x8007
+#define GL_MAX_EXT                        0x8008
+#endif /* GL_EXT_blend_minmax */
+
+#ifndef GL_EXT_buffer_storage
+#define GL_EXT_buffer_storage 1
+#define GL_MAP_READ_BIT                   0x0001
+#define GL_MAP_WRITE_BIT                  0x0002
+#define GL_MAP_PERSISTENT_BIT_EXT         0x0040
+#define GL_MAP_COHERENT_BIT_EXT           0x0080
+#define GL_DYNAMIC_STORAGE_BIT_EXT        0x0100
+#define GL_CLIENT_STORAGE_BIT_EXT         0x0200
+#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT_EXT 0x00004000
+#define GL_BUFFER_IMMUTABLE_STORAGE_EXT   0x821F
+#define GL_BUFFER_STORAGE_FLAGS_EXT       0x8220
+typedef void (GL_APIENTRYP PFNGLBUFFERSTORAGEEXTPROC) (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glBufferStorageEXT (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags);
+#endif
+#endif /* GL_EXT_buffer_storage */
+
+#ifndef GL_EXT_clear_texture
+#define GL_EXT_clear_texture 1
+typedef void (GL_APIENTRYP PFNGLCLEARTEXIMAGEEXTPROC) (GLuint texture, GLint level, GLenum format, GLenum type, const void *data);
+typedef void (GL_APIENTRYP PFNGLCLEARTEXSUBIMAGEEXTPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glClearTexImageEXT (GLuint texture, GLint level, GLenum format, GLenum type, const void *data);
+GL_APICALL void GL_APIENTRY glClearTexSubImageEXT (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data);
+#endif
+#endif /* GL_EXT_clear_texture */
+
+#ifndef GL_EXT_clip_control
+#define GL_EXT_clip_control 1
+#define GL_LOWER_LEFT_EXT                 0x8CA1
+#define GL_UPPER_LEFT_EXT                 0x8CA2
+#define GL_NEGATIVE_ONE_TO_ONE_EXT        0x935E
+#define GL_ZERO_TO_ONE_EXT                0x935F
+#define GL_CLIP_ORIGIN_EXT                0x935C
+#define GL_CLIP_DEPTH_MODE_EXT            0x935D
+typedef void (GL_APIENTRYP PFNGLCLIPCONTROLEXTPROC) (GLenum origin, GLenum depth);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glClipControlEXT (GLenum origin, GLenum depth);
+#endif
+#endif /* GL_EXT_clip_control */
+
+#ifndef GL_EXT_clip_cull_distance
+#define GL_EXT_clip_cull_distance 1
+#define GL_MAX_CLIP_DISTANCES_EXT         0x0D32
+#define GL_MAX_CULL_DISTANCES_EXT         0x82F9
+#define GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES_EXT 0x82FA
+#define GL_CLIP_DISTANCE0_EXT             0x3000
+#define GL_CLIP_DISTANCE1_EXT             0x3001
+#define GL_CLIP_DISTANCE2_EXT             0x3002
+#define GL_CLIP_DISTANCE3_EXT             0x3003
+#define GL_CLIP_DISTANCE4_EXT             0x3004
+#define GL_CLIP_DISTANCE5_EXT             0x3005
+#define GL_CLIP_DISTANCE6_EXT             0x3006
+#define GL_CLIP_DISTANCE7_EXT             0x3007
+#endif /* GL_EXT_clip_cull_distance */
+
+#ifndef GL_EXT_color_buffer_float
+#define GL_EXT_color_buffer_float 1
+#endif /* GL_EXT_color_buffer_float */
+
+#ifndef GL_EXT_color_buffer_half_float
+#define GL_EXT_color_buffer_half_float 1
+#define GL_RGBA16F_EXT                    0x881A
+#define GL_RGB16F_EXT                     0x881B
+#define GL_RG16F_EXT                      0x822F
+#define GL_R16F_EXT                       0x822D
+#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT 0x8211
+#define GL_UNSIGNED_NORMALIZED_EXT        0x8C17
+#endif /* GL_EXT_color_buffer_half_float */
+
+#ifndef GL_EXT_conservative_depth
+#define GL_EXT_conservative_depth 1
+#endif /* GL_EXT_conservative_depth */
+
+#ifndef GL_EXT_copy_image
+#define GL_EXT_copy_image 1
+typedef void (GL_APIENTRYP PFNGLCOPYIMAGESUBDATAEXTPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glCopyImageSubDataEXT (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth);
+#endif
+#endif /* GL_EXT_copy_image */
+
+#ifndef GL_EXT_debug_label
+#define GL_EXT_debug_label 1
+#define GL_PROGRAM_PIPELINE_OBJECT_EXT    0x8A4F
+#define GL_PROGRAM_OBJECT_EXT             0x8B40
+#define GL_SHADER_OBJECT_EXT              0x8B48
+#define GL_BUFFER_OBJECT_EXT              0x9151
+#define GL_QUERY_OBJECT_EXT               0x9153
+#define GL_VERTEX_ARRAY_OBJECT_EXT        0x9154
+#define GL_TRANSFORM_FEEDBACK             0x8E22
+typedef void (GL_APIENTRYP PFNGLLABELOBJECTEXTPROC) (GLenum type, GLuint object, GLsizei length, const GLchar *label);
+typedef void (GL_APIENTRYP PFNGLGETOBJECTLABELEXTPROC) (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glLabelObjectEXT (GLenum type, GLuint object, GLsizei length, const GLchar *label);
+GL_APICALL void GL_APIENTRY glGetObjectLabelEXT (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label);
+#endif
+#endif /* GL_EXT_debug_label */
+
+#ifndef GL_EXT_debug_marker
+#define GL_EXT_debug_marker 1
+typedef void (GL_APIENTRYP PFNGLINSERTEVENTMARKEREXTPROC) (GLsizei length, const GLchar *marker);
+typedef void (GL_APIENTRYP PFNGLPUSHGROUPMARKEREXTPROC) (GLsizei length, const GLchar *marker);
+typedef void (GL_APIENTRYP PFNGLPOPGROUPMARKEREXTPROC) (void);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glInsertEventMarkerEXT (GLsizei length, const GLchar *marker);
+GL_APICALL void GL_APIENTRY glPushGroupMarkerEXT (GLsizei length, const GLchar *marker);
+GL_APICALL void GL_APIENTRY glPopGroupMarkerEXT (void);
+#endif
+#endif /* GL_EXT_debug_marker */
+
+#ifndef GL_EXT_discard_framebuffer
+#define GL_EXT_discard_framebuffer 1
+#define GL_COLOR_EXT                      0x1800
+#define GL_DEPTH_EXT                      0x1801
+#define GL_STENCIL_EXT                    0x1802
+typedef void (GL_APIENTRYP PFNGLDISCARDFRAMEBUFFEREXTPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDiscardFramebufferEXT (GLenum target, GLsizei numAttachments, const GLenum *attachments);
+#endif
+#endif /* GL_EXT_discard_framebuffer */
+
+#ifndef GL_EXT_disjoint_timer_query
+#define GL_EXT_disjoint_timer_query 1
+#define GL_QUERY_COUNTER_BITS_EXT         0x8864
+#define GL_CURRENT_QUERY_EXT              0x8865
+#define GL_QUERY_RESULT_EXT               0x8866
+#define GL_QUERY_RESULT_AVAILABLE_EXT     0x8867
+#define GL_TIME_ELAPSED_EXT               0x88BF
+#define GL_TIMESTAMP_EXT                  0x8E28
+#define GL_GPU_DISJOINT_EXT               0x8FBB
+typedef void (GL_APIENTRYP PFNGLGENQUERIESEXTPROC) (GLsizei n, GLuint *ids);
+typedef void (GL_APIENTRYP PFNGLDELETEQUERIESEXTPROC) (GLsizei n, const GLuint *ids);
+typedef GLboolean (GL_APIENTRYP PFNGLISQUERYEXTPROC) (GLuint id);
+typedef void (GL_APIENTRYP PFNGLBEGINQUERYEXTPROC) (GLenum target, GLuint id);
+typedef void (GL_APIENTRYP PFNGLENDQUERYEXTPROC) (GLenum target);
+typedef void (GL_APIENTRYP PFNGLQUERYCOUNTEREXTPROC) (GLuint id, GLenum target);
+typedef void (GL_APIENTRYP PFNGLGETQUERYIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTIVEXTPROC) (GLuint id, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTUIVEXTPROC) (GLuint id, GLenum pname, GLuint *params);
+typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTI64VEXTPROC) (GLuint id, GLenum pname, GLint64 *params);
+typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTUI64VEXTPROC) (GLuint id, GLenum pname, GLuint64 *params);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGenQueriesEXT (GLsizei n, GLuint *ids);
+GL_APICALL void GL_APIENTRY glDeleteQueriesEXT (GLsizei n, const GLuint *ids);
+GL_APICALL GLboolean GL_APIENTRY glIsQueryEXT (GLuint id);
+GL_APICALL void GL_APIENTRY glBeginQueryEXT (GLenum target, GLuint id);
+GL_APICALL void GL_APIENTRY glEndQueryEXT (GLenum target);
+GL_APICALL void GL_APIENTRY glQueryCounterEXT (GLuint id, GLenum target);
+GL_APICALL void GL_APIENTRY glGetQueryivEXT (GLenum target, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetQueryObjectivEXT (GLuint id, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetQueryObjectuivEXT (GLuint id, GLenum pname, GLuint *params);
+GL_APICALL void GL_APIENTRY glGetQueryObjecti64vEXT (GLuint id, GLenum pname, GLint64 *params);
+GL_APICALL void GL_APIENTRY glGetQueryObjectui64vEXT (GLuint id, GLenum pname, GLuint64 *params);
+#endif
+#endif /* GL_EXT_disjoint_timer_query */
+
+#ifndef GL_EXT_draw_buffers
+#define GL_EXT_draw_buffers 1
+#define GL_MAX_COLOR_ATTACHMENTS_EXT      0x8CDF
+#define GL_MAX_DRAW_BUFFERS_EXT           0x8824
+#define GL_DRAW_BUFFER0_EXT               0x8825
+#define GL_DRAW_BUFFER1_EXT               0x8826
+#define GL_DRAW_BUFFER2_EXT               0x8827
+#define GL_DRAW_BUFFER3_EXT               0x8828
+#define GL_DRAW_BUFFER4_EXT               0x8829
+#define GL_DRAW_BUFFER5_EXT               0x882A
+#define GL_DRAW_BUFFER6_EXT               0x882B
+#define GL_DRAW_BUFFER7_EXT               0x882C
+#define GL_DRAW_BUFFER8_EXT               0x882D
+#define GL_DRAW_BUFFER9_EXT               0x882E
+#define GL_DRAW_BUFFER10_EXT              0x882F
+#define GL_DRAW_BUFFER11_EXT              0x8830
+#define GL_DRAW_BUFFER12_EXT              0x8831
+#define GL_DRAW_BUFFER13_EXT              0x8832
+#define GL_DRAW_BUFFER14_EXT              0x8833
+#define GL_DRAW_BUFFER15_EXT              0x8834
+#define GL_COLOR_ATTACHMENT0_EXT          0x8CE0
+#define GL_COLOR_ATTACHMENT1_EXT          0x8CE1
+#define GL_COLOR_ATTACHMENT2_EXT          0x8CE2
+#define GL_COLOR_ATTACHMENT3_EXT          0x8CE3
+#define GL_COLOR_ATTACHMENT4_EXT          0x8CE4
+#define GL_COLOR_ATTACHMENT5_EXT          0x8CE5
+#define GL_COLOR_ATTACHMENT6_EXT          0x8CE6
+#define GL_COLOR_ATTACHMENT7_EXT          0x8CE7
+#define GL_COLOR_ATTACHMENT8_EXT          0x8CE8
+#define GL_COLOR_ATTACHMENT9_EXT          0x8CE9
+#define GL_COLOR_ATTACHMENT10_EXT         0x8CEA
+#define GL_COLOR_ATTACHMENT11_EXT         0x8CEB
+#define GL_COLOR_ATTACHMENT12_EXT         0x8CEC
+#define GL_COLOR_ATTACHMENT13_EXT         0x8CED
+#define GL_COLOR_ATTACHMENT14_EXT         0x8CEE
+#define GL_COLOR_ATTACHMENT15_EXT         0x8CEF
+typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSEXTPROC) (GLsizei n, const GLenum *bufs);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawBuffersEXT (GLsizei n, const GLenum *bufs);
+#endif
+#endif /* GL_EXT_draw_buffers */
+
+#ifndef GL_EXT_draw_buffers_indexed
+#define GL_EXT_draw_buffers_indexed 1
+typedef void (GL_APIENTRYP PFNGLENABLEIEXTPROC) (GLenum target, GLuint index);
+typedef void (GL_APIENTRYP PFNGLDISABLEIEXTPROC) (GLenum target, GLuint index);
+typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONIEXTPROC) (GLuint buf, GLenum mode);
+typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEIEXTPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+typedef void (GL_APIENTRYP PFNGLBLENDFUNCIEXTPROC) (GLuint buf, GLenum src, GLenum dst);
+typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEIEXTPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+typedef void (GL_APIENTRYP PFNGLCOLORMASKIEXTPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
+typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDIEXTPROC) (GLenum target, GLuint index);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glEnableiEXT (GLenum target, GLuint index);
+GL_APICALL void GL_APIENTRY glDisableiEXT (GLenum target, GLuint index);
+GL_APICALL void GL_APIENTRY glBlendEquationiEXT (GLuint buf, GLenum mode);
+GL_APICALL void GL_APIENTRY glBlendEquationSeparateiEXT (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+GL_APICALL void GL_APIENTRY glBlendFunciEXT (GLuint buf, GLenum src, GLenum dst);
+GL_APICALL void GL_APIENTRY glBlendFuncSeparateiEXT (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+GL_APICALL void GL_APIENTRY glColorMaskiEXT (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
+GL_APICALL GLboolean GL_APIENTRY glIsEnablediEXT (GLenum target, GLuint index);
+#endif
+#endif /* GL_EXT_draw_buffers_indexed */
+
+#ifndef GL_EXT_draw_elements_base_vertex
+#define GL_EXT_draw_elements_base_vertex 1
+typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
+typedef void (GL_APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex);
+typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawElementsBaseVertexEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
+GL_APICALL void GL_APIENTRY glDrawRangeElementsBaseVertexEXT (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex);
+GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseVertexEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex);
+#endif
+#endif /* GL_EXT_draw_elements_base_vertex */
+
+#ifndef GL_EXT_draw_instanced
+#define GL_EXT_draw_instanced 1
+typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount);
+typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount);
+GL_APICALL void GL_APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);
+#endif
+#endif /* GL_EXT_draw_instanced */
+
+#ifndef GL_EXT_draw_transform_feedback
+#define GL_EXT_draw_transform_feedback 1
+typedef void (GL_APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKEXTPROC) (GLenum mode, GLuint id);
+typedef void (GL_APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDEXTPROC) (GLenum mode, GLuint id, GLsizei instancecount);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawTransformFeedbackEXT (GLenum mode, GLuint id);
+GL_APICALL void GL_APIENTRY glDrawTransformFeedbackInstancedEXT (GLenum mode, GLuint id, GLsizei instancecount);
+#endif
+#endif /* GL_EXT_draw_transform_feedback */
+
+#ifndef GL_EXT_external_buffer
+#define GL_EXT_external_buffer 1
+typedef void *GLeglClientBufferEXT;
+typedef void (GL_APIENTRYP PFNGLBUFFERSTORAGEEXTERNALEXTPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags);
+typedef void (GL_APIENTRYP PFNGLNAMEDBUFFERSTORAGEEXTERNALEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glBufferStorageExternalEXT (GLenum target, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags);
+GL_APICALL void GL_APIENTRY glNamedBufferStorageExternalEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags);
+#endif
+#endif /* GL_EXT_external_buffer */
+
+#ifndef GL_EXT_float_blend
+#define GL_EXT_float_blend 1
+#endif /* GL_EXT_float_blend */
+
+#ifndef GL_EXT_geometry_point_size
+#define GL_EXT_geometry_point_size 1
+#endif /* GL_EXT_geometry_point_size */
+
+#ifndef GL_EXT_geometry_shader
+#define GL_EXT_geometry_shader 1
+#define GL_GEOMETRY_SHADER_EXT            0x8DD9
+#define GL_GEOMETRY_SHADER_BIT_EXT        0x00000004
+#define GL_GEOMETRY_LINKED_VERTICES_OUT_EXT 0x8916
+#define GL_GEOMETRY_LINKED_INPUT_TYPE_EXT 0x8917
+#define GL_GEOMETRY_LINKED_OUTPUT_TYPE_EXT 0x8918
+#define GL_GEOMETRY_SHADER_INVOCATIONS_EXT 0x887F
+#define GL_LAYER_PROVOKING_VERTEX_EXT     0x825E
+#define GL_LINES_ADJACENCY_EXT            0x000A
+#define GL_LINE_STRIP_ADJACENCY_EXT       0x000B
+#define GL_TRIANGLES_ADJACENCY_EXT        0x000C
+#define GL_TRIANGLE_STRIP_ADJACENCY_EXT   0x000D
+#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF
+#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS_EXT 0x8A2C
+#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8A32
+#define GL_MAX_GEOMETRY_INPUT_COMPONENTS_EXT 0x9123
+#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS_EXT 0x9124
+#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0
+#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1
+#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS_EXT 0x8E5A
+#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29
+#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS_EXT 0x92CF
+#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS_EXT 0x92D5
+#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS_EXT 0x90CD
+#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS_EXT 0x90D7
+#define GL_FIRST_VERTEX_CONVENTION_EXT    0x8E4D
+#define GL_LAST_VERTEX_CONVENTION_EXT     0x8E4E
+#define GL_UNDEFINED_VERTEX_EXT           0x8260
+#define GL_PRIMITIVES_GENERATED_EXT       0x8C87
+#define GL_FRAMEBUFFER_DEFAULT_LAYERS_EXT 0x9312
+#define GL_MAX_FRAMEBUFFER_LAYERS_EXT     0x9317
+#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8
+#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7
+#define GL_REFERENCED_BY_GEOMETRY_SHADER_EXT 0x9309
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glFramebufferTextureEXT (GLenum target, GLenum attachment, GLuint texture, GLint level);
+#endif
+#endif /* GL_EXT_geometry_shader */
+
+#ifndef GL_EXT_gpu_shader5
+#define GL_EXT_gpu_shader5 1
+#endif /* GL_EXT_gpu_shader5 */
+
+#ifndef GL_EXT_instanced_arrays
+#define GL_EXT_instanced_arrays 1
+#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_EXT 0x88FE
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISOREXTPROC) (GLuint index, GLuint divisor);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glVertexAttribDivisorEXT (GLuint index, GLuint divisor);
+#endif
+#endif /* GL_EXT_instanced_arrays */
+
+#ifndef GL_EXT_map_buffer_range
+#define GL_EXT_map_buffer_range 1
+#define GL_MAP_READ_BIT_EXT               0x0001
+#define GL_MAP_WRITE_BIT_EXT              0x0002
+#define GL_MAP_INVALIDATE_RANGE_BIT_EXT   0x0004
+#define GL_MAP_INVALIDATE_BUFFER_BIT_EXT  0x0008
+#define GL_MAP_FLUSH_EXPLICIT_BIT_EXT     0x0010
+#define GL_MAP_UNSYNCHRONIZED_BIT_EXT     0x0020
+typedef void *(GL_APIENTRYP PFNGLMAPBUFFERRANGEEXTPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
+typedef void (GL_APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEEXTPROC) (GLenum target, GLintptr offset, GLsizeiptr length);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void *GL_APIENTRY glMapBufferRangeEXT (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
+GL_APICALL void GL_APIENTRY glFlushMappedBufferRangeEXT (GLenum target, GLintptr offset, GLsizeiptr length);
+#endif
+#endif /* GL_EXT_map_buffer_range */
+
+#ifndef GL_EXT_memory_object
+#define GL_EXT_memory_object 1
+#define GL_TEXTURE_TILING_EXT             0x9580
+#define GL_DEDICATED_MEMORY_OBJECT_EXT    0x9581
+#define GL_PROTECTED_MEMORY_OBJECT_EXT    0x959B
+#define GL_NUM_TILING_TYPES_EXT           0x9582
+#define GL_TILING_TYPES_EXT               0x9583
+#define GL_OPTIMAL_TILING_EXT             0x9584
+#define GL_LINEAR_TILING_EXT              0x9585
+#define GL_NUM_DEVICE_UUIDS_EXT           0x9596
+#define GL_DEVICE_UUID_EXT                0x9597
+#define GL_DRIVER_UUID_EXT                0x9598
+#define GL_UUID_SIZE_EXT                  16
+typedef void (GL_APIENTRYP PFNGLGETUNSIGNEDBYTEVEXTPROC) (GLenum pname, GLubyte *data);
+typedef void (GL_APIENTRYP PFNGLGETUNSIGNEDBYTEI_VEXTPROC) (GLenum target, GLuint index, GLubyte *data);
+typedef void (GL_APIENTRYP PFNGLDELETEMEMORYOBJECTSEXTPROC) (GLsizei n, const GLuint *memoryObjects);
+typedef GLboolean (GL_APIENTRYP PFNGLISMEMORYOBJECTEXTPROC) (GLuint memoryObject);
+typedef void (GL_APIENTRYP PFNGLCREATEMEMORYOBJECTSEXTPROC) (GLsizei n, GLuint *memoryObjects);
+typedef void (GL_APIENTRYP PFNGLMEMORYOBJECTPARAMETERIVEXTPROC) (GLuint memoryObject, GLenum pname, const GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETMEMORYOBJECTPARAMETERIVEXTPROC) (GLuint memoryObject, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGEMEM2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset);
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGEMEM2DMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset);
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGEMEM3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset);
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGEMEM3DMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset);
+typedef void (GL_APIENTRYP PFNGLBUFFERSTORAGEMEMEXTPROC) (GLenum target, GLsizeiptr size, GLuint memory, GLuint64 offset);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGEMEM2DEXTPROC) (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGEMEM2DMULTISAMPLEEXTPROC) (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGEMEM3DEXTPROC) (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGEMEM3DMULTISAMPLEEXTPROC) (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset);
+typedef void (GL_APIENTRYP PFNGLNAMEDBUFFERSTORAGEMEMEXTPROC) (GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetUnsignedBytevEXT (GLenum pname, GLubyte *data);
+GL_APICALL void GL_APIENTRY glGetUnsignedBytei_vEXT (GLenum target, GLuint index, GLubyte *data);
+GL_APICALL void GL_APIENTRY glDeleteMemoryObjectsEXT (GLsizei n, const GLuint *memoryObjects);
+GL_APICALL GLboolean GL_APIENTRY glIsMemoryObjectEXT (GLuint memoryObject);
+GL_APICALL void GL_APIENTRY glCreateMemoryObjectsEXT (GLsizei n, GLuint *memoryObjects);
+GL_APICALL void GL_APIENTRY glMemoryObjectParameterivEXT (GLuint memoryObject, GLenum pname, const GLint *params);
+GL_APICALL void GL_APIENTRY glGetMemoryObjectParameterivEXT (GLuint memoryObject, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glTexStorageMem2DEXT (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset);
+GL_APICALL void GL_APIENTRY glTexStorageMem2DMultisampleEXT (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset);
+GL_APICALL void GL_APIENTRY glTexStorageMem3DEXT (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset);
+GL_APICALL void GL_APIENTRY glTexStorageMem3DMultisampleEXT (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset);
+GL_APICALL void GL_APIENTRY glBufferStorageMemEXT (GLenum target, GLsizeiptr size, GLuint memory, GLuint64 offset);
+GL_APICALL void GL_APIENTRY glTextureStorageMem2DEXT (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset);
+GL_APICALL void GL_APIENTRY glTextureStorageMem2DMultisampleEXT (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset);
+GL_APICALL void GL_APIENTRY glTextureStorageMem3DEXT (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset);
+GL_APICALL void GL_APIENTRY glTextureStorageMem3DMultisampleEXT (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset);
+GL_APICALL void GL_APIENTRY glNamedBufferStorageMemEXT (GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset);
+#endif
+#endif /* GL_EXT_memory_object */
+
+#ifndef GL_EXT_memory_object_fd
+#define GL_EXT_memory_object_fd 1
+#define GL_HANDLE_TYPE_OPAQUE_FD_EXT      0x9586
+typedef void (GL_APIENTRYP PFNGLIMPORTMEMORYFDEXTPROC) (GLuint memory, GLuint64 size, GLenum handleType, GLint fd);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glImportMemoryFdEXT (GLuint memory, GLuint64 size, GLenum handleType, GLint fd);
+#endif
+#endif /* GL_EXT_memory_object_fd */
+
+#ifndef GL_EXT_memory_object_win32
+#define GL_EXT_memory_object_win32 1
+#define GL_HANDLE_TYPE_OPAQUE_WIN32_EXT   0x9587
+#define GL_HANDLE_TYPE_OPAQUE_WIN32_KMT_EXT 0x9588
+#define GL_DEVICE_LUID_EXT                0x9599
+#define GL_DEVICE_NODE_MASK_EXT           0x959A
+#define GL_LUID_SIZE_EXT                  8
+#define GL_HANDLE_TYPE_D3D12_TILEPOOL_EXT 0x9589
+#define GL_HANDLE_TYPE_D3D12_RESOURCE_EXT 0x958A
+#define GL_HANDLE_TYPE_D3D11_IMAGE_EXT    0x958B
+#define GL_HANDLE_TYPE_D3D11_IMAGE_KMT_EXT 0x958C
+typedef void (GL_APIENTRYP PFNGLIMPORTMEMORYWIN32HANDLEEXTPROC) (GLuint memory, GLuint64 size, GLenum handleType, void *handle);
+typedef void (GL_APIENTRYP PFNGLIMPORTMEMORYWIN32NAMEEXTPROC) (GLuint memory, GLuint64 size, GLenum handleType, const void *name);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glImportMemoryWin32HandleEXT (GLuint memory, GLuint64 size, GLenum handleType, void *handle);
+GL_APICALL void GL_APIENTRY glImportMemoryWin32NameEXT (GLuint memory, GLuint64 size, GLenum handleType, const void *name);
+#endif
+#endif /* GL_EXT_memory_object_win32 */
+
+#ifndef GL_EXT_multi_draw_arrays
+#define GL_EXT_multi_draw_arrays 1
+typedef void (GL_APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glMultiDrawArraysEXT (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+GL_APICALL void GL_APIENTRY glMultiDrawElementsEXT (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount);
+#endif
+#endif /* GL_EXT_multi_draw_arrays */
+
+#ifndef GL_EXT_multi_draw_indirect
+#define GL_EXT_multi_draw_indirect 1
+typedef void (GL_APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTEXTPROC) (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride);
+typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTEXTPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glMultiDrawArraysIndirectEXT (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride);
+GL_APICALL void GL_APIENTRY glMultiDrawElementsIndirectEXT (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride);
+#endif
+#endif /* GL_EXT_multi_draw_indirect */
+
+#ifndef GL_EXT_multisampled_compatibility
+#define GL_EXT_multisampled_compatibility 1
+#define GL_MULTISAMPLE_EXT                0x809D
+#define GL_SAMPLE_ALPHA_TO_ONE_EXT        0x809F
+#endif /* GL_EXT_multisampled_compatibility */
+
+#ifndef GL_EXT_multisampled_render_to_texture
+#define GL_EXT_multisampled_render_to_texture 1
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT 0x8D6C
+#define GL_RENDERBUFFER_SAMPLES_EXT       0x8CAB
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56
+#define GL_MAX_SAMPLES_EXT                0x8D57
+typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleEXT (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glFramebufferTexture2DMultisampleEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples);
+#endif
+#endif /* GL_EXT_multisampled_render_to_texture */
+
+#ifndef GL_EXT_multiview_draw_buffers
+#define GL_EXT_multiview_draw_buffers 1
+#define GL_COLOR_ATTACHMENT_EXT           0x90F0
+#define GL_MULTIVIEW_EXT                  0x90F1
+#define GL_DRAW_BUFFER_EXT                0x0C01
+#define GL_READ_BUFFER_EXT                0x0C02
+#define GL_MAX_MULTIVIEW_BUFFERS_EXT      0x90F2
+typedef void (GL_APIENTRYP PFNGLREADBUFFERINDEXEDEXTPROC) (GLenum src, GLint index);
+typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSINDEXEDEXTPROC) (GLint n, const GLenum *location, const GLint *indices);
+typedef void (GL_APIENTRYP PFNGLGETINTEGERI_VEXTPROC) (GLenum target, GLuint index, GLint *data);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glReadBufferIndexedEXT (GLenum src, GLint index);
+GL_APICALL void GL_APIENTRY glDrawBuffersIndexedEXT (GLint n, const GLenum *location, const GLint *indices);
+GL_APICALL void GL_APIENTRY glGetIntegeri_vEXT (GLenum target, GLuint index, GLint *data);
+#endif
+#endif /* GL_EXT_multiview_draw_buffers */
+
+#ifndef GL_EXT_occlusion_query_boolean
+#define GL_EXT_occlusion_query_boolean 1
+#define GL_ANY_SAMPLES_PASSED_EXT         0x8C2F
+#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT 0x8D6A
+#endif /* GL_EXT_occlusion_query_boolean */
+
+#ifndef GL_EXT_polygon_offset_clamp
+#define GL_EXT_polygon_offset_clamp 1
+#define GL_POLYGON_OFFSET_CLAMP_EXT       0x8E1B
+typedef void (GL_APIENTRYP PFNGLPOLYGONOFFSETCLAMPEXTPROC) (GLfloat factor, GLfloat units, GLfloat clamp);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glPolygonOffsetClampEXT (GLfloat factor, GLfloat units, GLfloat clamp);
+#endif
+#endif /* GL_EXT_polygon_offset_clamp */
+
+#ifndef GL_EXT_post_depth_coverage
+#define GL_EXT_post_depth_coverage 1
+#endif /* GL_EXT_post_depth_coverage */
+
+#ifndef GL_EXT_primitive_bounding_box
+#define GL_EXT_primitive_bounding_box 1
+#define GL_PRIMITIVE_BOUNDING_BOX_EXT     0x92BE
+typedef void (GL_APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXEXTPROC) (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glPrimitiveBoundingBoxEXT (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW);
+#endif
+#endif /* GL_EXT_primitive_bounding_box */
+
+#ifndef GL_EXT_protected_textures
+#define GL_EXT_protected_textures 1
+#define GL_CONTEXT_FLAG_PROTECTED_CONTENT_BIT_EXT 0x00000010
+#define GL_TEXTURE_PROTECTED_EXT          0x8BFA
+#endif /* GL_EXT_protected_textures */
+
+#ifndef GL_EXT_pvrtc_sRGB
+#define GL_EXT_pvrtc_sRGB 1
+#define GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54
+#define GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55
+#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56
+#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57
+#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV2_IMG 0x93F0
+#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV2_IMG 0x93F1
+#endif /* GL_EXT_pvrtc_sRGB */
+
+#ifndef GL_EXT_raster_multisample
+#define GL_EXT_raster_multisample 1
+#define GL_RASTER_MULTISAMPLE_EXT         0x9327
+#define GL_RASTER_SAMPLES_EXT             0x9328
+#define GL_MAX_RASTER_SAMPLES_EXT         0x9329
+#define GL_RASTER_FIXED_SAMPLE_LOCATIONS_EXT 0x932A
+#define GL_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT 0x932B
+#define GL_EFFECTIVE_RASTER_SAMPLES_EXT   0x932C
+typedef void (GL_APIENTRYP PFNGLRASTERSAMPLESEXTPROC) (GLuint samples, GLboolean fixedsamplelocations);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glRasterSamplesEXT (GLuint samples, GLboolean fixedsamplelocations);
+#endif
+#endif /* GL_EXT_raster_multisample */
+
+#ifndef GL_EXT_read_format_bgra
+#define GL_EXT_read_format_bgra 1
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT 0x8365
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT 0x8366
+#endif /* GL_EXT_read_format_bgra */
+
+#ifndef GL_EXT_render_snorm
+#define GL_EXT_render_snorm 1
+#define GL_R8_SNORM                       0x8F94
+#define GL_RG8_SNORM                      0x8F95
+#define GL_RGBA8_SNORM                    0x8F97
+#define GL_R16_SNORM_EXT                  0x8F98
+#define GL_RG16_SNORM_EXT                 0x8F99
+#define GL_RGBA16_SNORM_EXT               0x8F9B
+#endif /* GL_EXT_render_snorm */
+
+#ifndef GL_EXT_robustness
+#define GL_EXT_robustness 1
+#define GL_GUILTY_CONTEXT_RESET_EXT       0x8253
+#define GL_INNOCENT_CONTEXT_RESET_EXT     0x8254
+#define GL_UNKNOWN_CONTEXT_RESET_EXT      0x8255
+#define GL_CONTEXT_ROBUST_ACCESS_EXT      0x90F3
+#define GL_RESET_NOTIFICATION_STRATEGY_EXT 0x8256
+#define GL_LOSE_CONTEXT_ON_RESET_EXT      0x8252
+#define GL_NO_RESET_NOTIFICATION_EXT      0x8261
+typedef GLenum (GL_APIENTRYP PFNGLGETGRAPHICSRESETSTATUSEXTPROC) (void);
+typedef void (GL_APIENTRYP PFNGLREADNPIXELSEXTPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);
+typedef void (GL_APIENTRYP PFNGLGETNUNIFORMFVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params);
+typedef void (GL_APIENTRYP PFNGLGETNUNIFORMIVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL GLenum GL_APIENTRY glGetGraphicsResetStatusEXT (void);
+GL_APICALL void GL_APIENTRY glReadnPixelsEXT (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data);
+GL_APICALL void GL_APIENTRY glGetnUniformfvEXT (GLuint program, GLint location, GLsizei bufSize, GLfloat *params);
+GL_APICALL void GL_APIENTRY glGetnUniformivEXT (GLuint program, GLint location, GLsizei bufSize, GLint *params);
+#endif
+#endif /* GL_EXT_robustness */
+
+#ifndef GL_EXT_sRGB
+#define GL_EXT_sRGB 1
+#define GL_SRGB_EXT                       0x8C40
+#define GL_SRGB_ALPHA_EXT                 0x8C42
+#define GL_SRGB8_ALPHA8_EXT               0x8C43
+#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT 0x8210
+#endif /* GL_EXT_sRGB */
+
+#ifndef GL_EXT_sRGB_write_control
+#define GL_EXT_sRGB_write_control 1
+#define GL_FRAMEBUFFER_SRGB_EXT           0x8DB9
+#endif /* GL_EXT_sRGB_write_control */
+
+#ifndef GL_EXT_semaphore
+#define GL_EXT_semaphore 1
+#define GL_LAYOUT_GENERAL_EXT             0x958D
+#define GL_LAYOUT_COLOR_ATTACHMENT_EXT    0x958E
+#define GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT 0x958F
+#define GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT 0x9590
+#define GL_LAYOUT_SHADER_READ_ONLY_EXT    0x9591
+#define GL_LAYOUT_TRANSFER_SRC_EXT        0x9592
+#define GL_LAYOUT_TRANSFER_DST_EXT        0x9593
+typedef void (GL_APIENTRYP PFNGLGENSEMAPHORESEXTPROC) (GLsizei n, GLuint *semaphores);
+typedef void (GL_APIENTRYP PFNGLDELETESEMAPHORESEXTPROC) (GLsizei n, const GLuint *semaphores);
+typedef GLboolean (GL_APIENTRYP PFNGLISSEMAPHOREEXTPROC) (GLuint semaphore);
+typedef void (GL_APIENTRYP PFNGLSEMAPHOREPARAMETERUI64VEXTPROC) (GLuint semaphore, GLenum pname, const GLuint64 *params);
+typedef void (GL_APIENTRYP PFNGLGETSEMAPHOREPARAMETERUI64VEXTPROC) (GLuint semaphore, GLenum pname, GLuint64 *params);
+typedef void (GL_APIENTRYP PFNGLWAITSEMAPHOREEXTPROC) (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts);
+typedef void (GL_APIENTRYP PFNGLSIGNALSEMAPHOREEXTPROC) (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGenSemaphoresEXT (GLsizei n, GLuint *semaphores);
+GL_APICALL void GL_APIENTRY glDeleteSemaphoresEXT (GLsizei n, const GLuint *semaphores);
+GL_APICALL GLboolean GL_APIENTRY glIsSemaphoreEXT (GLuint semaphore);
+GL_APICALL void GL_APIENTRY glSemaphoreParameterui64vEXT (GLuint semaphore, GLenum pname, const GLuint64 *params);
+GL_APICALL void GL_APIENTRY glGetSemaphoreParameterui64vEXT (GLuint semaphore, GLenum pname, GLuint64 *params);
+GL_APICALL void GL_APIENTRY glWaitSemaphoreEXT (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts);
+GL_APICALL void GL_APIENTRY glSignalSemaphoreEXT (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts);
+#endif
+#endif /* GL_EXT_semaphore */
+
+#ifndef GL_EXT_semaphore_fd
+#define GL_EXT_semaphore_fd 1
+typedef void (GL_APIENTRYP PFNGLIMPORTSEMAPHOREFDEXTPROC) (GLuint semaphore, GLenum handleType, GLint fd);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glImportSemaphoreFdEXT (GLuint semaphore, GLenum handleType, GLint fd);
+#endif
+#endif /* GL_EXT_semaphore_fd */
+
+#ifndef GL_EXT_semaphore_win32
+#define GL_EXT_semaphore_win32 1
+#define GL_HANDLE_TYPE_D3D12_FENCE_EXT    0x9594
+#define GL_D3D12_FENCE_VALUE_EXT          0x9595
+typedef void (GL_APIENTRYP PFNGLIMPORTSEMAPHOREWIN32HANDLEEXTPROC) (GLuint semaphore, GLenum handleType, void *handle);
+typedef void (GL_APIENTRYP PFNGLIMPORTSEMAPHOREWIN32NAMEEXTPROC) (GLuint semaphore, GLenum handleType, const void *name);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glImportSemaphoreWin32HandleEXT (GLuint semaphore, GLenum handleType, void *handle);
+GL_APICALL void GL_APIENTRY glImportSemaphoreWin32NameEXT (GLuint semaphore, GLenum handleType, const void *name);
+#endif
+#endif /* GL_EXT_semaphore_win32 */
+
+#ifndef GL_EXT_separate_shader_objects
+#define GL_EXT_separate_shader_objects 1
+#define GL_ACTIVE_PROGRAM_EXT             0x8259
+#define GL_VERTEX_SHADER_BIT_EXT          0x00000001
+#define GL_FRAGMENT_SHADER_BIT_EXT        0x00000002
+#define GL_ALL_SHADER_BITS_EXT            0xFFFFFFFF
+#define GL_PROGRAM_SEPARABLE_EXT          0x8258
+#define GL_PROGRAM_PIPELINE_BINDING_EXT   0x825A
+typedef void (GL_APIENTRYP PFNGLACTIVESHADERPROGRAMEXTPROC) (GLuint pipeline, GLuint program);
+typedef void (GL_APIENTRYP PFNGLBINDPROGRAMPIPELINEEXTPROC) (GLuint pipeline);
+typedef GLuint (GL_APIENTRYP PFNGLCREATESHADERPROGRAMVEXTPROC) (GLenum type, GLsizei count, const GLchar **strings);
+typedef void (GL_APIENTRYP PFNGLDELETEPROGRAMPIPELINESEXTPROC) (GLsizei n, const GLuint *pipelines);
+typedef void (GL_APIENTRYP PFNGLGENPROGRAMPIPELINESEXTPROC) (GLsizei n, GLuint *pipelines);
+typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGEXTPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEIVEXTPROC) (GLuint pipeline, GLenum pname, GLint *params);
+typedef GLboolean (GL_APIENTRYP PFNGLISPROGRAMPIPELINEEXTPROC) (GLuint pipeline);
+typedef void (GL_APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat v0);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint v0);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUSEPROGRAMSTAGESEXTPROC) (GLuint pipeline, GLbitfield stages, GLuint program);
+typedef void (GL_APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEEXTPROC) (GLuint pipeline);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UIEXTPROC) (GLuint program, GLint location, GLuint v0);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glActiveShaderProgramEXT (GLuint pipeline, GLuint program);
+GL_APICALL void GL_APIENTRY glBindProgramPipelineEXT (GLuint pipeline);
+GL_APICALL GLuint GL_APIENTRY glCreateShaderProgramvEXT (GLenum type, GLsizei count, const GLchar **strings);
+GL_APICALL void GL_APIENTRY glDeleteProgramPipelinesEXT (GLsizei n, const GLuint *pipelines);
+GL_APICALL void GL_APIENTRY glGenProgramPipelinesEXT (GLsizei n, GLuint *pipelines);
+GL_APICALL void GL_APIENTRY glGetProgramPipelineInfoLogEXT (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+GL_APICALL void GL_APIENTRY glGetProgramPipelineivEXT (GLuint pipeline, GLenum pname, GLint *params);
+GL_APICALL GLboolean GL_APIENTRY glIsProgramPipelineEXT (GLuint pipeline);
+GL_APICALL void GL_APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value);
+GL_APICALL void GL_APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat v0);
+GL_APICALL void GL_APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint v0);
+GL_APICALL void GL_APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1);
+GL_APICALL void GL_APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint v0, GLint v1);
+GL_APICALL void GL_APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+GL_APICALL void GL_APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
+GL_APICALL void GL_APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+GL_APICALL void GL_APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+GL_APICALL void GL_APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUseProgramStagesEXT (GLuint pipeline, GLbitfield stages, GLuint program);
+GL_APICALL void GL_APIENTRY glValidateProgramPipelineEXT (GLuint pipeline);
+GL_APICALL void GL_APIENTRY glProgramUniform1uiEXT (GLuint program, GLint location, GLuint v0);
+GL_APICALL void GL_APIENTRY glProgramUniform2uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1);
+GL_APICALL void GL_APIENTRY glProgramUniform3uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
+GL_APICALL void GL_APIENTRY glProgramUniform4uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+GL_APICALL void GL_APIENTRY glProgramUniform1uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GL_APICALL void GL_APIENTRY glProgramUniform2uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GL_APICALL void GL_APIENTRY glProgramUniform3uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GL_APICALL void GL_APIENTRY glProgramUniform4uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix2x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix3x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix2x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix4x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix3x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glProgramUniformMatrix4x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+#endif
+#endif /* GL_EXT_separate_shader_objects */
+
+#ifndef GL_EXT_shader_framebuffer_fetch
+#define GL_EXT_shader_framebuffer_fetch 1
+#define GL_FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT 0x8A52
+#endif /* GL_EXT_shader_framebuffer_fetch */
+
+#ifndef GL_EXT_shader_group_vote
+#define GL_EXT_shader_group_vote 1
+#endif /* GL_EXT_shader_group_vote */
+
+#ifndef GL_EXT_shader_implicit_conversions
+#define GL_EXT_shader_implicit_conversions 1
+#endif /* GL_EXT_shader_implicit_conversions */
+
+#ifndef GL_EXT_shader_integer_mix
+#define GL_EXT_shader_integer_mix 1
+#endif /* GL_EXT_shader_integer_mix */
+
+#ifndef GL_EXT_shader_io_blocks
+#define GL_EXT_shader_io_blocks 1
+#endif /* GL_EXT_shader_io_blocks */
+
+#ifndef GL_EXT_shader_non_constant_global_initializers
+#define GL_EXT_shader_non_constant_global_initializers 1
+#endif /* GL_EXT_shader_non_constant_global_initializers */
+
+#ifndef GL_EXT_shader_pixel_local_storage
+#define GL_EXT_shader_pixel_local_storage 1
+#define GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_FAST_SIZE_EXT 0x8F63
+#define GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_SIZE_EXT 0x8F67
+#define GL_SHADER_PIXEL_LOCAL_STORAGE_EXT 0x8F64
+#endif /* GL_EXT_shader_pixel_local_storage */
+
+#ifndef GL_EXT_shader_pixel_local_storage2
+#define GL_EXT_shader_pixel_local_storage2 1
+#define GL_MAX_SHADER_COMBINED_LOCAL_STORAGE_FAST_SIZE_EXT 0x9650
+#define GL_MAX_SHADER_COMBINED_LOCAL_STORAGE_SIZE_EXT 0x9651
+#define GL_FRAMEBUFFER_INCOMPLETE_INSUFFICIENT_SHADER_COMBINED_LOCAL_STORAGE_EXT 0x9652
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC) (GLuint target, GLsizei size);
+typedef GLsizei (GL_APIENTRYP PFNGLGETFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC) (GLuint target);
+typedef void (GL_APIENTRYP PFNGLCLEARPIXELLOCALSTORAGEUIEXTPROC) (GLsizei offset, GLsizei n, const GLuint *values);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glFramebufferPixelLocalStorageSizeEXT (GLuint target, GLsizei size);
+GL_APICALL GLsizei GL_APIENTRY glGetFramebufferPixelLocalStorageSizeEXT (GLuint target);
+GL_APICALL void GL_APIENTRY glClearPixelLocalStorageuiEXT (GLsizei offset, GLsizei n, const GLuint *values);
+#endif
+#endif /* GL_EXT_shader_pixel_local_storage2 */
+
+#ifndef GL_EXT_shader_texture_lod
+#define GL_EXT_shader_texture_lod 1
+#endif /* GL_EXT_shader_texture_lod */
+
+#ifndef GL_EXT_shadow_samplers
+#define GL_EXT_shadow_samplers 1
+#define GL_TEXTURE_COMPARE_MODE_EXT       0x884C
+#define GL_TEXTURE_COMPARE_FUNC_EXT       0x884D
+#define GL_COMPARE_REF_TO_TEXTURE_EXT     0x884E
+#define GL_SAMPLER_2D_SHADOW_EXT          0x8B62
+#endif /* GL_EXT_shadow_samplers */
+
+#ifndef GL_EXT_sparse_texture
+#define GL_EXT_sparse_texture 1
+#define GL_TEXTURE_SPARSE_EXT             0x91A6
+#define GL_VIRTUAL_PAGE_SIZE_INDEX_EXT    0x91A7
+#define GL_NUM_SPARSE_LEVELS_EXT          0x91AA
+#define GL_NUM_VIRTUAL_PAGE_SIZES_EXT     0x91A8
+#define GL_VIRTUAL_PAGE_SIZE_X_EXT        0x9195
+#define GL_VIRTUAL_PAGE_SIZE_Y_EXT        0x9196
+#define GL_VIRTUAL_PAGE_SIZE_Z_EXT        0x9197
+#define GL_TEXTURE_2D_ARRAY               0x8C1A
+#define GL_TEXTURE_3D                     0x806F
+#define GL_MAX_SPARSE_TEXTURE_SIZE_EXT    0x9198
+#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_EXT 0x9199
+#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_EXT 0x919A
+#define GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_EXT 0x91A9
+typedef void (GL_APIENTRYP PFNGLTEXPAGECOMMITMENTEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexPageCommitmentEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit);
+#endif
+#endif /* GL_EXT_sparse_texture */
+
+#ifndef GL_EXT_sparse_texture2
+#define GL_EXT_sparse_texture2 1
+#endif /* GL_EXT_sparse_texture2 */
+
+#ifndef GL_EXT_tessellation_point_size
+#define GL_EXT_tessellation_point_size 1
+#endif /* GL_EXT_tessellation_point_size */
+
+#ifndef GL_EXT_tessellation_shader
+#define GL_EXT_tessellation_shader 1
+#define GL_PATCHES_EXT                    0x000E
+#define GL_PATCH_VERTICES_EXT             0x8E72
+#define GL_TESS_CONTROL_OUTPUT_VERTICES_EXT 0x8E75
+#define GL_TESS_GEN_MODE_EXT              0x8E76
+#define GL_TESS_GEN_SPACING_EXT           0x8E77
+#define GL_TESS_GEN_VERTEX_ORDER_EXT      0x8E78
+#define GL_TESS_GEN_POINT_MODE_EXT        0x8E79
+#define GL_ISOLINES_EXT                   0x8E7A
+#define GL_QUADS_EXT                      0x0007
+#define GL_FRACTIONAL_ODD_EXT             0x8E7B
+#define GL_FRACTIONAL_EVEN_EXT            0x8E7C
+#define GL_MAX_PATCH_VERTICES_EXT         0x8E7D
+#define GL_MAX_TESS_GEN_LEVEL_EXT         0x8E7E
+#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS_EXT 0x8E7F
+#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS_EXT 0x8E80
+#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS_EXT 0x8E81
+#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS_EXT 0x8E82
+#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS_EXT 0x8E83
+#define GL_MAX_TESS_PATCH_COMPONENTS_EXT  0x8E84
+#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS_EXT 0x8E85
+#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS_EXT 0x8E86
+#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS_EXT 0x8E89
+#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS_EXT 0x8E8A
+#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS_EXT 0x886C
+#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS_EXT 0x886D
+#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS_EXT 0x8E1E
+#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS_EXT 0x8E1F
+#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS_EXT 0x92CD
+#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS_EXT 0x92CE
+#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS_EXT 0x92D3
+#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS_EXT 0x92D4
+#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS_EXT 0x90CB
+#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS_EXT 0x90CC
+#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS_EXT 0x90D8
+#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS_EXT 0x90D9
+#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED 0x8221
+#define GL_IS_PER_PATCH_EXT               0x92E7
+#define GL_REFERENCED_BY_TESS_CONTROL_SHADER_EXT 0x9307
+#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER_EXT 0x9308
+#define GL_TESS_CONTROL_SHADER_EXT        0x8E88
+#define GL_TESS_EVALUATION_SHADER_EXT     0x8E87
+#define GL_TESS_CONTROL_SHADER_BIT_EXT    0x00000008
+#define GL_TESS_EVALUATION_SHADER_BIT_EXT 0x00000010
+typedef void (GL_APIENTRYP PFNGLPATCHPARAMETERIEXTPROC) (GLenum pname, GLint value);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glPatchParameteriEXT (GLenum pname, GLint value);
+#endif
+#endif /* GL_EXT_tessellation_shader */
+
+#ifndef GL_EXT_texture_border_clamp
+#define GL_EXT_texture_border_clamp 1
+#define GL_TEXTURE_BORDER_COLOR_EXT       0x1004
+#define GL_CLAMP_TO_BORDER_EXT            0x812D
+typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, const GLuint *params);
+typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, GLuint *params);
+typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIIVEXTPROC) (GLuint sampler, GLenum pname, const GLint *param);
+typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIUIVEXTPROC) (GLuint sampler, GLenum pname, const GLuint *param);
+typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIIVEXTPROC) (GLuint sampler, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVEXTPROC) (GLuint sampler, GLenum pname, GLuint *params);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexParameterIivEXT (GLenum target, GLenum pname, const GLint *params);
+GL_APICALL void GL_APIENTRY glTexParameterIuivEXT (GLenum target, GLenum pname, const GLuint *params);
+GL_APICALL void GL_APIENTRY glGetTexParameterIivEXT (GLenum target, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetTexParameterIuivEXT (GLenum target, GLenum pname, GLuint *params);
+GL_APICALL void GL_APIENTRY glSamplerParameterIivEXT (GLuint sampler, GLenum pname, const GLint *param);
+GL_APICALL void GL_APIENTRY glSamplerParameterIuivEXT (GLuint sampler, GLenum pname, const GLuint *param);
+GL_APICALL void GL_APIENTRY glGetSamplerParameterIivEXT (GLuint sampler, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glGetSamplerParameterIuivEXT (GLuint sampler, GLenum pname, GLuint *params);
+#endif
+#endif /* GL_EXT_texture_border_clamp */
+
+#ifndef GL_EXT_texture_buffer
+#define GL_EXT_texture_buffer 1
+#define GL_TEXTURE_BUFFER_EXT             0x8C2A
+#define GL_TEXTURE_BUFFER_BINDING_EXT     0x8C2A
+#define GL_MAX_TEXTURE_BUFFER_SIZE_EXT    0x8C2B
+#define GL_TEXTURE_BINDING_BUFFER_EXT     0x8C2C
+#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_EXT 0x8C2D
+#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT_EXT 0x919F
+#define GL_SAMPLER_BUFFER_EXT             0x8DC2
+#define GL_INT_SAMPLER_BUFFER_EXT         0x8DD0
+#define GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT 0x8DD8
+#define GL_IMAGE_BUFFER_EXT               0x9051
+#define GL_INT_IMAGE_BUFFER_EXT           0x905C
+#define GL_UNSIGNED_INT_IMAGE_BUFFER_EXT  0x9067
+#define GL_TEXTURE_BUFFER_OFFSET_EXT      0x919D
+#define GL_TEXTURE_BUFFER_SIZE_EXT        0x919E
+typedef void (GL_APIENTRYP PFNGLTEXBUFFEREXTPROC) (GLenum target, GLenum internalformat, GLuint buffer);
+typedef void (GL_APIENTRYP PFNGLTEXBUFFERRANGEEXTPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexBufferEXT (GLenum target, GLenum internalformat, GLuint buffer);
+GL_APICALL void GL_APIENTRY glTexBufferRangeEXT (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size);
+#endif
+#endif /* GL_EXT_texture_buffer */
+
+#ifndef GL_EXT_texture_compression_astc_decode_mode
+#define GL_EXT_texture_compression_astc_decode_mode 1
+#define GL_TEXTURE_ASTC_DECODE_PRECISION_EXT 0x8F69
+#endif /* GL_EXT_texture_compression_astc_decode_mode */
+
+#ifndef GL_EXT_texture_compression_bptc
+#define GL_EXT_texture_compression_bptc 1
+#define GL_COMPRESSED_RGBA_BPTC_UNORM_EXT 0x8E8C
+#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT 0x8E8D
+#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT 0x8E8E
+#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT 0x8E8F
+#endif /* GL_EXT_texture_compression_bptc */
+
+#ifndef GL_EXT_texture_compression_dxt1
+#define GL_EXT_texture_compression_dxt1 1
+#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT   0x83F0
+#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT  0x83F1
+#endif /* GL_EXT_texture_compression_dxt1 */
+
+#ifndef GL_EXT_texture_compression_rgtc
+#define GL_EXT_texture_compression_rgtc 1
+#define GL_COMPRESSED_RED_RGTC1_EXT       0x8DBB
+#define GL_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC
+#define GL_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD
+#define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE
+#endif /* GL_EXT_texture_compression_rgtc */
+
+#ifndef GL_EXT_texture_compression_s3tc
+#define GL_EXT_texture_compression_s3tc 1
+#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT  0x83F2
+#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT  0x83F3
+#endif /* GL_EXT_texture_compression_s3tc */
+
+#ifndef GL_EXT_texture_compression_s3tc_srgb
+#define GL_EXT_texture_compression_s3tc_srgb 1
+#define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT  0x8C4C
+#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D
+#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E
+#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F
+#endif /* GL_EXT_texture_compression_s3tc_srgb */
+
+#ifndef GL_EXT_texture_cube_map_array
+#define GL_EXT_texture_cube_map_array 1
+#define GL_TEXTURE_CUBE_MAP_ARRAY_EXT     0x9009
+#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_EXT 0x900A
+#define GL_SAMPLER_CUBE_MAP_ARRAY_EXT     0x900C
+#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_EXT 0x900D
+#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_EXT 0x900E
+#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_EXT 0x900F
+#define GL_IMAGE_CUBE_MAP_ARRAY_EXT       0x9054
+#define GL_INT_IMAGE_CUBE_MAP_ARRAY_EXT   0x905F
+#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x906A
+#endif /* GL_EXT_texture_cube_map_array */
+
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_EXT_texture_filter_anisotropic 1
+#define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE
+#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
+#endif /* GL_EXT_texture_filter_anisotropic */
+
+#ifndef GL_EXT_texture_filter_minmax
+#define GL_EXT_texture_filter_minmax 1
+#endif /* GL_EXT_texture_filter_minmax */
+
+#ifndef GL_EXT_texture_format_BGRA8888
+#define GL_EXT_texture_format_BGRA8888 1
+#endif /* GL_EXT_texture_format_BGRA8888 */
+
+#ifndef GL_EXT_texture_norm16
+#define GL_EXT_texture_norm16 1
+#define GL_R16_EXT                        0x822A
+#define GL_RG16_EXT                       0x822C
+#define GL_RGBA16_EXT                     0x805B
+#define GL_RGB16_EXT                      0x8054
+#define GL_RGB16_SNORM_EXT                0x8F9A
+#endif /* GL_EXT_texture_norm16 */
+
+#ifndef GL_EXT_texture_rg
+#define GL_EXT_texture_rg 1
+#define GL_RED_EXT                        0x1903
+#define GL_RG_EXT                         0x8227
+#define GL_R8_EXT                         0x8229
+#define GL_RG8_EXT                        0x822B
+#endif /* GL_EXT_texture_rg */
+
+#ifndef GL_EXT_texture_sRGB_R8
+#define GL_EXT_texture_sRGB_R8 1
+#define GL_SR8_EXT                        0x8FBD
+#endif /* GL_EXT_texture_sRGB_R8 */
+
+#ifndef GL_EXT_texture_sRGB_RG8
+#define GL_EXT_texture_sRGB_RG8 1
+#define GL_SRG8_EXT                       0x8FBE
+#endif /* GL_EXT_texture_sRGB_RG8 */
+
+#ifndef GL_EXT_texture_sRGB_decode
+#define GL_EXT_texture_sRGB_decode 1
+#define GL_TEXTURE_SRGB_DECODE_EXT        0x8A48
+#define GL_DECODE_EXT                     0x8A49
+#define GL_SKIP_DECODE_EXT                0x8A4A
+#endif /* GL_EXT_texture_sRGB_decode */
+
+#ifndef GL_EXT_texture_storage
+#define GL_EXT_texture_storage 1
+#define GL_TEXTURE_IMMUTABLE_FORMAT_EXT   0x912F
+#define GL_ALPHA8_EXT                     0x803C
+#define GL_LUMINANCE8_EXT                 0x8040
+#define GL_LUMINANCE8_ALPHA8_EXT          0x8045
+#define GL_RGBA32F_EXT                    0x8814
+#define GL_RGB32F_EXT                     0x8815
+#define GL_ALPHA32F_EXT                   0x8816
+#define GL_LUMINANCE32F_EXT               0x8818
+#define GL_LUMINANCE_ALPHA32F_EXT         0x8819
+#define GL_ALPHA16F_EXT                   0x881C
+#define GL_LUMINANCE16F_EXT               0x881E
+#define GL_LUMINANCE_ALPHA16F_EXT         0x881F
+#define GL_R32F_EXT                       0x822E
+#define GL_RG32F_EXT                      0x8230
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGE1DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGE2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexStorage1DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+GL_APICALL void GL_APIENTRY glTexStorage2DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glTexStorage3DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+GL_APICALL void GL_APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width);
+GL_APICALL void GL_APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth);
+#endif
+#endif /* GL_EXT_texture_storage */
+
+#ifndef GL_EXT_texture_type_2_10_10_10_REV
+#define GL_EXT_texture_type_2_10_10_10_REV 1
+#define GL_UNSIGNED_INT_2_10_10_10_REV_EXT 0x8368
+#endif /* GL_EXT_texture_type_2_10_10_10_REV */
+
+#ifndef GL_EXT_texture_view
+#define GL_EXT_texture_view 1
+#define GL_TEXTURE_VIEW_MIN_LEVEL_EXT     0x82DB
+#define GL_TEXTURE_VIEW_NUM_LEVELS_EXT    0x82DC
+#define GL_TEXTURE_VIEW_MIN_LAYER_EXT     0x82DD
+#define GL_TEXTURE_VIEW_NUM_LAYERS_EXT    0x82DE
+typedef void (GL_APIENTRYP PFNGLTEXTUREVIEWEXTPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTextureViewEXT (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers);
+#endif
+#endif /* GL_EXT_texture_view */
+
+#ifndef GL_EXT_unpack_subimage
+#define GL_EXT_unpack_subimage 1
+#define GL_UNPACK_ROW_LENGTH_EXT          0x0CF2
+#define GL_UNPACK_SKIP_ROWS_EXT           0x0CF3
+#define GL_UNPACK_SKIP_PIXELS_EXT         0x0CF4
+#endif /* GL_EXT_unpack_subimage */
+
+#ifndef GL_EXT_win32_keyed_mutex
+#define GL_EXT_win32_keyed_mutex 1
+typedef GLboolean (GL_APIENTRYP PFNGLACQUIREKEYEDMUTEXWIN32EXTPROC) (GLuint memory, GLuint64 key, GLuint timeout);
+typedef GLboolean (GL_APIENTRYP PFNGLRELEASEKEYEDMUTEXWIN32EXTPROC) (GLuint memory, GLuint64 key);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL GLboolean GL_APIENTRY glAcquireKeyedMutexWin32EXT (GLuint memory, GLuint64 key, GLuint timeout);
+GL_APICALL GLboolean GL_APIENTRY glReleaseKeyedMutexWin32EXT (GLuint memory, GLuint64 key);
+#endif
+#endif /* GL_EXT_win32_keyed_mutex */
+
+#ifndef GL_EXT_window_rectangles
+#define GL_EXT_window_rectangles 1
+#define GL_INCLUSIVE_EXT                  0x8F10
+#define GL_EXCLUSIVE_EXT                  0x8F11
+#define GL_WINDOW_RECTANGLE_EXT           0x8F12
+#define GL_WINDOW_RECTANGLE_MODE_EXT      0x8F13
+#define GL_MAX_WINDOW_RECTANGLES_EXT      0x8F14
+#define GL_NUM_WINDOW_RECTANGLES_EXT      0x8F15
+typedef void (GL_APIENTRYP PFNGLWINDOWRECTANGLESEXTPROC) (GLenum mode, GLsizei count, const GLint *box);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glWindowRectanglesEXT (GLenum mode, GLsizei count, const GLint *box);
+#endif
+#endif /* GL_EXT_window_rectangles */
+
+#ifndef GL_FJ_shader_binary_GCCSO
+#define GL_FJ_shader_binary_GCCSO 1
+#define GL_GCCSO_SHADER_BINARY_FJ         0x9260
+#endif /* GL_FJ_shader_binary_GCCSO */
+
+#ifndef GL_IMG_bindless_texture
+#define GL_IMG_bindless_texture 1
+typedef GLuint64 (GL_APIENTRYP PFNGLGETTEXTUREHANDLEIMGPROC) (GLuint texture);
+typedef GLuint64 (GL_APIENTRYP PFNGLGETTEXTURESAMPLERHANDLEIMGPROC) (GLuint texture, GLuint sampler);
+typedef void (GL_APIENTRYP PFNGLUNIFORMHANDLEUI64IMGPROC) (GLint location, GLuint64 value);
+typedef void (GL_APIENTRYP PFNGLUNIFORMHANDLEUI64VIMGPROC) (GLint location, GLsizei count, const GLuint64 *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64IMGPROC) (GLuint program, GLint location, GLuint64 value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VIMGPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL GLuint64 GL_APIENTRY glGetTextureHandleIMG (GLuint texture);
+GL_APICALL GLuint64 GL_APIENTRY glGetTextureSamplerHandleIMG (GLuint texture, GLuint sampler);
+GL_APICALL void GL_APIENTRY glUniformHandleui64IMG (GLint location, GLuint64 value);
+GL_APICALL void GL_APIENTRY glUniformHandleui64vIMG (GLint location, GLsizei count, const GLuint64 *value);
+GL_APICALL void GL_APIENTRY glProgramUniformHandleui64IMG (GLuint program, GLint location, GLuint64 value);
+GL_APICALL void GL_APIENTRY glProgramUniformHandleui64vIMG (GLuint program, GLint location, GLsizei count, const GLuint64 *values);
+#endif
+#endif /* GL_IMG_bindless_texture */
+
+#ifndef GL_IMG_framebuffer_downsample
+#define GL_IMG_framebuffer_downsample 1
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_AND_DOWNSAMPLE_IMG 0x913C
+#define GL_NUM_DOWNSAMPLE_SCALES_IMG      0x913D
+#define GL_DOWNSAMPLE_SCALES_IMG          0x913E
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SCALE_IMG 0x913F
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DDOWNSAMPLEIMGPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint xscale, GLint yscale);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERDOWNSAMPLEIMGPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer, GLint xscale, GLint yscale);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glFramebufferTexture2DDownsampleIMG (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint xscale, GLint yscale);
+GL_APICALL void GL_APIENTRY glFramebufferTextureLayerDownsampleIMG (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer, GLint xscale, GLint yscale);
+#endif
+#endif /* GL_IMG_framebuffer_downsample */
+
+#ifndef GL_IMG_multisampled_render_to_texture
+#define GL_IMG_multisampled_render_to_texture 1
+#define GL_RENDERBUFFER_SAMPLES_IMG       0x9133
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG 0x9134
+#define GL_MAX_SAMPLES_IMG                0x9135
+#define GL_TEXTURE_SAMPLES_IMG            0x9136
+typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMGPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleIMG (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glFramebufferTexture2DMultisampleIMG (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples);
+#endif
+#endif /* GL_IMG_multisampled_render_to_texture */
+
+#ifndef GL_IMG_program_binary
+#define GL_IMG_program_binary 1
+#define GL_SGX_PROGRAM_BINARY_IMG         0x9130
+#endif /* GL_IMG_program_binary */
+
+#ifndef GL_IMG_read_format
+#define GL_IMG_read_format 1
+#define GL_BGRA_IMG                       0x80E1
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV_IMG 0x8365
+#endif /* GL_IMG_read_format */
+
+#ifndef GL_IMG_shader_binary
+#define GL_IMG_shader_binary 1
+#define GL_SGX_BINARY_IMG                 0x8C0A
+#endif /* GL_IMG_shader_binary */
+
+#ifndef GL_IMG_texture_compression_pvrtc
+#define GL_IMG_texture_compression_pvrtc 1
+#define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
+#define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
+#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
+#define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
+#endif /* GL_IMG_texture_compression_pvrtc */
+
+#ifndef GL_IMG_texture_compression_pvrtc2
+#define GL_IMG_texture_compression_pvrtc2 1
+#define GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG 0x9137
+#define GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG 0x9138
+#endif /* GL_IMG_texture_compression_pvrtc2 */
+
+#ifndef GL_IMG_texture_filter_cubic
+#define GL_IMG_texture_filter_cubic 1
+#define GL_CUBIC_IMG                      0x9139
+#define GL_CUBIC_MIPMAP_NEAREST_IMG       0x913A
+#define GL_CUBIC_MIPMAP_LINEAR_IMG        0x913B
+#endif /* GL_IMG_texture_filter_cubic */
+
+#ifndef GL_INTEL_conservative_rasterization
+#define GL_INTEL_conservative_rasterization 1
+#define GL_CONSERVATIVE_RASTERIZATION_INTEL 0x83FE
+#endif /* GL_INTEL_conservative_rasterization */
+
+#ifndef GL_INTEL_framebuffer_CMAA
+#define GL_INTEL_framebuffer_CMAA 1
+typedef void (GL_APIENTRYP PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC) (void);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glApplyFramebufferAttachmentCMAAINTEL (void);
+#endif
+#endif /* GL_INTEL_framebuffer_CMAA */
+
+#ifndef GL_INTEL_performance_query
+#define GL_INTEL_performance_query 1
+#define GL_PERFQUERY_SINGLE_CONTEXT_INTEL 0x00000000
+#define GL_PERFQUERY_GLOBAL_CONTEXT_INTEL 0x00000001
+#define GL_PERFQUERY_WAIT_INTEL           0x83FB
+#define GL_PERFQUERY_FLUSH_INTEL          0x83FA
+#define GL_PERFQUERY_DONOT_FLUSH_INTEL    0x83F9
+#define GL_PERFQUERY_COUNTER_EVENT_INTEL  0x94F0
+#define GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL 0x94F1
+#define GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL 0x94F2
+#define GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL 0x94F3
+#define GL_PERFQUERY_COUNTER_RAW_INTEL    0x94F4
+#define GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL 0x94F5
+#define GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL 0x94F8
+#define GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL 0x94F9
+#define GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL 0x94FA
+#define GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL 0x94FB
+#define GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL 0x94FC
+#define GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL 0x94FD
+#define GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL 0x94FE
+#define GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL 0x94FF
+#define GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL 0x9500
+typedef void (GL_APIENTRYP PFNGLBEGINPERFQUERYINTELPROC) (GLuint queryHandle);
+typedef void (GL_APIENTRYP PFNGLCREATEPERFQUERYINTELPROC) (GLuint queryId, GLuint *queryHandle);
+typedef void (GL_APIENTRYP PFNGLDELETEPERFQUERYINTELPROC) (GLuint queryHandle);
+typedef void (GL_APIENTRYP PFNGLENDPERFQUERYINTELPROC) (GLuint queryHandle);
+typedef void (GL_APIENTRYP PFNGLGETFIRSTPERFQUERYIDINTELPROC) (GLuint *queryId);
+typedef void (GL_APIENTRYP PFNGLGETNEXTPERFQUERYIDINTELPROC) (GLuint queryId, GLuint *nextQueryId);
+typedef void (GL_APIENTRYP PFNGLGETPERFCOUNTERINFOINTELPROC) (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue);
+typedef void (GL_APIENTRYP PFNGLGETPERFQUERYDATAINTELPROC) (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten);
+typedef void (GL_APIENTRYP PFNGLGETPERFQUERYIDBYNAMEINTELPROC) (GLchar *queryName, GLuint *queryId);
+typedef void (GL_APIENTRYP PFNGLGETPERFQUERYINFOINTELPROC) (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glBeginPerfQueryINTEL (GLuint queryHandle);
+GL_APICALL void GL_APIENTRY glCreatePerfQueryINTEL (GLuint queryId, GLuint *queryHandle);
+GL_APICALL void GL_APIENTRY glDeletePerfQueryINTEL (GLuint queryHandle);
+GL_APICALL void GL_APIENTRY glEndPerfQueryINTEL (GLuint queryHandle);
+GL_APICALL void GL_APIENTRY glGetFirstPerfQueryIdINTEL (GLuint *queryId);
+GL_APICALL void GL_APIENTRY glGetNextPerfQueryIdINTEL (GLuint queryId, GLuint *nextQueryId);
+GL_APICALL void GL_APIENTRY glGetPerfCounterInfoINTEL (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue);
+GL_APICALL void GL_APIENTRY glGetPerfQueryDataINTEL (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten);
+GL_APICALL void GL_APIENTRY glGetPerfQueryIdByNameINTEL (GLchar *queryName, GLuint *queryId);
+GL_APICALL void GL_APIENTRY glGetPerfQueryInfoINTEL (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask);
+#endif
+#endif /* GL_INTEL_performance_query */
+
+#ifndef GL_MESA_shader_integer_functions
+#define GL_MESA_shader_integer_functions 1
+#endif /* GL_MESA_shader_integer_functions */
+
+#ifndef GL_NVX_blend_equation_advanced_multi_draw_buffers
+#define GL_NVX_blend_equation_advanced_multi_draw_buffers 1
+#endif /* GL_NVX_blend_equation_advanced_multi_draw_buffers */
+
+#ifndef GL_NV_bindless_texture
+#define GL_NV_bindless_texture 1
+typedef GLuint64 (GL_APIENTRYP PFNGLGETTEXTUREHANDLENVPROC) (GLuint texture);
+typedef GLuint64 (GL_APIENTRYP PFNGLGETTEXTURESAMPLERHANDLENVPROC) (GLuint texture, GLuint sampler);
+typedef void (GL_APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle);
+typedef void (GL_APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC) (GLuint64 handle);
+typedef GLuint64 (GL_APIENTRYP PFNGLGETIMAGEHANDLENVPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);
+typedef void (GL_APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle, GLenum access);
+typedef void (GL_APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC) (GLuint64 handle);
+typedef void (GL_APIENTRYP PFNGLUNIFORMHANDLEUI64NVPROC) (GLint location, GLuint64 value);
+typedef void (GL_APIENTRYP PFNGLUNIFORMHANDLEUI64VNVPROC) (GLint location, GLsizei count, const GLuint64 *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC) (GLuint program, GLint location, GLuint64 value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values);
+typedef GLboolean (GL_APIENTRYP PFNGLISTEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle);
+typedef GLboolean (GL_APIENTRYP PFNGLISIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL GLuint64 GL_APIENTRY glGetTextureHandleNV (GLuint texture);
+GL_APICALL GLuint64 GL_APIENTRY glGetTextureSamplerHandleNV (GLuint texture, GLuint sampler);
+GL_APICALL void GL_APIENTRY glMakeTextureHandleResidentNV (GLuint64 handle);
+GL_APICALL void GL_APIENTRY glMakeTextureHandleNonResidentNV (GLuint64 handle);
+GL_APICALL GLuint64 GL_APIENTRY glGetImageHandleNV (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format);
+GL_APICALL void GL_APIENTRY glMakeImageHandleResidentNV (GLuint64 handle, GLenum access);
+GL_APICALL void GL_APIENTRY glMakeImageHandleNonResidentNV (GLuint64 handle);
+GL_APICALL void GL_APIENTRY glUniformHandleui64NV (GLint location, GLuint64 value);
+GL_APICALL void GL_APIENTRY glUniformHandleui64vNV (GLint location, GLsizei count, const GLuint64 *value);
+GL_APICALL void GL_APIENTRY glProgramUniformHandleui64NV (GLuint program, GLint location, GLuint64 value);
+GL_APICALL void GL_APIENTRY glProgramUniformHandleui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64 *values);
+GL_APICALL GLboolean GL_APIENTRY glIsTextureHandleResidentNV (GLuint64 handle);
+GL_APICALL GLboolean GL_APIENTRY glIsImageHandleResidentNV (GLuint64 handle);
+#endif
+#endif /* GL_NV_bindless_texture */
+
+#ifndef GL_NV_blend_equation_advanced
+#define GL_NV_blend_equation_advanced 1
+#define GL_BLEND_OVERLAP_NV               0x9281
+#define GL_BLEND_PREMULTIPLIED_SRC_NV     0x9280
+#define GL_BLUE_NV                        0x1905
+#define GL_COLORBURN_NV                   0x929A
+#define GL_COLORDODGE_NV                  0x9299
+#define GL_CONJOINT_NV                    0x9284
+#define GL_CONTRAST_NV                    0x92A1
+#define GL_DARKEN_NV                      0x9297
+#define GL_DIFFERENCE_NV                  0x929E
+#define GL_DISJOINT_NV                    0x9283
+#define GL_DST_ATOP_NV                    0x928F
+#define GL_DST_IN_NV                      0x928B
+#define GL_DST_NV                         0x9287
+#define GL_DST_OUT_NV                     0x928D
+#define GL_DST_OVER_NV                    0x9289
+#define GL_EXCLUSION_NV                   0x92A0
+#define GL_GREEN_NV                       0x1904
+#define GL_HARDLIGHT_NV                   0x929B
+#define GL_HARDMIX_NV                     0x92A9
+#define GL_HSL_COLOR_NV                   0x92AF
+#define GL_HSL_HUE_NV                     0x92AD
+#define GL_HSL_LUMINOSITY_NV              0x92B0
+#define GL_HSL_SATURATION_NV              0x92AE
+#define GL_INVERT_OVG_NV                  0x92B4
+#define GL_INVERT_RGB_NV                  0x92A3
+#define GL_LIGHTEN_NV                     0x9298
+#define GL_LINEARBURN_NV                  0x92A5
+#define GL_LINEARDODGE_NV                 0x92A4
+#define GL_LINEARLIGHT_NV                 0x92A7
+#define GL_MINUS_CLAMPED_NV               0x92B3
+#define GL_MINUS_NV                       0x929F
+#define GL_MULTIPLY_NV                    0x9294
+#define GL_OVERLAY_NV                     0x9296
+#define GL_PINLIGHT_NV                    0x92A8
+#define GL_PLUS_CLAMPED_ALPHA_NV          0x92B2
+#define GL_PLUS_CLAMPED_NV                0x92B1
+#define GL_PLUS_DARKER_NV                 0x9292
+#define GL_PLUS_NV                        0x9291
+#define GL_RED_NV                         0x1903
+#define GL_SCREEN_NV                      0x9295
+#define GL_SOFTLIGHT_NV                   0x929C
+#define GL_SRC_ATOP_NV                    0x928E
+#define GL_SRC_IN_NV                      0x928A
+#define GL_SRC_NV                         0x9286
+#define GL_SRC_OUT_NV                     0x928C
+#define GL_SRC_OVER_NV                    0x9288
+#define GL_UNCORRELATED_NV                0x9282
+#define GL_VIVIDLIGHT_NV                  0x92A6
+#define GL_XOR_NV                         0x1506
+typedef void (GL_APIENTRYP PFNGLBLENDPARAMETERINVPROC) (GLenum pname, GLint value);
+typedef void (GL_APIENTRYP PFNGLBLENDBARRIERNVPROC) (void);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glBlendParameteriNV (GLenum pname, GLint value);
+GL_APICALL void GL_APIENTRY glBlendBarrierNV (void);
+#endif
+#endif /* GL_NV_blend_equation_advanced */
+
+#ifndef GL_NV_blend_equation_advanced_coherent
+#define GL_NV_blend_equation_advanced_coherent 1
+#define GL_BLEND_ADVANCED_COHERENT_NV     0x9285
+#endif /* GL_NV_blend_equation_advanced_coherent */
+
+#ifndef GL_NV_blend_minmax_factor
+#define GL_NV_blend_minmax_factor 1
+#define GL_FACTOR_MIN_AMD                 0x901C
+#define GL_FACTOR_MAX_AMD                 0x901D
+#endif /* GL_NV_blend_minmax_factor */
+
+#ifndef GL_NV_conditional_render
+#define GL_NV_conditional_render 1
+#define GL_QUERY_WAIT_NV                  0x8E13
+#define GL_QUERY_NO_WAIT_NV               0x8E14
+#define GL_QUERY_BY_REGION_WAIT_NV        0x8E15
+#define GL_QUERY_BY_REGION_NO_WAIT_NV     0x8E16
+typedef void (GL_APIENTRYP PFNGLBEGINCONDITIONALRENDERNVPROC) (GLuint id, GLenum mode);
+typedef void (GL_APIENTRYP PFNGLENDCONDITIONALRENDERNVPROC) (void);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glBeginConditionalRenderNV (GLuint id, GLenum mode);
+GL_APICALL void GL_APIENTRY glEndConditionalRenderNV (void);
+#endif
+#endif /* GL_NV_conditional_render */
+
+#ifndef GL_NV_conservative_raster
+#define GL_NV_conservative_raster 1
+#define GL_CONSERVATIVE_RASTERIZATION_NV  0x9346
+#define GL_SUBPIXEL_PRECISION_BIAS_X_BITS_NV 0x9347
+#define GL_SUBPIXEL_PRECISION_BIAS_Y_BITS_NV 0x9348
+#define GL_MAX_SUBPIXEL_PRECISION_BIAS_BITS_NV 0x9349
+typedef void (GL_APIENTRYP PFNGLSUBPIXELPRECISIONBIASNVPROC) (GLuint xbits, GLuint ybits);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glSubpixelPrecisionBiasNV (GLuint xbits, GLuint ybits);
+#endif
+#endif /* GL_NV_conservative_raster */
+
+#ifndef GL_NV_conservative_raster_pre_snap_triangles
+#define GL_NV_conservative_raster_pre_snap_triangles 1
+#define GL_CONSERVATIVE_RASTER_MODE_NV    0x954D
+#define GL_CONSERVATIVE_RASTER_MODE_POST_SNAP_NV 0x954E
+#define GL_CONSERVATIVE_RASTER_MODE_PRE_SNAP_TRIANGLES_NV 0x954F
+typedef void (GL_APIENTRYP PFNGLCONSERVATIVERASTERPARAMETERINVPROC) (GLenum pname, GLint param);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glConservativeRasterParameteriNV (GLenum pname, GLint param);
+#endif
+#endif /* GL_NV_conservative_raster_pre_snap_triangles */
+
+#ifndef GL_NV_copy_buffer
+#define GL_NV_copy_buffer 1
+#define GL_COPY_READ_BUFFER_NV            0x8F36
+#define GL_COPY_WRITE_BUFFER_NV           0x8F37
+typedef void (GL_APIENTRYP PFNGLCOPYBUFFERSUBDATANVPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glCopyBufferSubDataNV (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
+#endif
+#endif /* GL_NV_copy_buffer */
+
+#ifndef GL_NV_coverage_sample
+#define GL_NV_coverage_sample 1
+#define GL_COVERAGE_COMPONENT_NV          0x8ED0
+#define GL_COVERAGE_COMPONENT4_NV         0x8ED1
+#define GL_COVERAGE_ATTACHMENT_NV         0x8ED2
+#define GL_COVERAGE_BUFFERS_NV            0x8ED3
+#define GL_COVERAGE_SAMPLES_NV            0x8ED4
+#define GL_COVERAGE_ALL_FRAGMENTS_NV      0x8ED5
+#define GL_COVERAGE_EDGE_FRAGMENTS_NV     0x8ED6
+#define GL_COVERAGE_AUTOMATIC_NV          0x8ED7
+#define GL_COVERAGE_BUFFER_BIT_NV         0x00008000
+typedef void (GL_APIENTRYP PFNGLCOVERAGEMASKNVPROC) (GLboolean mask);
+typedef void (GL_APIENTRYP PFNGLCOVERAGEOPERATIONNVPROC) (GLenum operation);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glCoverageMaskNV (GLboolean mask);
+GL_APICALL void GL_APIENTRY glCoverageOperationNV (GLenum operation);
+#endif
+#endif /* GL_NV_coverage_sample */
+
+#ifndef GL_NV_depth_nonlinear
+#define GL_NV_depth_nonlinear 1
+#define GL_DEPTH_COMPONENT16_NONLINEAR_NV 0x8E2C
+#endif /* GL_NV_depth_nonlinear */
+
+#ifndef GL_NV_draw_buffers
+#define GL_NV_draw_buffers 1
+#define GL_MAX_DRAW_BUFFERS_NV            0x8824
+#define GL_DRAW_BUFFER0_NV                0x8825
+#define GL_DRAW_BUFFER1_NV                0x8826
+#define GL_DRAW_BUFFER2_NV                0x8827
+#define GL_DRAW_BUFFER3_NV                0x8828
+#define GL_DRAW_BUFFER4_NV                0x8829
+#define GL_DRAW_BUFFER5_NV                0x882A
+#define GL_DRAW_BUFFER6_NV                0x882B
+#define GL_DRAW_BUFFER7_NV                0x882C
+#define GL_DRAW_BUFFER8_NV                0x882D
+#define GL_DRAW_BUFFER9_NV                0x882E
+#define GL_DRAW_BUFFER10_NV               0x882F
+#define GL_DRAW_BUFFER11_NV               0x8830
+#define GL_DRAW_BUFFER12_NV               0x8831
+#define GL_DRAW_BUFFER13_NV               0x8832
+#define GL_DRAW_BUFFER14_NV               0x8833
+#define GL_DRAW_BUFFER15_NV               0x8834
+#define GL_COLOR_ATTACHMENT0_NV           0x8CE0
+#define GL_COLOR_ATTACHMENT1_NV           0x8CE1
+#define GL_COLOR_ATTACHMENT2_NV           0x8CE2
+#define GL_COLOR_ATTACHMENT3_NV           0x8CE3
+#define GL_COLOR_ATTACHMENT4_NV           0x8CE4
+#define GL_COLOR_ATTACHMENT5_NV           0x8CE5
+#define GL_COLOR_ATTACHMENT6_NV           0x8CE6
+#define GL_COLOR_ATTACHMENT7_NV           0x8CE7
+#define GL_COLOR_ATTACHMENT8_NV           0x8CE8
+#define GL_COLOR_ATTACHMENT9_NV           0x8CE9
+#define GL_COLOR_ATTACHMENT10_NV          0x8CEA
+#define GL_COLOR_ATTACHMENT11_NV          0x8CEB
+#define GL_COLOR_ATTACHMENT12_NV          0x8CEC
+#define GL_COLOR_ATTACHMENT13_NV          0x8CED
+#define GL_COLOR_ATTACHMENT14_NV          0x8CEE
+#define GL_COLOR_ATTACHMENT15_NV          0x8CEF
+typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSNVPROC) (GLsizei n, const GLenum *bufs);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawBuffersNV (GLsizei n, const GLenum *bufs);
+#endif
+#endif /* GL_NV_draw_buffers */
+
+#ifndef GL_NV_draw_instanced
+#define GL_NV_draw_instanced 1
+typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDNVPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
+typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDNVPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawArraysInstancedNV (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
+GL_APICALL void GL_APIENTRY glDrawElementsInstancedNV (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);
+#endif
+#endif /* GL_NV_draw_instanced */
+
+#ifndef GL_NV_draw_vulkan_image
+#define GL_NV_draw_vulkan_image 1
+typedef void (GL_APIENTRY  *GLVULKANPROCNV)(void);
+typedef void (GL_APIENTRYP PFNGLDRAWVKIMAGENVPROC) (GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1);
+typedef GLVULKANPROCNV (GL_APIENTRYP PFNGLGETVKPROCADDRNVPROC) (const GLchar *name);
+typedef void (GL_APIENTRYP PFNGLWAITVKSEMAPHORENVPROC) (GLuint64 vkSemaphore);
+typedef void (GL_APIENTRYP PFNGLSIGNALVKSEMAPHORENVPROC) (GLuint64 vkSemaphore);
+typedef void (GL_APIENTRYP PFNGLSIGNALVKFENCENVPROC) (GLuint64 vkFence);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDrawVkImageNV (GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1);
+GL_APICALL GLVULKANPROCNV GL_APIENTRY glGetVkProcAddrNV (const GLchar *name);
+GL_APICALL void GL_APIENTRY glWaitVkSemaphoreNV (GLuint64 vkSemaphore);
+GL_APICALL void GL_APIENTRY glSignalVkSemaphoreNV (GLuint64 vkSemaphore);
+GL_APICALL void GL_APIENTRY glSignalVkFenceNV (GLuint64 vkFence);
+#endif
+#endif /* GL_NV_draw_vulkan_image */
+
+#ifndef GL_NV_explicit_attrib_location
+#define GL_NV_explicit_attrib_location 1
+#endif /* GL_NV_explicit_attrib_location */
+
+#ifndef GL_NV_fbo_color_attachments
+#define GL_NV_fbo_color_attachments 1
+#define GL_MAX_COLOR_ATTACHMENTS_NV       0x8CDF
+#endif /* GL_NV_fbo_color_attachments */
+
+#ifndef GL_NV_fence
+#define GL_NV_fence 1
+#define GL_ALL_COMPLETED_NV               0x84F2
+#define GL_FENCE_STATUS_NV                0x84F3
+#define GL_FENCE_CONDITION_NV             0x84F4
+typedef void (GL_APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);
+typedef void (GL_APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);
+typedef GLboolean (GL_APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);
+typedef GLboolean (GL_APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);
+typedef void (GL_APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
+typedef void (GL_APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDeleteFencesNV (GLsizei n, const GLuint *fences);
+GL_APICALL void GL_APIENTRY glGenFencesNV (GLsizei n, GLuint *fences);
+GL_APICALL GLboolean GL_APIENTRY glIsFenceNV (GLuint fence);
+GL_APICALL GLboolean GL_APIENTRY glTestFenceNV (GLuint fence);
+GL_APICALL void GL_APIENTRY glGetFenceivNV (GLuint fence, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glFinishFenceNV (GLuint fence);
+GL_APICALL void GL_APIENTRY glSetFenceNV (GLuint fence, GLenum condition);
+#endif
+#endif /* GL_NV_fence */
+
+#ifndef GL_NV_fill_rectangle
+#define GL_NV_fill_rectangle 1
+#define GL_FILL_RECTANGLE_NV              0x933C
+#endif /* GL_NV_fill_rectangle */
+
+#ifndef GL_NV_fragment_coverage_to_color
+#define GL_NV_fragment_coverage_to_color 1
+#define GL_FRAGMENT_COVERAGE_TO_COLOR_NV  0x92DD
+#define GL_FRAGMENT_COVERAGE_COLOR_NV     0x92DE
+typedef void (GL_APIENTRYP PFNGLFRAGMENTCOVERAGECOLORNVPROC) (GLuint color);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glFragmentCoverageColorNV (GLuint color);
+#endif
+#endif /* GL_NV_fragment_coverage_to_color */
+
+#ifndef GL_NV_fragment_shader_interlock
+#define GL_NV_fragment_shader_interlock 1
+#endif /* GL_NV_fragment_shader_interlock */
+
+#ifndef GL_NV_framebuffer_blit
+#define GL_NV_framebuffer_blit 1
+#define GL_READ_FRAMEBUFFER_NV            0x8CA8
+#define GL_DRAW_FRAMEBUFFER_NV            0x8CA9
+#define GL_DRAW_FRAMEBUFFER_BINDING_NV    0x8CA6
+#define GL_READ_FRAMEBUFFER_BINDING_NV    0x8CAA
+typedef void (GL_APIENTRYP PFNGLBLITFRAMEBUFFERNVPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glBlitFramebufferNV (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+#endif
+#endif /* GL_NV_framebuffer_blit */
+
+#ifndef GL_NV_framebuffer_mixed_samples
+#define GL_NV_framebuffer_mixed_samples 1
+#define GL_COVERAGE_MODULATION_TABLE_NV   0x9331
+#define GL_COLOR_SAMPLES_NV               0x8E20
+#define GL_DEPTH_SAMPLES_NV               0x932D
+#define GL_STENCIL_SAMPLES_NV             0x932E
+#define GL_MIXED_DEPTH_SAMPLES_SUPPORTED_NV 0x932F
+#define GL_MIXED_STENCIL_SAMPLES_SUPPORTED_NV 0x9330
+#define GL_COVERAGE_MODULATION_NV         0x9332
+#define GL_COVERAGE_MODULATION_TABLE_SIZE_NV 0x9333
+typedef void (GL_APIENTRYP PFNGLCOVERAGEMODULATIONTABLENVPROC) (GLsizei n, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLGETCOVERAGEMODULATIONTABLENVPROC) (GLsizei bufsize, GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLCOVERAGEMODULATIONNVPROC) (GLenum components);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glCoverageModulationTableNV (GLsizei n, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glGetCoverageModulationTableNV (GLsizei bufsize, GLfloat *v);
+GL_APICALL void GL_APIENTRY glCoverageModulationNV (GLenum components);
+#endif
+#endif /* GL_NV_framebuffer_mixed_samples */
+
+#ifndef GL_NV_framebuffer_multisample
+#define GL_NV_framebuffer_multisample 1
+#define GL_RENDERBUFFER_SAMPLES_NV        0x8CAB
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_NV 0x8D56
+#define GL_MAX_SAMPLES_NV                 0x8D57
+typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLENVPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleNV (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+#endif
+#endif /* GL_NV_framebuffer_multisample */
+
+#ifndef GL_NV_generate_mipmap_sRGB
+#define GL_NV_generate_mipmap_sRGB 1
+#endif /* GL_NV_generate_mipmap_sRGB */
+
+#ifndef GL_NV_geometry_shader_passthrough
+#define GL_NV_geometry_shader_passthrough 1
+#endif /* GL_NV_geometry_shader_passthrough */
+
+#ifndef GL_NV_gpu_shader5
+#define GL_NV_gpu_shader5 1
+typedef khronos_int64_t GLint64EXT;
+typedef khronos_uint64_t GLuint64EXT;
+#define GL_INT64_NV                       0x140E
+#define GL_UNSIGNED_INT64_NV              0x140F
+#define GL_INT8_NV                        0x8FE0
+#define GL_INT8_VEC2_NV                   0x8FE1
+#define GL_INT8_VEC3_NV                   0x8FE2
+#define GL_INT8_VEC4_NV                   0x8FE3
+#define GL_INT16_NV                       0x8FE4
+#define GL_INT16_VEC2_NV                  0x8FE5
+#define GL_INT16_VEC3_NV                  0x8FE6
+#define GL_INT16_VEC4_NV                  0x8FE7
+#define GL_INT64_VEC2_NV                  0x8FE9
+#define GL_INT64_VEC3_NV                  0x8FEA
+#define GL_INT64_VEC4_NV                  0x8FEB
+#define GL_UNSIGNED_INT8_NV               0x8FEC
+#define GL_UNSIGNED_INT8_VEC2_NV          0x8FED
+#define GL_UNSIGNED_INT8_VEC3_NV          0x8FEE
+#define GL_UNSIGNED_INT8_VEC4_NV          0x8FEF
+#define GL_UNSIGNED_INT16_NV              0x8FF0
+#define GL_UNSIGNED_INT16_VEC2_NV         0x8FF1
+#define GL_UNSIGNED_INT16_VEC3_NV         0x8FF2
+#define GL_UNSIGNED_INT16_VEC4_NV         0x8FF3
+#define GL_UNSIGNED_INT64_VEC2_NV         0x8FF5
+#define GL_UNSIGNED_INT64_VEC3_NV         0x8FF6
+#define GL_UNSIGNED_INT64_VEC4_NV         0x8FF7
+#define GL_FLOAT16_NV                     0x8FF8
+#define GL_FLOAT16_VEC2_NV                0x8FF9
+#define GL_FLOAT16_VEC3_NV                0x8FFA
+#define GL_FLOAT16_VEC4_NV                0x8FFB
+#define GL_PATCHES                        0x000E
+typedef void (GL_APIENTRYP PFNGLUNIFORM1I64NVPROC) (GLint location, GLint64EXT x);
+typedef void (GL_APIENTRYP PFNGLUNIFORM2I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y);
+typedef void (GL_APIENTRYP PFNGLUNIFORM3I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+typedef void (GL_APIENTRYP PFNGLUNIFORM4I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+typedef void (GL_APIENTRYP PFNGLUNIFORM1I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM2I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM3I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM4I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM1UI64NVPROC) (GLint location, GLuint64EXT x);
+typedef void (GL_APIENTRYP PFNGLUNIFORM2UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y);
+typedef void (GL_APIENTRYP PFNGLUNIFORM3UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+typedef void (GL_APIENTRYP PFNGLUNIFORM4UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+typedef void (GL_APIENTRYP PFNGLUNIFORM1UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM2UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM3UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORM4UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLGETUNIFORMI64VNVPROC) (GLuint program, GLint location, GLint64EXT *params);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1I64NVPROC) (GLuint program, GLint location, GLint64EXT x);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glUniform1i64NV (GLint location, GLint64EXT x);
+GL_APICALL void GL_APIENTRY glUniform2i64NV (GLint location, GLint64EXT x, GLint64EXT y);
+GL_APICALL void GL_APIENTRY glUniform3i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+GL_APICALL void GL_APIENTRY glUniform4i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+GL_APICALL void GL_APIENTRY glUniform1i64vNV (GLint location, GLsizei count, const GLint64EXT *value);
+GL_APICALL void GL_APIENTRY glUniform2i64vNV (GLint location, GLsizei count, const GLint64EXT *value);
+GL_APICALL void GL_APIENTRY glUniform3i64vNV (GLint location, GLsizei count, const GLint64EXT *value);
+GL_APICALL void GL_APIENTRY glUniform4i64vNV (GLint location, GLsizei count, const GLint64EXT *value);
+GL_APICALL void GL_APIENTRY glUniform1ui64NV (GLint location, GLuint64EXT x);
+GL_APICALL void GL_APIENTRY glUniform2ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y);
+GL_APICALL void GL_APIENTRY glUniform3ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+GL_APICALL void GL_APIENTRY glUniform4ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+GL_APICALL void GL_APIENTRY glUniform1ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);
+GL_APICALL void GL_APIENTRY glUniform2ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);
+GL_APICALL void GL_APIENTRY glUniform3ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);
+GL_APICALL void GL_APIENTRY glUniform4ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);
+GL_APICALL void GL_APIENTRY glGetUniformi64vNV (GLuint program, GLint location, GLint64EXT *params);
+GL_APICALL void GL_APIENTRY glProgramUniform1i64NV (GLuint program, GLint location, GLint64EXT x);
+GL_APICALL void GL_APIENTRY glProgramUniform2i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y);
+GL_APICALL void GL_APIENTRY glProgramUniform3i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+GL_APICALL void GL_APIENTRY glProgramUniform4i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+GL_APICALL void GL_APIENTRY glProgramUniform1i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+GL_APICALL void GL_APIENTRY glProgramUniform2i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+GL_APICALL void GL_APIENTRY glProgramUniform3i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+GL_APICALL void GL_APIENTRY glProgramUniform4i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+GL_APICALL void GL_APIENTRY glProgramUniform1ui64NV (GLuint program, GLint location, GLuint64EXT x);
+GL_APICALL void GL_APIENTRY glProgramUniform2ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y);
+GL_APICALL void GL_APIENTRY glProgramUniform3ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+GL_APICALL void GL_APIENTRY glProgramUniform4ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+GL_APICALL void GL_APIENTRY glProgramUniform1ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+GL_APICALL void GL_APIENTRY glProgramUniform2ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+GL_APICALL void GL_APIENTRY glProgramUniform3ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+GL_APICALL void GL_APIENTRY glProgramUniform4ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+#endif
+#endif /* GL_NV_gpu_shader5 */
+
+#ifndef GL_NV_image_formats
+#define GL_NV_image_formats 1
+#endif /* GL_NV_image_formats */
+
+#ifndef GL_NV_instanced_arrays
+#define GL_NV_instanced_arrays 1
+#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_NV 0x88FE
+typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISORNVPROC) (GLuint index, GLuint divisor);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glVertexAttribDivisorNV (GLuint index, GLuint divisor);
+#endif
+#endif /* GL_NV_instanced_arrays */
+
+#ifndef GL_NV_internalformat_sample_query
+#define GL_NV_internalformat_sample_query 1
+#define GL_TEXTURE_2D_MULTISAMPLE         0x9100
+#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY   0x9102
+#define GL_MULTISAMPLES_NV                0x9371
+#define GL_SUPERSAMPLE_SCALE_X_NV         0x9372
+#define GL_SUPERSAMPLE_SCALE_Y_NV         0x9373
+#define GL_CONFORMANT_NV                  0x9374
+typedef void (GL_APIENTRYP PFNGLGETINTERNALFORMATSAMPLEIVNVPROC) (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetInternalformatSampleivNV (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params);
+#endif
+#endif /* GL_NV_internalformat_sample_query */
+
+#ifndef GL_NV_non_square_matrices
+#define GL_NV_non_square_matrices 1
+#define GL_FLOAT_MAT2x3_NV                0x8B65
+#define GL_FLOAT_MAT2x4_NV                0x8B66
+#define GL_FLOAT_MAT3x2_NV                0x8B67
+#define GL_FLOAT_MAT3x4_NV                0x8B68
+#define GL_FLOAT_MAT4x2_NV                0x8B69
+#define GL_FLOAT_MAT4x3_NV                0x8B6A
+typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2X3FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3X2FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2X4FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4X2FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3X4FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4X3FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glUniformMatrix2x3fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniformMatrix3x2fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniformMatrix2x4fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniformMatrix4x2fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniformMatrix3x4fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glUniformMatrix4x3fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+#endif
+#endif /* GL_NV_non_square_matrices */
+
+#ifndef GL_NV_path_rendering
+#define GL_NV_path_rendering 1
+#define GL_PATH_FORMAT_SVG_NV             0x9070
+#define GL_PATH_FORMAT_PS_NV              0x9071
+#define GL_STANDARD_FONT_NAME_NV          0x9072
+#define GL_SYSTEM_FONT_NAME_NV            0x9073
+#define GL_FILE_NAME_NV                   0x9074
+#define GL_PATH_STROKE_WIDTH_NV           0x9075
+#define GL_PATH_END_CAPS_NV               0x9076
+#define GL_PATH_INITIAL_END_CAP_NV        0x9077
+#define GL_PATH_TERMINAL_END_CAP_NV       0x9078
+#define GL_PATH_JOIN_STYLE_NV             0x9079
+#define GL_PATH_MITER_LIMIT_NV            0x907A
+#define GL_PATH_DASH_CAPS_NV              0x907B
+#define GL_PATH_INITIAL_DASH_CAP_NV       0x907C
+#define GL_PATH_TERMINAL_DASH_CAP_NV      0x907D
+#define GL_PATH_DASH_OFFSET_NV            0x907E
+#define GL_PATH_CLIENT_LENGTH_NV          0x907F
+#define GL_PATH_FILL_MODE_NV              0x9080
+#define GL_PATH_FILL_MASK_NV              0x9081
+#define GL_PATH_FILL_COVER_MODE_NV        0x9082
+#define GL_PATH_STROKE_COVER_MODE_NV      0x9083
+#define GL_PATH_STROKE_MASK_NV            0x9084
+#define GL_COUNT_UP_NV                    0x9088
+#define GL_COUNT_DOWN_NV                  0x9089
+#define GL_PATH_OBJECT_BOUNDING_BOX_NV    0x908A
+#define GL_CONVEX_HULL_NV                 0x908B
+#define GL_BOUNDING_BOX_NV                0x908D
+#define GL_TRANSLATE_X_NV                 0x908E
+#define GL_TRANSLATE_Y_NV                 0x908F
+#define GL_TRANSLATE_2D_NV                0x9090
+#define GL_TRANSLATE_3D_NV                0x9091
+#define GL_AFFINE_2D_NV                   0x9092
+#define GL_AFFINE_3D_NV                   0x9094
+#define GL_TRANSPOSE_AFFINE_2D_NV         0x9096
+#define GL_TRANSPOSE_AFFINE_3D_NV         0x9098
+#define GL_UTF8_NV                        0x909A
+#define GL_UTF16_NV                       0x909B
+#define GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV 0x909C
+#define GL_PATH_COMMAND_COUNT_NV          0x909D
+#define GL_PATH_COORD_COUNT_NV            0x909E
+#define GL_PATH_DASH_ARRAY_COUNT_NV       0x909F
+#define GL_PATH_COMPUTED_LENGTH_NV        0x90A0
+#define GL_PATH_FILL_BOUNDING_BOX_NV      0x90A1
+#define GL_PATH_STROKE_BOUNDING_BOX_NV    0x90A2
+#define GL_SQUARE_NV                      0x90A3
+#define GL_ROUND_NV                       0x90A4
+#define GL_TRIANGULAR_NV                  0x90A5
+#define GL_BEVEL_NV                       0x90A6
+#define GL_MITER_REVERT_NV                0x90A7
+#define GL_MITER_TRUNCATE_NV              0x90A8
+#define GL_SKIP_MISSING_GLYPH_NV          0x90A9
+#define GL_USE_MISSING_GLYPH_NV           0x90AA
+#define GL_PATH_ERROR_POSITION_NV         0x90AB
+#define GL_ACCUM_ADJACENT_PAIRS_NV        0x90AD
+#define GL_ADJACENT_PAIRS_NV              0x90AE
+#define GL_FIRST_TO_REST_NV               0x90AF
+#define GL_PATH_GEN_MODE_NV               0x90B0
+#define GL_PATH_GEN_COEFF_NV              0x90B1
+#define GL_PATH_GEN_COMPONENTS_NV         0x90B3
+#define GL_PATH_STENCIL_FUNC_NV           0x90B7
+#define GL_PATH_STENCIL_REF_NV            0x90B8
+#define GL_PATH_STENCIL_VALUE_MASK_NV     0x90B9
+#define GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV 0x90BD
+#define GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV 0x90BE
+#define GL_PATH_COVER_DEPTH_FUNC_NV       0x90BF
+#define GL_PATH_DASH_OFFSET_RESET_NV      0x90B4
+#define GL_MOVE_TO_RESETS_NV              0x90B5
+#define GL_MOVE_TO_CONTINUES_NV           0x90B6
+#define GL_CLOSE_PATH_NV                  0x00
+#define GL_MOVE_TO_NV                     0x02
+#define GL_RELATIVE_MOVE_TO_NV            0x03
+#define GL_LINE_TO_NV                     0x04
+#define GL_RELATIVE_LINE_TO_NV            0x05
+#define GL_HORIZONTAL_LINE_TO_NV          0x06
+#define GL_RELATIVE_HORIZONTAL_LINE_TO_NV 0x07
+#define GL_VERTICAL_LINE_TO_NV            0x08
+#define GL_RELATIVE_VERTICAL_LINE_TO_NV   0x09
+#define GL_QUADRATIC_CURVE_TO_NV          0x0A
+#define GL_RELATIVE_QUADRATIC_CURVE_TO_NV 0x0B
+#define GL_CUBIC_CURVE_TO_NV              0x0C
+#define GL_RELATIVE_CUBIC_CURVE_TO_NV     0x0D
+#define GL_SMOOTH_QUADRATIC_CURVE_TO_NV   0x0E
+#define GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0F
+#define GL_SMOOTH_CUBIC_CURVE_TO_NV       0x10
+#define GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV 0x11
+#define GL_SMALL_CCW_ARC_TO_NV            0x12
+#define GL_RELATIVE_SMALL_CCW_ARC_TO_NV   0x13
+#define GL_SMALL_CW_ARC_TO_NV             0x14
+#define GL_RELATIVE_SMALL_CW_ARC_TO_NV    0x15
+#define GL_LARGE_CCW_ARC_TO_NV            0x16
+#define GL_RELATIVE_LARGE_CCW_ARC_TO_NV   0x17
+#define GL_LARGE_CW_ARC_TO_NV             0x18
+#define GL_RELATIVE_LARGE_CW_ARC_TO_NV    0x19
+#define GL_RESTART_PATH_NV                0xF0
+#define GL_DUP_FIRST_CUBIC_CURVE_TO_NV    0xF2
+#define GL_DUP_LAST_CUBIC_CURVE_TO_NV     0xF4
+#define GL_RECT_NV                        0xF6
+#define GL_CIRCULAR_CCW_ARC_TO_NV         0xF8
+#define GL_CIRCULAR_CW_ARC_TO_NV          0xFA
+#define GL_CIRCULAR_TANGENT_ARC_TO_NV     0xFC
+#define GL_ARC_TO_NV                      0xFE
+#define GL_RELATIVE_ARC_TO_NV             0xFF
+#define GL_BOLD_BIT_NV                    0x01
+#define GL_ITALIC_BIT_NV                  0x02
+#define GL_GLYPH_WIDTH_BIT_NV             0x01
+#define GL_GLYPH_HEIGHT_BIT_NV            0x02
+#define GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV 0x04
+#define GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV 0x08
+#define GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV 0x10
+#define GL_GLYPH_VERTICAL_BEARING_X_BIT_NV 0x20
+#define GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV 0x40
+#define GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV 0x80
+#define GL_GLYPH_HAS_KERNING_BIT_NV       0x100
+#define GL_FONT_X_MIN_BOUNDS_BIT_NV       0x00010000
+#define GL_FONT_Y_MIN_BOUNDS_BIT_NV       0x00020000
+#define GL_FONT_X_MAX_BOUNDS_BIT_NV       0x00040000
+#define GL_FONT_Y_MAX_BOUNDS_BIT_NV       0x00080000
+#define GL_FONT_UNITS_PER_EM_BIT_NV       0x00100000
+#define GL_FONT_ASCENDER_BIT_NV           0x00200000
+#define GL_FONT_DESCENDER_BIT_NV          0x00400000
+#define GL_FONT_HEIGHT_BIT_NV             0x00800000
+#define GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV  0x01000000
+#define GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV 0x02000000
+#define GL_FONT_UNDERLINE_POSITION_BIT_NV 0x04000000
+#define GL_FONT_UNDERLINE_THICKNESS_BIT_NV 0x08000000
+#define GL_FONT_HAS_KERNING_BIT_NV        0x10000000
+#define GL_ROUNDED_RECT_NV                0xE8
+#define GL_RELATIVE_ROUNDED_RECT_NV       0xE9
+#define GL_ROUNDED_RECT2_NV               0xEA
+#define GL_RELATIVE_ROUNDED_RECT2_NV      0xEB
+#define GL_ROUNDED_RECT4_NV               0xEC
+#define GL_RELATIVE_ROUNDED_RECT4_NV      0xED
+#define GL_ROUNDED_RECT8_NV               0xEE
+#define GL_RELATIVE_ROUNDED_RECT8_NV      0xEF
+#define GL_RELATIVE_RECT_NV               0xF7
+#define GL_FONT_GLYPHS_AVAILABLE_NV       0x9368
+#define GL_FONT_TARGET_UNAVAILABLE_NV     0x9369
+#define GL_FONT_UNAVAILABLE_NV            0x936A
+#define GL_FONT_UNINTELLIGIBLE_NV         0x936B
+#define GL_CONIC_CURVE_TO_NV              0x1A
+#define GL_RELATIVE_CONIC_CURVE_TO_NV     0x1B
+#define GL_FONT_NUM_GLYPH_INDICES_BIT_NV  0x20000000
+#define GL_STANDARD_FONT_FORMAT_NV        0x936C
+#define GL_PATH_PROJECTION_NV             0x1701
+#define GL_PATH_MODELVIEW_NV              0x1700
+#define GL_PATH_MODELVIEW_STACK_DEPTH_NV  0x0BA3
+#define GL_PATH_MODELVIEW_MATRIX_NV       0x0BA6
+#define GL_PATH_MAX_MODELVIEW_STACK_DEPTH_NV 0x0D36
+#define GL_PATH_TRANSPOSE_MODELVIEW_MATRIX_NV 0x84E3
+#define GL_PATH_PROJECTION_STACK_DEPTH_NV 0x0BA4
+#define GL_PATH_PROJECTION_MATRIX_NV      0x0BA7
+#define GL_PATH_MAX_PROJECTION_STACK_DEPTH_NV 0x0D38
+#define GL_PATH_TRANSPOSE_PROJECTION_MATRIX_NV 0x84E4
+#define GL_FRAGMENT_INPUT_NV              0x936D
+typedef GLuint (GL_APIENTRYP PFNGLGENPATHSNVPROC) (GLsizei range);
+typedef void (GL_APIENTRYP PFNGLDELETEPATHSNVPROC) (GLuint path, GLsizei range);
+typedef GLboolean (GL_APIENTRYP PFNGLISPATHNVPROC) (GLuint path);
+typedef void (GL_APIENTRYP PFNGLPATHCOMMANDSNVPROC) (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords);
+typedef void (GL_APIENTRYP PFNGLPATHCOORDSNVPROC) (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords);
+typedef void (GL_APIENTRYP PFNGLPATHSUBCOMMANDSNVPROC) (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords);
+typedef void (GL_APIENTRYP PFNGLPATHSUBCOORDSNVPROC) (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords);
+typedef void (GL_APIENTRYP PFNGLPATHSTRINGNVPROC) (GLuint path, GLenum format, GLsizei length, const void *pathString);
+typedef void (GL_APIENTRYP PFNGLPATHGLYPHSNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale);
+typedef void (GL_APIENTRYP PFNGLPATHGLYPHRANGENVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale);
+typedef void (GL_APIENTRYP PFNGLWEIGHTPATHSNVPROC) (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights);
+typedef void (GL_APIENTRYP PFNGLCOPYPATHNVPROC) (GLuint resultPath, GLuint srcPath);
+typedef void (GL_APIENTRYP PFNGLINTERPOLATEPATHSNVPROC) (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight);
+typedef void (GL_APIENTRYP PFNGLTRANSFORMPATHNVPROC) (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues);
+typedef void (GL_APIENTRYP PFNGLPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, const GLint *value);
+typedef void (GL_APIENTRYP PFNGLPATHPARAMETERINVPROC) (GLuint path, GLenum pname, GLint value);
+typedef void (GL_APIENTRYP PFNGLPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, const GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLPATHPARAMETERFNVPROC) (GLuint path, GLenum pname, GLfloat value);
+typedef void (GL_APIENTRYP PFNGLPATHDASHARRAYNVPROC) (GLuint path, GLsizei dashCount, const GLfloat *dashArray);
+typedef void (GL_APIENTRYP PFNGLPATHSTENCILFUNCNVPROC) (GLenum func, GLint ref, GLuint mask);
+typedef void (GL_APIENTRYP PFNGLPATHSTENCILDEPTHOFFSETNVPROC) (GLfloat factor, GLfloat units);
+typedef void (GL_APIENTRYP PFNGLSTENCILFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask);
+typedef void (GL_APIENTRYP PFNGLSTENCILSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask);
+typedef void (GL_APIENTRYP PFNGLSTENCILFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues);
+typedef void (GL_APIENTRYP PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues);
+typedef void (GL_APIENTRYP PFNGLPATHCOVERDEPTHFUNCNVPROC) (GLenum func);
+typedef void (GL_APIENTRYP PFNGLCOVERFILLPATHNVPROC) (GLuint path, GLenum coverMode);
+typedef void (GL_APIENTRYP PFNGLCOVERSTROKEPATHNVPROC) (GLuint path, GLenum coverMode);
+typedef void (GL_APIENTRYP PFNGLCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);
+typedef void (GL_APIENTRYP PFNGLCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);
+typedef void (GL_APIENTRYP PFNGLGETPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, GLint *value);
+typedef void (GL_APIENTRYP PFNGLGETPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, GLfloat *value);
+typedef void (GL_APIENTRYP PFNGLGETPATHCOMMANDSNVPROC) (GLuint path, GLubyte *commands);
+typedef void (GL_APIENTRYP PFNGLGETPATHCOORDSNVPROC) (GLuint path, GLfloat *coords);
+typedef void (GL_APIENTRYP PFNGLGETPATHDASHARRAYNVPROC) (GLuint path, GLfloat *dashArray);
+typedef void (GL_APIENTRYP PFNGLGETPATHMETRICSNVPROC) (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics);
+typedef void (GL_APIENTRYP PFNGLGETPATHMETRICRANGENVPROC) (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics);
+typedef void (GL_APIENTRYP PFNGLGETPATHSPACINGNVPROC) (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing);
+typedef GLboolean (GL_APIENTRYP PFNGLISPOINTINFILLPATHNVPROC) (GLuint path, GLuint mask, GLfloat x, GLfloat y);
+typedef GLboolean (GL_APIENTRYP PFNGLISPOINTINSTROKEPATHNVPROC) (GLuint path, GLfloat x, GLfloat y);
+typedef GLfloat (GL_APIENTRYP PFNGLGETPATHLENGTHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments);
+typedef GLboolean (GL_APIENTRYP PFNGLPOINTALONGPATHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY);
+typedef void (GL_APIENTRYP PFNGLMATRIXLOAD3X2FNVPROC) (GLenum matrixMode, const GLfloat *m);
+typedef void (GL_APIENTRYP PFNGLMATRIXLOAD3X3FNVPROC) (GLenum matrixMode, const GLfloat *m);
+typedef void (GL_APIENTRYP PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m);
+typedef void (GL_APIENTRYP PFNGLMATRIXMULT3X2FNVPROC) (GLenum matrixMode, const GLfloat *m);
+typedef void (GL_APIENTRYP PFNGLMATRIXMULT3X3FNVPROC) (GLenum matrixMode, const GLfloat *m);
+typedef void (GL_APIENTRYP PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m);
+typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode);
+typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask, GLenum coverMode);
+typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);
+typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);
+typedef GLenum (GL_APIENTRYP PFNGLPATHGLYPHINDEXRANGENVPROC) (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint baseAndCount[2]);
+typedef GLenum (GL_APIENTRYP PFNGLPATHGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale);
+typedef GLenum (GL_APIENTRYP PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale);
+typedef void (GL_APIENTRYP PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC) (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs);
+typedef void (GL_APIENTRYP PFNGLGETPROGRAMRESOURCEFVNVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLfloat *params);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL GLuint GL_APIENTRY glGenPathsNV (GLsizei range);
+GL_APICALL void GL_APIENTRY glDeletePathsNV (GLuint path, GLsizei range);
+GL_APICALL GLboolean GL_APIENTRY glIsPathNV (GLuint path);
+GL_APICALL void GL_APIENTRY glPathCommandsNV (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords);
+GL_APICALL void GL_APIENTRY glPathCoordsNV (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords);
+GL_APICALL void GL_APIENTRY glPathSubCommandsNV (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords);
+GL_APICALL void GL_APIENTRY glPathSubCoordsNV (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords);
+GL_APICALL void GL_APIENTRY glPathStringNV (GLuint path, GLenum format, GLsizei length, const void *pathString);
+GL_APICALL void GL_APIENTRY glPathGlyphsNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale);
+GL_APICALL void GL_APIENTRY glPathGlyphRangeNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale);
+GL_APICALL void GL_APIENTRY glWeightPathsNV (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights);
+GL_APICALL void GL_APIENTRY glCopyPathNV (GLuint resultPath, GLuint srcPath);
+GL_APICALL void GL_APIENTRY glInterpolatePathsNV (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight);
+GL_APICALL void GL_APIENTRY glTransformPathNV (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues);
+GL_APICALL void GL_APIENTRY glPathParameterivNV (GLuint path, GLenum pname, const GLint *value);
+GL_APICALL void GL_APIENTRY glPathParameteriNV (GLuint path, GLenum pname, GLint value);
+GL_APICALL void GL_APIENTRY glPathParameterfvNV (GLuint path, GLenum pname, const GLfloat *value);
+GL_APICALL void GL_APIENTRY glPathParameterfNV (GLuint path, GLenum pname, GLfloat value);
+GL_APICALL void GL_APIENTRY glPathDashArrayNV (GLuint path, GLsizei dashCount, const GLfloat *dashArray);
+GL_APICALL void GL_APIENTRY glPathStencilFuncNV (GLenum func, GLint ref, GLuint mask);
+GL_APICALL void GL_APIENTRY glPathStencilDepthOffsetNV (GLfloat factor, GLfloat units);
+GL_APICALL void GL_APIENTRY glStencilFillPathNV (GLuint path, GLenum fillMode, GLuint mask);
+GL_APICALL void GL_APIENTRY glStencilStrokePathNV (GLuint path, GLint reference, GLuint mask);
+GL_APICALL void GL_APIENTRY glStencilFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues);
+GL_APICALL void GL_APIENTRY glStencilStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues);
+GL_APICALL void GL_APIENTRY glPathCoverDepthFuncNV (GLenum func);
+GL_APICALL void GL_APIENTRY glCoverFillPathNV (GLuint path, GLenum coverMode);
+GL_APICALL void GL_APIENTRY glCoverStrokePathNV (GLuint path, GLenum coverMode);
+GL_APICALL void GL_APIENTRY glCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);
+GL_APICALL void GL_APIENTRY glCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);
+GL_APICALL void GL_APIENTRY glGetPathParameterivNV (GLuint path, GLenum pname, GLint *value);
+GL_APICALL void GL_APIENTRY glGetPathParameterfvNV (GLuint path, GLenum pname, GLfloat *value);
+GL_APICALL void GL_APIENTRY glGetPathCommandsNV (GLuint path, GLubyte *commands);
+GL_APICALL void GL_APIENTRY glGetPathCoordsNV (GLuint path, GLfloat *coords);
+GL_APICALL void GL_APIENTRY glGetPathDashArrayNV (GLuint path, GLfloat *dashArray);
+GL_APICALL void GL_APIENTRY glGetPathMetricsNV (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics);
+GL_APICALL void GL_APIENTRY glGetPathMetricRangeNV (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics);
+GL_APICALL void GL_APIENTRY glGetPathSpacingNV (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing);
+GL_APICALL GLboolean GL_APIENTRY glIsPointInFillPathNV (GLuint path, GLuint mask, GLfloat x, GLfloat y);
+GL_APICALL GLboolean GL_APIENTRY glIsPointInStrokePathNV (GLuint path, GLfloat x, GLfloat y);
+GL_APICALL GLfloat GL_APIENTRY glGetPathLengthNV (GLuint path, GLsizei startSegment, GLsizei numSegments);
+GL_APICALL GLboolean GL_APIENTRY glPointAlongPathNV (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY);
+GL_APICALL void GL_APIENTRY glMatrixLoad3x2fNV (GLenum matrixMode, const GLfloat *m);
+GL_APICALL void GL_APIENTRY glMatrixLoad3x3fNV (GLenum matrixMode, const GLfloat *m);
+GL_APICALL void GL_APIENTRY glMatrixLoadTranspose3x3fNV (GLenum matrixMode, const GLfloat *m);
+GL_APICALL void GL_APIENTRY glMatrixMult3x2fNV (GLenum matrixMode, const GLfloat *m);
+GL_APICALL void GL_APIENTRY glMatrixMult3x3fNV (GLenum matrixMode, const GLfloat *m);
+GL_APICALL void GL_APIENTRY glMatrixMultTranspose3x3fNV (GLenum matrixMode, const GLfloat *m);
+GL_APICALL void GL_APIENTRY glStencilThenCoverFillPathNV (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode);
+GL_APICALL void GL_APIENTRY glStencilThenCoverStrokePathNV (GLuint path, GLint reference, GLuint mask, GLenum coverMode);
+GL_APICALL void GL_APIENTRY glStencilThenCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);
+GL_APICALL void GL_APIENTRY glStencilThenCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues);
+GL_APICALL GLenum GL_APIENTRY glPathGlyphIndexRangeNV (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint baseAndCount[2]);
+GL_APICALL GLenum GL_APIENTRY glPathGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale);
+GL_APICALL GLenum GL_APIENTRY glPathMemoryGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale);
+GL_APICALL void GL_APIENTRY glProgramPathFragmentInputGenNV (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs);
+GL_APICALL void GL_APIENTRY glGetProgramResourcefvNV (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLfloat *params);
+#endif
+#endif /* GL_NV_path_rendering */
+
+#ifndef GL_NV_path_rendering_shared_edge
+#define GL_NV_path_rendering_shared_edge 1
+#define GL_SHARED_EDGE_NV                 0xC0
+#endif /* GL_NV_path_rendering_shared_edge */
+
+#ifndef GL_NV_pixel_buffer_object
+#define GL_NV_pixel_buffer_object 1
+#define GL_PIXEL_PACK_BUFFER_NV           0x88EB
+#define GL_PIXEL_UNPACK_BUFFER_NV         0x88EC
+#define GL_PIXEL_PACK_BUFFER_BINDING_NV   0x88ED
+#define GL_PIXEL_UNPACK_BUFFER_BINDING_NV 0x88EF
+#endif /* GL_NV_pixel_buffer_object */
+
+#ifndef GL_NV_polygon_mode
+#define GL_NV_polygon_mode 1
+#define GL_POLYGON_MODE_NV                0x0B40
+#define GL_POLYGON_OFFSET_POINT_NV        0x2A01
+#define GL_POLYGON_OFFSET_LINE_NV         0x2A02
+#define GL_POINT_NV                       0x1B00
+#define GL_LINE_NV                        0x1B01
+#define GL_FILL_NV                        0x1B02
+typedef void (GL_APIENTRYP PFNGLPOLYGONMODENVPROC) (GLenum face, GLenum mode);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glPolygonModeNV (GLenum face, GLenum mode);
+#endif
+#endif /* GL_NV_polygon_mode */
+
+#ifndef GL_NV_read_buffer
+#define GL_NV_read_buffer 1
+#define GL_READ_BUFFER_NV                 0x0C02
+typedef void (GL_APIENTRYP PFNGLREADBUFFERNVPROC) (GLenum mode);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glReadBufferNV (GLenum mode);
+#endif
+#endif /* GL_NV_read_buffer */
+
+#ifndef GL_NV_read_buffer_front
+#define GL_NV_read_buffer_front 1
+#endif /* GL_NV_read_buffer_front */
+
+#ifndef GL_NV_read_depth
+#define GL_NV_read_depth 1
+#endif /* GL_NV_read_depth */
+
+#ifndef GL_NV_read_depth_stencil
+#define GL_NV_read_depth_stencil 1
+#endif /* GL_NV_read_depth_stencil */
+
+#ifndef GL_NV_read_stencil
+#define GL_NV_read_stencil 1
+#endif /* GL_NV_read_stencil */
+
+#ifndef GL_NV_sRGB_formats
+#define GL_NV_sRGB_formats 1
+#define GL_SLUMINANCE_NV                  0x8C46
+#define GL_SLUMINANCE_ALPHA_NV            0x8C44
+#define GL_SRGB8_NV                       0x8C41
+#define GL_SLUMINANCE8_NV                 0x8C47
+#define GL_SLUMINANCE8_ALPHA8_NV          0x8C45
+#define GL_COMPRESSED_SRGB_S3TC_DXT1_NV   0x8C4C
+#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV 0x8C4D
+#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV 0x8C4E
+#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV 0x8C4F
+#define GL_ETC1_SRGB8_NV                  0x88EE
+#endif /* GL_NV_sRGB_formats */
+
+#ifndef GL_NV_sample_locations
+#define GL_NV_sample_locations 1
+#define GL_SAMPLE_LOCATION_SUBPIXEL_BITS_NV 0x933D
+#define GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_NV 0x933E
+#define GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_NV 0x933F
+#define GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_NV 0x9340
+#define GL_SAMPLE_LOCATION_NV             0x8E50
+#define GL_PROGRAMMABLE_SAMPLE_LOCATION_NV 0x9341
+#define GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_NV 0x9342
+#define GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_NV 0x9343
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLenum target, GLuint start, GLsizei count, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLRESOLVEDEPTHVALUESNVPROC) (void);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glFramebufferSampleLocationsfvNV (GLenum target, GLuint start, GLsizei count, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glNamedFramebufferSampleLocationsfvNV (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glResolveDepthValuesNV (void);
+#endif
+#endif /* GL_NV_sample_locations */
+
+#ifndef GL_NV_sample_mask_override_coverage
+#define GL_NV_sample_mask_override_coverage 1
+#endif /* GL_NV_sample_mask_override_coverage */
+
+#ifndef GL_NV_shader_atomic_fp16_vector
+#define GL_NV_shader_atomic_fp16_vector 1
+#endif /* GL_NV_shader_atomic_fp16_vector */
+
+#ifndef GL_NV_shader_noperspective_interpolation
+#define GL_NV_shader_noperspective_interpolation 1
+#endif /* GL_NV_shader_noperspective_interpolation */
+
+#ifndef GL_NV_shadow_samplers_array
+#define GL_NV_shadow_samplers_array 1
+#define GL_SAMPLER_2D_ARRAY_SHADOW_NV     0x8DC4
+#endif /* GL_NV_shadow_samplers_array */
+
+#ifndef GL_NV_shadow_samplers_cube
+#define GL_NV_shadow_samplers_cube 1
+#define GL_SAMPLER_CUBE_SHADOW_NV         0x8DC5
+#endif /* GL_NV_shadow_samplers_cube */
+
+#ifndef GL_NV_texture_border_clamp
+#define GL_NV_texture_border_clamp 1
+#define GL_TEXTURE_BORDER_COLOR_NV        0x1004
+#define GL_CLAMP_TO_BORDER_NV             0x812D
+#endif /* GL_NV_texture_border_clamp */
+
+#ifndef GL_NV_texture_compression_s3tc_update
+#define GL_NV_texture_compression_s3tc_update 1
+#endif /* GL_NV_texture_compression_s3tc_update */
+
+#ifndef GL_NV_texture_npot_2D_mipmap
+#define GL_NV_texture_npot_2D_mipmap 1
+#endif /* GL_NV_texture_npot_2D_mipmap */
+
+#ifndef GL_NV_viewport_array
+#define GL_NV_viewport_array 1
+#define GL_MAX_VIEWPORTS_NV               0x825B
+#define GL_VIEWPORT_SUBPIXEL_BITS_NV      0x825C
+#define GL_VIEWPORT_BOUNDS_RANGE_NV       0x825D
+#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX_NV 0x825F
+typedef void (GL_APIENTRYP PFNGLVIEWPORTARRAYVNVPROC) (GLuint first, GLsizei count, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLVIEWPORTINDEXEDFNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h);
+typedef void (GL_APIENTRYP PFNGLVIEWPORTINDEXEDFVNVPROC) (GLuint index, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLSCISSORARRAYVNVPROC) (GLuint first, GLsizei count, const GLint *v);
+typedef void (GL_APIENTRYP PFNGLSCISSORINDEXEDNVPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLSCISSORINDEXEDVNVPROC) (GLuint index, const GLint *v);
+typedef void (GL_APIENTRYP PFNGLDEPTHRANGEARRAYFVNVPROC) (GLuint first, GLsizei count, const GLfloat *v);
+typedef void (GL_APIENTRYP PFNGLDEPTHRANGEINDEXEDFNVPROC) (GLuint index, GLfloat n, GLfloat f);
+typedef void (GL_APIENTRYP PFNGLGETFLOATI_VNVPROC) (GLenum target, GLuint index, GLfloat *data);
+typedef void (GL_APIENTRYP PFNGLENABLEINVPROC) (GLenum target, GLuint index);
+typedef void (GL_APIENTRYP PFNGLDISABLEINVPROC) (GLenum target, GLuint index);
+typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDINVPROC) (GLenum target, GLuint index);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glViewportArrayvNV (GLuint first, GLsizei count, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glViewportIndexedfNV (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h);
+GL_APICALL void GL_APIENTRY glViewportIndexedfvNV (GLuint index, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glScissorArrayvNV (GLuint first, GLsizei count, const GLint *v);
+GL_APICALL void GL_APIENTRY glScissorIndexedNV (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glScissorIndexedvNV (GLuint index, const GLint *v);
+GL_APICALL void GL_APIENTRY glDepthRangeArrayfvNV (GLuint first, GLsizei count, const GLfloat *v);
+GL_APICALL void GL_APIENTRY glDepthRangeIndexedfNV (GLuint index, GLfloat n, GLfloat f);
+GL_APICALL void GL_APIENTRY glGetFloati_vNV (GLenum target, GLuint index, GLfloat *data);
+GL_APICALL void GL_APIENTRY glEnableiNV (GLenum target, GLuint index);
+GL_APICALL void GL_APIENTRY glDisableiNV (GLenum target, GLuint index);
+GL_APICALL GLboolean GL_APIENTRY glIsEnablediNV (GLenum target, GLuint index);
+#endif
+#endif /* GL_NV_viewport_array */
+
+#ifndef GL_NV_viewport_array2
+#define GL_NV_viewport_array2 1
+#endif /* GL_NV_viewport_array2 */
+
+#ifndef GL_NV_viewport_swizzle
+#define GL_NV_viewport_swizzle 1
+#define GL_VIEWPORT_SWIZZLE_POSITIVE_X_NV 0x9350
+#define GL_VIEWPORT_SWIZZLE_NEGATIVE_X_NV 0x9351
+#define GL_VIEWPORT_SWIZZLE_POSITIVE_Y_NV 0x9352
+#define GL_VIEWPORT_SWIZZLE_NEGATIVE_Y_NV 0x9353
+#define GL_VIEWPORT_SWIZZLE_POSITIVE_Z_NV 0x9354
+#define GL_VIEWPORT_SWIZZLE_NEGATIVE_Z_NV 0x9355
+#define GL_VIEWPORT_SWIZZLE_POSITIVE_W_NV 0x9356
+#define GL_VIEWPORT_SWIZZLE_NEGATIVE_W_NV 0x9357
+#define GL_VIEWPORT_SWIZZLE_X_NV          0x9358
+#define GL_VIEWPORT_SWIZZLE_Y_NV          0x9359
+#define GL_VIEWPORT_SWIZZLE_Z_NV          0x935A
+#define GL_VIEWPORT_SWIZZLE_W_NV          0x935B
+typedef void (GL_APIENTRYP PFNGLVIEWPORTSWIZZLENVPROC) (GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glViewportSwizzleNV (GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew);
+#endif
+#endif /* GL_NV_viewport_swizzle */
+
+#ifndef GL_OVR_multiview
+#define GL_OVR_multiview 1
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR 0x9630
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR 0x9632
+#define GL_MAX_VIEWS_OVR                  0x9631
+#define GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR 0x9633
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glFramebufferTextureMultiviewOVR (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews);
+#endif
+#endif /* GL_OVR_multiview */
+
+#ifndef GL_OVR_multiview2
+#define GL_OVR_multiview2 1
+#endif /* GL_OVR_multiview2 */
+
+#ifndef GL_OVR_multiview_multisampled_render_to_texture
+#define GL_OVR_multiview_multisampled_render_to_texture 1
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREMULTISAMPLEMULTIVIEWOVRPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLsizei samples, GLint baseViewIndex, GLsizei numViews);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glFramebufferTextureMultisampleMultiviewOVR (GLenum target, GLenum attachment, GLuint texture, GLint level, GLsizei samples, GLint baseViewIndex, GLsizei numViews);
+#endif
+#endif /* GL_OVR_multiview_multisampled_render_to_texture */
+
+#ifndef GL_QCOM_alpha_test
+#define GL_QCOM_alpha_test 1
+#define GL_ALPHA_TEST_QCOM                0x0BC0
+#define GL_ALPHA_TEST_FUNC_QCOM           0x0BC1
+#define GL_ALPHA_TEST_REF_QCOM            0x0BC2
+typedef void (GL_APIENTRYP PFNGLALPHAFUNCQCOMPROC) (GLenum func, GLclampf ref);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glAlphaFuncQCOM (GLenum func, GLclampf ref);
+#endif
+#endif /* GL_QCOM_alpha_test */
+
+#ifndef GL_QCOM_binning_control
+#define GL_QCOM_binning_control 1
+#define GL_BINNING_CONTROL_HINT_QCOM      0x8FB0
+#define GL_CPU_OPTIMIZED_QCOM             0x8FB1
+#define GL_GPU_OPTIMIZED_QCOM             0x8FB2
+#define GL_RENDER_DIRECT_TO_FRAMEBUFFER_QCOM 0x8FB3
+#endif /* GL_QCOM_binning_control */
+
+#ifndef GL_QCOM_driver_control
+#define GL_QCOM_driver_control 1
+typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSQCOMPROC) (GLint *num, GLsizei size, GLuint *driverControls);
+typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSTRINGQCOMPROC) (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString);
+typedef void (GL_APIENTRYP PFNGLENABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl);
+typedef void (GL_APIENTRYP PFNGLDISABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetDriverControlsQCOM (GLint *num, GLsizei size, GLuint *driverControls);
+GL_APICALL void GL_APIENTRY glGetDriverControlStringQCOM (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString);
+GL_APICALL void GL_APIENTRY glEnableDriverControlQCOM (GLuint driverControl);
+GL_APICALL void GL_APIENTRY glDisableDriverControlQCOM (GLuint driverControl);
+#endif
+#endif /* GL_QCOM_driver_control */
+
+#ifndef GL_QCOM_extended_get
+#define GL_QCOM_extended_get 1
+#define GL_TEXTURE_WIDTH_QCOM             0x8BD2
+#define GL_TEXTURE_HEIGHT_QCOM            0x8BD3
+#define GL_TEXTURE_DEPTH_QCOM             0x8BD4
+#define GL_TEXTURE_INTERNAL_FORMAT_QCOM   0x8BD5
+#define GL_TEXTURE_FORMAT_QCOM            0x8BD6
+#define GL_TEXTURE_TYPE_QCOM              0x8BD7
+#define GL_TEXTURE_IMAGE_VALID_QCOM       0x8BD8
+#define GL_TEXTURE_NUM_LEVELS_QCOM        0x8BD9
+#define GL_TEXTURE_TARGET_QCOM            0x8BDA
+#define GL_TEXTURE_OBJECT_VALID_QCOM      0x8BDB
+#define GL_STATE_RESTORE                  0x8BDC
+typedef void (GL_APIENTRYP PFNGLEXTGETTEXTURESQCOMPROC) (GLuint *textures, GLint maxTextures, GLint *numTextures);
+typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERSQCOMPROC) (GLuint *buffers, GLint maxBuffers, GLint *numBuffers);
+typedef void (GL_APIENTRYP PFNGLEXTGETRENDERBUFFERSQCOMPROC) (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers);
+typedef void (GL_APIENTRYP PFNGLEXTGETFRAMEBUFFERSQCOMPROC) (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers);
+typedef void (GL_APIENTRYP PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC) (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC) (GLenum target, GLenum pname, GLint param);
+typedef void (GL_APIENTRYP PFNGLEXTGETTEXSUBIMAGEQCOMPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, void *texels);
+typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERPOINTERVQCOMPROC) (GLenum target, void **params);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glExtGetTexturesQCOM (GLuint *textures, GLint maxTextures, GLint *numTextures);
+GL_APICALL void GL_APIENTRY glExtGetBuffersQCOM (GLuint *buffers, GLint maxBuffers, GLint *numBuffers);
+GL_APICALL void GL_APIENTRY glExtGetRenderbuffersQCOM (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers);
+GL_APICALL void GL_APIENTRY glExtGetFramebuffersQCOM (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers);
+GL_APICALL void GL_APIENTRY glExtGetTexLevelParameterivQCOM (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glExtTexObjectStateOverrideiQCOM (GLenum target, GLenum pname, GLint param);
+GL_APICALL void GL_APIENTRY glExtGetTexSubImageQCOM (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, void *texels);
+GL_APICALL void GL_APIENTRY glExtGetBufferPointervQCOM (GLenum target, void **params);
+#endif
+#endif /* GL_QCOM_extended_get */
+
+#ifndef GL_QCOM_extended_get2
+#define GL_QCOM_extended_get2 1
+typedef void (GL_APIENTRYP PFNGLEXTGETSHADERSQCOMPROC) (GLuint *shaders, GLint maxShaders, GLint *numShaders);
+typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMSQCOMPROC) (GLuint *programs, GLint maxPrograms, GLint *numPrograms);
+typedef GLboolean (GL_APIENTRYP PFNGLEXTISPROGRAMBINARYQCOMPROC) (GLuint program);
+typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC) (GLuint program, GLenum shadertype, GLchar *source, GLint *length);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glExtGetShadersQCOM (GLuint *shaders, GLint maxShaders, GLint *numShaders);
+GL_APICALL void GL_APIENTRY glExtGetProgramsQCOM (GLuint *programs, GLint maxPrograms, GLint *numPrograms);
+GL_APICALL GLboolean GL_APIENTRY glExtIsProgramBinaryQCOM (GLuint program);
+GL_APICALL void GL_APIENTRY glExtGetProgramBinarySourceQCOM (GLuint program, GLenum shadertype, GLchar *source, GLint *length);
+#endif
+#endif /* GL_QCOM_extended_get2 */
+
+#ifndef GL_QCOM_framebuffer_foveated
+#define GL_QCOM_framebuffer_foveated 1
+#define GL_FOVEATION_ENABLE_BIT_QCOM      0x00000001
+#define GL_FOVEATION_SCALED_BIN_METHOD_BIT_QCOM 0x00000002
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERFOVEATIONCONFIGQCOMPROC) (GLuint framebuffer, GLuint numLayers, GLuint focalPointsPerLayer, GLuint requestedFeatures, GLuint *providedFeatures);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERFOVEATIONPARAMETERSQCOMPROC) (GLuint framebuffer, GLuint layer, GLuint focalPoint, GLfloat focalX, GLfloat focalY, GLfloat gainX, GLfloat gainY, GLfloat foveaArea);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glFramebufferFoveationConfigQCOM (GLuint framebuffer, GLuint numLayers, GLuint focalPointsPerLayer, GLuint requestedFeatures, GLuint *providedFeatures);
+GL_APICALL void GL_APIENTRY glFramebufferFoveationParametersQCOM (GLuint framebuffer, GLuint layer, GLuint focalPoint, GLfloat focalX, GLfloat focalY, GLfloat gainX, GLfloat gainY, GLfloat foveaArea);
+#endif
+#endif /* GL_QCOM_framebuffer_foveated */
+
+#ifndef GL_QCOM_perfmon_global_mode
+#define GL_QCOM_perfmon_global_mode 1
+#define GL_PERFMON_GLOBAL_MODE_QCOM       0x8FA0
+#endif /* GL_QCOM_perfmon_global_mode */
+
+#ifndef GL_QCOM_shader_framebuffer_fetch_noncoherent
+#define GL_QCOM_shader_framebuffer_fetch_noncoherent 1
+#define GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM 0x96A2
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERFETCHBARRIERQCOMPROC) (void);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glFramebufferFetchBarrierQCOM (void);
+#endif
+#endif /* GL_QCOM_shader_framebuffer_fetch_noncoherent */
+
+#ifndef GL_QCOM_tiled_rendering
+#define GL_QCOM_tiled_rendering 1
+#define GL_COLOR_BUFFER_BIT0_QCOM         0x00000001
+#define GL_COLOR_BUFFER_BIT1_QCOM         0x00000002
+#define GL_COLOR_BUFFER_BIT2_QCOM         0x00000004
+#define GL_COLOR_BUFFER_BIT3_QCOM         0x00000008
+#define GL_COLOR_BUFFER_BIT4_QCOM         0x00000010
+#define GL_COLOR_BUFFER_BIT5_QCOM         0x00000020
+#define GL_COLOR_BUFFER_BIT6_QCOM         0x00000040
+#define GL_COLOR_BUFFER_BIT7_QCOM         0x00000080
+#define GL_DEPTH_BUFFER_BIT0_QCOM         0x00000100
+#define GL_DEPTH_BUFFER_BIT1_QCOM         0x00000200
+#define GL_DEPTH_BUFFER_BIT2_QCOM         0x00000400
+#define GL_DEPTH_BUFFER_BIT3_QCOM         0x00000800
+#define GL_DEPTH_BUFFER_BIT4_QCOM         0x00001000
+#define GL_DEPTH_BUFFER_BIT5_QCOM         0x00002000
+#define GL_DEPTH_BUFFER_BIT6_QCOM         0x00004000
+#define GL_DEPTH_BUFFER_BIT7_QCOM         0x00008000
+#define GL_STENCIL_BUFFER_BIT0_QCOM       0x00010000
+#define GL_STENCIL_BUFFER_BIT1_QCOM       0x00020000
+#define GL_STENCIL_BUFFER_BIT2_QCOM       0x00040000
+#define GL_STENCIL_BUFFER_BIT3_QCOM       0x00080000
+#define GL_STENCIL_BUFFER_BIT4_QCOM       0x00100000
+#define GL_STENCIL_BUFFER_BIT5_QCOM       0x00200000
+#define GL_STENCIL_BUFFER_BIT6_QCOM       0x00400000
+#define GL_STENCIL_BUFFER_BIT7_QCOM       0x00800000
+#define GL_MULTISAMPLE_BUFFER_BIT0_QCOM   0x01000000
+#define GL_MULTISAMPLE_BUFFER_BIT1_QCOM   0x02000000
+#define GL_MULTISAMPLE_BUFFER_BIT2_QCOM   0x04000000
+#define GL_MULTISAMPLE_BUFFER_BIT3_QCOM   0x08000000
+#define GL_MULTISAMPLE_BUFFER_BIT4_QCOM   0x10000000
+#define GL_MULTISAMPLE_BUFFER_BIT5_QCOM   0x20000000
+#define GL_MULTISAMPLE_BUFFER_BIT6_QCOM   0x40000000
+#define GL_MULTISAMPLE_BUFFER_BIT7_QCOM   0x80000000
+typedef void (GL_APIENTRYP PFNGLSTARTTILINGQCOMPROC) (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask);
+typedef void (GL_APIENTRYP PFNGLENDTILINGQCOMPROC) (GLbitfield preserveMask);
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glStartTilingQCOM (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask);
+GL_APICALL void GL_APIENTRY glEndTilingQCOM (GLbitfield preserveMask);
+#endif
+#endif /* GL_QCOM_tiled_rendering */
+
+#ifndef GL_QCOM_writeonly_rendering
+#define GL_QCOM_writeonly_rendering 1
+#define GL_WRITEONLY_RENDERING_QCOM       0x8823
+#endif /* GL_QCOM_writeonly_rendering */
+
+#ifndef GL_VIV_shader_binary
+#define GL_VIV_shader_binary 1
+#define GL_SHADER_BINARY_VIV              0x8FC4
+#endif /* GL_VIV_shader_binary */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/video/khronos/GLES2/gl2platform.h b/src/video/khronos/GLES2/gl2platform.h
new file mode 100644
index 0000000..eb318dc
--- /dev/null
+++ b/src/video/khronos/GLES2/gl2platform.h
@@ -0,0 +1,38 @@
+#ifndef __gl2platform_h_
+#define __gl2platform_h_
+
+/*
+** Copyright (c) 2017 The Khronos Group Inc.
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+/* Platform-specific types and definitions for OpenGL ES 2.X  gl2.h
+ *
+ * Adopters may modify khrplatform.h and this file to suit their platform.
+ * Please contribute modifications back to Khronos as pull requests on the
+ * public github repository:
+ *      https://github.com/KhronosGroup/OpenGL-Registry
+ */
+
+#include <KHR/khrplatform.h>
+
+#ifndef GL_APICALL
+#define GL_APICALL  KHRONOS_APICALL
+#endif
+
+#ifndef GL_APIENTRY
+#define GL_APIENTRY KHRONOS_APIENTRY
+#endif
+
+#endif /* __gl2platform_h_ */
diff --git a/src/video/khronos/KHR/khrplatform.h b/src/video/khronos/KHR/khrplatform.h
new file mode 100644
index 0000000..1ad3554
--- /dev/null
+++ b/src/video/khronos/KHR/khrplatform.h
@@ -0,0 +1,284 @@
+#ifndef __khrplatform_h_
+#define __khrplatform_h_
+
+/*
+** Copyright (c) 2008-2009 The Khronos Group Inc.
+**
+** Permission is hereby granted, free of charge, to any person obtaining a
+** copy of this software and/or associated documentation files (the
+** "Materials"), to deal in the Materials without restriction, including
+** without limitation the rights to use, copy, modify, merge, publish,
+** distribute, sublicense, and/or sell copies of the Materials, and to
+** permit persons to whom the Materials are 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 Materials.
+**
+** THE MATERIALS ARE 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
+** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
+*/
+
+/* Khronos platform-specific types and definitions.
+ *
+ * $Revision: 32517 $ on $Date: 2016-03-11 02:41:19 -0800 (Fri, 11 Mar 2016) $
+ *
+ * Adopters may modify this file to suit their platform. Adopters are
+ * encouraged to submit platform specific modifications to the Khronos
+ * group so that they can be included in future versions of this file.
+ * Please submit changes by sending them to the public Khronos Bugzilla
+ * (http://khronos.org/bugzilla) by filing a bug against product
+ * "Khronos (general)" component "Registry".
+ *
+ * A predefined template which fills in some of the bug fields can be
+ * reached using http://tinyurl.com/khrplatform-h-bugreport, but you
+ * must create a Bugzilla login first.
+ *
+ *
+ * See the Implementer's Guidelines for information about where this file
+ * should be located on your system and for more details of its use:
+ *    http://www.khronos.org/registry/implementers_guide.pdf
+ *
+ * This file should be included as
+ *        #include <KHR/khrplatform.h>
+ * by Khronos client API header files that use its types and defines.
+ *
+ * The types in khrplatform.h should only be used to define API-specific types.
+ *
+ * Types defined in khrplatform.h:
+ *    khronos_int8_t              signed   8  bit
+ *    khronos_uint8_t             unsigned 8  bit
+ *    khronos_int16_t             signed   16 bit
+ *    khronos_uint16_t            unsigned 16 bit
+ *    khronos_int32_t             signed   32 bit
+ *    khronos_uint32_t            unsigned 32 bit
+ *    khronos_int64_t             signed   64 bit
+ *    khronos_uint64_t            unsigned 64 bit
+ *    khronos_intptr_t            signed   same number of bits as a pointer
+ *    khronos_uintptr_t           unsigned same number of bits as a pointer
+ *    khronos_ssize_t             signed   size
+ *    khronos_usize_t             unsigned size
+ *    khronos_float_t             signed   32 bit floating point
+ *    khronos_time_ns_t           unsigned 64 bit time in nanoseconds
+ *    khronos_utime_nanoseconds_t unsigned time interval or absolute time in
+ *                                         nanoseconds
+ *    khronos_stime_nanoseconds_t signed time interval in nanoseconds
+ *    khronos_boolean_enum_t      enumerated boolean type. This should
+ *      only be used as a base type when a client API's boolean type is
+ *      an enum. Client APIs which use an integer or other type for
+ *      booleans cannot use this as the base type for their boolean.
+ *
+ * Tokens defined in khrplatform.h:
+ *
+ *    KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
+ *
+ *    KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
+ *    KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
+ *
+ * Calling convention macros defined in this file:
+ *    KHRONOS_APICALL
+ *    KHRONOS_APIENTRY
+ *    KHRONOS_APIATTRIBUTES
+ *
+ * These may be used in function prototypes as:
+ *
+ *      KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
+ *                                  int arg1,
+ *                                  int arg2) KHRONOS_APIATTRIBUTES;
+ */
+
+/*-------------------------------------------------------------------------
+ * Definition of KHRONOS_APICALL
+ *-------------------------------------------------------------------------
+ * This precedes the return type of the function in the function prototype.
+ */
+#if defined(_WIN32) && !defined(__SCITECH_SNAP__)
+#   define KHRONOS_APICALL __declspec(dllimport)
+#elif defined (__SYMBIAN32__)
+#   define KHRONOS_APICALL IMPORT_C
+#elif defined(__ANDROID__)
+#   define KHRONOS_APICALL __attribute__((visibility("default")))
+#else
+#   define KHRONOS_APICALL
+#endif
+
+/*-------------------------------------------------------------------------
+ * Definition of KHRONOS_APIENTRY
+ *-------------------------------------------------------------------------
+ * This follows the return type of the function  and precedes the function
+ * name in the function prototype.
+ */
+#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
+    /* Win32 but not WinCE */
+#   define KHRONOS_APIENTRY __stdcall
+#else
+#   define KHRONOS_APIENTRY
+#endif
+
+/*-------------------------------------------------------------------------
+ * Definition of KHRONOS_APIATTRIBUTES
+ *-------------------------------------------------------------------------
+ * This follows the closing parenthesis of the function prototype arguments.
+ */
+#if defined (__ARMCC_2__)
+#define KHRONOS_APIATTRIBUTES __softfp
+#else
+#define KHRONOS_APIATTRIBUTES
+#endif
+
+/*-------------------------------------------------------------------------
+ * basic type definitions
+ *-----------------------------------------------------------------------*/
+#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
+
+
+/*
+ * Using <stdint.h>
+ */
+#include <stdint.h>
+typedef int32_t                 khronos_int32_t;
+typedef uint32_t                khronos_uint32_t;
+typedef int64_t                 khronos_int64_t;
+typedef uint64_t                khronos_uint64_t;
+#define KHRONOS_SUPPORT_INT64   1
+#define KHRONOS_SUPPORT_FLOAT   1
+
+#elif defined(__VMS ) || defined(__sgi)
+
+/*
+ * Using <inttypes.h>
+ */
+#include <inttypes.h>
+typedef int32_t                 khronos_int32_t;
+typedef uint32_t                khronos_uint32_t;
+typedef int64_t                 khronos_int64_t;
+typedef uint64_t                khronos_uint64_t;
+#define KHRONOS_SUPPORT_INT64   1
+#define KHRONOS_SUPPORT_FLOAT   1
+
+#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
+
+/*
+ * Win32
+ */
+typedef __int32                 khronos_int32_t;
+typedef unsigned __int32        khronos_uint32_t;
+typedef __int64                 khronos_int64_t;
+typedef unsigned __int64        khronos_uint64_t;
+#define KHRONOS_SUPPORT_INT64   1
+#define KHRONOS_SUPPORT_FLOAT   1
+
+#elif defined(__sun__) || defined(__digital__)
+
+/*
+ * Sun or Digital
+ */
+typedef int                     khronos_int32_t;
+typedef unsigned int            khronos_uint32_t;
+#if defined(__arch64__) || defined(_LP64)
+typedef long int                khronos_int64_t;
+typedef unsigned long int       khronos_uint64_t;
+#else
+typedef long long int           khronos_int64_t;
+typedef unsigned long long int  khronos_uint64_t;
+#endif /* __arch64__ */
+#define KHRONOS_SUPPORT_INT64   1
+#define KHRONOS_SUPPORT_FLOAT   1
+
+#elif 0
+
+/*
+ * Hypothetical platform with no float or int64 support
+ */
+typedef int                     khronos_int32_t;
+typedef unsigned int            khronos_uint32_t;
+#define KHRONOS_SUPPORT_INT64   0
+#define KHRONOS_SUPPORT_FLOAT   0
+
+#else
+
+/*
+ * Generic fallback
+ */
+#include <stdint.h>
+typedef int32_t                 khronos_int32_t;
+typedef uint32_t                khronos_uint32_t;
+typedef int64_t                 khronos_int64_t;
+typedef uint64_t                khronos_uint64_t;
+#define KHRONOS_SUPPORT_INT64   1
+#define KHRONOS_SUPPORT_FLOAT   1
+
+#endif
+
+
+/*
+ * Types that are (so far) the same on all platforms
+ */
+typedef signed   char          khronos_int8_t;
+typedef unsigned char          khronos_uint8_t;
+typedef signed   short int     khronos_int16_t;
+typedef unsigned short int     khronos_uint16_t;
+
+/*
+ * Types that differ between LLP64 and LP64 architectures - in LLP64,
+ * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
+ * to be the only LLP64 architecture in current use.
+ */
+#ifdef _WIN64
+typedef signed   long long int khronos_intptr_t;
+typedef unsigned long long int khronos_uintptr_t;
+typedef signed   long long int khronos_ssize_t;
+typedef unsigned long long int khronos_usize_t;
+#else
+typedef signed   long  int     khronos_intptr_t;
+typedef unsigned long  int     khronos_uintptr_t;
+typedef signed   long  int     khronos_ssize_t;
+typedef unsigned long  int     khronos_usize_t;
+#endif
+
+#if KHRONOS_SUPPORT_FLOAT
+/*
+ * Float type
+ */
+typedef          float         khronos_float_t;
+#endif
+
+#if KHRONOS_SUPPORT_INT64
+/* Time types
+ *
+ * These types can be used to represent a time interval in nanoseconds or
+ * an absolute Unadjusted System Time.  Unadjusted System Time is the number
+ * of nanoseconds since some arbitrary system event (e.g. since the last
+ * time the system booted).  The Unadjusted System Time is an unsigned
+ * 64 bit value that wraps back to 0 every 584 years.  Time intervals
+ * may be either signed or unsigned.
+ */
+typedef khronos_uint64_t       khronos_utime_nanoseconds_t;
+typedef khronos_int64_t        khronos_stime_nanoseconds_t;
+#endif
+
+/*
+ * Dummy value used to pad enum types to 32 bits.
+ */
+#ifndef KHRONOS_MAX_ENUM
+#define KHRONOS_MAX_ENUM 0x7FFFFFFF
+#endif
+
+/*
+ * Enumerated boolean type
+ *
+ * Values other than zero should be considered to be true.  Therefore
+ * comparisons should not be made against KHRONOS_TRUE.
+ */
+typedef enum {
+    KHRONOS_FALSE = 0,
+    KHRONOS_TRUE  = 1,
+    KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
+} khronos_boolean_enum_t;
+
+#endif /* __khrplatform_h_ */
diff --git a/src/video/khronos/vulkan/vk_platform.h b/src/video/khronos/vulkan/vk_platform.h
new file mode 100644
index 0000000..72f8049
--- /dev/null
+++ b/src/video/khronos/vulkan/vk_platform.h
@@ -0,0 +1,120 @@
+//
+// File: vk_platform.h
+//
+/*
+** Copyright (c) 2014-2017 The Khronos Group Inc.
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+
+#ifndef VK_PLATFORM_H_
+#define VK_PLATFORM_H_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif // __cplusplus
+
+/*
+***************************************************************************************************
+*   Platform-specific directives and type declarations
+***************************************************************************************************
+*/
+
+/* Platform-specific calling convention macros.
+ *
+ * Platforms should define these so that Vulkan clients call Vulkan commands
+ * with the same calling conventions that the Vulkan implementation expects.
+ *
+ * VKAPI_ATTR - Placed before the return type in function declarations.
+ *              Useful for C++11 and GCC/Clang-style function attribute syntax.
+ * VKAPI_CALL - Placed after the return type in function declarations.
+ *              Useful for MSVC-style calling convention syntax.
+ * VKAPI_PTR  - Placed between the '(' and '*' in function pointer types.
+ *
+ * Function declaration:  VKAPI_ATTR void VKAPI_CALL vkCommand(void);
+ * Function pointer type: typedef void (VKAPI_PTR *PFN_vkCommand)(void);
+ */
+#if defined(_WIN32)
+    // On Windows, Vulkan commands use the stdcall convention
+    #define VKAPI_ATTR
+    #define VKAPI_CALL __stdcall
+    #define VKAPI_PTR  VKAPI_CALL
+#elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH < 7
+    #error "Vulkan isn't supported for the 'armeabi' NDK ABI"
+#elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7 && defined(__ARM_32BIT_STATE)
+    // On Android 32-bit ARM targets, Vulkan functions use the "hardfloat"
+    // calling convention, i.e. float parameters are passed in registers. This
+    // is true even if the rest of the application passes floats on the stack,
+    // as it does by default when compiling for the armeabi-v7a NDK ABI.
+    #define VKAPI_ATTR __attribute__((pcs("aapcs-vfp")))
+    #define VKAPI_CALL
+    #define VKAPI_PTR  VKAPI_ATTR
+#else
+    // On other platforms, use the default calling convention
+    #define VKAPI_ATTR
+    #define VKAPI_CALL
+    #define VKAPI_PTR
+#endif
+
+#include <stddef.h>
+
+#if !defined(VK_NO_STDINT_H)
+    #if defined(_MSC_VER) && (_MSC_VER < 1600)
+        typedef signed   __int8  int8_t;
+        typedef unsigned __int8  uint8_t;
+        typedef signed   __int16 int16_t;
+        typedef unsigned __int16 uint16_t;
+        typedef signed   __int32 int32_t;
+        typedef unsigned __int32 uint32_t;
+        typedef signed   __int64 int64_t;
+        typedef unsigned __int64 uint64_t;
+    #else
+        #include <stdint.h>
+    #endif
+#endif // !defined(VK_NO_STDINT_H)
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
+
+// Platform-specific headers required by platform window system extensions.
+// These are enabled prior to #including "vulkan.h". The same enable then
+// controls inclusion of the extension interfaces in vulkan.h.
+
+#ifdef VK_USE_PLATFORM_ANDROID_KHR
+#include <android/native_window.h>
+#endif
+
+#ifdef VK_USE_PLATFORM_MIR_KHR
+#include <mir_toolkit/client_types.h>
+#endif
+
+#ifdef VK_USE_PLATFORM_WAYLAND_KHR
+#include <wayland-client.h>
+#endif
+
+#ifdef VK_USE_PLATFORM_WIN32_KHR
+#include <windows.h>
+#endif
+
+#ifdef VK_USE_PLATFORM_XLIB_KHR
+#include <X11/Xlib.h>
+#endif
+
+#ifdef VK_USE_PLATFORM_XCB_KHR
+#include <xcb/xcb.h>
+#endif
+
+#endif
diff --git a/src/video/khronos/vulkan/vulkan.h b/src/video/khronos/vulkan/vulkan.h
new file mode 100644
index 0000000..04495fa
--- /dev/null
+++ b/src/video/khronos/vulkan/vulkan.h
@@ -0,0 +1,6458 @@
+#ifndef VULKAN_H_
+#define VULKAN_H_ 1
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** Copyright (c) 2015-2017 The Khronos Group Inc.
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+/*
+** This header is generated from the Khronos Vulkan XML API Registry.
+**
+*/
+
+
+#define VK_VERSION_1_0 1
+#include "./vk_platform.h"
+
+#define VK_MAKE_VERSION(major, minor, patch) \
+    (((major) << 22) | ((minor) << 12) | (patch))
+
+// DEPRECATED: This define has been removed. Specific version defines (e.g. VK_API_VERSION_1_0), or the VK_MAKE_VERSION macro, should be used instead.
+//#define VK_API_VERSION VK_MAKE_VERSION(1, 0, 0) // Patch version should always be set to 0
+
+// Vulkan 1.0 version number
+#define VK_API_VERSION_1_0 VK_MAKE_VERSION(1, 0, 0)// Patch version should always be set to 0
+
+#define VK_VERSION_MAJOR(version) ((uint32_t)(version) >> 22)
+#define VK_VERSION_MINOR(version) (((uint32_t)(version) >> 12) & 0x3ff)
+#define VK_VERSION_PATCH(version) ((uint32_t)(version) & 0xfff)
+// Version of this file
+#define VK_HEADER_VERSION 59
+
+
+#define VK_NULL_HANDLE 0
+        
+
+
+#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object;
+
+
+#if !defined(VK_DEFINE_NON_DISPATCHABLE_HANDLE)
+#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
+        #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object;
+#else
+        #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object;
+#endif
+#endif
+        
+
+
+typedef uint32_t VkFlags;
+typedef uint32_t VkBool32;
+typedef uint64_t VkDeviceSize;
+typedef uint32_t VkSampleMask;
+
+VK_DEFINE_HANDLE(VkInstance)
+VK_DEFINE_HANDLE(VkPhysicalDevice)
+VK_DEFINE_HANDLE(VkDevice)
+VK_DEFINE_HANDLE(VkQueue)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSemaphore)
+VK_DEFINE_HANDLE(VkCommandBuffer)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkFence)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDeviceMemory)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkBuffer)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkImage)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkEvent)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkQueryPool)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkBufferView)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkImageView)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkShaderModule)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkPipelineCache)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkPipelineLayout)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkRenderPass)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkPipeline)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorSetLayout)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSampler)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorPool)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorSet)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkFramebuffer)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkCommandPool)
+
+#define VK_LOD_CLAMP_NONE                 1000.0f
+#define VK_REMAINING_MIP_LEVELS           (~0U)
+#define VK_REMAINING_ARRAY_LAYERS         (~0U)
+#define VK_WHOLE_SIZE                     (~0ULL)
+#define VK_ATTACHMENT_UNUSED              (~0U)
+#define VK_TRUE                           1
+#define VK_FALSE                          0
+#define VK_QUEUE_FAMILY_IGNORED           (~0U)
+#define VK_SUBPASS_EXTERNAL               (~0U)
+#define VK_MAX_PHYSICAL_DEVICE_NAME_SIZE  256
+#define VK_UUID_SIZE                      16
+#define VK_MAX_MEMORY_TYPES               32
+#define VK_MAX_MEMORY_HEAPS               16
+#define VK_MAX_EXTENSION_NAME_SIZE        256
+#define VK_MAX_DESCRIPTION_SIZE           256
+
+
+typedef enum VkPipelineCacheHeaderVersion {
+    VK_PIPELINE_CACHE_HEADER_VERSION_ONE = 1,
+    VK_PIPELINE_CACHE_HEADER_VERSION_BEGIN_RANGE = VK_PIPELINE_CACHE_HEADER_VERSION_ONE,
+    VK_PIPELINE_CACHE_HEADER_VERSION_END_RANGE = VK_PIPELINE_CACHE_HEADER_VERSION_ONE,
+    VK_PIPELINE_CACHE_HEADER_VERSION_RANGE_SIZE = (VK_PIPELINE_CACHE_HEADER_VERSION_ONE - VK_PIPELINE_CACHE_HEADER_VERSION_ONE + 1),
+    VK_PIPELINE_CACHE_HEADER_VERSION_MAX_ENUM = 0x7FFFFFFF
+} VkPipelineCacheHeaderVersion;
+
+typedef enum VkResult {
+    VK_SUCCESS = 0,
+    VK_NOT_READY = 1,
+    VK_TIMEOUT = 2,
+    VK_EVENT_SET = 3,
+    VK_EVENT_RESET = 4,
+    VK_INCOMPLETE = 5,
+    VK_ERROR_OUT_OF_HOST_MEMORY = -1,
+    VK_ERROR_OUT_OF_DEVICE_MEMORY = -2,
+    VK_ERROR_INITIALIZATION_FAILED = -3,
+    VK_ERROR_DEVICE_LOST = -4,
+    VK_ERROR_MEMORY_MAP_FAILED = -5,
+    VK_ERROR_LAYER_NOT_PRESENT = -6,
+    VK_ERROR_EXTENSION_NOT_PRESENT = -7,
+    VK_ERROR_FEATURE_NOT_PRESENT = -8,
+    VK_ERROR_INCOMPATIBLE_DRIVER = -9,
+    VK_ERROR_TOO_MANY_OBJECTS = -10,
+    VK_ERROR_FORMAT_NOT_SUPPORTED = -11,
+    VK_ERROR_FRAGMENTED_POOL = -12,
+    VK_ERROR_SURFACE_LOST_KHR = -1000000000,
+    VK_ERROR_NATIVE_WINDOW_IN_USE_KHR = -1000000001,
+    VK_SUBOPTIMAL_KHR = 1000001003,
+    VK_ERROR_OUT_OF_DATE_KHR = -1000001004,
+    VK_ERROR_INCOMPATIBLE_DISPLAY_KHR = -1000003001,
+    VK_ERROR_VALIDATION_FAILED_EXT = -1000011001,
+    VK_ERROR_INVALID_SHADER_NV = -1000012000,
+    VK_ERROR_OUT_OF_POOL_MEMORY_KHR = -1000069000,
+    VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR = -1000072003,
+    VK_RESULT_BEGIN_RANGE = VK_ERROR_FRAGMENTED_POOL,
+    VK_RESULT_END_RANGE = VK_INCOMPLETE,
+    VK_RESULT_RANGE_SIZE = (VK_INCOMPLETE - VK_ERROR_FRAGMENTED_POOL + 1),
+    VK_RESULT_MAX_ENUM = 0x7FFFFFFF
+} VkResult;
+
+typedef enum VkStructureType {
+    VK_STRUCTURE_TYPE_APPLICATION_INFO = 0,
+    VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO = 1,
+    VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO = 2,
+    VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO = 3,
+    VK_STRUCTURE_TYPE_SUBMIT_INFO = 4,
+    VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO = 5,
+    VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE = 6,
+    VK_STRUCTURE_TYPE_BIND_SPARSE_INFO = 7,
+    VK_STRUCTURE_TYPE_FENCE_CREATE_INFO = 8,
+    VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO = 9,
+    VK_STRUCTURE_TYPE_EVENT_CREATE_INFO = 10,
+    VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO = 11,
+    VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO = 12,
+    VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO = 13,
+    VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO = 14,
+    VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO = 15,
+    VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO = 16,
+    VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO = 17,
+    VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO = 18,
+    VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO = 19,
+    VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO = 20,
+    VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO = 21,
+    VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO = 22,
+    VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO = 23,
+    VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO = 24,
+    VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO = 25,
+    VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO = 26,
+    VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO = 27,
+    VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO = 28,
+    VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO = 29,
+    VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO = 30,
+    VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO = 31,
+    VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO = 32,
+    VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO = 33,
+    VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO = 34,
+    VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET = 35,
+    VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET = 36,
+    VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO = 37,
+    VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO = 38,
+    VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO = 39,
+    VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO = 40,
+    VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO = 41,
+    VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO = 42,
+    VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO = 43,
+    VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER = 44,
+    VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER = 45,
+    VK_STRUCTURE_TYPE_MEMORY_BARRIER = 46,
+    VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO = 47,
+    VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO = 48,
+    VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR = 1000001000,
+    VK_STRUCTURE_TYPE_PRESENT_INFO_KHR = 1000001001,
+    VK_STRUCTURE_TYPE_DISPLAY_MODE_CREATE_INFO_KHR = 1000002000,
+    VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR = 1000002001,
+    VK_STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR = 1000003000,
+    VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR = 1000004000,
+    VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR = 1000005000,
+    VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR = 1000006000,
+    VK_STRUCTURE_TYPE_MIR_SURFACE_CREATE_INFO_KHR = 1000007000,
+    VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR = 1000008000,
+    VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR = 1000009000,
+    VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT = 1000011000,
+    VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD = 1000018000,
+    VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT = 1000022000,
+    VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT = 1000022001,
+    VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT = 1000022002,
+    VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_IMAGE_CREATE_INFO_NV = 1000026000,
+    VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_BUFFER_CREATE_INFO_NV = 1000026001,
+    VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_MEMORY_ALLOCATE_INFO_NV = 1000026002,
+    VK_STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD = 1000041000,
+    VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHX = 1000053000,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHX = 1000053001,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHX = 1000053002,
+    VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV = 1000056000,
+    VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV = 1000056001,
+    VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV = 1000057000,
+    VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_NV = 1000057001,
+    VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_NV = 1000058000,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR = 1000059000,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR = 1000059001,
+    VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2_KHR = 1000059002,
+    VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR = 1000059003,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2_KHR = 1000059004,
+    VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2_KHR = 1000059005,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR = 1000059006,
+    VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2_KHR = 1000059007,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2_KHR = 1000059008,
+    VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHX = 1000060000,
+    VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHX = 1000060001,
+    VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHX = 1000060002,
+    VK_STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO_KHX = 1000060003,
+    VK_STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO_KHX = 1000060004,
+    VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO_KHX = 1000060005,
+    VK_STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO_KHX = 1000060006,
+    VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHX = 1000060007,
+    VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHX = 1000060008,
+    VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHX = 1000060009,
+    VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHX = 1000060010,
+    VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHX = 1000060011,
+    VK_STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHX = 1000060012,
+    VK_STRUCTURE_TYPE_VALIDATION_FLAGS_EXT = 1000061000,
+    VK_STRUCTURE_TYPE_VI_SURFACE_CREATE_INFO_NN = 1000062000,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES_KHX = 1000070000,
+    VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO_KHX = 1000070001,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO_KHR = 1000071000,
+    VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR = 1000071001,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO_KHR = 1000071002,
+    VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES_KHR = 1000071003,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR = 1000071004,
+    VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR = 1000072000,
+    VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR = 1000072001,
+    VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR = 1000072002,
+    VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR = 1000073000,
+    VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_KHR = 1000073001,
+    VK_STRUCTURE_TYPE_MEMORY_WIN32_HANDLE_PROPERTIES_KHR = 1000073002,
+    VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR = 1000073003,
+    VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR = 1000074000,
+    VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR = 1000074001,
+    VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR = 1000074002,
+    VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_KHR = 1000075000,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO_KHR = 1000076000,
+    VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES_KHR = 1000076001,
+    VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR = 1000077000,
+    VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR = 1000078000,
+    VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR = 1000078001,
+    VK_STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR = 1000078002,
+    VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR = 1000078003,
+    VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR = 1000079000,
+    VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR = 1000079001,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR = 1000080000,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR = 1000083000,
+    VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR = 1000084000,
+    VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO_KHR = 1000085000,
+    VK_STRUCTURE_TYPE_OBJECT_TABLE_CREATE_INFO_NVX = 1000086000,
+    VK_STRUCTURE_TYPE_INDIRECT_COMMANDS_LAYOUT_CREATE_INFO_NVX = 1000086001,
+    VK_STRUCTURE_TYPE_CMD_PROCESS_COMMANDS_INFO_NVX = 1000086002,
+    VK_STRUCTURE_TYPE_CMD_RESERVE_SPACE_FOR_COMMANDS_INFO_NVX = 1000086003,
+    VK_STRUCTURE_TYPE_DEVICE_GENERATED_COMMANDS_LIMITS_NVX = 1000086004,
+    VK_STRUCTURE_TYPE_DEVICE_GENERATED_COMMANDS_FEATURES_NVX = 1000086005,
+    VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV = 1000087000,
+    VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_EXT = 1000090000,
+    VK_STRUCTURE_TYPE_DISPLAY_POWER_INFO_EXT = 1000091000,
+    VK_STRUCTURE_TYPE_DEVICE_EVENT_INFO_EXT = 1000091001,
+    VK_STRUCTURE_TYPE_DISPLAY_EVENT_INFO_EXT = 1000091002,
+    VK_STRUCTURE_TYPE_SWAPCHAIN_COUNTER_CREATE_INFO_EXT = 1000091003,
+    VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE = 1000092000,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PER_VIEW_ATTRIBUTES_PROPERTIES_NVX = 1000097000,
+    VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_SWIZZLE_STATE_CREATE_INFO_NV = 1000098000,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DISCARD_RECTANGLE_PROPERTIES_EXT = 1000099000,
+    VK_STRUCTURE_TYPE_PIPELINE_DISCARD_RECTANGLE_STATE_CREATE_INFO_EXT = 1000099001,
+    VK_STRUCTURE_TYPE_HDR_METADATA_EXT = 1000105000,
+    VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR = 1000111000,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO_KHR = 1000112000,
+    VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES_KHR = 1000112001,
+    VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR = 1000113000,
+    VK_STRUCTURE_TYPE_IMPORT_FENCE_WIN32_HANDLE_INFO_KHR = 1000114000,
+    VK_STRUCTURE_TYPE_EXPORT_FENCE_WIN32_HANDLE_INFO_KHR = 1000114001,
+    VK_STRUCTURE_TYPE_FENCE_GET_WIN32_HANDLE_INFO_KHR = 1000114002,
+    VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR = 1000115000,
+    VK_STRUCTURE_TYPE_FENCE_GET_FD_INFO_KHR = 1000115001,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR = 1000119000,
+    VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR = 1000119001,
+    VK_STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR = 1000119002,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES_KHR = 1000120000,
+    VK_STRUCTURE_TYPE_IOS_SURFACE_CREATE_INFO_MVK = 1000122000,
+    VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK = 1000123000,
+    VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR = 1000127000,
+    VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR = 1000127001,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT = 1000130000,
+    VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT = 1000130001,
+    VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR = 1000146000,
+    VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR = 1000146001,
+    VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2_KHR = 1000146002,
+    VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR = 1000146003,
+    VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2_KHR = 1000146004,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_FEATURES_EXT = 1000148000,
+    VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_PROPERTIES_EXT = 1000148001,
+    VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_ADVANCED_STATE_CREATE_INFO_EXT = 1000148002,
+    VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_TO_COLOR_STATE_CREATE_INFO_NV = 1000149000,
+    VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_MODULATION_STATE_CREATE_INFO_NV = 1000152000,
+    VK_STRUCTURE_TYPE_BEGIN_RANGE = VK_STRUCTURE_TYPE_APPLICATION_INFO,
+    VK_STRUCTURE_TYPE_END_RANGE = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO,
+    VK_STRUCTURE_TYPE_RANGE_SIZE = (VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO - VK_STRUCTURE_TYPE_APPLICATION_INFO + 1),
+    VK_STRUCTURE_TYPE_MAX_ENUM = 0x7FFFFFFF
+} VkStructureType;
+
+typedef enum VkSystemAllocationScope {
+    VK_SYSTEM_ALLOCATION_SCOPE_COMMAND = 0,
+    VK_SYSTEM_ALLOCATION_SCOPE_OBJECT = 1,
+    VK_SYSTEM_ALLOCATION_SCOPE_CACHE = 2,
+    VK_SYSTEM_ALLOCATION_SCOPE_DEVICE = 3,
+    VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE = 4,
+    VK_SYSTEM_ALLOCATION_SCOPE_BEGIN_RANGE = VK_SYSTEM_ALLOCATION_SCOPE_COMMAND,
+    VK_SYSTEM_ALLOCATION_SCOPE_END_RANGE = VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE,
+    VK_SYSTEM_ALLOCATION_SCOPE_RANGE_SIZE = (VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE - VK_SYSTEM_ALLOCATION_SCOPE_COMMAND + 1),
+    VK_SYSTEM_ALLOCATION_SCOPE_MAX_ENUM = 0x7FFFFFFF
+} VkSystemAllocationScope;
+
+typedef enum VkInternalAllocationType {
+    VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE = 0,
+    VK_INTERNAL_ALLOCATION_TYPE_BEGIN_RANGE = VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE,
+    VK_INTERNAL_ALLOCATION_TYPE_END_RANGE = VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE,
+    VK_INTERNAL_ALLOCATION_TYPE_RANGE_SIZE = (VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE - VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE + 1),
+    VK_INTERNAL_ALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF
+} VkInternalAllocationType;
+
+typedef enum VkFormat {
+    VK_FORMAT_UNDEFINED = 0,
+    VK_FORMAT_R4G4_UNORM_PACK8 = 1,
+    VK_FORMAT_R4G4B4A4_UNORM_PACK16 = 2,
+    VK_FORMAT_B4G4R4A4_UNORM_PACK16 = 3,
+    VK_FORMAT_R5G6B5_UNORM_PACK16 = 4,
+    VK_FORMAT_B5G6R5_UNORM_PACK16 = 5,
+    VK_FORMAT_R5G5B5A1_UNORM_PACK16 = 6,
+    VK_FORMAT_B5G5R5A1_UNORM_PACK16 = 7,
+    VK_FORMAT_A1R5G5B5_UNORM_PACK16 = 8,
+    VK_FORMAT_R8_UNORM = 9,
+    VK_FORMAT_R8_SNORM = 10,
+    VK_FORMAT_R8_USCALED = 11,
+    VK_FORMAT_R8_SSCALED = 12,
+    VK_FORMAT_R8_UINT = 13,
+    VK_FORMAT_R8_SINT = 14,
+    VK_FORMAT_R8_SRGB = 15,
+    VK_FORMAT_R8G8_UNORM = 16,
+    VK_FORMAT_R8G8_SNORM = 17,
+    VK_FORMAT_R8G8_USCALED = 18,
+    VK_FORMAT_R8G8_SSCALED = 19,
+    VK_FORMAT_R8G8_UINT = 20,
+    VK_FORMAT_R8G8_SINT = 21,
+    VK_FORMAT_R8G8_SRGB = 22,
+    VK_FORMAT_R8G8B8_UNORM = 23,
+    VK_FORMAT_R8G8B8_SNORM = 24,
+    VK_FORMAT_R8G8B8_USCALED = 25,
+    VK_FORMAT_R8G8B8_SSCALED = 26,
+    VK_FORMAT_R8G8B8_UINT = 27,
+    VK_FORMAT_R8G8B8_SINT = 28,
+    VK_FORMAT_R8G8B8_SRGB = 29,
+    VK_FORMAT_B8G8R8_UNORM = 30,
+    VK_FORMAT_B8G8R8_SNORM = 31,
+    VK_FORMAT_B8G8R8_USCALED = 32,
+    VK_FORMAT_B8G8R8_SSCALED = 33,
+    VK_FORMAT_B8G8R8_UINT = 34,
+    VK_FORMAT_B8G8R8_SINT = 35,
+    VK_FORMAT_B8G8R8_SRGB = 36,
+    VK_FORMAT_R8G8B8A8_UNORM = 37,
+    VK_FORMAT_R8G8B8A8_SNORM = 38,
+    VK_FORMAT_R8G8B8A8_USCALED = 39,
+    VK_FORMAT_R8G8B8A8_SSCALED = 40,
+    VK_FORMAT_R8G8B8A8_UINT = 41,
+    VK_FORMAT_R8G8B8A8_SINT = 42,
+    VK_FORMAT_R8G8B8A8_SRGB = 43,
+    VK_FORMAT_B8G8R8A8_UNORM = 44,
+    VK_FORMAT_B8G8R8A8_SNORM = 45,
+    VK_FORMAT_B8G8R8A8_USCALED = 46,
+    VK_FORMAT_B8G8R8A8_SSCALED = 47,
+    VK_FORMAT_B8G8R8A8_UINT = 48,
+    VK_FORMAT_B8G8R8A8_SINT = 49,
+    VK_FORMAT_B8G8R8A8_SRGB = 50,
+    VK_FORMAT_A8B8G8R8_UNORM_PACK32 = 51,
+    VK_FORMAT_A8B8G8R8_SNORM_PACK32 = 52,
+    VK_FORMAT_A8B8G8R8_USCALED_PACK32 = 53,
+    VK_FORMAT_A8B8G8R8_SSCALED_PACK32 = 54,
+    VK_FORMAT_A8B8G8R8_UINT_PACK32 = 55,
+    VK_FORMAT_A8B8G8R8_SINT_PACK32 = 56,
+    VK_FORMAT_A8B8G8R8_SRGB_PACK32 = 57,
+    VK_FORMAT_A2R10G10B10_UNORM_PACK32 = 58,
+    VK_FORMAT_A2R10G10B10_SNORM_PACK32 = 59,
+    VK_FORMAT_A2R10G10B10_USCALED_PACK32 = 60,
+    VK_FORMAT_A2R10G10B10_SSCALED_PACK32 = 61,
+    VK_FORMAT_A2R10G10B10_UINT_PACK32 = 62,
+    VK_FORMAT_A2R10G10B10_SINT_PACK32 = 63,
+    VK_FORMAT_A2B10G10R10_UNORM_PACK32 = 64,
+    VK_FORMAT_A2B10G10R10_SNORM_PACK32 = 65,
+    VK_FORMAT_A2B10G10R10_USCALED_PACK32 = 66,
+    VK_FORMAT_A2B10G10R10_SSCALED_PACK32 = 67,
+    VK_FORMAT_A2B10G10R10_UINT_PACK32 = 68,
+    VK_FORMAT_A2B10G10R10_SINT_PACK32 = 69,
+    VK_FORMAT_R16_UNORM = 70,
+    VK_FORMAT_R16_SNORM = 71,
+    VK_FORMAT_R16_USCALED = 72,
+    VK_FORMAT_R16_SSCALED = 73,
+    VK_FORMAT_R16_UINT = 74,
+    VK_FORMAT_R16_SINT = 75,
+    VK_FORMAT_R16_SFLOAT = 76,
+    VK_FORMAT_R16G16_UNORM = 77,
+    VK_FORMAT_R16G16_SNORM = 78,
+    VK_FORMAT_R16G16_USCALED = 79,
+    VK_FORMAT_R16G16_SSCALED = 80,
+    VK_FORMAT_R16G16_UINT = 81,
+    VK_FORMAT_R16G16_SINT = 82,
+    VK_FORMAT_R16G16_SFLOAT = 83,
+    VK_FORMAT_R16G16B16_UNORM = 84,
+    VK_FORMAT_R16G16B16_SNORM = 85,
+    VK_FORMAT_R16G16B16_USCALED = 86,
+    VK_FORMAT_R16G16B16_SSCALED = 87,
+    VK_FORMAT_R16G16B16_UINT = 88,
+    VK_FORMAT_R16G16B16_SINT = 89,
+    VK_FORMAT_R16G16B16_SFLOAT = 90,
+    VK_FORMAT_R16G16B16A16_UNORM = 91,
+    VK_FORMAT_R16G16B16A16_SNORM = 92,
+    VK_FORMAT_R16G16B16A16_USCALED = 93,
+    VK_FORMAT_R16G16B16A16_SSCALED = 94,
+    VK_FORMAT_R16G16B16A16_UINT = 95,
+    VK_FORMAT_R16G16B16A16_SINT = 96,
+    VK_FORMAT_R16G16B16A16_SFLOAT = 97,
+    VK_FORMAT_R32_UINT = 98,
+    VK_FORMAT_R32_SINT = 99,
+    VK_FORMAT_R32_SFLOAT = 100,
+    VK_FORMAT_R32G32_UINT = 101,
+    VK_FORMAT_R32G32_SINT = 102,
+    VK_FORMAT_R32G32_SFLOAT = 103,
+    VK_FORMAT_R32G32B32_UINT = 104,
+    VK_FORMAT_R32G32B32_SINT = 105,
+    VK_FORMAT_R32G32B32_SFLOAT = 106,
+    VK_FORMAT_R32G32B32A32_UINT = 107,
+    VK_FORMAT_R32G32B32A32_SINT = 108,
+    VK_FORMAT_R32G32B32A32_SFLOAT = 109,
+    VK_FORMAT_R64_UINT = 110,
+    VK_FORMAT_R64_SINT = 111,
+    VK_FORMAT_R64_SFLOAT = 112,
+    VK_FORMAT_R64G64_UINT = 113,
+    VK_FORMAT_R64G64_SINT = 114,
+    VK_FORMAT_R64G64_SFLOAT = 115,
+    VK_FORMAT_R64G64B64_UINT = 116,
+    VK_FORMAT_R64G64B64_SINT = 117,
+    VK_FORMAT_R64G64B64_SFLOAT = 118,
+    VK_FORMAT_R64G64B64A64_UINT = 119,
+    VK_FORMAT_R64G64B64A64_SINT = 120,
+    VK_FORMAT_R64G64B64A64_SFLOAT = 121,
+    VK_FORMAT_B10G11R11_UFLOAT_PACK32 = 122,
+    VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 = 123,
+    VK_FORMAT_D16_UNORM = 124,
+    VK_FORMAT_X8_D24_UNORM_PACK32 = 125,
+    VK_FORMAT_D32_SFLOAT = 126,
+    VK_FORMAT_S8_UINT = 127,
+    VK_FORMAT_D16_UNORM_S8_UINT = 128,
+    VK_FORMAT_D24_UNORM_S8_UINT = 129,
+    VK_FORMAT_D32_SFLOAT_S8_UINT = 130,
+    VK_FORMAT_BC1_RGB_UNORM_BLOCK = 131,
+    VK_FORMAT_BC1_RGB_SRGB_BLOCK = 132,
+    VK_FORMAT_BC1_RGBA_UNORM_BLOCK = 133,
+    VK_FORMAT_BC1_RGBA_SRGB_BLOCK = 134,
+    VK_FORMAT_BC2_UNORM_BLOCK = 135,
+    VK_FORMAT_BC2_SRGB_BLOCK = 136,
+    VK_FORMAT_BC3_UNORM_BLOCK = 137,
+    VK_FORMAT_BC3_SRGB_BLOCK = 138,
+    VK_FORMAT_BC4_UNORM_BLOCK = 139,
+    VK_FORMAT_BC4_SNORM_BLOCK = 140,
+    VK_FORMAT_BC5_UNORM_BLOCK = 141,
+    VK_FORMAT_BC5_SNORM_BLOCK = 142,
+    VK_FORMAT_BC6H_UFLOAT_BLOCK = 143,
+    VK_FORMAT_BC6H_SFLOAT_BLOCK = 144,
+    VK_FORMAT_BC7_UNORM_BLOCK = 145,
+    VK_FORMAT_BC7_SRGB_BLOCK = 146,
+    VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK = 147,
+    VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK = 148,
+    VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK = 149,
+    VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK = 150,
+    VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK = 151,
+    VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK = 152,
+    VK_FORMAT_EAC_R11_UNORM_BLOCK = 153,
+    VK_FORMAT_EAC_R11_SNORM_BLOCK = 154,
+    VK_FORMAT_EAC_R11G11_UNORM_BLOCK = 155,
+    VK_FORMAT_EAC_R11G11_SNORM_BLOCK = 156,
+    VK_FORMAT_ASTC_4x4_UNORM_BLOCK = 157,
+    VK_FORMAT_ASTC_4x4_SRGB_BLOCK = 158,
+    VK_FORMAT_ASTC_5x4_UNORM_BLOCK = 159,
+    VK_FORMAT_ASTC_5x4_SRGB_BLOCK = 160,
+    VK_FORMAT_ASTC_5x5_UNORM_BLOCK = 161,
+    VK_FORMAT_ASTC_5x5_SRGB_BLOCK = 162,
+    VK_FORMAT_ASTC_6x5_UNORM_BLOCK = 163,
+    VK_FORMAT_ASTC_6x5_SRGB_BLOCK = 164,
+    VK_FORMAT_ASTC_6x6_UNORM_BLOCK = 165,
+    VK_FORMAT_ASTC_6x6_SRGB_BLOCK = 166,
+    VK_FORMAT_ASTC_8x5_UNORM_BLOCK = 167,
+    VK_FORMAT_ASTC_8x5_SRGB_BLOCK = 168,
+    VK_FORMAT_ASTC_8x6_UNORM_BLOCK = 169,
+    VK_FORMAT_ASTC_8x6_SRGB_BLOCK = 170,
+    VK_FORMAT_ASTC_8x8_UNORM_BLOCK = 171,
+    VK_FORMAT_ASTC_8x8_SRGB_BLOCK = 172,
+    VK_FORMAT_ASTC_10x5_UNORM_BLOCK = 173,
+    VK_FORMAT_ASTC_10x5_SRGB_BLOCK = 174,
+    VK_FORMAT_ASTC_10x6_UNORM_BLOCK = 175,
+    VK_FORMAT_ASTC_10x6_SRGB_BLOCK = 176,
+    VK_FORMAT_ASTC_10x8_UNORM_BLOCK = 177,
+    VK_FORMAT_ASTC_10x8_SRGB_BLOCK = 178,
+    VK_FORMAT_ASTC_10x10_UNORM_BLOCK = 179,
+    VK_FORMAT_ASTC_10x10_SRGB_BLOCK = 180,
+    VK_FORMAT_ASTC_12x10_UNORM_BLOCK = 181,
+    VK_FORMAT_ASTC_12x10_SRGB_BLOCK = 182,
+    VK_FORMAT_ASTC_12x12_UNORM_BLOCK = 183,
+    VK_FORMAT_ASTC_12x12_SRGB_BLOCK = 184,
+    VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG = 1000054000,
+    VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG = 1000054001,
+    VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG = 1000054002,
+    VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG = 1000054003,
+    VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG = 1000054004,
+    VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG = 1000054005,
+    VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG = 1000054006,
+    VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG = 1000054007,
+    VK_FORMAT_BEGIN_RANGE = VK_FORMAT_UNDEFINED,
+    VK_FORMAT_END_RANGE = VK_FORMAT_ASTC_12x12_SRGB_BLOCK,
+    VK_FORMAT_RANGE_SIZE = (VK_FORMAT_ASTC_12x12_SRGB_BLOCK - VK_FORMAT_UNDEFINED + 1),
+    VK_FORMAT_MAX_ENUM = 0x7FFFFFFF
+} VkFormat;
+
+typedef enum VkImageType {
+    VK_IMAGE_TYPE_1D = 0,
+    VK_IMAGE_TYPE_2D = 1,
+    VK_IMAGE_TYPE_3D = 2,
+    VK_IMAGE_TYPE_BEGIN_RANGE = VK_IMAGE_TYPE_1D,
+    VK_IMAGE_TYPE_END_RANGE = VK_IMAGE_TYPE_3D,
+    VK_IMAGE_TYPE_RANGE_SIZE = (VK_IMAGE_TYPE_3D - VK_IMAGE_TYPE_1D + 1),
+    VK_IMAGE_TYPE_MAX_ENUM = 0x7FFFFFFF
+} VkImageType;
+
+typedef enum VkImageTiling {
+    VK_IMAGE_TILING_OPTIMAL = 0,
+    VK_IMAGE_TILING_LINEAR = 1,
+    VK_IMAGE_TILING_BEGIN_RANGE = VK_IMAGE_TILING_OPTIMAL,
+    VK_IMAGE_TILING_END_RANGE = VK_IMAGE_TILING_LINEAR,
+    VK_IMAGE_TILING_RANGE_SIZE = (VK_IMAGE_TILING_LINEAR - VK_IMAGE_TILING_OPTIMAL + 1),
+    VK_IMAGE_TILING_MAX_ENUM = 0x7FFFFFFF
+} VkImageTiling;
+
+typedef enum VkPhysicalDeviceType {
+    VK_PHYSICAL_DEVICE_TYPE_OTHER = 0,
+    VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU = 1,
+    VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU = 2,
+    VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU = 3,
+    VK_PHYSICAL_DEVICE_TYPE_CPU = 4,
+    VK_PHYSICAL_DEVICE_TYPE_BEGIN_RANGE = VK_PHYSICAL_DEVICE_TYPE_OTHER,
+    VK_PHYSICAL_DEVICE_TYPE_END_RANGE = VK_PHYSICAL_DEVICE_TYPE_CPU,
+    VK_PHYSICAL_DEVICE_TYPE_RANGE_SIZE = (VK_PHYSICAL_DEVICE_TYPE_CPU - VK_PHYSICAL_DEVICE_TYPE_OTHER + 1),
+    VK_PHYSICAL_DEVICE_TYPE_MAX_ENUM = 0x7FFFFFFF
+} VkPhysicalDeviceType;
+
+typedef enum VkQueryType {
+    VK_QUERY_TYPE_OCCLUSION = 0,
+    VK_QUERY_TYPE_PIPELINE_STATISTICS = 1,
+    VK_QUERY_TYPE_TIMESTAMP = 2,
+    VK_QUERY_TYPE_BEGIN_RANGE = VK_QUERY_TYPE_OCCLUSION,
+    VK_QUERY_TYPE_END_RANGE = VK_QUERY_TYPE_TIMESTAMP,
+    VK_QUERY_TYPE_RANGE_SIZE = (VK_QUERY_TYPE_TIMESTAMP - VK_QUERY_TYPE_OCCLUSION + 1),
+    VK_QUERY_TYPE_MAX_ENUM = 0x7FFFFFFF
+} VkQueryType;
+
+typedef enum VkSharingMode {
+    VK_SHARING_MODE_EXCLUSIVE = 0,
+    VK_SHARING_MODE_CONCURRENT = 1,
+    VK_SHARING_MODE_BEGIN_RANGE = VK_SHARING_MODE_EXCLUSIVE,
+    VK_SHARING_MODE_END_RANGE = VK_SHARING_MODE_CONCURRENT,
+    VK_SHARING_MODE_RANGE_SIZE = (VK_SHARING_MODE_CONCURRENT - VK_SHARING_MODE_EXCLUSIVE + 1),
+    VK_SHARING_MODE_MAX_ENUM = 0x7FFFFFFF
+} VkSharingMode;
+
+typedef enum VkImageLayout {
+    VK_IMAGE_LAYOUT_UNDEFINED = 0,
+    VK_IMAGE_LAYOUT_GENERAL = 1,
+    VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL = 2,
+    VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL = 3,
+    VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL = 4,
+    VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL = 5,
+    VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL = 6,
+    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL = 7,
+    VK_IMAGE_LAYOUT_PREINITIALIZED = 8,
+    VK_IMAGE_LAYOUT_PRESENT_SRC_KHR = 1000001002,
+    VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR = 1000111000,
+    VK_IMAGE_LAYOUT_BEGIN_RANGE = VK_IMAGE_LAYOUT_UNDEFINED,
+    VK_IMAGE_LAYOUT_END_RANGE = VK_IMAGE_LAYOUT_PREINITIALIZED,
+    VK_IMAGE_LAYOUT_RANGE_SIZE = (VK_IMAGE_LAYOUT_PREINITIALIZED - VK_IMAGE_LAYOUT_UNDEFINED + 1),
+    VK_IMAGE_LAYOUT_MAX_ENUM = 0x7FFFFFFF
+} VkImageLayout;
+
+typedef enum VkImageViewType {
+    VK_IMAGE_VIEW_TYPE_1D = 0,
+    VK_IMAGE_VIEW_TYPE_2D = 1,
+    VK_IMAGE_VIEW_TYPE_3D = 2,
+    VK_IMAGE_VIEW_TYPE_CUBE = 3,
+    VK_IMAGE_VIEW_TYPE_1D_ARRAY = 4,
+    VK_IMAGE_VIEW_TYPE_2D_ARRAY = 5,
+    VK_IMAGE_VIEW_TYPE_CUBE_ARRAY = 6,
+    VK_IMAGE_VIEW_TYPE_BEGIN_RANGE = VK_IMAGE_VIEW_TYPE_1D,
+    VK_IMAGE_VIEW_TYPE_END_RANGE = VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
+    VK_IMAGE_VIEW_TYPE_RANGE_SIZE = (VK_IMAGE_VIEW_TYPE_CUBE_ARRAY - VK_IMAGE_VIEW_TYPE_1D + 1),
+    VK_IMAGE_VIEW_TYPE_MAX_ENUM = 0x7FFFFFFF
+} VkImageViewType;
+
+typedef enum VkComponentSwizzle {
+    VK_COMPONENT_SWIZZLE_IDENTITY = 0,
+    VK_COMPONENT_SWIZZLE_ZERO = 1,
+    VK_COMPONENT_SWIZZLE_ONE = 2,
+    VK_COMPONENT_SWIZZLE_R = 3,
+    VK_COMPONENT_SWIZZLE_G = 4,
+    VK_COMPONENT_SWIZZLE_B = 5,
+    VK_COMPONENT_SWIZZLE_A = 6,
+    VK_COMPONENT_SWIZZLE_BEGIN_RANGE = VK_COMPONENT_SWIZZLE_IDENTITY,
+    VK_COMPONENT_SWIZZLE_END_RANGE = VK_COMPONENT_SWIZZLE_A,
+    VK_COMPONENT_SWIZZLE_RANGE_SIZE = (VK_COMPONENT_SWIZZLE_A - VK_COMPONENT_SWIZZLE_IDENTITY + 1),
+    VK_COMPONENT_SWIZZLE_MAX_ENUM = 0x7FFFFFFF
+} VkComponentSwizzle;
+
+typedef enum VkVertexInputRate {
+    VK_VERTEX_INPUT_RATE_VERTEX = 0,
+    VK_VERTEX_INPUT_RATE_INSTANCE = 1,
+    VK_VERTEX_INPUT_RATE_BEGIN_RANGE = VK_VERTEX_INPUT_RATE_VERTEX,
+    VK_VERTEX_INPUT_RATE_END_RANGE = VK_VERTEX_INPUT_RATE_INSTANCE,
+    VK_VERTEX_INPUT_RATE_RANGE_SIZE = (VK_VERTEX_INPUT_RATE_INSTANCE - VK_VERTEX_INPUT_RATE_VERTEX + 1),
+    VK_VERTEX_INPUT_RATE_MAX_ENUM = 0x7FFFFFFF
+} VkVertexInputRate;
+
+typedef enum VkPrimitiveTopology {
+    VK_PRIMITIVE_TOPOLOGY_POINT_LIST = 0,
+    VK_PRIMITIVE_TOPOLOGY_LINE_LIST = 1,
+    VK_PRIMITIVE_TOPOLOGY_LINE_STRIP = 2,
+    VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST = 3,
+    VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP = 4,
+    VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN = 5,
+    VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY = 6,
+    VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY = 7,
+    VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY = 8,
+    VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY = 9,
+    VK_PRIMITIVE_TOPOLOGY_PATCH_LIST = 10,
+    VK_PRIMITIVE_TOPOLOGY_BEGIN_RANGE = VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
+    VK_PRIMITIVE_TOPOLOGY_END_RANGE = VK_PRIMITIVE_TOPOLOGY_PATCH_LIST,
+    VK_PRIMITIVE_TOPOLOGY_RANGE_SIZE = (VK_PRIMITIVE_TOPOLOGY_PATCH_LIST - VK_PRIMITIVE_TOPOLOGY_POINT_LIST + 1),
+    VK_PRIMITIVE_TOPOLOGY_MAX_ENUM = 0x7FFFFFFF
+} VkPrimitiveTopology;
+
+typedef enum VkPolygonMode {
+    VK_POLYGON_MODE_FILL = 0,
+    VK_POLYGON_MODE_LINE = 1,
+    VK_POLYGON_MODE_POINT = 2,
+    VK_POLYGON_MODE_FILL_RECTANGLE_NV = 1000153000,
+    VK_POLYGON_MODE_BEGIN_RANGE = VK_POLYGON_MODE_FILL,
+    VK_POLYGON_MODE_END_RANGE = VK_POLYGON_MODE_POINT,
+    VK_POLYGON_MODE_RANGE_SIZE = (VK_POLYGON_MODE_POINT - VK_POLYGON_MODE_FILL + 1),
+    VK_POLYGON_MODE_MAX_ENUM = 0x7FFFFFFF
+} VkPolygonMode;
+
+typedef enum VkFrontFace {
+    VK_FRONT_FACE_COUNTER_CLOCKWISE = 0,
+    VK_FRONT_FACE_CLOCKWISE = 1,
+    VK_FRONT_FACE_BEGIN_RANGE = VK_FRONT_FACE_COUNTER_CLOCKWISE,
+    VK_FRONT_FACE_END_RANGE = VK_FRONT_FACE_CLOCKWISE,
+    VK_FRONT_FACE_RANGE_SIZE = (VK_FRONT_FACE_CLOCKWISE - VK_FRONT_FACE_COUNTER_CLOCKWISE + 1),
+    VK_FRONT_FACE_MAX_ENUM = 0x7FFFFFFF
+} VkFrontFace;
+
+typedef enum VkCompareOp {
+    VK_COMPARE_OP_NEVER = 0,
+    VK_COMPARE_OP_LESS = 1,
+    VK_COMPARE_OP_EQUAL = 2,
+    VK_COMPARE_OP_LESS_OR_EQUAL = 3,
+    VK_COMPARE_OP_GREATER = 4,
+    VK_COMPARE_OP_NOT_EQUAL = 5,
+    VK_COMPARE_OP_GREATER_OR_EQUAL = 6,
+    VK_COMPARE_OP_ALWAYS = 7,
+    VK_COMPARE_OP_BEGIN_RANGE = VK_COMPARE_OP_NEVER,
+    VK_COMPARE_OP_END_RANGE = VK_COMPARE_OP_ALWAYS,
+    VK_COMPARE_OP_RANGE_SIZE = (VK_COMPARE_OP_ALWAYS - VK_COMPARE_OP_NEVER + 1),
+    VK_COMPARE_OP_MAX_ENUM = 0x7FFFFFFF
+} VkCompareOp;
+
+typedef enum VkStencilOp {
+    VK_STENCIL_OP_KEEP = 0,
+    VK_STENCIL_OP_ZERO = 1,
+    VK_STENCIL_OP_REPLACE = 2,
+    VK_STENCIL_OP_INCREMENT_AND_CLAMP = 3,
+    VK_STENCIL_OP_DECREMENT_AND_CLAMP = 4,
+    VK_STENCIL_OP_INVERT = 5,
+    VK_STENCIL_OP_INCREMENT_AND_WRAP = 6,
+    VK_STENCIL_OP_DECREMENT_AND_WRAP = 7,
+    VK_STENCIL_OP_BEGIN_RANGE = VK_STENCIL_OP_KEEP,
+    VK_STENCIL_OP_END_RANGE = VK_STENCIL_OP_DECREMENT_AND_WRAP,
+    VK_STENCIL_OP_RANGE_SIZE = (VK_STENCIL_OP_DECREMENT_AND_WRAP - VK_STENCIL_OP_KEEP + 1),
+    VK_STENCIL_OP_MAX_ENUM = 0x7FFFFFFF
+} VkStencilOp;
+
+typedef enum VkLogicOp {
+    VK_LOGIC_OP_CLEAR = 0,
+    VK_LOGIC_OP_AND = 1,
+    VK_LOGIC_OP_AND_REVERSE = 2,
+    VK_LOGIC_OP_COPY = 3,
+    VK_LOGIC_OP_AND_INVERTED = 4,
+    VK_LOGIC_OP_NO_OP = 5,
+    VK_LOGIC_OP_XOR = 6,
+    VK_LOGIC_OP_OR = 7,
+    VK_LOGIC_OP_NOR = 8,
+    VK_LOGIC_OP_EQUIVALENT = 9,
+    VK_LOGIC_OP_INVERT = 10,
+    VK_LOGIC_OP_OR_REVERSE = 11,
+    VK_LOGIC_OP_COPY_INVERTED = 12,
+    VK_LOGIC_OP_OR_INVERTED = 13,
+    VK_LOGIC_OP_NAND = 14,
+    VK_LOGIC_OP_SET = 15,
+    VK_LOGIC_OP_BEGIN_RANGE = VK_LOGIC_OP_CLEAR,
+    VK_LOGIC_OP_END_RANGE = VK_LOGIC_OP_SET,
+    VK_LOGIC_OP_RANGE_SIZE = (VK_LOGIC_OP_SET - VK_LOGIC_OP_CLEAR + 1),
+    VK_LOGIC_OP_MAX_ENUM = 0x7FFFFFFF
+} VkLogicOp;
+
+typedef enum VkBlendFactor {
+    VK_BLEND_FACTOR_ZERO = 0,
+    VK_BLEND_FACTOR_ONE = 1,
+    VK_BLEND_FACTOR_SRC_COLOR = 2,
+    VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR = 3,
+    VK_BLEND_FACTOR_DST_COLOR = 4,
+    VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR = 5,
+    VK_BLEND_FACTOR_SRC_ALPHA = 6,
+    VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA = 7,
+    VK_BLEND_FACTOR_DST_ALPHA = 8,
+    VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA = 9,
+    VK_BLEND_FACTOR_CONSTANT_COLOR = 10,
+    VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR = 11,
+    VK_BLEND_FACTOR_CONSTANT_ALPHA = 12,
+    VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA = 13,
+    VK_BLEND_FACTOR_SRC_ALPHA_SATURATE = 14,
+    VK_BLEND_FACTOR_SRC1_COLOR = 15,
+    VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR = 16,
+    VK_BLEND_FACTOR_SRC1_ALPHA = 17,
+    VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA = 18,
+    VK_BLEND_FACTOR_BEGIN_RANGE = VK_BLEND_FACTOR_ZERO,
+    VK_BLEND_FACTOR_END_RANGE = VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA,
+    VK_BLEND_FACTOR_RANGE_SIZE = (VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA - VK_BLEND_FACTOR_ZERO + 1),
+    VK_BLEND_FACTOR_MAX_ENUM = 0x7FFFFFFF
+} VkBlendFactor;
+
+typedef enum VkBlendOp {
+    VK_BLEND_OP_ADD = 0,
+    VK_BLEND_OP_SUBTRACT = 1,
+    VK_BLEND_OP_REVERSE_SUBTRACT = 2,
+    VK_BLEND_OP_MIN = 3,
+    VK_BLEND_OP_MAX = 4,
+    VK_BLEND_OP_ZERO_EXT = 1000148000,
+    VK_BLEND_OP_SRC_EXT = 1000148001,
+    VK_BLEND_OP_DST_EXT = 1000148002,
+    VK_BLEND_OP_SRC_OVER_EXT = 1000148003,
+    VK_BLEND_OP_DST_OVER_EXT = 1000148004,
+    VK_BLEND_OP_SRC_IN_EXT = 1000148005,
+    VK_BLEND_OP_DST_IN_EXT = 1000148006,
+    VK_BLEND_OP_SRC_OUT_EXT = 1000148007,
+    VK_BLEND_OP_DST_OUT_EXT = 1000148008,
+    VK_BLEND_OP_SRC_ATOP_EXT = 1000148009,
+    VK_BLEND_OP_DST_ATOP_EXT = 1000148010,
+    VK_BLEND_OP_XOR_EXT = 1000148011,
+    VK_BLEND_OP_MULTIPLY_EXT = 1000148012,
+    VK_BLEND_OP_SCREEN_EXT = 1000148013,
+    VK_BLEND_OP_OVERLAY_EXT = 1000148014,
+    VK_BLEND_OP_DARKEN_EXT = 1000148015,
+    VK_BLEND_OP_LIGHTEN_EXT = 1000148016,
+    VK_BLEND_OP_COLORDODGE_EXT = 1000148017,
+    VK_BLEND_OP_COLORBURN_EXT = 1000148018,
+    VK_BLEND_OP_HARDLIGHT_EXT = 1000148019,
+    VK_BLEND_OP_SOFTLIGHT_EXT = 1000148020,
+    VK_BLEND_OP_DIFFERENCE_EXT = 1000148021,
+    VK_BLEND_OP_EXCLUSION_EXT = 1000148022,
+    VK_BLEND_OP_INVERT_EXT = 1000148023,
+    VK_BLEND_OP_INVERT_RGB_EXT = 1000148024,
+    VK_BLEND_OP_LINEARDODGE_EXT = 1000148025,
+    VK_BLEND_OP_LINEARBURN_EXT = 1000148026,
+    VK_BLEND_OP_VIVIDLIGHT_EXT = 1000148027,
+    VK_BLEND_OP_LINEARLIGHT_EXT = 1000148028,
+    VK_BLEND_OP_PINLIGHT_EXT = 1000148029,
+    VK_BLEND_OP_HARDMIX_EXT = 1000148030,
+    VK_BLEND_OP_HSL_HUE_EXT = 1000148031,
+    VK_BLEND_OP_HSL_SATURATION_EXT = 1000148032,
+    VK_BLEND_OP_HSL_COLOR_EXT = 1000148033,
+    VK_BLEND_OP_HSL_LUMINOSITY_EXT = 1000148034,
+    VK_BLEND_OP_PLUS_EXT = 1000148035,
+    VK_BLEND_OP_PLUS_CLAMPED_EXT = 1000148036,
+    VK_BLEND_OP_PLUS_CLAMPED_ALPHA_EXT = 1000148037,
+    VK_BLEND_OP_PLUS_DARKER_EXT = 1000148038,
+    VK_BLEND_OP_MINUS_EXT = 1000148039,
+    VK_BLEND_OP_MINUS_CLAMPED_EXT = 1000148040,
+    VK_BLEND_OP_CONTRAST_EXT = 1000148041,
+    VK_BLEND_OP_INVERT_OVG_EXT = 1000148042,
+    VK_BLEND_OP_RED_EXT = 1000148043,
+    VK_BLEND_OP_GREEN_EXT = 1000148044,
+    VK_BLEND_OP_BLUE_EXT = 1000148045,
+    VK_BLEND_OP_BEGIN_RANGE = VK_BLEND_OP_ADD,
+    VK_BLEND_OP_END_RANGE = VK_BLEND_OP_MAX,
+    VK_BLEND_OP_RANGE_SIZE = (VK_BLEND_OP_MAX - VK_BLEND_OP_ADD + 1),
+    VK_BLEND_OP_MAX_ENUM = 0x7FFFFFFF
+} VkBlendOp;
+
+typedef enum VkDynamicState {
+    VK_DYNAMIC_STATE_VIEWPORT = 0,
+    VK_DYNAMIC_STATE_SCISSOR = 1,
+    VK_DYNAMIC_STATE_LINE_WIDTH = 2,
+    VK_DYNAMIC_STATE_DEPTH_BIAS = 3,
+    VK_DYNAMIC_STATE_BLEND_CONSTANTS = 4,
+    VK_DYNAMIC_STATE_DEPTH_BOUNDS = 5,
+    VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK = 6,
+    VK_DYNAMIC_STATE_STENCIL_WRITE_MASK = 7,
+    VK_DYNAMIC_STATE_STENCIL_REFERENCE = 8,
+    VK_DYNAMIC_STATE_VIEWPORT_W_SCALING_NV = 1000087000,
+    VK_DYNAMIC_STATE_DISCARD_RECTANGLE_EXT = 1000099000,
+    VK_DYNAMIC_STATE_BEGIN_RANGE = VK_DYNAMIC_STATE_VIEWPORT,
+    VK_DYNAMIC_STATE_END_RANGE = VK_DYNAMIC_STATE_STENCIL_REFERENCE,
+    VK_DYNAMIC_STATE_RANGE_SIZE = (VK_DYNAMIC_STATE_STENCIL_REFERENCE - VK_DYNAMIC_STATE_VIEWPORT + 1),
+    VK_DYNAMIC_STATE_MAX_ENUM = 0x7FFFFFFF
+} VkDynamicState;
+
+typedef enum VkFilter {
+    VK_FILTER_NEAREST = 0,
+    VK_FILTER_LINEAR = 1,
+    VK_FILTER_CUBIC_IMG = 1000015000,
+    VK_FILTER_BEGIN_RANGE = VK_FILTER_NEAREST,
+    VK_FILTER_END_RANGE = VK_FILTER_LINEAR,
+    VK_FILTER_RANGE_SIZE = (VK_FILTER_LINEAR - VK_FILTER_NEAREST + 1),
+    VK_FILTER_MAX_ENUM = 0x7FFFFFFF
+} VkFilter;
+
+typedef enum VkSamplerMipmapMode {
+    VK_SAMPLER_MIPMAP_MODE_NEAREST = 0,
+    VK_SAMPLER_MIPMAP_MODE_LINEAR = 1,
+    VK_SAMPLER_MIPMAP_MODE_BEGIN_RANGE = VK_SAMPLER_MIPMAP_MODE_NEAREST,
+    VK_SAMPLER_MIPMAP_MODE_END_RANGE = VK_SAMPLER_MIPMAP_MODE_LINEAR,
+    VK_SAMPLER_MIPMAP_MODE_RANGE_SIZE = (VK_SAMPLER_MIPMAP_MODE_LINEAR - VK_SAMPLER_MIPMAP_MODE_NEAREST + 1),
+    VK_SAMPLER_MIPMAP_MODE_MAX_ENUM = 0x7FFFFFFF
+} VkSamplerMipmapMode;
+
+typedef enum VkSamplerAddressMode {
+    VK_SAMPLER_ADDRESS_MODE_REPEAT = 0,
+    VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT = 1,
+    VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE = 2,
+    VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER = 3,
+    VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE = 4,
+    VK_SAMPLER_ADDRESS_MODE_BEGIN_RANGE = VK_SAMPLER_ADDRESS_MODE_REPEAT,
+    VK_SAMPLER_ADDRESS_MODE_END_RANGE = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
+    VK_SAMPLER_ADDRESS_MODE_RANGE_SIZE = (VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER - VK_SAMPLER_ADDRESS_MODE_REPEAT + 1),
+    VK_SAMPLER_ADDRESS_MODE_MAX_ENUM = 0x7FFFFFFF
+} VkSamplerAddressMode;
+
+typedef enum VkBorderColor {
+    VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK = 0,
+    VK_BORDER_COLOR_INT_TRANSPARENT_BLACK = 1,
+    VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK = 2,
+    VK_BORDER_COLOR_INT_OPAQUE_BLACK = 3,
+    VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE = 4,
+    VK_BORDER_COLOR_INT_OPAQUE_WHITE = 5,
+    VK_BORDER_COLOR_BEGIN_RANGE = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK,
+    VK_BORDER_COLOR_END_RANGE = VK_BORDER_COLOR_INT_OPAQUE_WHITE,
+    VK_BORDER_COLOR_RANGE_SIZE = (VK_BORDER_COLOR_INT_OPAQUE_WHITE - VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK + 1),
+    VK_BORDER_COLOR_MAX_ENUM = 0x7FFFFFFF
+} VkBorderColor;
+
+typedef enum VkDescriptorType {
+    VK_DESCRIPTOR_TYPE_SAMPLER = 0,
+    VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER = 1,
+    VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE = 2,
+    VK_DESCRIPTOR_TYPE_STORAGE_IMAGE = 3,
+    VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER = 4,
+    VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER = 5,
+    VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER = 6,
+    VK_DESCRIPTOR_TYPE_STORAGE_BUFFER = 7,
+    VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC = 8,
+    VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC = 9,
+    VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT = 10,
+    VK_DESCRIPTOR_TYPE_BEGIN_RANGE = VK_DESCRIPTOR_TYPE_SAMPLER,
+    VK_DESCRIPTOR_TYPE_END_RANGE = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT,
+    VK_DESCRIPTOR_TYPE_RANGE_SIZE = (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT - VK_DESCRIPTOR_TYPE_SAMPLER + 1),
+    VK_DESCRIPTOR_TYPE_MAX_ENUM = 0x7FFFFFFF
+} VkDescriptorType;
+
+typedef enum VkAttachmentLoadOp {
+    VK_ATTACHMENT_LOAD_OP_LOAD = 0,
+    VK_ATTACHMENT_LOAD_OP_CLEAR = 1,
+    VK_ATTACHMENT_LOAD_OP_DONT_CARE = 2,
+    VK_ATTACHMENT_LOAD_OP_BEGIN_RANGE = VK_ATTACHMENT_LOAD_OP_LOAD,
+    VK_ATTACHMENT_LOAD_OP_END_RANGE = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
+    VK_ATTACHMENT_LOAD_OP_RANGE_SIZE = (VK_ATTACHMENT_LOAD_OP_DONT_CARE - VK_ATTACHMENT_LOAD_OP_LOAD + 1),
+    VK_ATTACHMENT_LOAD_OP_MAX_ENUM = 0x7FFFFFFF
+} VkAttachmentLoadOp;
+
+typedef enum VkAttachmentStoreOp {
+    VK_ATTACHMENT_STORE_OP_STORE = 0,
+    VK_ATTACHMENT_STORE_OP_DONT_CARE = 1,
+    VK_ATTACHMENT_STORE_OP_BEGIN_RANGE = VK_ATTACHMENT_STORE_OP_STORE,
+    VK_ATTACHMENT_STORE_OP_END_RANGE = VK_ATTACHMENT_STORE_OP_DONT_CARE,
+    VK_ATTACHMENT_STORE_OP_RANGE_SIZE = (VK_ATTACHMENT_STORE_OP_DONT_CARE - VK_ATTACHMENT_STORE_OP_STORE + 1),
+    VK_ATTACHMENT_STORE_OP_MAX_ENUM = 0x7FFFFFFF
+} VkAttachmentStoreOp;
+
+typedef enum VkPipelineBindPoint {
+    VK_PIPELINE_BIND_POINT_GRAPHICS = 0,
+    VK_PIPELINE_BIND_POINT_COMPUTE = 1,
+    VK_PIPELINE_BIND_POINT_BEGIN_RANGE = VK_PIPELINE_BIND_POINT_GRAPHICS,
+    VK_PIPELINE_BIND_POINT_END_RANGE = VK_PIPELINE_BIND_POINT_COMPUTE,
+    VK_PIPELINE_BIND_POINT_RANGE_SIZE = (VK_PIPELINE_BIND_POINT_COMPUTE - VK_PIPELINE_BIND_POINT_GRAPHICS + 1),
+    VK_PIPELINE_BIND_POINT_MAX_ENUM = 0x7FFFFFFF
+} VkPipelineBindPoint;
+
+typedef enum VkCommandBufferLevel {
+    VK_COMMAND_BUFFER_LEVEL_PRIMARY = 0,
+    VK_COMMAND_BUFFER_LEVEL_SECONDARY = 1,
+    VK_COMMAND_BUFFER_LEVEL_BEGIN_RANGE = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
+    VK_COMMAND_BUFFER_LEVEL_END_RANGE = VK_COMMAND_BUFFER_LEVEL_SECONDARY,
+    VK_COMMAND_BUFFER_LEVEL_RANGE_SIZE = (VK_COMMAND_BUFFER_LEVEL_SECONDARY - VK_COMMAND_BUFFER_LEVEL_PRIMARY + 1),
+    VK_COMMAND_BUFFER_LEVEL_MAX_ENUM = 0x7FFFFFFF
+} VkCommandBufferLevel;
+
+typedef enum VkIndexType {
+    VK_INDEX_TYPE_UINT16 = 0,
+    VK_INDEX_TYPE_UINT32 = 1,
+    VK_INDEX_TYPE_BEGIN_RANGE = VK_INDEX_TYPE_UINT16,
+    VK_INDEX_TYPE_END_RANGE = VK_INDEX_TYPE_UINT32,
+    VK_INDEX_TYPE_RANGE_SIZE = (VK_INDEX_TYPE_UINT32 - VK_INDEX_TYPE_UINT16 + 1),
+    VK_INDEX_TYPE_MAX_ENUM = 0x7FFFFFFF
+} VkIndexType;
+
+typedef enum VkSubpassContents {
+    VK_SUBPASS_CONTENTS_INLINE = 0,
+    VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS = 1,
+    VK_SUBPASS_CONTENTS_BEGIN_RANGE = VK_SUBPASS_CONTENTS_INLINE,
+    VK_SUBPASS_CONTENTS_END_RANGE = VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS,
+    VK_SUBPASS_CONTENTS_RANGE_SIZE = (VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS - VK_SUBPASS_CONTENTS_INLINE + 1),
+    VK_SUBPASS_CONTENTS_MAX_ENUM = 0x7FFFFFFF
+} VkSubpassContents;
+
+typedef enum VkObjectType {
+    VK_OBJECT_TYPE_UNKNOWN = 0,
+    VK_OBJECT_TYPE_INSTANCE = 1,
+    VK_OBJECT_TYPE_PHYSICAL_DEVICE = 2,
+    VK_OBJECT_TYPE_DEVICE = 3,
+    VK_OBJECT_TYPE_QUEUE = 4,
+    VK_OBJECT_TYPE_SEMAPHORE = 5,
+    VK_OBJECT_TYPE_COMMAND_BUFFER = 6,
+    VK_OBJECT_TYPE_FENCE = 7,
+    VK_OBJECT_TYPE_DEVICE_MEMORY = 8,
+    VK_OBJECT_TYPE_BUFFER = 9,
+    VK_OBJECT_TYPE_IMAGE = 10,
+    VK_OBJECT_TYPE_EVENT = 11,
+    VK_OBJECT_TYPE_QUERY_POOL = 12,
+    VK_OBJECT_TYPE_BUFFER_VIEW = 13,
+    VK_OBJECT_TYPE_IMAGE_VIEW = 14,
+    VK_OBJECT_TYPE_SHADER_MODULE = 15,
+    VK_OBJECT_TYPE_PIPELINE_CACHE = 16,
+    VK_OBJECT_TYPE_PIPELINE_LAYOUT = 17,
+    VK_OBJECT_TYPE_RENDER_PASS = 18,
+    VK_OBJECT_TYPE_PIPELINE = 19,
+    VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT = 20,
+    VK_OBJECT_TYPE_SAMPLER = 21,
+    VK_OBJECT_TYPE_DESCRIPTOR_POOL = 22,
+    VK_OBJECT_TYPE_DESCRIPTOR_SET = 23,
+    VK_OBJECT_TYPE_FRAMEBUFFER = 24,
+    VK_OBJECT_TYPE_COMMAND_POOL = 25,
+    VK_OBJECT_TYPE_SURFACE_KHR = 1000000000,
+    VK_OBJECT_TYPE_SWAPCHAIN_KHR = 1000001000,
+    VK_OBJECT_TYPE_DISPLAY_KHR = 1000002000,
+    VK_OBJECT_TYPE_DISPLAY_MODE_KHR = 1000002001,
+    VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT = 1000011000,
+    VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR = 1000085000,
+    VK_OBJECT_TYPE_OBJECT_TABLE_NVX = 1000086000,
+    VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX = 1000086001,
+    VK_OBJECT_TYPE_BEGIN_RANGE = VK_OBJECT_TYPE_UNKNOWN,
+    VK_OBJECT_TYPE_END_RANGE = VK_OBJECT_TYPE_COMMAND_POOL,
+    VK_OBJECT_TYPE_RANGE_SIZE = (VK_OBJECT_TYPE_COMMAND_POOL - VK_OBJECT_TYPE_UNKNOWN + 1),
+    VK_OBJECT_TYPE_MAX_ENUM = 0x7FFFFFFF
+} VkObjectType;
+
+typedef VkFlags VkInstanceCreateFlags;
+
+typedef enum VkFormatFeatureFlagBits {
+    VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT = 0x00000001,
+    VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT = 0x00000002,
+    VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT = 0x00000004,
+    VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT = 0x00000008,
+    VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT = 0x00000010,
+    VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT = 0x00000020,
+    VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT = 0x00000040,
+    VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT = 0x00000080,
+    VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT = 0x00000100,
+    VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT = 0x00000200,
+    VK_FORMAT_FEATURE_BLIT_SRC_BIT = 0x00000400,
+    VK_FORMAT_FEATURE_BLIT_DST_BIT = 0x00000800,
+    VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT = 0x00001000,
+    VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG = 0x00002000,
+    VK_FORMAT_FEATURE_TRANSFER_SRC_BIT_KHR = 0x00004000,
+    VK_FORMAT_FEATURE_TRANSFER_DST_BIT_KHR = 0x00008000,
+    VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT_EXT = 0x00010000,
+    VK_FORMAT_FEATURE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkFormatFeatureFlagBits;
+typedef VkFlags VkFormatFeatureFlags;
+
+typedef enum VkImageUsageFlagBits {
+    VK_IMAGE_USAGE_TRANSFER_SRC_BIT = 0x00000001,
+    VK_IMAGE_USAGE_TRANSFER_DST_BIT = 0x00000002,
+    VK_IMAGE_USAGE_SAMPLED_BIT = 0x00000004,
+    VK_IMAGE_USAGE_STORAGE_BIT = 0x00000008,
+    VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT = 0x00000010,
+    VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT = 0x00000020,
+    VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT = 0x00000040,
+    VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT = 0x00000080,
+    VK_IMAGE_USAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkImageUsageFlagBits;
+typedef VkFlags VkImageUsageFlags;
+
+typedef enum VkImageCreateFlagBits {
+    VK_IMAGE_CREATE_SPARSE_BINDING_BIT = 0x00000001,
+    VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002,
+    VK_IMAGE_CREATE_SPARSE_ALIASED_BIT = 0x00000004,
+    VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT = 0x00000008,
+    VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT = 0x00000010,
+    VK_IMAGE_CREATE_BIND_SFR_BIT_KHX = 0x00000040,
+    VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR = 0x00000020,
+    VK_IMAGE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkImageCreateFlagBits;
+typedef VkFlags VkImageCreateFlags;
+
+typedef enum VkSampleCountFlagBits {
+    VK_SAMPLE_COUNT_1_BIT = 0x00000001,
+    VK_SAMPLE_COUNT_2_BIT = 0x00000002,
+    VK_SAMPLE_COUNT_4_BIT = 0x00000004,
+    VK_SAMPLE_COUNT_8_BIT = 0x00000008,
+    VK_SAMPLE_COUNT_16_BIT = 0x00000010,
+    VK_SAMPLE_COUNT_32_BIT = 0x00000020,
+    VK_SAMPLE_COUNT_64_BIT = 0x00000040,
+    VK_SAMPLE_COUNT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkSampleCountFlagBits;
+typedef VkFlags VkSampleCountFlags;
+
+typedef enum VkQueueFlagBits {
+    VK_QUEUE_GRAPHICS_BIT = 0x00000001,
+    VK_QUEUE_COMPUTE_BIT = 0x00000002,
+    VK_QUEUE_TRANSFER_BIT = 0x00000004,
+    VK_QUEUE_SPARSE_BINDING_BIT = 0x00000008,
+    VK_QUEUE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkQueueFlagBits;
+typedef VkFlags VkQueueFlags;
+
+typedef enum VkMemoryPropertyFlagBits {
+    VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT = 0x00000001,
+    VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT = 0x00000002,
+    VK_MEMORY_PROPERTY_HOST_COHERENT_BIT = 0x00000004,
+    VK_MEMORY_PROPERTY_HOST_CACHED_BIT = 0x00000008,
+    VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT = 0x00000010,
+    VK_MEMORY_PROPERTY_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkMemoryPropertyFlagBits;
+typedef VkFlags VkMemoryPropertyFlags;
+
+typedef enum VkMemoryHeapFlagBits {
+    VK_MEMORY_HEAP_DEVICE_LOCAL_BIT = 0x00000001,
+    VK_MEMORY_HEAP_MULTI_INSTANCE_BIT_KHX = 0x00000002,
+    VK_MEMORY_HEAP_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkMemoryHeapFlagBits;
+typedef VkFlags VkMemoryHeapFlags;
+typedef VkFlags VkDeviceCreateFlags;
+typedef VkFlags VkDeviceQueueCreateFlags;
+
+typedef enum VkPipelineStageFlagBits {
+    VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT = 0x00000001,
+    VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT = 0x00000002,
+    VK_PIPELINE_STAGE_VERTEX_INPUT_BIT = 0x00000004,
+    VK_PIPELINE_STAGE_VERTEX_SHADER_BIT = 0x00000008,
+    VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT = 0x00000010,
+    VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT = 0x00000020,
+    VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT = 0x00000040,
+    VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT = 0x00000080,
+    VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT = 0x00000100,
+    VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT = 0x00000200,
+    VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT = 0x00000400,
+    VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT = 0x00000800,
+    VK_PIPELINE_STAGE_TRANSFER_BIT = 0x00001000,
+    VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT = 0x00002000,
+    VK_PIPELINE_STAGE_HOST_BIT = 0x00004000,
+    VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT = 0x00008000,
+    VK_PIPELINE_STAGE_ALL_COMMANDS_BIT = 0x00010000,
+    VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX = 0x00020000,
+    VK_PIPELINE_STAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkPipelineStageFlagBits;
+typedef VkFlags VkPipelineStageFlags;
+typedef VkFlags VkMemoryMapFlags;
+
+typedef enum VkImageAspectFlagBits {
+    VK_IMAGE_ASPECT_COLOR_BIT = 0x00000001,
+    VK_IMAGE_ASPECT_DEPTH_BIT = 0x00000002,
+    VK_IMAGE_ASPECT_STENCIL_BIT = 0x00000004,
+    VK_IMAGE_ASPECT_METADATA_BIT = 0x00000008,
+    VK_IMAGE_ASPECT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkImageAspectFlagBits;
+typedef VkFlags VkImageAspectFlags;
+
+typedef enum VkSparseImageFormatFlagBits {
+    VK_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT = 0x00000001,
+    VK_SPARSE_IMAGE_FORMAT_ALIGNED_MIP_SIZE_BIT = 0x00000002,
+    VK_SPARSE_IMAGE_FORMAT_NONSTANDARD_BLOCK_SIZE_BIT = 0x00000004,
+    VK_SPARSE_IMAGE_FORMAT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkSparseImageFormatFlagBits;
+typedef VkFlags VkSparseImageFormatFlags;
+
+typedef enum VkSparseMemoryBindFlagBits {
+    VK_SPARSE_MEMORY_BIND_METADATA_BIT = 0x00000001,
+    VK_SPARSE_MEMORY_BIND_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkSparseMemoryBindFlagBits;
+typedef VkFlags VkSparseMemoryBindFlags;
+
+typedef enum VkFenceCreateFlagBits {
+    VK_FENCE_CREATE_SIGNALED_BIT = 0x00000001,
+    VK_FENCE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkFenceCreateFlagBits;
+typedef VkFlags VkFenceCreateFlags;
+typedef VkFlags VkSemaphoreCreateFlags;
+typedef VkFlags VkEventCreateFlags;
+typedef VkFlags VkQueryPoolCreateFlags;
+
+typedef enum VkQueryPipelineStatisticFlagBits {
+    VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT = 0x00000001,
+    VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT = 0x00000002,
+    VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT = 0x00000004,
+    VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT = 0x00000008,
+    VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT = 0x00000010,
+    VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT = 0x00000020,
+    VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT = 0x00000040,
+    VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT = 0x00000080,
+    VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT = 0x00000100,
+    VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT = 0x00000200,
+    VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT = 0x00000400,
+    VK_QUERY_PIPELINE_STATISTIC_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkQueryPipelineStatisticFlagBits;
+typedef VkFlags VkQueryPipelineStatisticFlags;
+
+typedef enum VkQueryResultFlagBits {
+    VK_QUERY_RESULT_64_BIT = 0x00000001,
+    VK_QUERY_RESULT_WAIT_BIT = 0x00000002,
+    VK_QUERY_RESULT_WITH_AVAILABILITY_BIT = 0x00000004,
+    VK_QUERY_RESULT_PARTIAL_BIT = 0x00000008,
+    VK_QUERY_RESULT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkQueryResultFlagBits;
+typedef VkFlags VkQueryResultFlags;
+
+typedef enum VkBufferCreateFlagBits {
+    VK_BUFFER_CREATE_SPARSE_BINDING_BIT = 0x00000001,
+    VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002,
+    VK_BUFFER_CREATE_SPARSE_ALIASED_BIT = 0x00000004,
+    VK_BUFFER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkBufferCreateFlagBits;
+typedef VkFlags VkBufferCreateFlags;
+
+typedef enum VkBufferUsageFlagBits {
+    VK_BUFFER_USAGE_TRANSFER_SRC_BIT = 0x00000001,
+    VK_BUFFER_USAGE_TRANSFER_DST_BIT = 0x00000002,
+    VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT = 0x00000004,
+    VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT = 0x00000008,
+    VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT = 0x00000010,
+    VK_BUFFER_USAGE_STORAGE_BUFFER_BIT = 0x00000020,
+    VK_BUFFER_USAGE_INDEX_BUFFER_BIT = 0x00000040,
+    VK_BUFFER_USAGE_VERTEX_BUFFER_BIT = 0x00000080,
+    VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT = 0x00000100,
+    VK_BUFFER_USAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkBufferUsageFlagBits;
+typedef VkFlags VkBufferUsageFlags;
+typedef VkFlags VkBufferViewCreateFlags;
+typedef VkFlags VkImageViewCreateFlags;
+typedef VkFlags VkShaderModuleCreateFlags;
+typedef VkFlags VkPipelineCacheCreateFlags;
+
+typedef enum VkPipelineCreateFlagBits {
+    VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT = 0x00000001,
+    VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT = 0x00000002,
+    VK_PIPELINE_CREATE_DERIVATIVE_BIT = 0x00000004,
+    VK_PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT_KHX = 0x00000008,
+    VK_PIPELINE_CREATE_DISPATCH_BASE_KHX = 0x00000010,
+    VK_PIPELINE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkPipelineCreateFlagBits;
+typedef VkFlags VkPipelineCreateFlags;
+typedef VkFlags VkPipelineShaderStageCreateFlags;
+
+typedef enum VkShaderStageFlagBits {
+    VK_SHADER_STAGE_VERTEX_BIT = 0x00000001,
+    VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT = 0x00000002,
+    VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT = 0x00000004,
+    VK_SHADER_STAGE_GEOMETRY_BIT = 0x00000008,
+    VK_SHADER_STAGE_FRAGMENT_BIT = 0x00000010,
+    VK_SHADER_STAGE_COMPUTE_BIT = 0x00000020,
+    VK_SHADER_STAGE_ALL_GRAPHICS = 0x0000001F,
+    VK_SHADER_STAGE_ALL = 0x7FFFFFFF,
+    VK_SHADER_STAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkShaderStageFlagBits;
+typedef VkFlags VkPipelineVertexInputStateCreateFlags;
+typedef VkFlags VkPipelineInputAssemblyStateCreateFlags;
+typedef VkFlags VkPipelineTessellationStateCreateFlags;
+typedef VkFlags VkPipelineViewportStateCreateFlags;
+typedef VkFlags VkPipelineRasterizationStateCreateFlags;
+
+typedef enum VkCullModeFlagBits {
+    VK_CULL_MODE_NONE = 0,
+    VK_CULL_MODE_FRONT_BIT = 0x00000001,
+    VK_CULL_MODE_BACK_BIT = 0x00000002,
+    VK_CULL_MODE_FRONT_AND_BACK = 0x00000003,
+    VK_CULL_MODE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkCullModeFlagBits;
+typedef VkFlags VkCullModeFlags;
+typedef VkFlags VkPipelineMultisampleStateCreateFlags;
+typedef VkFlags VkPipelineDepthStencilStateCreateFlags;
+typedef VkFlags VkPipelineColorBlendStateCreateFlags;
+
+typedef enum VkColorComponentFlagBits {
+    VK_COLOR_COMPONENT_R_BIT = 0x00000001,
+    VK_COLOR_COMPONENT_G_BIT = 0x00000002,
+    VK_COLOR_COMPONENT_B_BIT = 0x00000004,
+    VK_COLOR_COMPONENT_A_BIT = 0x00000008,
+    VK_COLOR_COMPONENT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkColorComponentFlagBits;
+typedef VkFlags VkColorComponentFlags;
+typedef VkFlags VkPipelineDynamicStateCreateFlags;
+typedef VkFlags VkPipelineLayoutCreateFlags;
+typedef VkFlags VkShaderStageFlags;
+typedef VkFlags VkSamplerCreateFlags;
+
+typedef enum VkDescriptorSetLayoutCreateFlagBits {
+    VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR = 0x00000001,
+    VK_DESCRIPTOR_SET_LAYOUT_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkDescriptorSetLayoutCreateFlagBits;
+typedef VkFlags VkDescriptorSetLayoutCreateFlags;
+
+typedef enum VkDescriptorPoolCreateFlagBits {
+    VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT = 0x00000001,
+    VK_DESCRIPTOR_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkDescriptorPoolCreateFlagBits;
+typedef VkFlags VkDescriptorPoolCreateFlags;
+typedef VkFlags VkDescriptorPoolResetFlags;
+typedef VkFlags VkFramebufferCreateFlags;
+typedef VkFlags VkRenderPassCreateFlags;
+
+typedef enum VkAttachmentDescriptionFlagBits {
+    VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT = 0x00000001,
+    VK_ATTACHMENT_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkAttachmentDescriptionFlagBits;
+typedef VkFlags VkAttachmentDescriptionFlags;
+
+typedef enum VkSubpassDescriptionFlagBits {
+    VK_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX = 0x00000001,
+    VK_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX = 0x00000002,
+    VK_SUBPASS_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkSubpassDescriptionFlagBits;
+typedef VkFlags VkSubpassDescriptionFlags;
+
+typedef enum VkAccessFlagBits {
+    VK_ACCESS_INDIRECT_COMMAND_READ_BIT = 0x00000001,
+    VK_ACCESS_INDEX_READ_BIT = 0x00000002,
+    VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT = 0x00000004,
+    VK_ACCESS_UNIFORM_READ_BIT = 0x00000008,
+    VK_ACCESS_INPUT_ATTACHMENT_READ_BIT = 0x00000010,
+    VK_ACCESS_SHADER_READ_BIT = 0x00000020,
+    VK_ACCESS_SHADER_WRITE_BIT = 0x00000040,
+    VK_ACCESS_COLOR_ATTACHMENT_READ_BIT = 0x00000080,
+    VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT = 0x00000100,
+    VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT = 0x00000200,
+    VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT = 0x00000400,
+    VK_ACCESS_TRANSFER_READ_BIT = 0x00000800,
+    VK_ACCESS_TRANSFER_WRITE_BIT = 0x00001000,
+    VK_ACCESS_HOST_READ_BIT = 0x00002000,
+    VK_ACCESS_HOST_WRITE_BIT = 0x00004000,
+    VK_ACCESS_MEMORY_READ_BIT = 0x00008000,
+    VK_ACCESS_MEMORY_WRITE_BIT = 0x00010000,
+    VK_ACCESS_COMMAND_PROCESS_READ_BIT_NVX = 0x00020000,
+    VK_ACCESS_COMMAND_PROCESS_WRITE_BIT_NVX = 0x00040000,
+    VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT = 0x00080000,
+    VK_ACCESS_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkAccessFlagBits;
+typedef VkFlags VkAccessFlags;
+
+typedef enum VkDependencyFlagBits {
+    VK_DEPENDENCY_BY_REGION_BIT = 0x00000001,
+    VK_DEPENDENCY_VIEW_LOCAL_BIT_KHX = 0x00000002,
+    VK_DEPENDENCY_DEVICE_GROUP_BIT_KHX = 0x00000004,
+    VK_DEPENDENCY_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkDependencyFlagBits;
+typedef VkFlags VkDependencyFlags;
+
+typedef enum VkCommandPoolCreateFlagBits {
+    VK_COMMAND_POOL_CREATE_TRANSIENT_BIT = 0x00000001,
+    VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT = 0x00000002,
+    VK_COMMAND_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkCommandPoolCreateFlagBits;
+typedef VkFlags VkCommandPoolCreateFlags;
+
+typedef enum VkCommandPoolResetFlagBits {
+    VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT = 0x00000001,
+    VK_COMMAND_POOL_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkCommandPoolResetFlagBits;
+typedef VkFlags VkCommandPoolResetFlags;
+
+typedef enum VkCommandBufferUsageFlagBits {
+    VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT = 0x00000001,
+    VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT = 0x00000002,
+    VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT = 0x00000004,
+    VK_COMMAND_BUFFER_USAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkCommandBufferUsageFlagBits;
+typedef VkFlags VkCommandBufferUsageFlags;
+
+typedef enum VkQueryControlFlagBits {
+    VK_QUERY_CONTROL_PRECISE_BIT = 0x00000001,
+    VK_QUERY_CONTROL_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkQueryControlFlagBits;
+typedef VkFlags VkQueryControlFlags;
+
+typedef enum VkCommandBufferResetFlagBits {
+    VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT = 0x00000001,
+    VK_COMMAND_BUFFER_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkCommandBufferResetFlagBits;
+typedef VkFlags VkCommandBufferResetFlags;
+
+typedef enum VkStencilFaceFlagBits {
+    VK_STENCIL_FACE_FRONT_BIT = 0x00000001,
+    VK_STENCIL_FACE_BACK_BIT = 0x00000002,
+    VK_STENCIL_FRONT_AND_BACK = 0x00000003,
+    VK_STENCIL_FACE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkStencilFaceFlagBits;
+typedef VkFlags VkStencilFaceFlags;
+
+typedef struct VkApplicationInfo {
+    VkStructureType    sType;
+    const void*        pNext;
+    const char*        pApplicationName;
+    uint32_t           applicationVersion;
+    const char*        pEngineName;
+    uint32_t           engineVersion;
+    uint32_t           apiVersion;
+} VkApplicationInfo;
+
+typedef struct VkInstanceCreateInfo {
+    VkStructureType             sType;
+    const void*                 pNext;
+    VkInstanceCreateFlags       flags;
+    const VkApplicationInfo*    pApplicationInfo;
+    uint32_t                    enabledLayerCount;
+    const char* const*          ppEnabledLayerNames;
+    uint32_t                    enabledExtensionCount;
+    const char* const*          ppEnabledExtensionNames;
+} VkInstanceCreateInfo;
+
+typedef void* (VKAPI_PTR *PFN_vkAllocationFunction)(
+    void*                                       pUserData,
+    size_t                                      size,
+    size_t                                      alignment,
+    VkSystemAllocationScope                     allocationScope);
+
+typedef void* (VKAPI_PTR *PFN_vkReallocationFunction)(
+    void*                                       pUserData,
+    void*                                       pOriginal,
+    size_t                                      size,
+    size_t                                      alignment,
+    VkSystemAllocationScope                     allocationScope);
+
+typedef void (VKAPI_PTR *PFN_vkFreeFunction)(
+    void*                                       pUserData,
+    void*                                       pMemory);
+
+typedef void (VKAPI_PTR *PFN_vkInternalAllocationNotification)(
+    void*                                       pUserData,
+    size_t                                      size,
+    VkInternalAllocationType                    allocationType,
+    VkSystemAllocationScope                     allocationScope);
+
+typedef void (VKAPI_PTR *PFN_vkInternalFreeNotification)(
+    void*                                       pUserData,
+    size_t                                      size,
+    VkInternalAllocationType                    allocationType,
+    VkSystemAllocationScope                     allocationScope);
+
+typedef struct VkAllocationCallbacks {
+    void*                                   pUserData;
+    PFN_vkAllocationFunction                pfnAllocation;
+    PFN_vkReallocationFunction              pfnReallocation;
+    PFN_vkFreeFunction                      pfnFree;
+    PFN_vkInternalAllocationNotification    pfnInternalAllocation;
+    PFN_vkInternalFreeNotification          pfnInternalFree;
+} VkAllocationCallbacks;
+
+typedef struct VkPhysicalDeviceFeatures {
+    VkBool32    robustBufferAccess;
+    VkBool32    fullDrawIndexUint32;
+    VkBool32    imageCubeArray;
+    VkBool32    independentBlend;
+    VkBool32    geometryShader;
+    VkBool32    tessellationShader;
+    VkBool32    sampleRateShading;
+    VkBool32    dualSrcBlend;
+    VkBool32    logicOp;
+    VkBool32    multiDrawIndirect;
+    VkBool32    drawIndirectFirstInstance;
+    VkBool32    depthClamp;
+    VkBool32    depthBiasClamp;
+    VkBool32    fillModeNonSolid;
+    VkBool32    depthBounds;
+    VkBool32    wideLines;
+    VkBool32    largePoints;
+    VkBool32    alphaToOne;
+    VkBool32    multiViewport;
+    VkBool32    samplerAnisotropy;
+    VkBool32    textureCompressionETC2;
+    VkBool32    textureCompressionASTC_LDR;
+    VkBool32    textureCompressionBC;
+    VkBool32    occlusionQueryPrecise;
+    VkBool32    pipelineStatisticsQuery;
+    VkBool32    vertexPipelineStoresAndAtomics;
+    VkBool32    fragmentStoresAndAtomics;
+    VkBool32    shaderTessellationAndGeometryPointSize;
+    VkBool32    shaderImageGatherExtended;
+    VkBool32    shaderStorageImageExtendedFormats;
+    VkBool32    shaderStorageImageMultisample;
+    VkBool32    shaderStorageImageReadWithoutFormat;
+    VkBool32    shaderStorageImageWriteWithoutFormat;
+    VkBool32    shaderUniformBufferArrayDynamicIndexing;
+    VkBool32    shaderSampledImageArrayDynamicIndexing;
+    VkBool32    shaderStorageBufferArrayDynamicIndexing;
+    VkBool32    shaderStorageImageArrayDynamicIndexing;
+    VkBool32    shaderClipDistance;
+    VkBool32    shaderCullDistance;
+    VkBool32    shaderFloat64;
+    VkBool32    shaderInt64;
+    VkBool32    shaderInt16;
+    VkBool32    shaderResourceResidency;
+    VkBool32    shaderResourceMinLod;
+    VkBool32    sparseBinding;
+    VkBool32    sparseResidencyBuffer;
+    VkBool32    sparseResidencyImage2D;
+    VkBool32    sparseResidencyImage3D;
+    VkBool32    sparseResidency2Samples;
+    VkBool32    sparseResidency4Samples;
+    VkBool32    sparseResidency8Samples;
+    VkBool32    sparseResidency16Samples;
+    VkBool32    sparseResidencyAliased;
+    VkBool32    variableMultisampleRate;
+    VkBool32    inheritedQueries;
+} VkPhysicalDeviceFeatures;
+
+typedef struct VkFormatProperties {
+    VkFormatFeatureFlags    linearTilingFeatures;
+    VkFormatFeatureFlags    optimalTilingFeatures;
+    VkFormatFeatureFlags    bufferFeatures;
+} VkFormatProperties;
+
+typedef struct VkExtent3D {
+    uint32_t    width;
+    uint32_t    height;
+    uint32_t    depth;
+} VkExtent3D;
+
+typedef struct VkImageFormatProperties {
+    VkExtent3D            maxExtent;
+    uint32_t              maxMipLevels;
+    uint32_t              maxArrayLayers;
+    VkSampleCountFlags    sampleCounts;
+    VkDeviceSize          maxResourceSize;
+} VkImageFormatProperties;
+
+typedef struct VkPhysicalDeviceLimits {
+    uint32_t              maxImageDimension1D;
+    uint32_t              maxImageDimension2D;
+    uint32_t              maxImageDimension3D;
+    uint32_t              maxImageDimensionCube;
+    uint32_t              maxImageArrayLayers;
+    uint32_t              maxTexelBufferElements;
+    uint32_t              maxUniformBufferRange;
+    uint32_t              maxStorageBufferRange;
+    uint32_t              maxPushConstantsSize;
+    uint32_t              maxMemoryAllocationCount;
+    uint32_t              maxSamplerAllocationCount;
+    VkDeviceSize          bufferImageGranularity;
+    VkDeviceSize          sparseAddressSpaceSize;
+    uint32_t              maxBoundDescriptorSets;
+    uint32_t              maxPerStageDescriptorSamplers;
+    uint32_t              maxPerStageDescriptorUniformBuffers;
+    uint32_t              maxPerStageDescriptorStorageBuffers;
+    uint32_t              maxPerStageDescriptorSampledImages;
+    uint32_t              maxPerStageDescriptorStorageImages;
+    uint32_t              maxPerStageDescriptorInputAttachments;
+    uint32_t              maxPerStageResources;
+    uint32_t              maxDescriptorSetSamplers;
+    uint32_t              maxDescriptorSetUniformBuffers;
+    uint32_t              maxDescriptorSetUniformBuffersDynamic;
+    uint32_t              maxDescriptorSetStorageBuffers;
+    uint32_t              maxDescriptorSetStorageBuffersDynamic;
+    uint32_t              maxDescriptorSetSampledImages;
+    uint32_t              maxDescriptorSetStorageImages;
+    uint32_t              maxDescriptorSetInputAttachments;
+    uint32_t              maxVertexInputAttributes;
+    uint32_t              maxVertexInputBindings;
+    uint32_t              maxVertexInputAttributeOffset;
+    uint32_t              maxVertexInputBindingStride;
+    uint32_t              maxVertexOutputComponents;
+    uint32_t              maxTessellationGenerationLevel;
+    uint32_t              maxTessellationPatchSize;
+    uint32_t              maxTessellationControlPerVertexInputComponents;
+    uint32_t              maxTessellationControlPerVertexOutputComponents;
+    uint32_t              maxTessellationControlPerPatchOutputComponents;
+    uint32_t              maxTessellationControlTotalOutputComponents;
+    uint32_t              maxTessellationEvaluationInputComponents;
+    uint32_t              maxTessellationEvaluationOutputComponents;
+    uint32_t              maxGeometryShaderInvocations;
+    uint32_t              maxGeometryInputComponents;
+    uint32_t              maxGeometryOutputComponents;
+    uint32_t              maxGeometryOutputVertices;
+    uint32_t              maxGeometryTotalOutputComponents;
+    uint32_t              maxFragmentInputComponents;
+    uint32_t              maxFragmentOutputAttachments;
+    uint32_t              maxFragmentDualSrcAttachments;
+    uint32_t              maxFragmentCombinedOutputResources;
+    uint32_t              maxComputeSharedMemorySize;
+    uint32_t              maxComputeWorkGroupCount[3];
+    uint32_t              maxComputeWorkGroupInvocations;
+    uint32_t              maxComputeWorkGroupSize[3];
+    uint32_t              subPixelPrecisionBits;
+    uint32_t              subTexelPrecisionBits;
+    uint32_t              mipmapPrecisionBits;
+    uint32_t              maxDrawIndexedIndexValue;
+    uint32_t              maxDrawIndirectCount;
+    float                 maxSamplerLodBias;
+    float                 maxSamplerAnisotropy;
+    uint32_t              maxViewports;
+    uint32_t              maxViewportDimensions[2];
+    float                 viewportBoundsRange[2];
+    uint32_t              viewportSubPixelBits;
+    size_t                minMemoryMapAlignment;
+    VkDeviceSize          minTexelBufferOffsetAlignment;
+    VkDeviceSize          minUniformBufferOffsetAlignment;
+    VkDeviceSize          minStorageBufferOffsetAlignment;
+    int32_t               minTexelOffset;
+    uint32_t              maxTexelOffset;
+    int32_t               minTexelGatherOffset;
+    uint32_t              maxTexelGatherOffset;
+    float                 minInterpolationOffset;
+    float                 maxInterpolationOffset;
+    uint32_t              subPixelInterpolationOffsetBits;
+    uint32_t              maxFramebufferWidth;
+    uint32_t              maxFramebufferHeight;
+    uint32_t              maxFramebufferLayers;
+    VkSampleCountFlags    framebufferColorSampleCounts;
+    VkSampleCountFlags    framebufferDepthSampleCounts;
+    VkSampleCountFlags    framebufferStencilSampleCounts;
+    VkSampleCountFlags    framebufferNoAttachmentsSampleCounts;
+    uint32_t              maxColorAttachments;
+    VkSampleCountFlags    sampledImageColorSampleCounts;
+    VkSampleCountFlags    sampledImageIntegerSampleCounts;
+    VkSampleCountFlags    sampledImageDepthSampleCounts;
+    VkSampleCountFlags    sampledImageStencilSampleCounts;
+    VkSampleCountFlags    storageImageSampleCounts;
+    uint32_t              maxSampleMaskWords;
+    VkBool32              timestampComputeAndGraphics;
+    float                 timestampPeriod;
+    uint32_t              maxClipDistances;
+    uint32_t              maxCullDistances;
+    uint32_t              maxCombinedClipAndCullDistances;
+    uint32_t              discreteQueuePriorities;
+    float                 pointSizeRange[2];
+    float                 lineWidthRange[2];
+    float                 pointSizeGranularity;
+    float                 lineWidthGranularity;
+    VkBool32              strictLines;
+    VkBool32              standardSampleLocations;
+    VkDeviceSize          optimalBufferCopyOffsetAlignment;
+    VkDeviceSize          optimalBufferCopyRowPitchAlignment;
+    VkDeviceSize          nonCoherentAtomSize;
+} VkPhysicalDeviceLimits;
+
+typedef struct VkPhysicalDeviceSparseProperties {
+    VkBool32    residencyStandard2DBlockShape;
+    VkBool32    residencyStandard2DMultisampleBlockShape;
+    VkBool32    residencyStandard3DBlockShape;
+    VkBool32    residencyAlignedMipSize;
+    VkBool32    residencyNonResidentStrict;
+} VkPhysicalDeviceSparseProperties;
+
+typedef struct VkPhysicalDeviceProperties {
+    uint32_t                            apiVersion;
+    uint32_t                            driverVersion;
+    uint32_t                            vendorID;
+    uint32_t                            deviceID;
+    VkPhysicalDeviceType                deviceType;
+    char                                deviceName[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
+    uint8_t                             pipelineCacheUUID[VK_UUID_SIZE];
+    VkPhysicalDeviceLimits              limits;
+    VkPhysicalDeviceSparseProperties    sparseProperties;
+} VkPhysicalDeviceProperties;
+
+typedef struct VkQueueFamilyProperties {
+    VkQueueFlags    queueFlags;
+    uint32_t        queueCount;
+    uint32_t        timestampValidBits;
+    VkExtent3D      minImageTransferGranularity;
+} VkQueueFamilyProperties;
+
+typedef struct VkMemoryType {
+    VkMemoryPropertyFlags    propertyFlags;
+    uint32_t                 heapIndex;
+} VkMemoryType;
+
+typedef struct VkMemoryHeap {
+    VkDeviceSize         size;
+    VkMemoryHeapFlags    flags;
+} VkMemoryHeap;
+
+typedef struct VkPhysicalDeviceMemoryProperties {
+    uint32_t        memoryTypeCount;
+    VkMemoryType    memoryTypes[VK_MAX_MEMORY_TYPES];
+    uint32_t        memoryHeapCount;
+    VkMemoryHeap    memoryHeaps[VK_MAX_MEMORY_HEAPS];
+} VkPhysicalDeviceMemoryProperties;
+
+typedef void (VKAPI_PTR *PFN_vkVoidFunction)(void);
+typedef struct VkDeviceQueueCreateInfo {
+    VkStructureType             sType;
+    const void*                 pNext;
+    VkDeviceQueueCreateFlags    flags;
+    uint32_t                    queueFamilyIndex;
+    uint32_t                    queueCount;
+    const float*                pQueuePriorities;
+} VkDeviceQueueCreateInfo;
+
+typedef struct VkDeviceCreateInfo {
+    VkStructureType                    sType;
+    const void*                        pNext;
+    VkDeviceCreateFlags                flags;
+    uint32_t                           queueCreateInfoCount;
+    const VkDeviceQueueCreateInfo*     pQueueCreateInfos;
+    uint32_t                           enabledLayerCount;
+    const char* const*                 ppEnabledLayerNames;
+    uint32_t                           enabledExtensionCount;
+    const char* const*                 ppEnabledExtensionNames;
+    const VkPhysicalDeviceFeatures*    pEnabledFeatures;
+} VkDeviceCreateInfo;
+
+typedef struct VkExtensionProperties {
+    char        extensionName[VK_MAX_EXTENSION_NAME_SIZE];
+    uint32_t    specVersion;
+} VkExtensionProperties;
+
+typedef struct VkLayerProperties {
+    char        layerName[VK_MAX_EXTENSION_NAME_SIZE];
+    uint32_t    specVersion;
+    uint32_t    implementationVersion;
+    char        description[VK_MAX_DESCRIPTION_SIZE];
+} VkLayerProperties;
+
+typedef struct VkSubmitInfo {
+    VkStructureType                sType;
+    const void*                    pNext;
+    uint32_t                       waitSemaphoreCount;
+    const VkSemaphore*             pWaitSemaphores;
+    const VkPipelineStageFlags*    pWaitDstStageMask;
+    uint32_t                       commandBufferCount;
+    const VkCommandBuffer*         pCommandBuffers;
+    uint32_t                       signalSemaphoreCount;
+    const VkSemaphore*             pSignalSemaphores;
+} VkSubmitInfo;
+
+typedef struct VkMemoryAllocateInfo {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkDeviceSize       allocationSize;
+    uint32_t           memoryTypeIndex;
+} VkMemoryAllocateInfo;
+
+typedef struct VkMappedMemoryRange {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkDeviceMemory     memory;
+    VkDeviceSize       offset;
+    VkDeviceSize       size;
+} VkMappedMemoryRange;
+
+typedef struct VkMemoryRequirements {
+    VkDeviceSize    size;
+    VkDeviceSize    alignment;
+    uint32_t        memoryTypeBits;
+} VkMemoryRequirements;
+
+typedef struct VkSparseImageFormatProperties {
+    VkImageAspectFlags          aspectMask;
+    VkExtent3D                  imageGranularity;
+    VkSparseImageFormatFlags    flags;
+} VkSparseImageFormatProperties;
+
+typedef struct VkSparseImageMemoryRequirements {
+    VkSparseImageFormatProperties    formatProperties;
+    uint32_t                         imageMipTailFirstLod;
+    VkDeviceSize                     imageMipTailSize;
+    VkDeviceSize                     imageMipTailOffset;
+    VkDeviceSize                     imageMipTailStride;
+} VkSparseImageMemoryRequirements;
+
+typedef struct VkSparseMemoryBind {
+    VkDeviceSize               resourceOffset;
+    VkDeviceSize               size;
+    VkDeviceMemory             memory;
+    VkDeviceSize               memoryOffset;
+    VkSparseMemoryBindFlags    flags;
+} VkSparseMemoryBind;
+
+typedef struct VkSparseBufferMemoryBindInfo {
+    VkBuffer                     buffer;
+    uint32_t                     bindCount;
+    const VkSparseMemoryBind*    pBinds;
+} VkSparseBufferMemoryBindInfo;
+
+typedef struct VkSparseImageOpaqueMemoryBindInfo {
+    VkImage                      image;
+    uint32_t                     bindCount;
+    const VkSparseMemoryBind*    pBinds;
+} VkSparseImageOpaqueMemoryBindInfo;
+
+typedef struct VkImageSubresource {
+    VkImageAspectFlags    aspectMask;
+    uint32_t              mipLevel;
+    uint32_t              arrayLayer;
+} VkImageSubresource;
+
+typedef struct VkOffset3D {
+    int32_t    x;
+    int32_t    y;
+    int32_t    z;
+} VkOffset3D;
+
+typedef struct VkSparseImageMemoryBind {
+    VkImageSubresource         subresource;
+    VkOffset3D                 offset;
+    VkExtent3D                 extent;
+    VkDeviceMemory             memory;
+    VkDeviceSize               memoryOffset;
+    VkSparseMemoryBindFlags    flags;
+} VkSparseImageMemoryBind;
+
+typedef struct VkSparseImageMemoryBindInfo {
+    VkImage                           image;
+    uint32_t                          bindCount;
+    const VkSparseImageMemoryBind*    pBinds;
+} VkSparseImageMemoryBindInfo;
+
+typedef struct VkBindSparseInfo {
+    VkStructureType                             sType;
+    const void*                                 pNext;
+    uint32_t                                    waitSemaphoreCount;
+    const VkSemaphore*                          pWaitSemaphores;
+    uint32_t                                    bufferBindCount;
+    const VkSparseBufferMemoryBindInfo*         pBufferBinds;
+    uint32_t                                    imageOpaqueBindCount;
+    const VkSparseImageOpaqueMemoryBindInfo*    pImageOpaqueBinds;
+    uint32_t                                    imageBindCount;
+    const VkSparseImageMemoryBindInfo*          pImageBinds;
+    uint32_t                                    signalSemaphoreCount;
+    const VkSemaphore*                          pSignalSemaphores;
+} VkBindSparseInfo;
+
+typedef struct VkFenceCreateInfo {
+    VkStructureType       sType;
+    const void*           pNext;
+    VkFenceCreateFlags    flags;
+} VkFenceCreateInfo;
+
+typedef struct VkSemaphoreCreateInfo {
+    VkStructureType           sType;
+    const void*               pNext;
+    VkSemaphoreCreateFlags    flags;
+} VkSemaphoreCreateInfo;
+
+typedef struct VkEventCreateInfo {
+    VkStructureType       sType;
+    const void*           pNext;
+    VkEventCreateFlags    flags;
+} VkEventCreateInfo;
+
+typedef struct VkQueryPoolCreateInfo {
+    VkStructureType                  sType;
+    const void*                      pNext;
+    VkQueryPoolCreateFlags           flags;
+    VkQueryType                      queryType;
+    uint32_t                         queryCount;
+    VkQueryPipelineStatisticFlags    pipelineStatistics;
+} VkQueryPoolCreateInfo;
+
+typedef struct VkBufferCreateInfo {
+    VkStructureType        sType;
+    const void*            pNext;
+    VkBufferCreateFlags    flags;
+    VkDeviceSize           size;
+    VkBufferUsageFlags     usage;
+    VkSharingMode          sharingMode;
+    uint32_t               queueFamilyIndexCount;
+    const uint32_t*        pQueueFamilyIndices;
+} VkBufferCreateInfo;
+
+typedef struct VkBufferViewCreateInfo {
+    VkStructureType            sType;
+    const void*                pNext;
+    VkBufferViewCreateFlags    flags;
+    VkBuffer                   buffer;
+    VkFormat                   format;
+    VkDeviceSize               offset;
+    VkDeviceSize               range;
+} VkBufferViewCreateInfo;
+
+typedef struct VkImageCreateInfo {
+    VkStructureType          sType;
+    const void*              pNext;
+    VkImageCreateFlags       flags;
+    VkImageType              imageType;
+    VkFormat                 format;
+    VkExtent3D               extent;
+    uint32_t                 mipLevels;
+    uint32_t                 arrayLayers;
+    VkSampleCountFlagBits    samples;
+    VkImageTiling            tiling;
+    VkImageUsageFlags        usage;
+    VkSharingMode            sharingMode;
+    uint32_t                 queueFamilyIndexCount;
+    const uint32_t*          pQueueFamilyIndices;
+    VkImageLayout            initialLayout;
+} VkImageCreateInfo;
+
+typedef struct VkSubresourceLayout {
+    VkDeviceSize    offset;
+    VkDeviceSize    size;
+    VkDeviceSize    rowPitch;
+    VkDeviceSize    arrayPitch;
+    VkDeviceSize    depthPitch;
+} VkSubresourceLayout;
+
+typedef struct VkComponentMapping {
+    VkComponentSwizzle    r;
+    VkComponentSwizzle    g;
+    VkComponentSwizzle    b;
+    VkComponentSwizzle    a;
+} VkComponentMapping;
+
+typedef struct VkImageSubresourceRange {
+    VkImageAspectFlags    aspectMask;
+    uint32_t              baseMipLevel;
+    uint32_t              levelCount;
+    uint32_t              baseArrayLayer;
+    uint32_t              layerCount;
+} VkImageSubresourceRange;
+
+typedef struct VkImageViewCreateInfo {
+    VkStructureType            sType;
+    const void*                pNext;
+    VkImageViewCreateFlags     flags;
+    VkImage                    image;
+    VkImageViewType            viewType;
+    VkFormat                   format;
+    VkComponentMapping         components;
+    VkImageSubresourceRange    subresourceRange;
+} VkImageViewCreateInfo;
+
+typedef struct VkShaderModuleCreateInfo {
+    VkStructureType              sType;
+    const void*                  pNext;
+    VkShaderModuleCreateFlags    flags;
+    size_t                       codeSize;
+    const uint32_t*              pCode;
+} VkShaderModuleCreateInfo;
+
+typedef struct VkPipelineCacheCreateInfo {
+    VkStructureType               sType;
+    const void*                   pNext;
+    VkPipelineCacheCreateFlags    flags;
+    size_t                        initialDataSize;
+    const void*                   pInitialData;
+} VkPipelineCacheCreateInfo;
+
+typedef struct VkSpecializationMapEntry {
+    uint32_t    constantID;
+    uint32_t    offset;
+    size_t      size;
+} VkSpecializationMapEntry;
+
+typedef struct VkSpecializationInfo {
+    uint32_t                           mapEntryCount;
+    const VkSpecializationMapEntry*    pMapEntries;
+    size_t                             dataSize;
+    const void*                        pData;
+} VkSpecializationInfo;
+
+typedef struct VkPipelineShaderStageCreateInfo {
+    VkStructureType                     sType;
+    const void*                         pNext;
+    VkPipelineShaderStageCreateFlags    flags;
+    VkShaderStageFlagBits               stage;
+    VkShaderModule                      module;
+    const char*                         pName;
+    const VkSpecializationInfo*         pSpecializationInfo;
+} VkPipelineShaderStageCreateInfo;
+
+typedef struct VkVertexInputBindingDescription {
+    uint32_t             binding;
+    uint32_t             stride;
+    VkVertexInputRate    inputRate;
+} VkVertexInputBindingDescription;
+
+typedef struct VkVertexInputAttributeDescription {
+    uint32_t    location;
+    uint32_t    binding;
+    VkFormat    format;
+    uint32_t    offset;
+} VkVertexInputAttributeDescription;
+
+typedef struct VkPipelineVertexInputStateCreateInfo {
+    VkStructureType                             sType;
+    const void*                                 pNext;
+    VkPipelineVertexInputStateCreateFlags       flags;
+    uint32_t                                    vertexBindingDescriptionCount;
+    const VkVertexInputBindingDescription*      pVertexBindingDescriptions;
+    uint32_t                                    vertexAttributeDescriptionCount;
+    const VkVertexInputAttributeDescription*    pVertexAttributeDescriptions;
+} VkPipelineVertexInputStateCreateInfo;
+
+typedef struct VkPipelineInputAssemblyStateCreateInfo {
+    VkStructureType                            sType;
+    const void*                                pNext;
+    VkPipelineInputAssemblyStateCreateFlags    flags;
+    VkPrimitiveTopology                        topology;
+    VkBool32                                   primitiveRestartEnable;
+} VkPipelineInputAssemblyStateCreateInfo;
+
+typedef struct VkPipelineTessellationStateCreateInfo {
+    VkStructureType                           sType;
+    const void*                               pNext;
+    VkPipelineTessellationStateCreateFlags    flags;
+    uint32_t                                  patchControlPoints;
+} VkPipelineTessellationStateCreateInfo;
+
+typedef struct VkViewport {
+    float    x;
+    float    y;
+    float    width;
+    float    height;
+    float    minDepth;
+    float    maxDepth;
+} VkViewport;
+
+typedef struct VkOffset2D {
+    int32_t    x;
+    int32_t    y;
+} VkOffset2D;
+
+typedef struct VkExtent2D {
+    uint32_t    width;
+    uint32_t    height;
+} VkExtent2D;
+
+typedef struct VkRect2D {
+    VkOffset2D    offset;
+    VkExtent2D    extent;
+} VkRect2D;
+
+typedef struct VkPipelineViewportStateCreateInfo {
+    VkStructureType                       sType;
+    const void*                           pNext;
+    VkPipelineViewportStateCreateFlags    flags;
+    uint32_t                              viewportCount;
+    const VkViewport*                     pViewports;
+    uint32_t                              scissorCount;
+    const VkRect2D*                       pScissors;
+} VkPipelineViewportStateCreateInfo;
+
+typedef struct VkPipelineRasterizationStateCreateInfo {
+    VkStructureType                            sType;
+    const void*                                pNext;
+    VkPipelineRasterizationStateCreateFlags    flags;
+    VkBool32                                   depthClampEnable;
+    VkBool32                                   rasterizerDiscardEnable;
+    VkPolygonMode                              polygonMode;
+    VkCullModeFlags                            cullMode;
+    VkFrontFace                                frontFace;
+    VkBool32                                   depthBiasEnable;
+    float                                      depthBiasConstantFactor;
+    float                                      depthBiasClamp;
+    float                                      depthBiasSlopeFactor;
+    float                                      lineWidth;
+} VkPipelineRasterizationStateCreateInfo;
+
+typedef struct VkPipelineMultisampleStateCreateInfo {
+    VkStructureType                          sType;
+    const void*                              pNext;
+    VkPipelineMultisampleStateCreateFlags    flags;
+    VkSampleCountFlagBits                    rasterizationSamples;
+    VkBool32                                 sampleShadingEnable;
+    float                                    minSampleShading;
+    const VkSampleMask*                      pSampleMask;
+    VkBool32                                 alphaToCoverageEnable;
+    VkBool32                                 alphaToOneEnable;
+} VkPipelineMultisampleStateCreateInfo;
+
+typedef struct VkStencilOpState {
+    VkStencilOp    failOp;
+    VkStencilOp    passOp;
+    VkStencilOp    depthFailOp;
+    VkCompareOp    compareOp;
+    uint32_t       compareMask;
+    uint32_t       writeMask;
+    uint32_t       reference;
+} VkStencilOpState;
+
+typedef struct VkPipelineDepthStencilStateCreateInfo {
+    VkStructureType                           sType;
+    const void*                               pNext;
+    VkPipelineDepthStencilStateCreateFlags    flags;
+    VkBool32                                  depthTestEnable;
+    VkBool32                                  depthWriteEnable;
+    VkCompareOp                               depthCompareOp;
+    VkBool32                                  depthBoundsTestEnable;
+    VkBool32                                  stencilTestEnable;
+    VkStencilOpState                          front;
+    VkStencilOpState                          back;
+    float                                     minDepthBounds;
+    float                                     maxDepthBounds;
+} VkPipelineDepthStencilStateCreateInfo;
+
+typedef struct VkPipelineColorBlendAttachmentState {
+    VkBool32                 blendEnable;
+    VkBlendFactor            srcColorBlendFactor;
+    VkBlendFactor            dstColorBlendFactor;
+    VkBlendOp                colorBlendOp;
+    VkBlendFactor            srcAlphaBlendFactor;
+    VkBlendFactor            dstAlphaBlendFactor;
+    VkBlendOp                alphaBlendOp;
+    VkColorComponentFlags    colorWriteMask;
+} VkPipelineColorBlendAttachmentState;
+
+typedef struct VkPipelineColorBlendStateCreateInfo {
+    VkStructureType                               sType;
+    const void*                                   pNext;
+    VkPipelineColorBlendStateCreateFlags          flags;
+    VkBool32                                      logicOpEnable;
+    VkLogicOp                                     logicOp;
+    uint32_t                                      attachmentCount;
+    const VkPipelineColorBlendAttachmentState*    pAttachments;
+    float                                         blendConstants[4];
+} VkPipelineColorBlendStateCreateInfo;
+
+typedef struct VkPipelineDynamicStateCreateInfo {
+    VkStructureType                      sType;
+    const void*                          pNext;
+    VkPipelineDynamicStateCreateFlags    flags;
+    uint32_t                             dynamicStateCount;
+    const VkDynamicState*                pDynamicStates;
+} VkPipelineDynamicStateCreateInfo;
+
+typedef struct VkGraphicsPipelineCreateInfo {
+    VkStructureType                                  sType;
+    const void*                                      pNext;
+    VkPipelineCreateFlags                            flags;
+    uint32_t                                         stageCount;
+    const VkPipelineShaderStageCreateInfo*           pStages;
+    const VkPipelineVertexInputStateCreateInfo*      pVertexInputState;
+    const VkPipelineInputAssemblyStateCreateInfo*    pInputAssemblyState;
+    const VkPipelineTessellationStateCreateInfo*     pTessellationState;
+    const VkPipelineViewportStateCreateInfo*         pViewportState;
+    const VkPipelineRasterizationStateCreateInfo*    pRasterizationState;
+    const VkPipelineMultisampleStateCreateInfo*      pMultisampleState;
+    const VkPipelineDepthStencilStateCreateInfo*     pDepthStencilState;
+    const VkPipelineColorBlendStateCreateInfo*       pColorBlendState;
+    const VkPipelineDynamicStateCreateInfo*          pDynamicState;
+    VkPipelineLayout                                 layout;
+    VkRenderPass                                     renderPass;
+    uint32_t                                         subpass;
+    VkPipeline                                       basePipelineHandle;
+    int32_t                                          basePipelineIndex;
+} VkGraphicsPipelineCreateInfo;
+
+typedef struct VkComputePipelineCreateInfo {
+    VkStructureType                    sType;
+    const void*                        pNext;
+    VkPipelineCreateFlags              flags;
+    VkPipelineShaderStageCreateInfo    stage;
+    VkPipelineLayout                   layout;
+    VkPipeline                         basePipelineHandle;
+    int32_t                            basePipelineIndex;
+} VkComputePipelineCreateInfo;
+
+typedef struct VkPushConstantRange {
+    VkShaderStageFlags    stageFlags;
+    uint32_t              offset;
+    uint32_t              size;
+} VkPushConstantRange;
+
+typedef struct VkPipelineLayoutCreateInfo {
+    VkStructureType                 sType;
+    const void*                     pNext;
+    VkPipelineLayoutCreateFlags     flags;
+    uint32_t                        setLayoutCount;
+    const VkDescriptorSetLayout*    pSetLayouts;
+    uint32_t                        pushConstantRangeCount;
+    const VkPushConstantRange*      pPushConstantRanges;
+} VkPipelineLayoutCreateInfo;
+
+typedef struct VkSamplerCreateInfo {
+    VkStructureType         sType;
+    const void*             pNext;
+    VkSamplerCreateFlags    flags;
+    VkFilter                magFilter;
+    VkFilter                minFilter;
+    VkSamplerMipmapMode     mipmapMode;
+    VkSamplerAddressMode    addressModeU;
+    VkSamplerAddressMode    addressModeV;
+    VkSamplerAddressMode    addressModeW;
+    float                   mipLodBias;
+    VkBool32                anisotropyEnable;
+    float                   maxAnisotropy;
+    VkBool32                compareEnable;
+    VkCompareOp             compareOp;
+    float                   minLod;
+    float                   maxLod;
+    VkBorderColor           borderColor;
+    VkBool32                unnormalizedCoordinates;
+} VkSamplerCreateInfo;
+
+typedef struct VkDescriptorSetLayoutBinding {
+    uint32_t              binding;
+    VkDescriptorType      descriptorType;
+    uint32_t              descriptorCount;
+    VkShaderStageFlags    stageFlags;
+    const VkSampler*      pImmutableSamplers;
+} VkDescriptorSetLayoutBinding;
+
+typedef struct VkDescriptorSetLayoutCreateInfo {
+    VkStructureType                        sType;
+    const void*                            pNext;
+    VkDescriptorSetLayoutCreateFlags       flags;
+    uint32_t                               bindingCount;
+    const VkDescriptorSetLayoutBinding*    pBindings;
+} VkDescriptorSetLayoutCreateInfo;
+
+typedef struct VkDescriptorPoolSize {
+    VkDescriptorType    type;
+    uint32_t            descriptorCount;
+} VkDescriptorPoolSize;
+
+typedef struct VkDescriptorPoolCreateInfo {
+    VkStructureType                sType;
+    const void*                    pNext;
+    VkDescriptorPoolCreateFlags    flags;
+    uint32_t                       maxSets;
+    uint32_t                       poolSizeCount;
+    const VkDescriptorPoolSize*    pPoolSizes;
+} VkDescriptorPoolCreateInfo;
+
+typedef struct VkDescriptorSetAllocateInfo {
+    VkStructureType                 sType;
+    const void*                     pNext;
+    VkDescriptorPool                descriptorPool;
+    uint32_t                        descriptorSetCount;
+    const VkDescriptorSetLayout*    pSetLayouts;
+} VkDescriptorSetAllocateInfo;
+
+typedef struct VkDescriptorImageInfo {
+    VkSampler        sampler;
+    VkImageView      imageView;
+    VkImageLayout    imageLayout;
+} VkDescriptorImageInfo;
+
+typedef struct VkDescriptorBufferInfo {
+    VkBuffer        buffer;
+    VkDeviceSize    offset;
+    VkDeviceSize    range;
+} VkDescriptorBufferInfo;
+
+typedef struct VkWriteDescriptorSet {
+    VkStructureType                  sType;
+    const void*                      pNext;
+    VkDescriptorSet                  dstSet;
+    uint32_t                         dstBinding;
+    uint32_t                         dstArrayElement;
+    uint32_t                         descriptorCount;
+    VkDescriptorType                 descriptorType;
+    const VkDescriptorImageInfo*     pImageInfo;
+    const VkDescriptorBufferInfo*    pBufferInfo;
+    const VkBufferView*              pTexelBufferView;
+} VkWriteDescriptorSet;
+
+typedef struct VkCopyDescriptorSet {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkDescriptorSet    srcSet;
+    uint32_t           srcBinding;
+    uint32_t           srcArrayElement;
+    VkDescriptorSet    dstSet;
+    uint32_t           dstBinding;
+    uint32_t           dstArrayElement;
+    uint32_t           descriptorCount;
+} VkCopyDescriptorSet;
+
+typedef struct VkFramebufferCreateInfo {
+    VkStructureType             sType;
+    const void*                 pNext;
+    VkFramebufferCreateFlags    flags;
+    VkRenderPass                renderPass;
+    uint32_t                    attachmentCount;
+    const VkImageView*          pAttachments;
+    uint32_t                    width;
+    uint32_t                    height;
+    uint32_t                    layers;
+} VkFramebufferCreateInfo;
+
+typedef struct VkAttachmentDescription {
+    VkAttachmentDescriptionFlags    flags;
+    VkFormat                        format;
+    VkSampleCountFlagBits           samples;
+    VkAttachmentLoadOp              loadOp;
+    VkAttachmentStoreOp             storeOp;
+    VkAttachmentLoadOp              stencilLoadOp;
+    VkAttachmentStoreOp             stencilStoreOp;
+    VkImageLayout                   initialLayout;
+    VkImageLayout                   finalLayout;
+} VkAttachmentDescription;
+
+typedef struct VkAttachmentReference {
+    uint32_t         attachment;
+    VkImageLayout    layout;
+} VkAttachmentReference;
+
+typedef struct VkSubpassDescription {
+    VkSubpassDescriptionFlags       flags;
+    VkPipelineBindPoint             pipelineBindPoint;
+    uint32_t                        inputAttachmentCount;
+    const VkAttachmentReference*    pInputAttachments;
+    uint32_t                        colorAttachmentCount;
+    const VkAttachmentReference*    pColorAttachments;
+    const VkAttachmentReference*    pResolveAttachments;
+    const VkAttachmentReference*    pDepthStencilAttachment;
+    uint32_t                        preserveAttachmentCount;
+    const uint32_t*                 pPreserveAttachments;
+} VkSubpassDescription;
+
+typedef struct VkSubpassDependency {
+    uint32_t                srcSubpass;
+    uint32_t                dstSubpass;
+    VkPipelineStageFlags    srcStageMask;
+    VkPipelineStageFlags    dstStageMask;
+    VkAccessFlags           srcAccessMask;
+    VkAccessFlags           dstAccessMask;
+    VkDependencyFlags       dependencyFlags;
+} VkSubpassDependency;
+
+typedef struct VkRenderPassCreateInfo {
+    VkStructureType                   sType;
+    const void*                       pNext;
+    VkRenderPassCreateFlags           flags;
+    uint32_t                          attachmentCount;
+    const VkAttachmentDescription*    pAttachments;
+    uint32_t                          subpassCount;
+    const VkSubpassDescription*       pSubpasses;
+    uint32_t                          dependencyCount;
+    const VkSubpassDependency*        pDependencies;
+} VkRenderPassCreateInfo;
+
+typedef struct VkCommandPoolCreateInfo {
+    VkStructureType             sType;
+    const void*                 pNext;
+    VkCommandPoolCreateFlags    flags;
+    uint32_t                    queueFamilyIndex;
+} VkCommandPoolCreateInfo;
+
+typedef struct VkCommandBufferAllocateInfo {
+    VkStructureType         sType;
+    const void*             pNext;
+    VkCommandPool           commandPool;
+    VkCommandBufferLevel    level;
+    uint32_t                commandBufferCount;
+} VkCommandBufferAllocateInfo;
+
+typedef struct VkCommandBufferInheritanceInfo {
+    VkStructureType                  sType;
+    const void*                      pNext;
+    VkRenderPass                     renderPass;
+    uint32_t                         subpass;
+    VkFramebuffer                    framebuffer;
+    VkBool32                         occlusionQueryEnable;
+    VkQueryControlFlags              queryFlags;
+    VkQueryPipelineStatisticFlags    pipelineStatistics;
+} VkCommandBufferInheritanceInfo;
+
+typedef struct VkCommandBufferBeginInfo {
+    VkStructureType                          sType;
+    const void*                              pNext;
+    VkCommandBufferUsageFlags                flags;
+    const VkCommandBufferInheritanceInfo*    pInheritanceInfo;
+} VkCommandBufferBeginInfo;
+
+typedef struct VkBufferCopy {
+    VkDeviceSize    srcOffset;
+    VkDeviceSize    dstOffset;
+    VkDeviceSize    size;
+} VkBufferCopy;
+
+typedef struct VkImageSubresourceLayers {
+    VkImageAspectFlags    aspectMask;
+    uint32_t              mipLevel;
+    uint32_t              baseArrayLayer;
+    uint32_t              layerCount;
+} VkImageSubresourceLayers;
+
+typedef struct VkImageCopy {
+    VkImageSubresourceLayers    srcSubresource;
+    VkOffset3D                  srcOffset;
+    VkImageSubresourceLayers    dstSubresource;
+    VkOffset3D                  dstOffset;
+    VkExtent3D                  extent;
+} VkImageCopy;
+
+typedef struct VkImageBlit {
+    VkImageSubresourceLayers    srcSubresource;
+    VkOffset3D                  srcOffsets[2];
+    VkImageSubresourceLayers    dstSubresource;
+    VkOffset3D                  dstOffsets[2];
+} VkImageBlit;
+
+typedef struct VkBufferImageCopy {
+    VkDeviceSize                bufferOffset;
+    uint32_t                    bufferRowLength;
+    uint32_t                    bufferImageHeight;
+    VkImageSubresourceLayers    imageSubresource;
+    VkOffset3D                  imageOffset;
+    VkExtent3D                  imageExtent;
+} VkBufferImageCopy;
+
+typedef union VkClearColorValue {
+    float       float32[4];
+    int32_t     int32[4];
+    uint32_t    uint32[4];
+} VkClearColorValue;
+
+typedef struct VkClearDepthStencilValue {
+    float       depth;
+    uint32_t    stencil;
+} VkClearDepthStencilValue;
+
+typedef union VkClearValue {
+    VkClearColorValue           color;
+    VkClearDepthStencilValue    depthStencil;
+} VkClearValue;
+
+typedef struct VkClearAttachment {
+    VkImageAspectFlags    aspectMask;
+    uint32_t              colorAttachment;
+    VkClearValue          clearValue;
+} VkClearAttachment;
+
+typedef struct VkClearRect {
+    VkRect2D    rect;
+    uint32_t    baseArrayLayer;
+    uint32_t    layerCount;
+} VkClearRect;
+
+typedef struct VkImageResolve {
+    VkImageSubresourceLayers    srcSubresource;
+    VkOffset3D                  srcOffset;
+    VkImageSubresourceLayers    dstSubresource;
+    VkOffset3D                  dstOffset;
+    VkExtent3D                  extent;
+} VkImageResolve;
+
+typedef struct VkMemoryBarrier {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkAccessFlags      srcAccessMask;
+    VkAccessFlags      dstAccessMask;
+} VkMemoryBarrier;
+
+typedef struct VkBufferMemoryBarrier {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkAccessFlags      srcAccessMask;
+    VkAccessFlags      dstAccessMask;
+    uint32_t           srcQueueFamilyIndex;
+    uint32_t           dstQueueFamilyIndex;
+    VkBuffer           buffer;
+    VkDeviceSize       offset;
+    VkDeviceSize       size;
+} VkBufferMemoryBarrier;
+
+typedef struct VkImageMemoryBarrier {
+    VkStructureType            sType;
+    const void*                pNext;
+    VkAccessFlags              srcAccessMask;
+    VkAccessFlags              dstAccessMask;
+    VkImageLayout              oldLayout;
+    VkImageLayout              newLayout;
+    uint32_t                   srcQueueFamilyIndex;
+    uint32_t                   dstQueueFamilyIndex;
+    VkImage                    image;
+    VkImageSubresourceRange    subresourceRange;
+} VkImageMemoryBarrier;
+
+typedef struct VkRenderPassBeginInfo {
+    VkStructureType        sType;
+    const void*            pNext;
+    VkRenderPass           renderPass;
+    VkFramebuffer          framebuffer;
+    VkRect2D               renderArea;
+    uint32_t               clearValueCount;
+    const VkClearValue*    pClearValues;
+} VkRenderPassBeginInfo;
+
+typedef struct VkDispatchIndirectCommand {
+    uint32_t    x;
+    uint32_t    y;
+    uint32_t    z;
+} VkDispatchIndirectCommand;
+
+typedef struct VkDrawIndexedIndirectCommand {
+    uint32_t    indexCount;
+    uint32_t    instanceCount;
+    uint32_t    firstIndex;
+    int32_t     vertexOffset;
+    uint32_t    firstInstance;
+} VkDrawIndexedIndirectCommand;
+
+typedef struct VkDrawIndirectCommand {
+    uint32_t    vertexCount;
+    uint32_t    instanceCount;
+    uint32_t    firstVertex;
+    uint32_t    firstInstance;
+} VkDrawIndirectCommand;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateInstance)(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkInstance* pInstance);
+typedef void (VKAPI_PTR *PFN_vkDestroyInstance)(VkInstance instance, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkEnumeratePhysicalDevices)(VkInstance instance, uint32_t* pPhysicalDeviceCount, VkPhysicalDevice* pPhysicalDevices);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceFeatures)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceFormatProperties)(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties* pFormatProperties);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceImageFormatProperties)(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkImageFormatProperties* pImageFormatProperties);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceProperties)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties* pProperties);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceQueueFamilyProperties)(VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties* pQueueFamilyProperties);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceMemoryProperties)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties* pMemoryProperties);
+typedef PFN_vkVoidFunction (VKAPI_PTR *PFN_vkGetInstanceProcAddr)(VkInstance instance, const char* pName);
+typedef PFN_vkVoidFunction (VKAPI_PTR *PFN_vkGetDeviceProcAddr)(VkDevice device, const char* pName);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateDevice)(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDevice* pDevice);
+typedef void (VKAPI_PTR *PFN_vkDestroyDevice)(VkDevice device, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkEnumerateInstanceExtensionProperties)(const char* pLayerName, uint32_t* pPropertyCount, VkExtensionProperties* pProperties);
+typedef VkResult (VKAPI_PTR *PFN_vkEnumerateDeviceExtensionProperties)(VkPhysicalDevice physicalDevice, const char* pLayerName, uint32_t* pPropertyCount, VkExtensionProperties* pProperties);
+typedef VkResult (VKAPI_PTR *PFN_vkEnumerateInstanceLayerProperties)(uint32_t* pPropertyCount, VkLayerProperties* pProperties);
+typedef VkResult (VKAPI_PTR *PFN_vkEnumerateDeviceLayerProperties)(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkLayerProperties* pProperties);
+typedef void (VKAPI_PTR *PFN_vkGetDeviceQueue)(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue* pQueue);
+typedef VkResult (VKAPI_PTR *PFN_vkQueueSubmit)(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence);
+typedef VkResult (VKAPI_PTR *PFN_vkQueueWaitIdle)(VkQueue queue);
+typedef VkResult (VKAPI_PTR *PFN_vkDeviceWaitIdle)(VkDevice device);
+typedef VkResult (VKAPI_PTR *PFN_vkAllocateMemory)(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo, const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory);
+typedef void (VKAPI_PTR *PFN_vkFreeMemory)(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkMapMemory)(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size, VkMemoryMapFlags flags, void** ppData);
+typedef void (VKAPI_PTR *PFN_vkUnmapMemory)(VkDevice device, VkDeviceMemory memory);
+typedef VkResult (VKAPI_PTR *PFN_vkFlushMappedMemoryRanges)(VkDevice device, uint32_t memoryRangeCount, const VkMappedMemoryRange* pMemoryRanges);
+typedef VkResult (VKAPI_PTR *PFN_vkInvalidateMappedMemoryRanges)(VkDevice device, uint32_t memoryRangeCount, const VkMappedMemoryRange* pMemoryRanges);
+typedef void (VKAPI_PTR *PFN_vkGetDeviceMemoryCommitment)(VkDevice device, VkDeviceMemory memory, VkDeviceSize* pCommittedMemoryInBytes);
+typedef VkResult (VKAPI_PTR *PFN_vkBindBufferMemory)(VkDevice device, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize memoryOffset);
+typedef VkResult (VKAPI_PTR *PFN_vkBindImageMemory)(VkDevice device, VkImage image, VkDeviceMemory memory, VkDeviceSize memoryOffset);
+typedef void (VKAPI_PTR *PFN_vkGetBufferMemoryRequirements)(VkDevice device, VkBuffer buffer, VkMemoryRequirements* pMemoryRequirements);
+typedef void (VKAPI_PTR *PFN_vkGetImageMemoryRequirements)(VkDevice device, VkImage image, VkMemoryRequirements* pMemoryRequirements);
+typedef void (VKAPI_PTR *PFN_vkGetImageSparseMemoryRequirements)(VkDevice device, VkImage image, uint32_t* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements* pSparseMemoryRequirements);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceSparseImageFormatProperties)(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkSampleCountFlagBits samples, VkImageUsageFlags usage, VkImageTiling tiling, uint32_t* pPropertyCount, VkSparseImageFormatProperties* pProperties);
+typedef VkResult (VKAPI_PTR *PFN_vkQueueBindSparse)(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo, VkFence fence);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateFence)(VkDevice device, const VkFenceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence);
+typedef void (VKAPI_PTR *PFN_vkDestroyFence)(VkDevice device, VkFence fence, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkResetFences)(VkDevice device, uint32_t fenceCount, const VkFence* pFences);
+typedef VkResult (VKAPI_PTR *PFN_vkGetFenceStatus)(VkDevice device, VkFence fence);
+typedef VkResult (VKAPI_PTR *PFN_vkWaitForFences)(VkDevice device, uint32_t fenceCount, const VkFence* pFences, VkBool32 waitAll, uint64_t timeout);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateSemaphore)(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore);
+typedef void (VKAPI_PTR *PFN_vkDestroySemaphore)(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateEvent)(VkDevice device, const VkEventCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkEvent* pEvent);
+typedef void (VKAPI_PTR *PFN_vkDestroyEvent)(VkDevice device, VkEvent event, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkGetEventStatus)(VkDevice device, VkEvent event);
+typedef VkResult (VKAPI_PTR *PFN_vkSetEvent)(VkDevice device, VkEvent event);
+typedef VkResult (VKAPI_PTR *PFN_vkResetEvent)(VkDevice device, VkEvent event);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateQueryPool)(VkDevice device, const VkQueryPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkQueryPool* pQueryPool);
+typedef void (VKAPI_PTR *PFN_vkDestroyQueryPool)(VkDevice device, VkQueryPool queryPool, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkGetQueryPoolResults)(VkDevice device, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, size_t dataSize, void* pData, VkDeviceSize stride, VkQueryResultFlags flags);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateBuffer)(VkDevice device, const VkBufferCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer);
+typedef void (VKAPI_PTR *PFN_vkDestroyBuffer)(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateBufferView)(VkDevice device, const VkBufferViewCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkBufferView* pView);
+typedef void (VKAPI_PTR *PFN_vkDestroyBufferView)(VkDevice device, VkBufferView bufferView, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateImage)(VkDevice device, const VkImageCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkImage* pImage);
+typedef void (VKAPI_PTR *PFN_vkDestroyImage)(VkDevice device, VkImage image, const VkAllocationCallbacks* pAllocator);
+typedef void (VKAPI_PTR *PFN_vkGetImageSubresourceLayout)(VkDevice device, VkImage image, const VkImageSubresource* pSubresource, VkSubresourceLayout* pLayout);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateImageView)(VkDevice device, const VkImageViewCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkImageView* pView);
+typedef void (VKAPI_PTR *PFN_vkDestroyImageView)(VkDevice device, VkImageView imageView, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateShaderModule)(VkDevice device, const VkShaderModuleCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkShaderModule* pShaderModule);
+typedef void (VKAPI_PTR *PFN_vkDestroyShaderModule)(VkDevice device, VkShaderModule shaderModule, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreatePipelineCache)(VkDevice device, const VkPipelineCacheCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPipelineCache* pPipelineCache);
+typedef void (VKAPI_PTR *PFN_vkDestroyPipelineCache)(VkDevice device, VkPipelineCache pipelineCache, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPipelineCacheData)(VkDevice device, VkPipelineCache pipelineCache, size_t* pDataSize, void* pData);
+typedef VkResult (VKAPI_PTR *PFN_vkMergePipelineCaches)(VkDevice device, VkPipelineCache dstCache, uint32_t srcCacheCount, const VkPipelineCache* pSrcCaches);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateGraphicsPipelines)(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkGraphicsPipelineCreateInfo* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateComputePipelines)(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkComputePipelineCreateInfo* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines);
+typedef void (VKAPI_PTR *PFN_vkDestroyPipeline)(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreatePipelineLayout)(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPipelineLayout* pPipelineLayout);
+typedef void (VKAPI_PTR *PFN_vkDestroyPipelineLayout)(VkDevice device, VkPipelineLayout pipelineLayout, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateSampler)(VkDevice device, const VkSamplerCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSampler* pSampler);
+typedef void (VKAPI_PTR *PFN_vkDestroySampler)(VkDevice device, VkSampler sampler, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateDescriptorSetLayout)(VkDevice device, const VkDescriptorSetLayoutCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorSetLayout* pSetLayout);
+typedef void (VKAPI_PTR *PFN_vkDestroyDescriptorSetLayout)(VkDevice device, VkDescriptorSetLayout descriptorSetLayout, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateDescriptorPool)(VkDevice device, const VkDescriptorPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorPool* pDescriptorPool);
+typedef void (VKAPI_PTR *PFN_vkDestroyDescriptorPool)(VkDevice device, VkDescriptorPool descriptorPool, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkResetDescriptorPool)(VkDevice device, VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags);
+typedef VkResult (VKAPI_PTR *PFN_vkAllocateDescriptorSets)(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo, VkDescriptorSet* pDescriptorSets);
+typedef VkResult (VKAPI_PTR *PFN_vkFreeDescriptorSets)(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount, const VkDescriptorSet* pDescriptorSets);
+typedef void (VKAPI_PTR *PFN_vkUpdateDescriptorSets)(VkDevice device, uint32_t descriptorWriteCount, const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount, const VkCopyDescriptorSet* pDescriptorCopies);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateFramebuffer)(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer);
+typedef void (VKAPI_PTR *PFN_vkDestroyFramebuffer)(VkDevice device, VkFramebuffer framebuffer, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateRenderPass)(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass);
+typedef void (VKAPI_PTR *PFN_vkDestroyRenderPass)(VkDevice device, VkRenderPass renderPass, const VkAllocationCallbacks* pAllocator);
+typedef void (VKAPI_PTR *PFN_vkGetRenderAreaGranularity)(VkDevice device, VkRenderPass renderPass, VkExtent2D* pGranularity);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateCommandPool)(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool);
+typedef void (VKAPI_PTR *PFN_vkDestroyCommandPool)(VkDevice device, VkCommandPool commandPool, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkResetCommandPool)(VkDevice device, VkCommandPool commandPool, VkCommandPoolResetFlags flags);
+typedef VkResult (VKAPI_PTR *PFN_vkAllocateCommandBuffers)(VkDevice device, const VkCommandBufferAllocateInfo* pAllocateInfo, VkCommandBuffer* pCommandBuffers);
+typedef void (VKAPI_PTR *PFN_vkFreeCommandBuffers)(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers);
+typedef VkResult (VKAPI_PTR *PFN_vkBeginCommandBuffer)(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo* pBeginInfo);
+typedef VkResult (VKAPI_PTR *PFN_vkEndCommandBuffer)(VkCommandBuffer commandBuffer);
+typedef VkResult (VKAPI_PTR *PFN_vkResetCommandBuffer)(VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags);
+typedef void (VKAPI_PTR *PFN_vkCmdBindPipeline)(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline);
+typedef void (VKAPI_PTR *PFN_vkCmdSetViewport)(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewport* pViewports);
+typedef void (VKAPI_PTR *PFN_vkCmdSetScissor)(VkCommandBuffer commandBuffer, uint32_t firstScissor, uint32_t scissorCount, const VkRect2D* pScissors);
+typedef void (VKAPI_PTR *PFN_vkCmdSetLineWidth)(VkCommandBuffer commandBuffer, float lineWidth);
+typedef void (VKAPI_PTR *PFN_vkCmdSetDepthBias)(VkCommandBuffer commandBuffer, float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor);
+typedef void (VKAPI_PTR *PFN_vkCmdSetBlendConstants)(VkCommandBuffer commandBuffer, const float blendConstants[4]);
+typedef void (VKAPI_PTR *PFN_vkCmdSetDepthBounds)(VkCommandBuffer commandBuffer, float minDepthBounds, float maxDepthBounds);
+typedef void (VKAPI_PTR *PFN_vkCmdSetStencilCompareMask)(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t compareMask);
+typedef void (VKAPI_PTR *PFN_vkCmdSetStencilWriteMask)(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t writeMask);
+typedef void (VKAPI_PTR *PFN_vkCmdSetStencilReference)(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t reference);
+typedef void (VKAPI_PTR *PFN_vkCmdBindDescriptorSets)(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t firstSet, uint32_t descriptorSetCount, const VkDescriptorSet* pDescriptorSets, uint32_t dynamicOffsetCount, const uint32_t* pDynamicOffsets);
+typedef void (VKAPI_PTR *PFN_vkCmdBindIndexBuffer)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType indexType);
+typedef void (VKAPI_PTR *PFN_vkCmdBindVertexBuffers)(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer* pBuffers, const VkDeviceSize* pOffsets);
+typedef void (VKAPI_PTR *PFN_vkCmdDraw)(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance);
+typedef void (VKAPI_PTR *PFN_vkCmdDrawIndexed)(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance);
+typedef void (VKAPI_PTR *PFN_vkCmdDrawIndirect)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride);
+typedef void (VKAPI_PTR *PFN_vkCmdDrawIndexedIndirect)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride);
+typedef void (VKAPI_PTR *PFN_vkCmdDispatch)(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ);
+typedef void (VKAPI_PTR *PFN_vkCmdDispatchIndirect)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset);
+typedef void (VKAPI_PTR *PFN_vkCmdCopyBuffer)(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferCopy* pRegions);
+typedef void (VKAPI_PTR *PFN_vkCmdCopyImage)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageCopy* pRegions);
+typedef void (VKAPI_PTR *PFN_vkCmdBlitImage)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageBlit* pRegions, VkFilter filter);
+typedef void (VKAPI_PTR *PFN_vkCmdCopyBufferToImage)(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkBufferImageCopy* pRegions);
+typedef void (VKAPI_PTR *PFN_vkCmdCopyImageToBuffer)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions);
+typedef void (VKAPI_PTR *PFN_vkCmdUpdateBuffer)(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize dataSize, const void* pData);
+typedef void (VKAPI_PTR *PFN_vkCmdFillBuffer)(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize size, uint32_t data);
+typedef void (VKAPI_PTR *PFN_vkCmdClearColorImage)(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearColorValue* pColor, uint32_t rangeCount, const VkImageSubresourceRange* pRanges);
+typedef void (VKAPI_PTR *PFN_vkCmdClearDepthStencilImage)(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount, const VkImageSubresourceRange* pRanges);
+typedef void (VKAPI_PTR *PFN_vkCmdClearAttachments)(VkCommandBuffer commandBuffer, uint32_t attachmentCount, const VkClearAttachment* pAttachments, uint32_t rectCount, const VkClearRect* pRects);
+typedef void (VKAPI_PTR *PFN_vkCmdResolveImage)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageResolve* pRegions);
+typedef void (VKAPI_PTR *PFN_vkCmdSetEvent)(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask);
+typedef void (VKAPI_PTR *PFN_vkCmdResetEvent)(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask);
+typedef void (VKAPI_PTR *PFN_vkCmdWaitEvents)(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier* pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier* pImageMemoryBarriers);
+typedef void (VKAPI_PTR *PFN_vkCmdPipelineBarrier)(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier* pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier* pImageMemoryBarriers);
+typedef void (VKAPI_PTR *PFN_vkCmdBeginQuery)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query, VkQueryControlFlags flags);
+typedef void (VKAPI_PTR *PFN_vkCmdEndQuery)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query);
+typedef void (VKAPI_PTR *PFN_vkCmdResetQueryPool)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount);
+typedef void (VKAPI_PTR *PFN_vkCmdWriteTimestamp)(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkQueryPool queryPool, uint32_t query);
+typedef void (VKAPI_PTR *PFN_vkCmdCopyQueryPoolResults)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize stride, VkQueryResultFlags flags);
+typedef void (VKAPI_PTR *PFN_vkCmdPushConstants)(VkCommandBuffer commandBuffer, VkPipelineLayout layout, VkShaderStageFlags stageFlags, uint32_t offset, uint32_t size, const void* pValues);
+typedef void (VKAPI_PTR *PFN_vkCmdBeginRenderPass)(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin, VkSubpassContents contents);
+typedef void (VKAPI_PTR *PFN_vkCmdNextSubpass)(VkCommandBuffer commandBuffer, VkSubpassContents contents);
+typedef void (VKAPI_PTR *PFN_vkCmdEndRenderPass)(VkCommandBuffer commandBuffer);
+typedef void (VKAPI_PTR *PFN_vkCmdExecuteCommands)(VkCommandBuffer commandBuffer, uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateInstance(
+    const VkInstanceCreateInfo*                 pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkInstance*                                 pInstance);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyInstance(
+    VkInstance                                  instance,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkEnumeratePhysicalDevices(
+    VkInstance                                  instance,
+    uint32_t*                                   pPhysicalDeviceCount,
+    VkPhysicalDevice*                           pPhysicalDevices);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceFeatures(
+    VkPhysicalDevice                            physicalDevice,
+    VkPhysicalDeviceFeatures*                   pFeatures);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceFormatProperties(
+    VkPhysicalDevice                            physicalDevice,
+    VkFormat                                    format,
+    VkFormatProperties*                         pFormatProperties);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceImageFormatProperties(
+    VkPhysicalDevice                            physicalDevice,
+    VkFormat                                    format,
+    VkImageType                                 type,
+    VkImageTiling                               tiling,
+    VkImageUsageFlags                           usage,
+    VkImageCreateFlags                          flags,
+    VkImageFormatProperties*                    pImageFormatProperties);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceProperties(
+    VkPhysicalDevice                            physicalDevice,
+    VkPhysicalDeviceProperties*                 pProperties);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceQueueFamilyProperties(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t*                                   pQueueFamilyPropertyCount,
+    VkQueueFamilyProperties*                    pQueueFamilyProperties);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceMemoryProperties(
+    VkPhysicalDevice                            physicalDevice,
+    VkPhysicalDeviceMemoryProperties*           pMemoryProperties);
+
+VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(
+    VkInstance                                  instance,
+    const char*                                 pName);
+
+VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(
+    VkDevice                                    device,
+    const char*                                 pName);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateDevice(
+    VkPhysicalDevice                            physicalDevice,
+    const VkDeviceCreateInfo*                   pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkDevice*                                   pDevice);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyDevice(
+    VkDevice                                    device,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceExtensionProperties(
+    const char*                                 pLayerName,
+    uint32_t*                                   pPropertyCount,
+    VkExtensionProperties*                      pProperties);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceExtensionProperties(
+    VkPhysicalDevice                            physicalDevice,
+    const char*                                 pLayerName,
+    uint32_t*                                   pPropertyCount,
+    VkExtensionProperties*                      pProperties);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceLayerProperties(
+    uint32_t*                                   pPropertyCount,
+    VkLayerProperties*                          pProperties);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceLayerProperties(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t*                                   pPropertyCount,
+    VkLayerProperties*                          pProperties);
+
+VKAPI_ATTR void VKAPI_CALL vkGetDeviceQueue(
+    VkDevice                                    device,
+    uint32_t                                    queueFamilyIndex,
+    uint32_t                                    queueIndex,
+    VkQueue*                                    pQueue);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkQueueSubmit(
+    VkQueue                                     queue,
+    uint32_t                                    submitCount,
+    const VkSubmitInfo*                         pSubmits,
+    VkFence                                     fence);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkQueueWaitIdle(
+    VkQueue                                     queue);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkDeviceWaitIdle(
+    VkDevice                                    device);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkAllocateMemory(
+    VkDevice                                    device,
+    const VkMemoryAllocateInfo*                 pAllocateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkDeviceMemory*                             pMemory);
+
+VKAPI_ATTR void VKAPI_CALL vkFreeMemory(
+    VkDevice                                    device,
+    VkDeviceMemory                              memory,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkMapMemory(
+    VkDevice                                    device,
+    VkDeviceMemory                              memory,
+    VkDeviceSize                                offset,
+    VkDeviceSize                                size,
+    VkMemoryMapFlags                            flags,
+    void**                                      ppData);
+
+VKAPI_ATTR void VKAPI_CALL vkUnmapMemory(
+    VkDevice                                    device,
+    VkDeviceMemory                              memory);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkFlushMappedMemoryRanges(
+    VkDevice                                    device,
+    uint32_t                                    memoryRangeCount,
+    const VkMappedMemoryRange*                  pMemoryRanges);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkInvalidateMappedMemoryRanges(
+    VkDevice                                    device,
+    uint32_t                                    memoryRangeCount,
+    const VkMappedMemoryRange*                  pMemoryRanges);
+
+VKAPI_ATTR void VKAPI_CALL vkGetDeviceMemoryCommitment(
+    VkDevice                                    device,
+    VkDeviceMemory                              memory,
+    VkDeviceSize*                               pCommittedMemoryInBytes);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkBindBufferMemory(
+    VkDevice                                    device,
+    VkBuffer                                    buffer,
+    VkDeviceMemory                              memory,
+    VkDeviceSize                                memoryOffset);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkBindImageMemory(
+    VkDevice                                    device,
+    VkImage                                     image,
+    VkDeviceMemory                              memory,
+    VkDeviceSize                                memoryOffset);
+
+VKAPI_ATTR void VKAPI_CALL vkGetBufferMemoryRequirements(
+    VkDevice                                    device,
+    VkBuffer                                    buffer,
+    VkMemoryRequirements*                       pMemoryRequirements);
+
+VKAPI_ATTR void VKAPI_CALL vkGetImageMemoryRequirements(
+    VkDevice                                    device,
+    VkImage                                     image,
+    VkMemoryRequirements*                       pMemoryRequirements);
+
+VKAPI_ATTR void VKAPI_CALL vkGetImageSparseMemoryRequirements(
+    VkDevice                                    device,
+    VkImage                                     image,
+    uint32_t*                                   pSparseMemoryRequirementCount,
+    VkSparseImageMemoryRequirements*            pSparseMemoryRequirements);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceSparseImageFormatProperties(
+    VkPhysicalDevice                            physicalDevice,
+    VkFormat                                    format,
+    VkImageType                                 type,
+    VkSampleCountFlagBits                       samples,
+    VkImageUsageFlags                           usage,
+    VkImageTiling                               tiling,
+    uint32_t*                                   pPropertyCount,
+    VkSparseImageFormatProperties*              pProperties);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkQueueBindSparse(
+    VkQueue                                     queue,
+    uint32_t                                    bindInfoCount,
+    const VkBindSparseInfo*                     pBindInfo,
+    VkFence                                     fence);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateFence(
+    VkDevice                                    device,
+    const VkFenceCreateInfo*                    pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkFence*                                    pFence);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyFence(
+    VkDevice                                    device,
+    VkFence                                     fence,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkResetFences(
+    VkDevice                                    device,
+    uint32_t                                    fenceCount,
+    const VkFence*                              pFences);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetFenceStatus(
+    VkDevice                                    device,
+    VkFence                                     fence);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkWaitForFences(
+    VkDevice                                    device,
+    uint32_t                                    fenceCount,
+    const VkFence*                              pFences,
+    VkBool32                                    waitAll,
+    uint64_t                                    timeout);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateSemaphore(
+    VkDevice                                    device,
+    const VkSemaphoreCreateInfo*                pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSemaphore*                                pSemaphore);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroySemaphore(
+    VkDevice                                    device,
+    VkSemaphore                                 semaphore,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateEvent(
+    VkDevice                                    device,
+    const VkEventCreateInfo*                    pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkEvent*                                    pEvent);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyEvent(
+    VkDevice                                    device,
+    VkEvent                                     event,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetEventStatus(
+    VkDevice                                    device,
+    VkEvent                                     event);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkSetEvent(
+    VkDevice                                    device,
+    VkEvent                                     event);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkResetEvent(
+    VkDevice                                    device,
+    VkEvent                                     event);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateQueryPool(
+    VkDevice                                    device,
+    const VkQueryPoolCreateInfo*                pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkQueryPool*                                pQueryPool);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyQueryPool(
+    VkDevice                                    device,
+    VkQueryPool                                 queryPool,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetQueryPoolResults(
+    VkDevice                                    device,
+    VkQueryPool                                 queryPool,
+    uint32_t                                    firstQuery,
+    uint32_t                                    queryCount,
+    size_t                                      dataSize,
+    void*                                       pData,
+    VkDeviceSize                                stride,
+    VkQueryResultFlags                          flags);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateBuffer(
+    VkDevice                                    device,
+    const VkBufferCreateInfo*                   pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkBuffer*                                   pBuffer);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyBuffer(
+    VkDevice                                    device,
+    VkBuffer                                    buffer,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateBufferView(
+    VkDevice                                    device,
+    const VkBufferViewCreateInfo*               pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkBufferView*                               pView);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyBufferView(
+    VkDevice                                    device,
+    VkBufferView                                bufferView,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateImage(
+    VkDevice                                    device,
+    const VkImageCreateInfo*                    pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkImage*                                    pImage);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyImage(
+    VkDevice                                    device,
+    VkImage                                     image,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR void VKAPI_CALL vkGetImageSubresourceLayout(
+    VkDevice                                    device,
+    VkImage                                     image,
+    const VkImageSubresource*                   pSubresource,
+    VkSubresourceLayout*                        pLayout);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateImageView(
+    VkDevice                                    device,
+    const VkImageViewCreateInfo*                pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkImageView*                                pView);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyImageView(
+    VkDevice                                    device,
+    VkImageView                                 imageView,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateShaderModule(
+    VkDevice                                    device,
+    const VkShaderModuleCreateInfo*             pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkShaderModule*                             pShaderModule);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyShaderModule(
+    VkDevice                                    device,
+    VkShaderModule                              shaderModule,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreatePipelineCache(
+    VkDevice                                    device,
+    const VkPipelineCacheCreateInfo*            pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkPipelineCache*                            pPipelineCache);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyPipelineCache(
+    VkDevice                                    device,
+    VkPipelineCache                             pipelineCache,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPipelineCacheData(
+    VkDevice                                    device,
+    VkPipelineCache                             pipelineCache,
+    size_t*                                     pDataSize,
+    void*                                       pData);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkMergePipelineCaches(
+    VkDevice                                    device,
+    VkPipelineCache                             dstCache,
+    uint32_t                                    srcCacheCount,
+    const VkPipelineCache*                      pSrcCaches);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateGraphicsPipelines(
+    VkDevice                                    device,
+    VkPipelineCache                             pipelineCache,
+    uint32_t                                    createInfoCount,
+    const VkGraphicsPipelineCreateInfo*         pCreateInfos,
+    const VkAllocationCallbacks*                pAllocator,
+    VkPipeline*                                 pPipelines);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateComputePipelines(
+    VkDevice                                    device,
+    VkPipelineCache                             pipelineCache,
+    uint32_t                                    createInfoCount,
+    const VkComputePipelineCreateInfo*          pCreateInfos,
+    const VkAllocationCallbacks*                pAllocator,
+    VkPipeline*                                 pPipelines);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyPipeline(
+    VkDevice                                    device,
+    VkPipeline                                  pipeline,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreatePipelineLayout(
+    VkDevice                                    device,
+    const VkPipelineLayoutCreateInfo*           pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkPipelineLayout*                           pPipelineLayout);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyPipelineLayout(
+    VkDevice                                    device,
+    VkPipelineLayout                            pipelineLayout,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateSampler(
+    VkDevice                                    device,
+    const VkSamplerCreateInfo*                  pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSampler*                                  pSampler);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroySampler(
+    VkDevice                                    device,
+    VkSampler                                   sampler,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateDescriptorSetLayout(
+    VkDevice                                    device,
+    const VkDescriptorSetLayoutCreateInfo*      pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkDescriptorSetLayout*                      pSetLayout);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyDescriptorSetLayout(
+    VkDevice                                    device,
+    VkDescriptorSetLayout                       descriptorSetLayout,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateDescriptorPool(
+    VkDevice                                    device,
+    const VkDescriptorPoolCreateInfo*           pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkDescriptorPool*                           pDescriptorPool);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyDescriptorPool(
+    VkDevice                                    device,
+    VkDescriptorPool                            descriptorPool,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkResetDescriptorPool(
+    VkDevice                                    device,
+    VkDescriptorPool                            descriptorPool,
+    VkDescriptorPoolResetFlags                  flags);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkAllocateDescriptorSets(
+    VkDevice                                    device,
+    const VkDescriptorSetAllocateInfo*          pAllocateInfo,
+    VkDescriptorSet*                            pDescriptorSets);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkFreeDescriptorSets(
+    VkDevice                                    device,
+    VkDescriptorPool                            descriptorPool,
+    uint32_t                                    descriptorSetCount,
+    const VkDescriptorSet*                      pDescriptorSets);
+
+VKAPI_ATTR void VKAPI_CALL vkUpdateDescriptorSets(
+    VkDevice                                    device,
+    uint32_t                                    descriptorWriteCount,
+    const VkWriteDescriptorSet*                 pDescriptorWrites,
+    uint32_t                                    descriptorCopyCount,
+    const VkCopyDescriptorSet*                  pDescriptorCopies);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateFramebuffer(
+    VkDevice                                    device,
+    const VkFramebufferCreateInfo*              pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkFramebuffer*                              pFramebuffer);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyFramebuffer(
+    VkDevice                                    device,
+    VkFramebuffer                               framebuffer,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateRenderPass(
+    VkDevice                                    device,
+    const VkRenderPassCreateInfo*               pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkRenderPass*                               pRenderPass);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyRenderPass(
+    VkDevice                                    device,
+    VkRenderPass                                renderPass,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR void VKAPI_CALL vkGetRenderAreaGranularity(
+    VkDevice                                    device,
+    VkRenderPass                                renderPass,
+    VkExtent2D*                                 pGranularity);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateCommandPool(
+    VkDevice                                    device,
+    const VkCommandPoolCreateInfo*              pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkCommandPool*                              pCommandPool);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyCommandPool(
+    VkDevice                                    device,
+    VkCommandPool                               commandPool,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkResetCommandPool(
+    VkDevice                                    device,
+    VkCommandPool                               commandPool,
+    VkCommandPoolResetFlags                     flags);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkAllocateCommandBuffers(
+    VkDevice                                    device,
+    const VkCommandBufferAllocateInfo*          pAllocateInfo,
+    VkCommandBuffer*                            pCommandBuffers);
+
+VKAPI_ATTR void VKAPI_CALL vkFreeCommandBuffers(
+    VkDevice                                    device,
+    VkCommandPool                               commandPool,
+    uint32_t                                    commandBufferCount,
+    const VkCommandBuffer*                      pCommandBuffers);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkBeginCommandBuffer(
+    VkCommandBuffer                             commandBuffer,
+    const VkCommandBufferBeginInfo*             pBeginInfo);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkEndCommandBuffer(
+    VkCommandBuffer                             commandBuffer);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkResetCommandBuffer(
+    VkCommandBuffer                             commandBuffer,
+    VkCommandBufferResetFlags                   flags);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdBindPipeline(
+    VkCommandBuffer                             commandBuffer,
+    VkPipelineBindPoint                         pipelineBindPoint,
+    VkPipeline                                  pipeline);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetViewport(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    firstViewport,
+    uint32_t                                    viewportCount,
+    const VkViewport*                           pViewports);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetScissor(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    firstScissor,
+    uint32_t                                    scissorCount,
+    const VkRect2D*                             pScissors);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetLineWidth(
+    VkCommandBuffer                             commandBuffer,
+    float                                       lineWidth);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetDepthBias(
+    VkCommandBuffer                             commandBuffer,
+    float                                       depthBiasConstantFactor,
+    float                                       depthBiasClamp,
+    float                                       depthBiasSlopeFactor);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetBlendConstants(
+    VkCommandBuffer                             commandBuffer,
+    const float                                 blendConstants[4]);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetDepthBounds(
+    VkCommandBuffer                             commandBuffer,
+    float                                       minDepthBounds,
+    float                                       maxDepthBounds);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetStencilCompareMask(
+    VkCommandBuffer                             commandBuffer,
+    VkStencilFaceFlags                          faceMask,
+    uint32_t                                    compareMask);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetStencilWriteMask(
+    VkCommandBuffer                             commandBuffer,
+    VkStencilFaceFlags                          faceMask,
+    uint32_t                                    writeMask);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetStencilReference(
+    VkCommandBuffer                             commandBuffer,
+    VkStencilFaceFlags                          faceMask,
+    uint32_t                                    reference);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdBindDescriptorSets(
+    VkCommandBuffer                             commandBuffer,
+    VkPipelineBindPoint                         pipelineBindPoint,
+    VkPipelineLayout                            layout,
+    uint32_t                                    firstSet,
+    uint32_t                                    descriptorSetCount,
+    const VkDescriptorSet*                      pDescriptorSets,
+    uint32_t                                    dynamicOffsetCount,
+    const uint32_t*                             pDynamicOffsets);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdBindIndexBuffer(
+    VkCommandBuffer                             commandBuffer,
+    VkBuffer                                    buffer,
+    VkDeviceSize                                offset,
+    VkIndexType                                 indexType);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdBindVertexBuffers(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    firstBinding,
+    uint32_t                                    bindingCount,
+    const VkBuffer*                             pBuffers,
+    const VkDeviceSize*                         pOffsets);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDraw(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    vertexCount,
+    uint32_t                                    instanceCount,
+    uint32_t                                    firstVertex,
+    uint32_t                                    firstInstance);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndexed(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    indexCount,
+    uint32_t                                    instanceCount,
+    uint32_t                                    firstIndex,
+    int32_t                                     vertexOffset,
+    uint32_t                                    firstInstance);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndirect(
+    VkCommandBuffer                             commandBuffer,
+    VkBuffer                                    buffer,
+    VkDeviceSize                                offset,
+    uint32_t                                    drawCount,
+    uint32_t                                    stride);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndexedIndirect(
+    VkCommandBuffer                             commandBuffer,
+    VkBuffer                                    buffer,
+    VkDeviceSize                                offset,
+    uint32_t                                    drawCount,
+    uint32_t                                    stride);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDispatch(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    groupCountX,
+    uint32_t                                    groupCountY,
+    uint32_t                                    groupCountZ);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDispatchIndirect(
+    VkCommandBuffer                             commandBuffer,
+    VkBuffer                                    buffer,
+    VkDeviceSize                                offset);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdCopyBuffer(
+    VkCommandBuffer                             commandBuffer,
+    VkBuffer                                    srcBuffer,
+    VkBuffer                                    dstBuffer,
+    uint32_t                                    regionCount,
+    const VkBufferCopy*                         pRegions);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdCopyImage(
+    VkCommandBuffer                             commandBuffer,
+    VkImage                                     srcImage,
+    VkImageLayout                               srcImageLayout,
+    VkImage                                     dstImage,
+    VkImageLayout                               dstImageLayout,
+    uint32_t                                    regionCount,
+    const VkImageCopy*                          pRegions);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdBlitImage(
+    VkCommandBuffer                             commandBuffer,
+    VkImage                                     srcImage,
+    VkImageLayout                               srcImageLayout,
+    VkImage                                     dstImage,
+    VkImageLayout                               dstImageLayout,
+    uint32_t                                    regionCount,
+    const VkImageBlit*                          pRegions,
+    VkFilter                                    filter);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdCopyBufferToImage(
+    VkCommandBuffer                             commandBuffer,
+    VkBuffer                                    srcBuffer,
+    VkImage                                     dstImage,
+    VkImageLayout                               dstImageLayout,
+    uint32_t                                    regionCount,
+    const VkBufferImageCopy*                    pRegions);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdCopyImageToBuffer(
+    VkCommandBuffer                             commandBuffer,
+    VkImage                                     srcImage,
+    VkImageLayout                               srcImageLayout,
+    VkBuffer                                    dstBuffer,
+    uint32_t                                    regionCount,
+    const VkBufferImageCopy*                    pRegions);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdUpdateBuffer(
+    VkCommandBuffer                             commandBuffer,
+    VkBuffer                                    dstBuffer,
+    VkDeviceSize                                dstOffset,
+    VkDeviceSize                                dataSize,
+    const void*                                 pData);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdFillBuffer(
+    VkCommandBuffer                             commandBuffer,
+    VkBuffer                                    dstBuffer,
+    VkDeviceSize                                dstOffset,
+    VkDeviceSize                                size,
+    uint32_t                                    data);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdClearColorImage(
+    VkCommandBuffer                             commandBuffer,
+    VkImage                                     image,
+    VkImageLayout                               imageLayout,
+    const VkClearColorValue*                    pColor,
+    uint32_t                                    rangeCount,
+    const VkImageSubresourceRange*              pRanges);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdClearDepthStencilImage(
+    VkCommandBuffer                             commandBuffer,
+    VkImage                                     image,
+    VkImageLayout                               imageLayout,
+    const VkClearDepthStencilValue*             pDepthStencil,
+    uint32_t                                    rangeCount,
+    const VkImageSubresourceRange*              pRanges);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdClearAttachments(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    attachmentCount,
+    const VkClearAttachment*                    pAttachments,
+    uint32_t                                    rectCount,
+    const VkClearRect*                          pRects);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdResolveImage(
+    VkCommandBuffer                             commandBuffer,
+    VkImage                                     srcImage,
+    VkImageLayout                               srcImageLayout,
+    VkImage                                     dstImage,
+    VkImageLayout                               dstImageLayout,
+    uint32_t                                    regionCount,
+    const VkImageResolve*                       pRegions);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetEvent(
+    VkCommandBuffer                             commandBuffer,
+    VkEvent                                     event,
+    VkPipelineStageFlags                        stageMask);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdResetEvent(
+    VkCommandBuffer                             commandBuffer,
+    VkEvent                                     event,
+    VkPipelineStageFlags                        stageMask);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdWaitEvents(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    eventCount,
+    const VkEvent*                              pEvents,
+    VkPipelineStageFlags                        srcStageMask,
+    VkPipelineStageFlags                        dstStageMask,
+    uint32_t                                    memoryBarrierCount,
+    const VkMemoryBarrier*                      pMemoryBarriers,
+    uint32_t                                    bufferMemoryBarrierCount,
+    const VkBufferMemoryBarrier*                pBufferMemoryBarriers,
+    uint32_t                                    imageMemoryBarrierCount,
+    const VkImageMemoryBarrier*                 pImageMemoryBarriers);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdPipelineBarrier(
+    VkCommandBuffer                             commandBuffer,
+    VkPipelineStageFlags                        srcStageMask,
+    VkPipelineStageFlags                        dstStageMask,
+    VkDependencyFlags                           dependencyFlags,
+    uint32_t                                    memoryBarrierCount,
+    const VkMemoryBarrier*                      pMemoryBarriers,
+    uint32_t                                    bufferMemoryBarrierCount,
+    const VkBufferMemoryBarrier*                pBufferMemoryBarriers,
+    uint32_t                                    imageMemoryBarrierCount,
+    const VkImageMemoryBarrier*                 pImageMemoryBarriers);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdBeginQuery(
+    VkCommandBuffer                             commandBuffer,
+    VkQueryPool                                 queryPool,
+    uint32_t                                    query,
+    VkQueryControlFlags                         flags);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdEndQuery(
+    VkCommandBuffer                             commandBuffer,
+    VkQueryPool                                 queryPool,
+    uint32_t                                    query);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdResetQueryPool(
+    VkCommandBuffer                             commandBuffer,
+    VkQueryPool                                 queryPool,
+    uint32_t                                    firstQuery,
+    uint32_t                                    queryCount);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdWriteTimestamp(
+    VkCommandBuffer                             commandBuffer,
+    VkPipelineStageFlagBits                     pipelineStage,
+    VkQueryPool                                 queryPool,
+    uint32_t                                    query);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdCopyQueryPoolResults(
+    VkCommandBuffer                             commandBuffer,
+    VkQueryPool                                 queryPool,
+    uint32_t                                    firstQuery,
+    uint32_t                                    queryCount,
+    VkBuffer                                    dstBuffer,
+    VkDeviceSize                                dstOffset,
+    VkDeviceSize                                stride,
+    VkQueryResultFlags                          flags);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdPushConstants(
+    VkCommandBuffer                             commandBuffer,
+    VkPipelineLayout                            layout,
+    VkShaderStageFlags                          stageFlags,
+    uint32_t                                    offset,
+    uint32_t                                    size,
+    const void*                                 pValues);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdBeginRenderPass(
+    VkCommandBuffer                             commandBuffer,
+    const VkRenderPassBeginInfo*                pRenderPassBegin,
+    VkSubpassContents                           contents);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdNextSubpass(
+    VkCommandBuffer                             commandBuffer,
+    VkSubpassContents                           contents);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdEndRenderPass(
+    VkCommandBuffer                             commandBuffer);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdExecuteCommands(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    commandBufferCount,
+    const VkCommandBuffer*                      pCommandBuffers);
+#endif
+
+#define VK_KHR_surface 1
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR)
+
+#define VK_KHR_SURFACE_SPEC_VERSION       25
+#define VK_KHR_SURFACE_EXTENSION_NAME     "VK_KHR_surface"
+#define VK_COLORSPACE_SRGB_NONLINEAR_KHR  VK_COLOR_SPACE_SRGB_NONLINEAR_KHR
+
+
+typedef enum VkColorSpaceKHR {
+    VK_COLOR_SPACE_SRGB_NONLINEAR_KHR = 0,
+    VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT = 1000104001,
+    VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT = 1000104002,
+    VK_COLOR_SPACE_DCI_P3_LINEAR_EXT = 1000104003,
+    VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT = 1000104004,
+    VK_COLOR_SPACE_BT709_LINEAR_EXT = 1000104005,
+    VK_COLOR_SPACE_BT709_NONLINEAR_EXT = 1000104006,
+    VK_COLOR_SPACE_BT2020_LINEAR_EXT = 1000104007,
+    VK_COLOR_SPACE_HDR10_ST2084_EXT = 1000104008,
+    VK_COLOR_SPACE_DOLBYVISION_EXT = 1000104009,
+    VK_COLOR_SPACE_HDR10_HLG_EXT = 1000104010,
+    VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT = 1000104011,
+    VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT = 1000104012,
+    VK_COLOR_SPACE_PASS_THROUGH_EXT = 1000104013,
+    VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT = 1000104014,
+    VK_COLOR_SPACE_BEGIN_RANGE_KHR = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR,
+    VK_COLOR_SPACE_END_RANGE_KHR = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR,
+    VK_COLOR_SPACE_RANGE_SIZE_KHR = (VK_COLOR_SPACE_SRGB_NONLINEAR_KHR - VK_COLOR_SPACE_SRGB_NONLINEAR_KHR + 1),
+    VK_COLOR_SPACE_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkColorSpaceKHR;
+
+typedef enum VkPresentModeKHR {
+    VK_PRESENT_MODE_IMMEDIATE_KHR = 0,
+    VK_PRESENT_MODE_MAILBOX_KHR = 1,
+    VK_PRESENT_MODE_FIFO_KHR = 2,
+    VK_PRESENT_MODE_FIFO_RELAXED_KHR = 3,
+    VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR = 1000111000,
+    VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR = 1000111001,
+    VK_PRESENT_MODE_BEGIN_RANGE_KHR = VK_PRESENT_MODE_IMMEDIATE_KHR,
+    VK_PRESENT_MODE_END_RANGE_KHR = VK_PRESENT_MODE_FIFO_RELAXED_KHR,
+    VK_PRESENT_MODE_RANGE_SIZE_KHR = (VK_PRESENT_MODE_FIFO_RELAXED_KHR - VK_PRESENT_MODE_IMMEDIATE_KHR + 1),
+    VK_PRESENT_MODE_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkPresentModeKHR;
+
+
+typedef enum VkSurfaceTransformFlagBitsKHR {
+    VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR = 0x00000001,
+    VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR = 0x00000002,
+    VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR = 0x00000004,
+    VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR = 0x00000008,
+    VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR = 0x00000010,
+    VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR = 0x00000020,
+    VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR = 0x00000040,
+    VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR = 0x00000080,
+    VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR = 0x00000100,
+    VK_SURFACE_TRANSFORM_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkSurfaceTransformFlagBitsKHR;
+typedef VkFlags VkSurfaceTransformFlagsKHR;
+
+typedef enum VkCompositeAlphaFlagBitsKHR {
+    VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR = 0x00000001,
+    VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR = 0x00000002,
+    VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR = 0x00000004,
+    VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR = 0x00000008,
+    VK_COMPOSITE_ALPHA_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkCompositeAlphaFlagBitsKHR;
+typedef VkFlags VkCompositeAlphaFlagsKHR;
+
+typedef struct VkSurfaceCapabilitiesKHR {
+    uint32_t                         minImageCount;
+    uint32_t                         maxImageCount;
+    VkExtent2D                       currentExtent;
+    VkExtent2D                       minImageExtent;
+    VkExtent2D                       maxImageExtent;
+    uint32_t                         maxImageArrayLayers;
+    VkSurfaceTransformFlagsKHR       supportedTransforms;
+    VkSurfaceTransformFlagBitsKHR    currentTransform;
+    VkCompositeAlphaFlagsKHR         supportedCompositeAlpha;
+    VkImageUsageFlags                supportedUsageFlags;
+} VkSurfaceCapabilitiesKHR;
+
+typedef struct VkSurfaceFormatKHR {
+    VkFormat           format;
+    VkColorSpaceKHR    colorSpace;
+} VkSurfaceFormatKHR;
+
+
+typedef void (VKAPI_PTR *PFN_vkDestroySurfaceKHR)(VkInstance instance, VkSurfaceKHR surface, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceSupportKHR)(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, VkSurfaceKHR surface, VkBool32* pSupported);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkSurfaceCapabilitiesKHR* pSurfaceCapabilities);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pSurfaceFormatCount, VkSurfaceFormatKHR* pSurfaceFormats);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pPresentModeCount, VkPresentModeKHR* pPresentModes);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkDestroySurfaceKHR(
+    VkInstance                                  instance,
+    VkSurfaceKHR                                surface,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceSupportKHR(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t                                    queueFamilyIndex,
+    VkSurfaceKHR                                surface,
+    VkBool32*                                   pSupported);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
+    VkPhysicalDevice                            physicalDevice,
+    VkSurfaceKHR                                surface,
+    VkSurfaceCapabilitiesKHR*                   pSurfaceCapabilities);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceFormatsKHR(
+    VkPhysicalDevice                            physicalDevice,
+    VkSurfaceKHR                                surface,
+    uint32_t*                                   pSurfaceFormatCount,
+    VkSurfaceFormatKHR*                         pSurfaceFormats);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfacePresentModesKHR(
+    VkPhysicalDevice                            physicalDevice,
+    VkSurfaceKHR                                surface,
+    uint32_t*                                   pPresentModeCount,
+    VkPresentModeKHR*                           pPresentModes);
+#endif
+
+#define VK_KHR_swapchain 1
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSwapchainKHR)
+
+#define VK_KHR_SWAPCHAIN_SPEC_VERSION     68
+#define VK_KHR_SWAPCHAIN_EXTENSION_NAME   "VK_KHR_swapchain"
+
+
+typedef enum VkSwapchainCreateFlagBitsKHR {
+    VK_SWAPCHAIN_CREATE_BIND_SFR_BIT_KHX = 0x00000001,
+    VK_SWAPCHAIN_CREATE_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkSwapchainCreateFlagBitsKHR;
+typedef VkFlags VkSwapchainCreateFlagsKHR;
+
+typedef struct VkSwapchainCreateInfoKHR {
+    VkStructureType                  sType;
+    const void*                      pNext;
+    VkSwapchainCreateFlagsKHR        flags;
+    VkSurfaceKHR                     surface;
+    uint32_t                         minImageCount;
+    VkFormat                         imageFormat;
+    VkColorSpaceKHR                  imageColorSpace;
+    VkExtent2D                       imageExtent;
+    uint32_t                         imageArrayLayers;
+    VkImageUsageFlags                imageUsage;
+    VkSharingMode                    imageSharingMode;
+    uint32_t                         queueFamilyIndexCount;
+    const uint32_t*                  pQueueFamilyIndices;
+    VkSurfaceTransformFlagBitsKHR    preTransform;
+    VkCompositeAlphaFlagBitsKHR      compositeAlpha;
+    VkPresentModeKHR                 presentMode;
+    VkBool32                         clipped;
+    VkSwapchainKHR                   oldSwapchain;
+} VkSwapchainCreateInfoKHR;
+
+typedef struct VkPresentInfoKHR {
+    VkStructureType          sType;
+    const void*              pNext;
+    uint32_t                 waitSemaphoreCount;
+    const VkSemaphore*       pWaitSemaphores;
+    uint32_t                 swapchainCount;
+    const VkSwapchainKHR*    pSwapchains;
+    const uint32_t*          pImageIndices;
+    VkResult*                pResults;
+} VkPresentInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateSwapchainKHR)(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain);
+typedef void (VKAPI_PTR *PFN_vkDestroySwapchainKHR)(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkGetSwapchainImagesKHR)(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages);
+typedef VkResult (VKAPI_PTR *PFN_vkAcquireNextImageKHR)(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex);
+typedef VkResult (VKAPI_PTR *PFN_vkQueuePresentKHR)(VkQueue queue, const VkPresentInfoKHR* pPresentInfo);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateSwapchainKHR(
+    VkDevice                                    device,
+    const VkSwapchainCreateInfoKHR*             pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSwapchainKHR*                             pSwapchain);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroySwapchainKHR(
+    VkDevice                                    device,
+    VkSwapchainKHR                              swapchain,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetSwapchainImagesKHR(
+    VkDevice                                    device,
+    VkSwapchainKHR                              swapchain,
+    uint32_t*                                   pSwapchainImageCount,
+    VkImage*                                    pSwapchainImages);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImageKHR(
+    VkDevice                                    device,
+    VkSwapchainKHR                              swapchain,
+    uint64_t                                    timeout,
+    VkSemaphore                                 semaphore,
+    VkFence                                     fence,
+    uint32_t*                                   pImageIndex);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkQueuePresentKHR(
+    VkQueue                                     queue,
+    const VkPresentInfoKHR*                     pPresentInfo);
+#endif
+
+#define VK_KHR_display 1
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDisplayKHR)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDisplayModeKHR)
+
+#define VK_KHR_DISPLAY_SPEC_VERSION       21
+#define VK_KHR_DISPLAY_EXTENSION_NAME     "VK_KHR_display"
+
+
+typedef enum VkDisplayPlaneAlphaFlagBitsKHR {
+    VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR = 0x00000001,
+    VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR = 0x00000002,
+    VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR = 0x00000004,
+    VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR = 0x00000008,
+    VK_DISPLAY_PLANE_ALPHA_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkDisplayPlaneAlphaFlagBitsKHR;
+typedef VkFlags VkDisplayPlaneAlphaFlagsKHR;
+typedef VkFlags VkDisplayModeCreateFlagsKHR;
+typedef VkFlags VkDisplaySurfaceCreateFlagsKHR;
+
+typedef struct VkDisplayPropertiesKHR {
+    VkDisplayKHR                  display;
+    const char*                   displayName;
+    VkExtent2D                    physicalDimensions;
+    VkExtent2D                    physicalResolution;
+    VkSurfaceTransformFlagsKHR    supportedTransforms;
+    VkBool32                      planeReorderPossible;
+    VkBool32                      persistentContent;
+} VkDisplayPropertiesKHR;
+
+typedef struct VkDisplayModeParametersKHR {
+    VkExtent2D    visibleRegion;
+    uint32_t      refreshRate;
+} VkDisplayModeParametersKHR;
+
+typedef struct VkDisplayModePropertiesKHR {
+    VkDisplayModeKHR              displayMode;
+    VkDisplayModeParametersKHR    parameters;
+} VkDisplayModePropertiesKHR;
+
+typedef struct VkDisplayModeCreateInfoKHR {
+    VkStructureType                sType;
+    const void*                    pNext;
+    VkDisplayModeCreateFlagsKHR    flags;
+    VkDisplayModeParametersKHR     parameters;
+} VkDisplayModeCreateInfoKHR;
+
+typedef struct VkDisplayPlaneCapabilitiesKHR {
+    VkDisplayPlaneAlphaFlagsKHR    supportedAlpha;
+    VkOffset2D                     minSrcPosition;
+    VkOffset2D                     maxSrcPosition;
+    VkExtent2D                     minSrcExtent;
+    VkExtent2D                     maxSrcExtent;
+    VkOffset2D                     minDstPosition;
+    VkOffset2D                     maxDstPosition;
+    VkExtent2D                     minDstExtent;
+    VkExtent2D                     maxDstExtent;
+} VkDisplayPlaneCapabilitiesKHR;
+
+typedef struct VkDisplayPlanePropertiesKHR {
+    VkDisplayKHR    currentDisplay;
+    uint32_t        currentStackIndex;
+} VkDisplayPlanePropertiesKHR;
+
+typedef struct VkDisplaySurfaceCreateInfoKHR {
+    VkStructureType                   sType;
+    const void*                       pNext;
+    VkDisplaySurfaceCreateFlagsKHR    flags;
+    VkDisplayModeKHR                  displayMode;
+    uint32_t                          planeIndex;
+    uint32_t                          planeStackIndex;
+    VkSurfaceTransformFlagBitsKHR     transform;
+    float                             globalAlpha;
+    VkDisplayPlaneAlphaFlagBitsKHR    alphaMode;
+    VkExtent2D                        imageExtent;
+} VkDisplaySurfaceCreateInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceDisplayPropertiesKHR)(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkDisplayPropertiesKHR* pProperties);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR)(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkDisplayPlanePropertiesKHR* pProperties);
+typedef VkResult (VKAPI_PTR *PFN_vkGetDisplayPlaneSupportedDisplaysKHR)(VkPhysicalDevice physicalDevice, uint32_t planeIndex, uint32_t* pDisplayCount, VkDisplayKHR* pDisplays);
+typedef VkResult (VKAPI_PTR *PFN_vkGetDisplayModePropertiesKHR)(VkPhysicalDevice physicalDevice, VkDisplayKHR display, uint32_t* pPropertyCount, VkDisplayModePropertiesKHR* pProperties);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateDisplayModeKHR)(VkPhysicalDevice physicalDevice, VkDisplayKHR display, const VkDisplayModeCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDisplayModeKHR* pMode);
+typedef VkResult (VKAPI_PTR *PFN_vkGetDisplayPlaneCapabilitiesKHR)(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode, uint32_t planeIndex, VkDisplayPlaneCapabilitiesKHR* pCapabilities);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateDisplayPlaneSurfaceKHR)(VkInstance instance, const VkDisplaySurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceDisplayPropertiesKHR(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t*                                   pPropertyCount,
+    VkDisplayPropertiesKHR*                     pProperties);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceDisplayPlanePropertiesKHR(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t*                                   pPropertyCount,
+    VkDisplayPlanePropertiesKHR*                pProperties);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetDisplayPlaneSupportedDisplaysKHR(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t                                    planeIndex,
+    uint32_t*                                   pDisplayCount,
+    VkDisplayKHR*                               pDisplays);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetDisplayModePropertiesKHR(
+    VkPhysicalDevice                            physicalDevice,
+    VkDisplayKHR                                display,
+    uint32_t*                                   pPropertyCount,
+    VkDisplayModePropertiesKHR*                 pProperties);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateDisplayModeKHR(
+    VkPhysicalDevice                            physicalDevice,
+    VkDisplayKHR                                display,
+    const VkDisplayModeCreateInfoKHR*           pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkDisplayModeKHR*                           pMode);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetDisplayPlaneCapabilitiesKHR(
+    VkPhysicalDevice                            physicalDevice,
+    VkDisplayModeKHR                            mode,
+    uint32_t                                    planeIndex,
+    VkDisplayPlaneCapabilitiesKHR*              pCapabilities);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateDisplayPlaneSurfaceKHR(
+    VkInstance                                  instance,
+    const VkDisplaySurfaceCreateInfoKHR*        pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSurfaceKHR*                               pSurface);
+#endif
+
+#define VK_KHR_display_swapchain 1
+#define VK_KHR_DISPLAY_SWAPCHAIN_SPEC_VERSION 9
+#define VK_KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME "VK_KHR_display_swapchain"
+
+typedef struct VkDisplayPresentInfoKHR {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkRect2D           srcRect;
+    VkRect2D           dstRect;
+    VkBool32           persistent;
+} VkDisplayPresentInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateSharedSwapchainsKHR)(VkDevice device, uint32_t swapchainCount, const VkSwapchainCreateInfoKHR* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchains);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateSharedSwapchainsKHR(
+    VkDevice                                    device,
+    uint32_t                                    swapchainCount,
+    const VkSwapchainCreateInfoKHR*             pCreateInfos,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSwapchainKHR*                             pSwapchains);
+#endif
+
+#ifdef VK_USE_PLATFORM_XLIB_KHR
+#define VK_KHR_xlib_surface 1
+#include <X11/Xlib.h>
+
+#define VK_KHR_XLIB_SURFACE_SPEC_VERSION  6
+#define VK_KHR_XLIB_SURFACE_EXTENSION_NAME "VK_KHR_xlib_surface"
+
+typedef VkFlags VkXlibSurfaceCreateFlagsKHR;
+
+typedef struct VkXlibSurfaceCreateInfoKHR {
+    VkStructureType                sType;
+    const void*                    pNext;
+    VkXlibSurfaceCreateFlagsKHR    flags;
+    Display*                       dpy;
+    Window                         window;
+} VkXlibSurfaceCreateInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateXlibSurfaceKHR)(VkInstance instance, const VkXlibSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);
+typedef VkBool32 (VKAPI_PTR *PFN_vkGetPhysicalDeviceXlibPresentationSupportKHR)(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, Display* dpy, VisualID visualID);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateXlibSurfaceKHR(
+    VkInstance                                  instance,
+    const VkXlibSurfaceCreateInfoKHR*           pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSurfaceKHR*                               pSurface);
+
+VKAPI_ATTR VkBool32 VKAPI_CALL vkGetPhysicalDeviceXlibPresentationSupportKHR(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t                                    queueFamilyIndex,
+    Display*                                    dpy,
+    VisualID                                    visualID);
+#endif
+#endif /* VK_USE_PLATFORM_XLIB_KHR */
+
+#ifdef VK_USE_PLATFORM_XCB_KHR
+#define VK_KHR_xcb_surface 1
+#include <xcb/xcb.h>
+
+#define VK_KHR_XCB_SURFACE_SPEC_VERSION   6
+#define VK_KHR_XCB_SURFACE_EXTENSION_NAME "VK_KHR_xcb_surface"
+
+typedef VkFlags VkXcbSurfaceCreateFlagsKHR;
+
+typedef struct VkXcbSurfaceCreateInfoKHR {
+    VkStructureType               sType;
+    const void*                   pNext;
+    VkXcbSurfaceCreateFlagsKHR    flags;
+    xcb_connection_t*             connection;
+    xcb_window_t                  window;
+} VkXcbSurfaceCreateInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateXcbSurfaceKHR)(VkInstance instance, const VkXcbSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);
+typedef VkBool32 (VKAPI_PTR *PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR)(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, xcb_connection_t* connection, xcb_visualid_t visual_id);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateXcbSurfaceKHR(
+    VkInstance                                  instance,
+    const VkXcbSurfaceCreateInfoKHR*            pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSurfaceKHR*                               pSurface);
+
+VKAPI_ATTR VkBool32 VKAPI_CALL vkGetPhysicalDeviceXcbPresentationSupportKHR(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t                                    queueFamilyIndex,
+    xcb_connection_t*                           connection,
+    xcb_visualid_t                              visual_id);
+#endif
+#endif /* VK_USE_PLATFORM_XCB_KHR */
+
+#ifdef VK_USE_PLATFORM_WAYLAND_KHR
+#define VK_KHR_wayland_surface 1
+#include <wayland-client.h>
+
+#define VK_KHR_WAYLAND_SURFACE_SPEC_VERSION 6
+#define VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME "VK_KHR_wayland_surface"
+
+typedef VkFlags VkWaylandSurfaceCreateFlagsKHR;
+
+typedef struct VkWaylandSurfaceCreateInfoKHR {
+    VkStructureType                   sType;
+    const void*                       pNext;
+    VkWaylandSurfaceCreateFlagsKHR    flags;
+    struct wl_display*                display;
+    struct wl_surface*                surface;
+} VkWaylandSurfaceCreateInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateWaylandSurfaceKHR)(VkInstance instance, const VkWaylandSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);
+typedef VkBool32 (VKAPI_PTR *PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR)(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, struct wl_display* display);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateWaylandSurfaceKHR(
+    VkInstance                                  instance,
+    const VkWaylandSurfaceCreateInfoKHR*        pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSurfaceKHR*                               pSurface);
+
+VKAPI_ATTR VkBool32 VKAPI_CALL vkGetPhysicalDeviceWaylandPresentationSupportKHR(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t                                    queueFamilyIndex,
+    struct wl_display*                          display);
+#endif
+#endif /* VK_USE_PLATFORM_WAYLAND_KHR */
+
+#ifdef VK_USE_PLATFORM_MIR_KHR
+#define VK_KHR_mir_surface 1
+#include <mir_toolkit/client_types.h>
+
+#define VK_KHR_MIR_SURFACE_SPEC_VERSION   4
+#define VK_KHR_MIR_SURFACE_EXTENSION_NAME "VK_KHR_mir_surface"
+
+typedef VkFlags VkMirSurfaceCreateFlagsKHR;
+
+typedef struct VkMirSurfaceCreateInfoKHR {
+    VkStructureType               sType;
+    const void*                   pNext;
+    VkMirSurfaceCreateFlagsKHR    flags;
+    MirConnection*                connection;
+    MirSurface*                   mirSurface;
+} VkMirSurfaceCreateInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateMirSurfaceKHR)(VkInstance instance, const VkMirSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);
+typedef VkBool32 (VKAPI_PTR *PFN_vkGetPhysicalDeviceMirPresentationSupportKHR)(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, MirConnection* connection);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateMirSurfaceKHR(
+    VkInstance                                  instance,
+    const VkMirSurfaceCreateInfoKHR*            pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSurfaceKHR*                               pSurface);
+
+VKAPI_ATTR VkBool32 VKAPI_CALL vkGetPhysicalDeviceMirPresentationSupportKHR(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t                                    queueFamilyIndex,
+    MirConnection*                              connection);
+#endif
+#endif /* VK_USE_PLATFORM_MIR_KHR */
+
+#ifdef VK_USE_PLATFORM_ANDROID_KHR
+#define VK_KHR_android_surface 1
+#include <android/native_window.h>
+
+#define VK_KHR_ANDROID_SURFACE_SPEC_VERSION 6
+#define VK_KHR_ANDROID_SURFACE_EXTENSION_NAME "VK_KHR_android_surface"
+
+typedef VkFlags VkAndroidSurfaceCreateFlagsKHR;
+
+typedef struct VkAndroidSurfaceCreateInfoKHR {
+    VkStructureType                   sType;
+    const void*                       pNext;
+    VkAndroidSurfaceCreateFlagsKHR    flags;
+    ANativeWindow*                    window;
+} VkAndroidSurfaceCreateInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateAndroidSurfaceKHR)(VkInstance instance, const VkAndroidSurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateAndroidSurfaceKHR(
+    VkInstance                                  instance,
+    const VkAndroidSurfaceCreateInfoKHR*        pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSurfaceKHR*                               pSurface);
+#endif
+#endif /* VK_USE_PLATFORM_ANDROID_KHR */
+
+#ifdef VK_USE_PLATFORM_WIN32_KHR
+#define VK_KHR_win32_surface 1
+#include <windows.h>
+
+#define VK_KHR_WIN32_SURFACE_SPEC_VERSION 6
+#define VK_KHR_WIN32_SURFACE_EXTENSION_NAME "VK_KHR_win32_surface"
+
+typedef VkFlags VkWin32SurfaceCreateFlagsKHR;
+
+typedef struct VkWin32SurfaceCreateInfoKHR {
+    VkStructureType                 sType;
+    const void*                     pNext;
+    VkWin32SurfaceCreateFlagsKHR    flags;
+    HINSTANCE                       hinstance;
+    HWND                            hwnd;
+} VkWin32SurfaceCreateInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateWin32SurfaceKHR)(VkInstance instance, const VkWin32SurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);
+typedef VkBool32 (VKAPI_PTR *PFN_vkGetPhysicalDeviceWin32PresentationSupportKHR)(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateWin32SurfaceKHR(
+    VkInstance                                  instance,
+    const VkWin32SurfaceCreateInfoKHR*          pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSurfaceKHR*                               pSurface);
+
+VKAPI_ATTR VkBool32 VKAPI_CALL vkGetPhysicalDeviceWin32PresentationSupportKHR(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t                                    queueFamilyIndex);
+#endif
+#endif /* VK_USE_PLATFORM_WIN32_KHR */
+
+#define VK_KHR_sampler_mirror_clamp_to_edge 1
+#define VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_SPEC_VERSION 1
+#define VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME "VK_KHR_sampler_mirror_clamp_to_edge"
+
+
+#define VK_KHR_get_physical_device_properties2 1
+#define VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_SPEC_VERSION 1
+#define VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME "VK_KHR_get_physical_device_properties2"
+
+typedef struct VkPhysicalDeviceFeatures2KHR {
+    VkStructureType             sType;
+    void*                       pNext;
+    VkPhysicalDeviceFeatures    features;
+} VkPhysicalDeviceFeatures2KHR;
+
+typedef struct VkPhysicalDeviceProperties2KHR {
+    VkStructureType               sType;
+    void*                         pNext;
+    VkPhysicalDeviceProperties    properties;
+} VkPhysicalDeviceProperties2KHR;
+
+typedef struct VkFormatProperties2KHR {
+    VkStructureType       sType;
+    void*                 pNext;
+    VkFormatProperties    formatProperties;
+} VkFormatProperties2KHR;
+
+typedef struct VkImageFormatProperties2KHR {
+    VkStructureType            sType;
+    void*                      pNext;
+    VkImageFormatProperties    imageFormatProperties;
+} VkImageFormatProperties2KHR;
+
+typedef struct VkPhysicalDeviceImageFormatInfo2KHR {
+    VkStructureType       sType;
+    const void*           pNext;
+    VkFormat              format;
+    VkImageType           type;
+    VkImageTiling         tiling;
+    VkImageUsageFlags     usage;
+    VkImageCreateFlags    flags;
+} VkPhysicalDeviceImageFormatInfo2KHR;
+
+typedef struct VkQueueFamilyProperties2KHR {
+    VkStructureType            sType;
+    void*                      pNext;
+    VkQueueFamilyProperties    queueFamilyProperties;
+} VkQueueFamilyProperties2KHR;
+
+typedef struct VkPhysicalDeviceMemoryProperties2KHR {
+    VkStructureType                     sType;
+    void*                               pNext;
+    VkPhysicalDeviceMemoryProperties    memoryProperties;
+} VkPhysicalDeviceMemoryProperties2KHR;
+
+typedef struct VkSparseImageFormatProperties2KHR {
+    VkStructureType                  sType;
+    void*                            pNext;
+    VkSparseImageFormatProperties    properties;
+} VkSparseImageFormatProperties2KHR;
+
+typedef struct VkPhysicalDeviceSparseImageFormatInfo2KHR {
+    VkStructureType          sType;
+    const void*              pNext;
+    VkFormat                 format;
+    VkImageType              type;
+    VkSampleCountFlagBits    samples;
+    VkImageUsageFlags        usage;
+    VkImageTiling            tiling;
+} VkPhysicalDeviceSparseImageFormatInfo2KHR;
+
+
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceFeatures2KHR)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures2KHR* pFeatures);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceProperties2KHR)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties2KHR* pProperties);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceFormatProperties2KHR)(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties2KHR* pFormatProperties);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceImageFormatProperties2KHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceImageFormatInfo2KHR* pImageFormatInfo, VkImageFormatProperties2KHR* pImageFormatProperties);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR)(VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2KHR* pQueueFamilyProperties);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceMemoryProperties2KHR)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties2KHR* pMemoryProperties);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceSparseImageFormatProperties2KHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSparseImageFormatInfo2KHR* pFormatInfo, uint32_t* pPropertyCount, VkSparseImageFormatProperties2KHR* pProperties);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceFeatures2KHR(
+    VkPhysicalDevice                            physicalDevice,
+    VkPhysicalDeviceFeatures2KHR*               pFeatures);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceProperties2KHR(
+    VkPhysicalDevice                            physicalDevice,
+    VkPhysicalDeviceProperties2KHR*             pProperties);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceFormatProperties2KHR(
+    VkPhysicalDevice                            physicalDevice,
+    VkFormat                                    format,
+    VkFormatProperties2KHR*                     pFormatProperties);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceImageFormatProperties2KHR(
+    VkPhysicalDevice                            physicalDevice,
+    const VkPhysicalDeviceImageFormatInfo2KHR*  pImageFormatInfo,
+    VkImageFormatProperties2KHR*                pImageFormatProperties);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceQueueFamilyProperties2KHR(
+    VkPhysicalDevice                            physicalDevice,
+    uint32_t*                                   pQueueFamilyPropertyCount,
+    VkQueueFamilyProperties2KHR*                pQueueFamilyProperties);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceMemoryProperties2KHR(
+    VkPhysicalDevice                            physicalDevice,
+    VkPhysicalDeviceMemoryProperties2KHR*       pMemoryProperties);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceSparseImageFormatProperties2KHR(
+    VkPhysicalDevice                            physicalDevice,
+    const VkPhysicalDeviceSparseImageFormatInfo2KHR* pFormatInfo,
+    uint32_t*                                   pPropertyCount,
+    VkSparseImageFormatProperties2KHR*          pProperties);
+#endif
+
+#define VK_KHR_shader_draw_parameters 1
+#define VK_KHR_SHADER_DRAW_PARAMETERS_SPEC_VERSION 1
+#define VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME "VK_KHR_shader_draw_parameters"
+
+
+#define VK_KHR_maintenance1 1
+#define VK_KHR_MAINTENANCE1_SPEC_VERSION  1
+#define VK_KHR_MAINTENANCE1_EXTENSION_NAME "VK_KHR_maintenance1"
+
+typedef VkFlags VkCommandPoolTrimFlagsKHR;
+
+typedef void (VKAPI_PTR *PFN_vkTrimCommandPoolKHR)(VkDevice device, VkCommandPool commandPool, VkCommandPoolTrimFlagsKHR flags);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkTrimCommandPoolKHR(
+    VkDevice                                    device,
+    VkCommandPool                               commandPool,
+    VkCommandPoolTrimFlagsKHR                   flags);
+#endif
+
+#define VK_KHR_external_memory_capabilities 1
+#define VK_LUID_SIZE_KHR                  8
+#define VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME "VK_KHR_external_memory_capabilities"
+
+
+typedef enum VkExternalMemoryHandleTypeFlagBitsKHR {
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR = 0x00000001,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR = 0x00000002,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_KHR = 0x00000004,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT_KHR = 0x00000008,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT_KHR = 0x00000010,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT_KHR = 0x00000020,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT_KHR = 0x00000040,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkExternalMemoryHandleTypeFlagBitsKHR;
+typedef VkFlags VkExternalMemoryHandleTypeFlagsKHR;
+
+typedef enum VkExternalMemoryFeatureFlagBitsKHR {
+    VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT_KHR = 0x00000001,
+    VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT_KHR = 0x00000002,
+    VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT_KHR = 0x00000004,
+    VK_EXTERNAL_MEMORY_FEATURE_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkExternalMemoryFeatureFlagBitsKHR;
+typedef VkFlags VkExternalMemoryFeatureFlagsKHR;
+
+typedef struct VkExternalMemoryPropertiesKHR {
+    VkExternalMemoryFeatureFlagsKHR       externalMemoryFeatures;
+    VkExternalMemoryHandleTypeFlagsKHR    exportFromImportedHandleTypes;
+    VkExternalMemoryHandleTypeFlagsKHR    compatibleHandleTypes;
+} VkExternalMemoryPropertiesKHR;
+
+typedef struct VkPhysicalDeviceExternalImageFormatInfoKHR {
+    VkStructureType                          sType;
+    const void*                              pNext;
+    VkExternalMemoryHandleTypeFlagBitsKHR    handleType;
+} VkPhysicalDeviceExternalImageFormatInfoKHR;
+
+typedef struct VkExternalImageFormatPropertiesKHR {
+    VkStructureType                  sType;
+    void*                            pNext;
+    VkExternalMemoryPropertiesKHR    externalMemoryProperties;
+} VkExternalImageFormatPropertiesKHR;
+
+typedef struct VkPhysicalDeviceExternalBufferInfoKHR {
+    VkStructureType                          sType;
+    const void*                              pNext;
+    VkBufferCreateFlags                      flags;
+    VkBufferUsageFlags                       usage;
+    VkExternalMemoryHandleTypeFlagBitsKHR    handleType;
+} VkPhysicalDeviceExternalBufferInfoKHR;
+
+typedef struct VkExternalBufferPropertiesKHR {
+    VkStructureType                  sType;
+    void*                            pNext;
+    VkExternalMemoryPropertiesKHR    externalMemoryProperties;
+} VkExternalBufferPropertiesKHR;
+
+typedef struct VkPhysicalDeviceIDPropertiesKHR {
+    VkStructureType    sType;
+    void*              pNext;
+    uint8_t            deviceUUID[VK_UUID_SIZE];
+    uint8_t            driverUUID[VK_UUID_SIZE];
+    uint8_t            deviceLUID[VK_LUID_SIZE_KHR];
+    uint32_t           deviceNodeMask;
+    VkBool32           deviceLUIDValid;
+} VkPhysicalDeviceIDPropertiesKHR;
+
+
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalBufferInfoKHR* pExternalBufferInfo, VkExternalBufferPropertiesKHR* pExternalBufferProperties);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceExternalBufferPropertiesKHR(
+    VkPhysicalDevice                            physicalDevice,
+    const VkPhysicalDeviceExternalBufferInfoKHR* pExternalBufferInfo,
+    VkExternalBufferPropertiesKHR*              pExternalBufferProperties);
+#endif
+
+#define VK_KHR_external_memory 1
+#define VK_KHR_EXTERNAL_MEMORY_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME "VK_KHR_external_memory"
+#define VK_QUEUE_FAMILY_EXTERNAL_KHR      (~0U-1)
+
+typedef struct VkExternalMemoryImageCreateInfoKHR {
+    VkStructureType                       sType;
+    const void*                           pNext;
+    VkExternalMemoryHandleTypeFlagsKHR    handleTypes;
+} VkExternalMemoryImageCreateInfoKHR;
+
+typedef struct VkExternalMemoryBufferCreateInfoKHR {
+    VkStructureType                       sType;
+    const void*                           pNext;
+    VkExternalMemoryHandleTypeFlagsKHR    handleTypes;
+} VkExternalMemoryBufferCreateInfoKHR;
+
+typedef struct VkExportMemoryAllocateInfoKHR {
+    VkStructureType                       sType;
+    const void*                           pNext;
+    VkExternalMemoryHandleTypeFlagsKHR    handleTypes;
+} VkExportMemoryAllocateInfoKHR;
+
+
+
+#ifdef VK_USE_PLATFORM_WIN32_KHR
+#define VK_KHR_external_memory_win32 1
+#define VK_KHR_EXTERNAL_MEMORY_WIN32_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME "VK_KHR_external_memory_win32"
+
+typedef struct VkImportMemoryWin32HandleInfoKHR {
+    VkStructureType                          sType;
+    const void*                              pNext;
+    VkExternalMemoryHandleTypeFlagBitsKHR    handleType;
+    HANDLE                                   handle;
+    LPCWSTR                                  name;
+} VkImportMemoryWin32HandleInfoKHR;
+
+typedef struct VkExportMemoryWin32HandleInfoKHR {
+    VkStructureType               sType;
+    const void*                   pNext;
+    const SECURITY_ATTRIBUTES*    pAttributes;
+    DWORD                         dwAccess;
+    LPCWSTR                       name;
+} VkExportMemoryWin32HandleInfoKHR;
+
+typedef struct VkMemoryWin32HandlePropertiesKHR {
+    VkStructureType    sType;
+    void*              pNext;
+    uint32_t           memoryTypeBits;
+} VkMemoryWin32HandlePropertiesKHR;
+
+typedef struct VkMemoryGetWin32HandleInfoKHR {
+    VkStructureType                          sType;
+    const void*                              pNext;
+    VkDeviceMemory                           memory;
+    VkExternalMemoryHandleTypeFlagBitsKHR    handleType;
+} VkMemoryGetWin32HandleInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkGetMemoryWin32HandleKHR)(VkDevice device, const VkMemoryGetWin32HandleInfoKHR* pGetWin32HandleInfo, HANDLE* pHandle);
+typedef VkResult (VKAPI_PTR *PFN_vkGetMemoryWin32HandlePropertiesKHR)(VkDevice device, VkExternalMemoryHandleTypeFlagBitsKHR handleType, HANDLE handle, VkMemoryWin32HandlePropertiesKHR* pMemoryWin32HandleProperties);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkGetMemoryWin32HandleKHR(
+    VkDevice                                    device,
+    const VkMemoryGetWin32HandleInfoKHR*        pGetWin32HandleInfo,
+    HANDLE*                                     pHandle);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetMemoryWin32HandlePropertiesKHR(
+    VkDevice                                    device,
+    VkExternalMemoryHandleTypeFlagBitsKHR       handleType,
+    HANDLE                                      handle,
+    VkMemoryWin32HandlePropertiesKHR*           pMemoryWin32HandleProperties);
+#endif
+#endif /* VK_USE_PLATFORM_WIN32_KHR */
+
+#define VK_KHR_external_memory_fd 1
+#define VK_KHR_EXTERNAL_MEMORY_FD_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME "VK_KHR_external_memory_fd"
+
+typedef struct VkImportMemoryFdInfoKHR {
+    VkStructureType                          sType;
+    const void*                              pNext;
+    VkExternalMemoryHandleTypeFlagBitsKHR    handleType;
+    int                                      fd;
+} VkImportMemoryFdInfoKHR;
+
+typedef struct VkMemoryFdPropertiesKHR {
+    VkStructureType    sType;
+    void*              pNext;
+    uint32_t           memoryTypeBits;
+} VkMemoryFdPropertiesKHR;
+
+typedef struct VkMemoryGetFdInfoKHR {
+    VkStructureType                          sType;
+    const void*                              pNext;
+    VkDeviceMemory                           memory;
+    VkExternalMemoryHandleTypeFlagBitsKHR    handleType;
+} VkMemoryGetFdInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkGetMemoryFdKHR)(VkDevice device, const VkMemoryGetFdInfoKHR* pGetFdInfo, int* pFd);
+typedef VkResult (VKAPI_PTR *PFN_vkGetMemoryFdPropertiesKHR)(VkDevice device, VkExternalMemoryHandleTypeFlagBitsKHR handleType, int fd, VkMemoryFdPropertiesKHR* pMemoryFdProperties);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkGetMemoryFdKHR(
+    VkDevice                                    device,
+    const VkMemoryGetFdInfoKHR*                 pGetFdInfo,
+    int*                                        pFd);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetMemoryFdPropertiesKHR(
+    VkDevice                                    device,
+    VkExternalMemoryHandleTypeFlagBitsKHR       handleType,
+    int                                         fd,
+    VkMemoryFdPropertiesKHR*                    pMemoryFdProperties);
+#endif
+
+#ifdef VK_USE_PLATFORM_WIN32_KHR
+#define VK_KHR_win32_keyed_mutex 1
+#define VK_KHR_WIN32_KEYED_MUTEX_SPEC_VERSION 1
+#define VK_KHR_WIN32_KEYED_MUTEX_EXTENSION_NAME "VK_KHR_win32_keyed_mutex"
+
+typedef struct VkWin32KeyedMutexAcquireReleaseInfoKHR {
+    VkStructureType          sType;
+    const void*              pNext;
+    uint32_t                 acquireCount;
+    const VkDeviceMemory*    pAcquireSyncs;
+    const uint64_t*          pAcquireKeys;
+    const uint32_t*          pAcquireTimeouts;
+    uint32_t                 releaseCount;
+    const VkDeviceMemory*    pReleaseSyncs;
+    const uint64_t*          pReleaseKeys;
+} VkWin32KeyedMutexAcquireReleaseInfoKHR;
+
+
+#endif /* VK_USE_PLATFORM_WIN32_KHR */
+
+#define VK_KHR_external_semaphore_capabilities 1
+#define VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME "VK_KHR_external_semaphore_capabilities"
+
+
+typedef enum VkExternalSemaphoreHandleTypeFlagBitsKHR {
+    VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR = 0x00000001,
+    VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR = 0x00000002,
+    VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_KHR = 0x00000004,
+    VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT_KHR = 0x00000008,
+    VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT_KHR = 0x00000010,
+    VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkExternalSemaphoreHandleTypeFlagBitsKHR;
+typedef VkFlags VkExternalSemaphoreHandleTypeFlagsKHR;
+
+typedef enum VkExternalSemaphoreFeatureFlagBitsKHR {
+    VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT_KHR = 0x00000001,
+    VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT_KHR = 0x00000002,
+    VK_EXTERNAL_SEMAPHORE_FEATURE_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkExternalSemaphoreFeatureFlagBitsKHR;
+typedef VkFlags VkExternalSemaphoreFeatureFlagsKHR;
+
+typedef struct VkPhysicalDeviceExternalSemaphoreInfoKHR {
+    VkStructureType                             sType;
+    const void*                                 pNext;
+    VkExternalSemaphoreHandleTypeFlagBitsKHR    handleType;
+} VkPhysicalDeviceExternalSemaphoreInfoKHR;
+
+typedef struct VkExternalSemaphorePropertiesKHR {
+    VkStructureType                          sType;
+    void*                                    pNext;
+    VkExternalSemaphoreHandleTypeFlagsKHR    exportFromImportedHandleTypes;
+    VkExternalSemaphoreHandleTypeFlagsKHR    compatibleHandleTypes;
+    VkExternalSemaphoreFeatureFlagsKHR       externalSemaphoreFeatures;
+} VkExternalSemaphorePropertiesKHR;
+
+
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalSemaphoreInfoKHR* pExternalSemaphoreInfo, VkExternalSemaphorePropertiesKHR* pExternalSemaphoreProperties);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(
+    VkPhysicalDevice                            physicalDevice,
+    const VkPhysicalDeviceExternalSemaphoreInfoKHR* pExternalSemaphoreInfo,
+    VkExternalSemaphorePropertiesKHR*           pExternalSemaphoreProperties);
+#endif
+
+#define VK_KHR_external_semaphore 1
+#define VK_KHR_EXTERNAL_SEMAPHORE_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME "VK_KHR_external_semaphore"
+
+
+typedef enum VkSemaphoreImportFlagBitsKHR {
+    VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR = 0x00000001,
+    VK_SEMAPHORE_IMPORT_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkSemaphoreImportFlagBitsKHR;
+typedef VkFlags VkSemaphoreImportFlagsKHR;
+
+typedef struct VkExportSemaphoreCreateInfoKHR {
+    VkStructureType                          sType;
+    const void*                              pNext;
+    VkExternalSemaphoreHandleTypeFlagsKHR    handleTypes;
+} VkExportSemaphoreCreateInfoKHR;
+
+
+
+#ifdef VK_USE_PLATFORM_WIN32_KHR
+#define VK_KHR_external_semaphore_win32 1
+#define VK_KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME "VK_KHR_external_semaphore_win32"
+
+typedef struct VkImportSemaphoreWin32HandleInfoKHR {
+    VkStructureType                             sType;
+    const void*                                 pNext;
+    VkSemaphore                                 semaphore;
+    VkSemaphoreImportFlagsKHR                   flags;
+    VkExternalSemaphoreHandleTypeFlagBitsKHR    handleType;
+    HANDLE                                      handle;
+    LPCWSTR                                     name;
+} VkImportSemaphoreWin32HandleInfoKHR;
+
+typedef struct VkExportSemaphoreWin32HandleInfoKHR {
+    VkStructureType               sType;
+    const void*                   pNext;
+    const SECURITY_ATTRIBUTES*    pAttributes;
+    DWORD                         dwAccess;
+    LPCWSTR                       name;
+} VkExportSemaphoreWin32HandleInfoKHR;
+
+typedef struct VkD3D12FenceSubmitInfoKHR {
+    VkStructureType    sType;
+    const void*        pNext;
+    uint32_t           waitSemaphoreValuesCount;
+    const uint64_t*    pWaitSemaphoreValues;
+    uint32_t           signalSemaphoreValuesCount;
+    const uint64_t*    pSignalSemaphoreValues;
+} VkD3D12FenceSubmitInfoKHR;
+
+typedef struct VkSemaphoreGetWin32HandleInfoKHR {
+    VkStructureType                             sType;
+    const void*                                 pNext;
+    VkSemaphore                                 semaphore;
+    VkExternalSemaphoreHandleTypeFlagBitsKHR    handleType;
+} VkSemaphoreGetWin32HandleInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkImportSemaphoreWin32HandleKHR)(VkDevice device, const VkImportSemaphoreWin32HandleInfoKHR* pImportSemaphoreWin32HandleInfo);
+typedef VkResult (VKAPI_PTR *PFN_vkGetSemaphoreWin32HandleKHR)(VkDevice device, const VkSemaphoreGetWin32HandleInfoKHR* pGetWin32HandleInfo, HANDLE* pHandle);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkImportSemaphoreWin32HandleKHR(
+    VkDevice                                    device,
+    const VkImportSemaphoreWin32HandleInfoKHR*  pImportSemaphoreWin32HandleInfo);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetSemaphoreWin32HandleKHR(
+    VkDevice                                    device,
+    const VkSemaphoreGetWin32HandleInfoKHR*     pGetWin32HandleInfo,
+    HANDLE*                                     pHandle);
+#endif
+#endif /* VK_USE_PLATFORM_WIN32_KHR */
+
+#define VK_KHR_external_semaphore_fd 1
+#define VK_KHR_EXTERNAL_SEMAPHORE_FD_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME "VK_KHR_external_semaphore_fd"
+
+typedef struct VkImportSemaphoreFdInfoKHR {
+    VkStructureType                             sType;
+    const void*                                 pNext;
+    VkSemaphore                                 semaphore;
+    VkSemaphoreImportFlagsKHR                   flags;
+    VkExternalSemaphoreHandleTypeFlagBitsKHR    handleType;
+    int                                         fd;
+} VkImportSemaphoreFdInfoKHR;
+
+typedef struct VkSemaphoreGetFdInfoKHR {
+    VkStructureType                             sType;
+    const void*                                 pNext;
+    VkSemaphore                                 semaphore;
+    VkExternalSemaphoreHandleTypeFlagBitsKHR    handleType;
+} VkSemaphoreGetFdInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkImportSemaphoreFdKHR)(VkDevice device, const VkImportSemaphoreFdInfoKHR* pImportSemaphoreFdInfo);
+typedef VkResult (VKAPI_PTR *PFN_vkGetSemaphoreFdKHR)(VkDevice device, const VkSemaphoreGetFdInfoKHR* pGetFdInfo, int* pFd);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkImportSemaphoreFdKHR(
+    VkDevice                                    device,
+    const VkImportSemaphoreFdInfoKHR*           pImportSemaphoreFdInfo);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetSemaphoreFdKHR(
+    VkDevice                                    device,
+    const VkSemaphoreGetFdInfoKHR*              pGetFdInfo,
+    int*                                        pFd);
+#endif
+
+#define VK_KHR_push_descriptor 1
+#define VK_KHR_PUSH_DESCRIPTOR_SPEC_VERSION 1
+#define VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME "VK_KHR_push_descriptor"
+
+typedef struct VkPhysicalDevicePushDescriptorPropertiesKHR {
+    VkStructureType    sType;
+    void*              pNext;
+    uint32_t           maxPushDescriptors;
+} VkPhysicalDevicePushDescriptorPropertiesKHR;
+
+
+typedef void (VKAPI_PTR *PFN_vkCmdPushDescriptorSetKHR)(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t set, uint32_t descriptorWriteCount, const VkWriteDescriptorSet* pDescriptorWrites);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkCmdPushDescriptorSetKHR(
+    VkCommandBuffer                             commandBuffer,
+    VkPipelineBindPoint                         pipelineBindPoint,
+    VkPipelineLayout                            layout,
+    uint32_t                                    set,
+    uint32_t                                    descriptorWriteCount,
+    const VkWriteDescriptorSet*                 pDescriptorWrites);
+#endif
+
+#define VK_KHR_16bit_storage 1
+#define VK_KHR_16BIT_STORAGE_SPEC_VERSION 1
+#define VK_KHR_16BIT_STORAGE_EXTENSION_NAME "VK_KHR_16bit_storage"
+
+typedef struct VkPhysicalDevice16BitStorageFeaturesKHR {
+    VkStructureType    sType;
+    void*              pNext;
+    VkBool32           storageBuffer16BitAccess;
+    VkBool32           uniformAndStorageBuffer16BitAccess;
+    VkBool32           storagePushConstant16;
+    VkBool32           storageInputOutput16;
+} VkPhysicalDevice16BitStorageFeaturesKHR;
+
+
+
+#define VK_KHR_incremental_present 1
+#define VK_KHR_INCREMENTAL_PRESENT_SPEC_VERSION 1
+#define VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME "VK_KHR_incremental_present"
+
+typedef struct VkRectLayerKHR {
+    VkOffset2D    offset;
+    VkExtent2D    extent;
+    uint32_t      layer;
+} VkRectLayerKHR;
+
+typedef struct VkPresentRegionKHR {
+    uint32_t                 rectangleCount;
+    const VkRectLayerKHR*    pRectangles;
+} VkPresentRegionKHR;
+
+typedef struct VkPresentRegionsKHR {
+    VkStructureType              sType;
+    const void*                  pNext;
+    uint32_t                     swapchainCount;
+    const VkPresentRegionKHR*    pRegions;
+} VkPresentRegionsKHR;
+
+
+
+#define VK_KHR_descriptor_update_template 1
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorUpdateTemplateKHR)
+
+#define VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_SPEC_VERSION 1
+#define VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME "VK_KHR_descriptor_update_template"
+
+
+typedef enum VkDescriptorUpdateTemplateTypeKHR {
+    VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET_KHR = 0,
+    VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR = 1,
+    VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_BEGIN_RANGE_KHR = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET_KHR,
+    VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_END_RANGE_KHR = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR,
+    VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_RANGE_SIZE_KHR = (VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR - VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET_KHR + 1),
+    VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkDescriptorUpdateTemplateTypeKHR;
+
+typedef VkFlags VkDescriptorUpdateTemplateCreateFlagsKHR;
+
+typedef struct VkDescriptorUpdateTemplateEntryKHR {
+    uint32_t            dstBinding;
+    uint32_t            dstArrayElement;
+    uint32_t            descriptorCount;
+    VkDescriptorType    descriptorType;
+    size_t              offset;
+    size_t              stride;
+} VkDescriptorUpdateTemplateEntryKHR;
+
+typedef struct VkDescriptorUpdateTemplateCreateInfoKHR {
+    VkStructureType                              sType;
+    void*                                        pNext;
+    VkDescriptorUpdateTemplateCreateFlagsKHR     flags;
+    uint32_t                                     descriptorUpdateEntryCount;
+    const VkDescriptorUpdateTemplateEntryKHR*    pDescriptorUpdateEntries;
+    VkDescriptorUpdateTemplateTypeKHR            templateType;
+    VkDescriptorSetLayout                        descriptorSetLayout;
+    VkPipelineBindPoint                          pipelineBindPoint;
+    VkPipelineLayout                             pipelineLayout;
+    uint32_t                                     set;
+} VkDescriptorUpdateTemplateCreateInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateDescriptorUpdateTemplateKHR)(VkDevice device, const VkDescriptorUpdateTemplateCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorUpdateTemplateKHR* pDescriptorUpdateTemplate);
+typedef void (VKAPI_PTR *PFN_vkDestroyDescriptorUpdateTemplateKHR)(VkDevice device, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, const VkAllocationCallbacks* pAllocator);
+typedef void (VKAPI_PTR *PFN_vkUpdateDescriptorSetWithTemplateKHR)(VkDevice device, VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, const void* pData);
+typedef void (VKAPI_PTR *PFN_vkCmdPushDescriptorSetWithTemplateKHR)(VkCommandBuffer commandBuffer, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, VkPipelineLayout layout, uint32_t set, const void* pData);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateDescriptorUpdateTemplateKHR(
+    VkDevice                                    device,
+    const VkDescriptorUpdateTemplateCreateInfoKHR* pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkDescriptorUpdateTemplateKHR*              pDescriptorUpdateTemplate);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyDescriptorUpdateTemplateKHR(
+    VkDevice                                    device,
+    VkDescriptorUpdateTemplateKHR               descriptorUpdateTemplate,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR void VKAPI_CALL vkUpdateDescriptorSetWithTemplateKHR(
+    VkDevice                                    device,
+    VkDescriptorSet                             descriptorSet,
+    VkDescriptorUpdateTemplateKHR               descriptorUpdateTemplate,
+    const void*                                 pData);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdPushDescriptorSetWithTemplateKHR(
+    VkCommandBuffer                             commandBuffer,
+    VkDescriptorUpdateTemplateKHR               descriptorUpdateTemplate,
+    VkPipelineLayout                            layout,
+    uint32_t                                    set,
+    const void*                                 pData);
+#endif
+
+#define VK_KHR_shared_presentable_image 1
+#define VK_KHR_SHARED_PRESENTABLE_IMAGE_SPEC_VERSION 1
+#define VK_KHR_SHARED_PRESENTABLE_IMAGE_EXTENSION_NAME "VK_KHR_shared_presentable_image"
+
+typedef struct VkSharedPresentSurfaceCapabilitiesKHR {
+    VkStructureType      sType;
+    void*                pNext;
+    VkImageUsageFlags    sharedPresentSupportedUsageFlags;
+} VkSharedPresentSurfaceCapabilitiesKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkGetSwapchainStatusKHR)(VkDevice device, VkSwapchainKHR swapchain);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkGetSwapchainStatusKHR(
+    VkDevice                                    device,
+    VkSwapchainKHR                              swapchain);
+#endif
+
+#define VK_KHR_external_fence_capabilities 1
+#define VK_KHR_EXTERNAL_FENCE_CAPABILITIES_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_FENCE_CAPABILITIES_EXTENSION_NAME "VK_KHR_external_fence_capabilities"
+
+
+typedef enum VkExternalFenceHandleTypeFlagBitsKHR {
+    VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR = 0x00000001,
+    VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR = 0x00000002,
+    VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_KHR = 0x00000004,
+    VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT_KHR = 0x00000008,
+    VK_EXTERNAL_FENCE_HANDLE_TYPE_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkExternalFenceHandleTypeFlagBitsKHR;
+typedef VkFlags VkExternalFenceHandleTypeFlagsKHR;
+
+typedef enum VkExternalFenceFeatureFlagBitsKHR {
+    VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT_KHR = 0x00000001,
+    VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT_KHR = 0x00000002,
+    VK_EXTERNAL_FENCE_FEATURE_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkExternalFenceFeatureFlagBitsKHR;
+typedef VkFlags VkExternalFenceFeatureFlagsKHR;
+
+typedef struct VkPhysicalDeviceExternalFenceInfoKHR {
+    VkStructureType                         sType;
+    const void*                             pNext;
+    VkExternalFenceHandleTypeFlagBitsKHR    handleType;
+} VkPhysicalDeviceExternalFenceInfoKHR;
+
+typedef struct VkExternalFencePropertiesKHR {
+    VkStructureType                      sType;
+    void*                                pNext;
+    VkExternalFenceHandleTypeFlagsKHR    exportFromImportedHandleTypes;
+    VkExternalFenceHandleTypeFlagsKHR    compatibleHandleTypes;
+    VkExternalFenceFeatureFlagsKHR       externalFenceFeatures;
+} VkExternalFencePropertiesKHR;
+
+
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalFencePropertiesKHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalFenceInfoKHR* pExternalFenceInfo, VkExternalFencePropertiesKHR* pExternalFenceProperties);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceExternalFencePropertiesKHR(
+    VkPhysicalDevice                            physicalDevice,
+    const VkPhysicalDeviceExternalFenceInfoKHR* pExternalFenceInfo,
+    VkExternalFencePropertiesKHR*               pExternalFenceProperties);
+#endif
+
+#define VK_KHR_external_fence 1
+#define VK_KHR_EXTERNAL_FENCE_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME "VK_KHR_external_fence"
+
+
+typedef enum VkFenceImportFlagBitsKHR {
+    VK_FENCE_IMPORT_TEMPORARY_BIT_KHR = 0x00000001,
+    VK_FENCE_IMPORT_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
+} VkFenceImportFlagBitsKHR;
+typedef VkFlags VkFenceImportFlagsKHR;
+
+typedef struct VkExportFenceCreateInfoKHR {
+    VkStructureType                      sType;
+    const void*                          pNext;
+    VkExternalFenceHandleTypeFlagsKHR    handleTypes;
+} VkExportFenceCreateInfoKHR;
+
+
+
+#ifdef VK_USE_PLATFORM_WIN32_KHR
+#define VK_KHR_external_fence_win32 1
+#define VK_KHR_EXTERNAL_FENCE_WIN32_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_FENCE_WIN32_EXTENSION_NAME "VK_KHR_external_fence_win32"
+
+typedef struct VkImportFenceWin32HandleInfoKHR {
+    VkStructureType                         sType;
+    const void*                             pNext;
+    VkFence                                 fence;
+    VkFenceImportFlagsKHR                   flags;
+    VkExternalFenceHandleTypeFlagBitsKHR    handleType;
+    HANDLE                                  handle;
+    LPCWSTR                                 name;
+} VkImportFenceWin32HandleInfoKHR;
+
+typedef struct VkExportFenceWin32HandleInfoKHR {
+    VkStructureType               sType;
+    const void*                   pNext;
+    const SECURITY_ATTRIBUTES*    pAttributes;
+    DWORD                         dwAccess;
+    LPCWSTR                       name;
+} VkExportFenceWin32HandleInfoKHR;
+
+typedef struct VkFenceGetWin32HandleInfoKHR {
+    VkStructureType                         sType;
+    const void*                             pNext;
+    VkFence                                 fence;
+    VkExternalFenceHandleTypeFlagBitsKHR    handleType;
+} VkFenceGetWin32HandleInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkImportFenceWin32HandleKHR)(VkDevice device, const VkImportFenceWin32HandleInfoKHR* pImportFenceWin32HandleInfo);
+typedef VkResult (VKAPI_PTR *PFN_vkGetFenceWin32HandleKHR)(VkDevice device, const VkFenceGetWin32HandleInfoKHR* pGetWin32HandleInfo, HANDLE* pHandle);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkImportFenceWin32HandleKHR(
+    VkDevice                                    device,
+    const VkImportFenceWin32HandleInfoKHR*      pImportFenceWin32HandleInfo);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetFenceWin32HandleKHR(
+    VkDevice                                    device,
+    const VkFenceGetWin32HandleInfoKHR*         pGetWin32HandleInfo,
+    HANDLE*                                     pHandle);
+#endif
+#endif /* VK_USE_PLATFORM_WIN32_KHR */
+
+#define VK_KHR_external_fence_fd 1
+#define VK_KHR_EXTERNAL_FENCE_FD_SPEC_VERSION 1
+#define VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME "VK_KHR_external_fence_fd"
+
+typedef struct VkImportFenceFdInfoKHR {
+    VkStructureType                         sType;
+    const void*                             pNext;
+    VkFence                                 fence;
+    VkFenceImportFlagsKHR                   flags;
+    VkExternalFenceHandleTypeFlagBitsKHR    handleType;
+    int                                     fd;
+} VkImportFenceFdInfoKHR;
+
+typedef struct VkFenceGetFdInfoKHR {
+    VkStructureType                         sType;
+    const void*                             pNext;
+    VkFence                                 fence;
+    VkExternalFenceHandleTypeFlagBitsKHR    handleType;
+} VkFenceGetFdInfoKHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkImportFenceFdKHR)(VkDevice device, const VkImportFenceFdInfoKHR* pImportFenceFdInfo);
+typedef VkResult (VKAPI_PTR *PFN_vkGetFenceFdKHR)(VkDevice device, const VkFenceGetFdInfoKHR* pGetFdInfo, int* pFd);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkImportFenceFdKHR(
+    VkDevice                                    device,
+    const VkImportFenceFdInfoKHR*               pImportFenceFdInfo);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetFenceFdKHR(
+    VkDevice                                    device,
+    const VkFenceGetFdInfoKHR*                  pGetFdInfo,
+    int*                                        pFd);
+#endif
+
+#define VK_KHR_get_surface_capabilities2 1
+#define VK_KHR_GET_SURFACE_CAPABILITIES_2_SPEC_VERSION 1
+#define VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME "VK_KHR_get_surface_capabilities2"
+
+typedef struct VkPhysicalDeviceSurfaceInfo2KHR {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkSurfaceKHR       surface;
+} VkPhysicalDeviceSurfaceInfo2KHR;
+
+typedef struct VkSurfaceCapabilities2KHR {
+    VkStructureType             sType;
+    void*                       pNext;
+    VkSurfaceCapabilitiesKHR    surfaceCapabilities;
+} VkSurfaceCapabilities2KHR;
+
+typedef struct VkSurfaceFormat2KHR {
+    VkStructureType       sType;
+    void*                 pNext;
+    VkSurfaceFormatKHR    surfaceFormat;
+} VkSurfaceFormat2KHR;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, VkSurfaceCapabilities2KHR* pSurfaceCapabilities);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceFormats2KHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, uint32_t* pSurfaceFormatCount, VkSurfaceFormat2KHR* pSurfaceFormats);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceCapabilities2KHR(
+    VkPhysicalDevice                            physicalDevice,
+    const VkPhysicalDeviceSurfaceInfo2KHR*      pSurfaceInfo,
+    VkSurfaceCapabilities2KHR*                  pSurfaceCapabilities);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceFormats2KHR(
+    VkPhysicalDevice                            physicalDevice,
+    const VkPhysicalDeviceSurfaceInfo2KHR*      pSurfaceInfo,
+    uint32_t*                                   pSurfaceFormatCount,
+    VkSurfaceFormat2KHR*                        pSurfaceFormats);
+#endif
+
+#define VK_KHR_variable_pointers 1
+#define VK_KHR_VARIABLE_POINTERS_SPEC_VERSION 1
+#define VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME "VK_KHR_variable_pointers"
+
+typedef struct VkPhysicalDeviceVariablePointerFeaturesKHR {
+    VkStructureType    sType;
+    void*              pNext;
+    VkBool32           variablePointersStorageBuffer;
+    VkBool32           variablePointers;
+} VkPhysicalDeviceVariablePointerFeaturesKHR;
+
+
+
+#define VK_KHR_dedicated_allocation 1
+#define VK_KHR_DEDICATED_ALLOCATION_SPEC_VERSION 3
+#define VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME "VK_KHR_dedicated_allocation"
+
+typedef struct VkMemoryDedicatedRequirementsKHR {
+    VkStructureType    sType;
+    void*              pNext;
+    VkBool32           prefersDedicatedAllocation;
+    VkBool32           requiresDedicatedAllocation;
+} VkMemoryDedicatedRequirementsKHR;
+
+typedef struct VkMemoryDedicatedAllocateInfoKHR {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkImage            image;
+    VkBuffer           buffer;
+} VkMemoryDedicatedAllocateInfoKHR;
+
+
+
+#define VK_KHR_storage_buffer_storage_class 1
+#define VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_SPEC_VERSION 1
+#define VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME "VK_KHR_storage_buffer_storage_class"
+
+
+#define VK_KHR_relaxed_block_layout 1
+#define VK_KHR_RELAXED_BLOCK_LAYOUT_SPEC_VERSION 1
+#define VK_KHR_RELAXED_BLOCK_LAYOUT_EXTENSION_NAME "VK_KHR_relaxed_block_layout"
+
+
+#define VK_KHR_get_memory_requirements2 1
+#define VK_KHR_GET_MEMORY_REQUIREMENTS_2_SPEC_VERSION 1
+#define VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME "VK_KHR_get_memory_requirements2"
+
+typedef struct VkBufferMemoryRequirementsInfo2KHR {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkBuffer           buffer;
+} VkBufferMemoryRequirementsInfo2KHR;
+
+typedef struct VkImageMemoryRequirementsInfo2KHR {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkImage            image;
+} VkImageMemoryRequirementsInfo2KHR;
+
+typedef struct VkImageSparseMemoryRequirementsInfo2KHR {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkImage            image;
+} VkImageSparseMemoryRequirementsInfo2KHR;
+
+typedef struct VkMemoryRequirements2KHR {
+    VkStructureType         sType;
+    void*                   pNext;
+    VkMemoryRequirements    memoryRequirements;
+} VkMemoryRequirements2KHR;
+
+typedef struct VkSparseImageMemoryRequirements2KHR {
+    VkStructureType                    sType;
+    void*                              pNext;
+    VkSparseImageMemoryRequirements    memoryRequirements;
+} VkSparseImageMemoryRequirements2KHR;
+
+
+typedef void (VKAPI_PTR *PFN_vkGetImageMemoryRequirements2KHR)(VkDevice device, const VkImageMemoryRequirementsInfo2KHR* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements);
+typedef void (VKAPI_PTR *PFN_vkGetBufferMemoryRequirements2KHR)(VkDevice device, const VkBufferMemoryRequirementsInfo2KHR* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements);
+typedef void (VKAPI_PTR *PFN_vkGetImageSparseMemoryRequirements2KHR)(VkDevice device, const VkImageSparseMemoryRequirementsInfo2KHR* pInfo, uint32_t* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements2KHR* pSparseMemoryRequirements);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkGetImageMemoryRequirements2KHR(
+    VkDevice                                    device,
+    const VkImageMemoryRequirementsInfo2KHR*    pInfo,
+    VkMemoryRequirements2KHR*                   pMemoryRequirements);
+
+VKAPI_ATTR void VKAPI_CALL vkGetBufferMemoryRequirements2KHR(
+    VkDevice                                    device,
+    const VkBufferMemoryRequirementsInfo2KHR*   pInfo,
+    VkMemoryRequirements2KHR*                   pMemoryRequirements);
+
+VKAPI_ATTR void VKAPI_CALL vkGetImageSparseMemoryRequirements2KHR(
+    VkDevice                                    device,
+    const VkImageSparseMemoryRequirementsInfo2KHR* pInfo,
+    uint32_t*                                   pSparseMemoryRequirementCount,
+    VkSparseImageMemoryRequirements2KHR*        pSparseMemoryRequirements);
+#endif
+
+#define VK_EXT_debug_report 1
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDebugReportCallbackEXT)
+
+#define VK_EXT_DEBUG_REPORT_SPEC_VERSION  8
+#define VK_EXT_DEBUG_REPORT_EXTENSION_NAME "VK_EXT_debug_report"
+#define VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT
+#define VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT
+
+
+typedef enum VkDebugReportObjectTypeEXT {
+    VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT = 0,
+    VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT = 1,
+    VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT = 2,
+    VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT = 3,
+    VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT = 4,
+    VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT = 5,
+    VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT = 6,
+    VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT = 7,
+    VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT = 8,
+    VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT = 9,
+    VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT = 10,
+    VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT = 11,
+    VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT = 12,
+    VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT = 13,
+    VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT = 14,
+    VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT = 15,
+    VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT = 16,
+    VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT = 17,
+    VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT = 18,
+    VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT = 19,
+    VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT = 20,
+    VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT = 21,
+    VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT = 22,
+    VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT = 23,
+    VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT = 24,
+    VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT = 25,
+    VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT = 26,
+    VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT = 27,
+    VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT = 28,
+    VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_KHR_EXT = 29,
+    VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_MODE_KHR_EXT = 30,
+    VK_DEBUG_REPORT_OBJECT_TYPE_OBJECT_TABLE_NVX_EXT = 31,
+    VK_DEBUG_REPORT_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX_EXT = 32,
+    VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR_EXT = 1000085000,
+    VK_DEBUG_REPORT_OBJECT_TYPE_BEGIN_RANGE_EXT = VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
+    VK_DEBUG_REPORT_OBJECT_TYPE_END_RANGE_EXT = VK_DEBUG_REPORT_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX_EXT,
+    VK_DEBUG_REPORT_OBJECT_TYPE_RANGE_SIZE_EXT = (VK_DEBUG_REPORT_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX_EXT - VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT + 1),
+    VK_DEBUG_REPORT_OBJECT_TYPE_MAX_ENUM_EXT = 0x7FFFFFFF
+} VkDebugReportObjectTypeEXT;
+
+
+typedef enum VkDebugReportFlagBitsEXT {
+    VK_DEBUG_REPORT_INFORMATION_BIT_EXT = 0x00000001,
+    VK_DEBUG_REPORT_WARNING_BIT_EXT = 0x00000002,
+    VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT = 0x00000004,
+    VK_DEBUG_REPORT_ERROR_BIT_EXT = 0x00000008,
+    VK_DEBUG_REPORT_DEBUG_BIT_EXT = 0x00000010,
+    VK_DEBUG_REPORT_FLAG_BITS_MAX_ENUM_EXT = 0x7FFFFFFF
+} VkDebugReportFlagBitsEXT;
+typedef VkFlags VkDebugReportFlagsEXT;
+
+typedef VkBool32 (VKAPI_PTR *PFN_vkDebugReportCallbackEXT)(
+    VkDebugReportFlagsEXT                       flags,
+    VkDebugReportObjectTypeEXT                  objectType,
+    uint64_t                                    object,
+    size_t                                      location,
+    int32_t                                     messageCode,
+    const char*                                 pLayerPrefix,
+    const char*                                 pMessage,
+    void*                                       pUserData);
+
+typedef struct VkDebugReportCallbackCreateInfoEXT {
+    VkStructureType                 sType;
+    const void*                     pNext;
+    VkDebugReportFlagsEXT           flags;
+    PFN_vkDebugReportCallbackEXT    pfnCallback;
+    void*                           pUserData;
+} VkDebugReportCallbackCreateInfoEXT;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateDebugReportCallbackEXT)(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugReportCallbackEXT* pCallback);
+typedef void (VKAPI_PTR *PFN_vkDestroyDebugReportCallbackEXT)(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* pAllocator);
+typedef void (VKAPI_PTR *PFN_vkDebugReportMessageEXT)(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateDebugReportCallbackEXT(
+    VkInstance                                  instance,
+    const VkDebugReportCallbackCreateInfoEXT*   pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkDebugReportCallbackEXT*                   pCallback);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyDebugReportCallbackEXT(
+    VkInstance                                  instance,
+    VkDebugReportCallbackEXT                    callback,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR void VKAPI_CALL vkDebugReportMessageEXT(
+    VkInstance                                  instance,
+    VkDebugReportFlagsEXT                       flags,
+    VkDebugReportObjectTypeEXT                  objectType,
+    uint64_t                                    object,
+    size_t                                      location,
+    int32_t                                     messageCode,
+    const char*                                 pLayerPrefix,
+    const char*                                 pMessage);
+#endif
+
+#define VK_NV_glsl_shader 1
+#define VK_NV_GLSL_SHADER_SPEC_VERSION    1
+#define VK_NV_GLSL_SHADER_EXTENSION_NAME  "VK_NV_glsl_shader"
+
+
+#define VK_EXT_depth_range_unrestricted 1
+#define VK_EXT_DEPTH_RANGE_UNRESTRICTED_SPEC_VERSION 1
+#define VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME "VK_EXT_depth_range_unrestricted"
+
+
+#define VK_IMG_filter_cubic 1
+#define VK_IMG_FILTER_CUBIC_SPEC_VERSION  1
+#define VK_IMG_FILTER_CUBIC_EXTENSION_NAME "VK_IMG_filter_cubic"
+
+
+#define VK_AMD_rasterization_order 1
+#define VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION 1
+#define VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME "VK_AMD_rasterization_order"
+
+
+typedef enum VkRasterizationOrderAMD {
+    VK_RASTERIZATION_ORDER_STRICT_AMD = 0,
+    VK_RASTERIZATION_ORDER_RELAXED_AMD = 1,
+    VK_RASTERIZATION_ORDER_BEGIN_RANGE_AMD = VK_RASTERIZATION_ORDER_STRICT_AMD,
+    VK_RASTERIZATION_ORDER_END_RANGE_AMD = VK_RASTERIZATION_ORDER_RELAXED_AMD,
+    VK_RASTERIZATION_ORDER_RANGE_SIZE_AMD = (VK_RASTERIZATION_ORDER_RELAXED_AMD - VK_RASTERIZATION_ORDER_STRICT_AMD + 1),
+    VK_RASTERIZATION_ORDER_MAX_ENUM_AMD = 0x7FFFFFFF
+} VkRasterizationOrderAMD;
+
+typedef struct VkPipelineRasterizationStateRasterizationOrderAMD {
+    VkStructureType            sType;
+    const void*                pNext;
+    VkRasterizationOrderAMD    rasterizationOrder;
+} VkPipelineRasterizationStateRasterizationOrderAMD;
+
+
+
+#define VK_AMD_shader_trinary_minmax 1
+#define VK_AMD_SHADER_TRINARY_MINMAX_SPEC_VERSION 1
+#define VK_AMD_SHADER_TRINARY_MINMAX_EXTENSION_NAME "VK_AMD_shader_trinary_minmax"
+
+
+#define VK_AMD_shader_explicit_vertex_parameter 1
+#define VK_AMD_SHADER_EXPLICIT_VERTEX_PARAMETER_SPEC_VERSION 1
+#define VK_AMD_SHADER_EXPLICIT_VERTEX_PARAMETER_EXTENSION_NAME "VK_AMD_shader_explicit_vertex_parameter"
+
+
+#define VK_EXT_debug_marker 1
+#define VK_EXT_DEBUG_MARKER_SPEC_VERSION  4
+#define VK_EXT_DEBUG_MARKER_EXTENSION_NAME "VK_EXT_debug_marker"
+
+typedef struct VkDebugMarkerObjectNameInfoEXT {
+    VkStructureType               sType;
+    const void*                   pNext;
+    VkDebugReportObjectTypeEXT    objectType;
+    uint64_t                      object;
+    const char*                   pObjectName;
+} VkDebugMarkerObjectNameInfoEXT;
+
+typedef struct VkDebugMarkerObjectTagInfoEXT {
+    VkStructureType               sType;
+    const void*                   pNext;
+    VkDebugReportObjectTypeEXT    objectType;
+    uint64_t                      object;
+    uint64_t                      tagName;
+    size_t                        tagSize;
+    const void*                   pTag;
+} VkDebugMarkerObjectTagInfoEXT;
+
+typedef struct VkDebugMarkerMarkerInfoEXT {
+    VkStructureType    sType;
+    const void*        pNext;
+    const char*        pMarkerName;
+    float              color[4];
+} VkDebugMarkerMarkerInfoEXT;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkDebugMarkerSetObjectTagEXT)(VkDevice device, const VkDebugMarkerObjectTagInfoEXT* pTagInfo);
+typedef VkResult (VKAPI_PTR *PFN_vkDebugMarkerSetObjectNameEXT)(VkDevice device, const VkDebugMarkerObjectNameInfoEXT* pNameInfo);
+typedef void (VKAPI_PTR *PFN_vkCmdDebugMarkerBeginEXT)(VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT* pMarkerInfo);
+typedef void (VKAPI_PTR *PFN_vkCmdDebugMarkerEndEXT)(VkCommandBuffer commandBuffer);
+typedef void (VKAPI_PTR *PFN_vkCmdDebugMarkerInsertEXT)(VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT* pMarkerInfo);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkDebugMarkerSetObjectTagEXT(
+    VkDevice                                    device,
+    const VkDebugMarkerObjectTagInfoEXT*        pTagInfo);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkDebugMarkerSetObjectNameEXT(
+    VkDevice                                    device,
+    const VkDebugMarkerObjectNameInfoEXT*       pNameInfo);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDebugMarkerBeginEXT(
+    VkCommandBuffer                             commandBuffer,
+    const VkDebugMarkerMarkerInfoEXT*           pMarkerInfo);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDebugMarkerEndEXT(
+    VkCommandBuffer                             commandBuffer);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDebugMarkerInsertEXT(
+    VkCommandBuffer                             commandBuffer,
+    const VkDebugMarkerMarkerInfoEXT*           pMarkerInfo);
+#endif
+
+#define VK_AMD_gcn_shader 1
+#define VK_AMD_GCN_SHADER_SPEC_VERSION    1
+#define VK_AMD_GCN_SHADER_EXTENSION_NAME  "VK_AMD_gcn_shader"
+
+
+#define VK_NV_dedicated_allocation 1
+#define VK_NV_DEDICATED_ALLOCATION_SPEC_VERSION 1
+#define VK_NV_DEDICATED_ALLOCATION_EXTENSION_NAME "VK_NV_dedicated_allocation"
+
+typedef struct VkDedicatedAllocationImageCreateInfoNV {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkBool32           dedicatedAllocation;
+} VkDedicatedAllocationImageCreateInfoNV;
+
+typedef struct VkDedicatedAllocationBufferCreateInfoNV {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkBool32           dedicatedAllocation;
+} VkDedicatedAllocationBufferCreateInfoNV;
+
+typedef struct VkDedicatedAllocationMemoryAllocateInfoNV {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkImage            image;
+    VkBuffer           buffer;
+} VkDedicatedAllocationMemoryAllocateInfoNV;
+
+
+
+#define VK_AMD_draw_indirect_count 1
+#define VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION 1
+#define VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME "VK_AMD_draw_indirect_count"
+
+typedef void (VKAPI_PTR *PFN_vkCmdDrawIndirectCountAMD)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride);
+typedef void (VKAPI_PTR *PFN_vkCmdDrawIndexedIndirectCountAMD)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndirectCountAMD(
+    VkCommandBuffer                             commandBuffer,
+    VkBuffer                                    buffer,
+    VkDeviceSize                                offset,
+    VkBuffer                                    countBuffer,
+    VkDeviceSize                                countBufferOffset,
+    uint32_t                                    maxDrawCount,
+    uint32_t                                    stride);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndexedIndirectCountAMD(
+    VkCommandBuffer                             commandBuffer,
+    VkBuffer                                    buffer,
+    VkDeviceSize                                offset,
+    VkBuffer                                    countBuffer,
+    VkDeviceSize                                countBufferOffset,
+    uint32_t                                    maxDrawCount,
+    uint32_t                                    stride);
+#endif
+
+#define VK_AMD_negative_viewport_height 1
+#define VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_SPEC_VERSION 1
+#define VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_EXTENSION_NAME "VK_AMD_negative_viewport_height"
+
+
+#define VK_AMD_gpu_shader_half_float 1
+#define VK_AMD_GPU_SHADER_HALF_FLOAT_SPEC_VERSION 1
+#define VK_AMD_GPU_SHADER_HALF_FLOAT_EXTENSION_NAME "VK_AMD_gpu_shader_half_float"
+
+
+#define VK_AMD_shader_ballot 1
+#define VK_AMD_SHADER_BALLOT_SPEC_VERSION 1
+#define VK_AMD_SHADER_BALLOT_EXTENSION_NAME "VK_AMD_shader_ballot"
+
+
+#define VK_AMD_texture_gather_bias_lod 1
+#define VK_AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION 1
+#define VK_AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME "VK_AMD_texture_gather_bias_lod"
+
+typedef struct VkTextureLODGatherFormatPropertiesAMD {
+    VkStructureType    sType;
+    void*              pNext;
+    VkBool32           supportsTextureGatherLODBiasAMD;
+} VkTextureLODGatherFormatPropertiesAMD;
+
+
+
+#define VK_KHX_multiview 1
+#define VK_KHX_MULTIVIEW_SPEC_VERSION     1
+#define VK_KHX_MULTIVIEW_EXTENSION_NAME   "VK_KHX_multiview"
+
+typedef struct VkRenderPassMultiviewCreateInfoKHX {
+    VkStructureType    sType;
+    const void*        pNext;
+    uint32_t           subpassCount;
+    const uint32_t*    pViewMasks;
+    uint32_t           dependencyCount;
+    const int32_t*     pViewOffsets;
+    uint32_t           correlationMaskCount;
+    const uint32_t*    pCorrelationMasks;
+} VkRenderPassMultiviewCreateInfoKHX;
+
+typedef struct VkPhysicalDeviceMultiviewFeaturesKHX {
+    VkStructureType    sType;
+    void*              pNext;
+    VkBool32           multiview;
+    VkBool32           multiviewGeometryShader;
+    VkBool32           multiviewTessellationShader;
+} VkPhysicalDeviceMultiviewFeaturesKHX;
+
+typedef struct VkPhysicalDeviceMultiviewPropertiesKHX {
+    VkStructureType    sType;
+    void*              pNext;
+    uint32_t           maxMultiviewViewCount;
+    uint32_t           maxMultiviewInstanceIndex;
+} VkPhysicalDeviceMultiviewPropertiesKHX;
+
+
+
+#define VK_IMG_format_pvrtc 1
+#define VK_IMG_FORMAT_PVRTC_SPEC_VERSION  1
+#define VK_IMG_FORMAT_PVRTC_EXTENSION_NAME "VK_IMG_format_pvrtc"
+
+
+#define VK_NV_external_memory_capabilities 1
+#define VK_NV_EXTERNAL_MEMORY_CAPABILITIES_SPEC_VERSION 1
+#define VK_NV_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME "VK_NV_external_memory_capabilities"
+
+
+typedef enum VkExternalMemoryHandleTypeFlagBitsNV {
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_NV = 0x00000001,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_NV = 0x00000002,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_IMAGE_BIT_NV = 0x00000004,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_IMAGE_KMT_BIT_NV = 0x00000008,
+    VK_EXTERNAL_MEMORY_HANDLE_TYPE_FLAG_BITS_MAX_ENUM_NV = 0x7FFFFFFF
+} VkExternalMemoryHandleTypeFlagBitsNV;
+typedef VkFlags VkExternalMemoryHandleTypeFlagsNV;
+
+typedef enum VkExternalMemoryFeatureFlagBitsNV {
+    VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT_NV = 0x00000001,
+    VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT_NV = 0x00000002,
+    VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT_NV = 0x00000004,
+    VK_EXTERNAL_MEMORY_FEATURE_FLAG_BITS_MAX_ENUM_NV = 0x7FFFFFFF
+} VkExternalMemoryFeatureFlagBitsNV;
+typedef VkFlags VkExternalMemoryFeatureFlagsNV;
+
+typedef struct VkExternalImageFormatPropertiesNV {
+    VkImageFormatProperties              imageFormatProperties;
+    VkExternalMemoryFeatureFlagsNV       externalMemoryFeatures;
+    VkExternalMemoryHandleTypeFlagsNV    exportFromImportedHandleTypes;
+    VkExternalMemoryHandleTypeFlagsNV    compatibleHandleTypes;
+} VkExternalImageFormatPropertiesNV;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalImageFormatPropertiesNV)(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkExternalMemoryHandleTypeFlagsNV externalHandleType, VkExternalImageFormatPropertiesNV* pExternalImageFormatProperties);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceExternalImageFormatPropertiesNV(
+    VkPhysicalDevice                            physicalDevice,
+    VkFormat                                    format,
+    VkImageType                                 type,
+    VkImageTiling                               tiling,
+    VkImageUsageFlags                           usage,
+    VkImageCreateFlags                          flags,
+    VkExternalMemoryHandleTypeFlagsNV           externalHandleType,
+    VkExternalImageFormatPropertiesNV*          pExternalImageFormatProperties);
+#endif
+
+#define VK_NV_external_memory 1
+#define VK_NV_EXTERNAL_MEMORY_SPEC_VERSION 1
+#define VK_NV_EXTERNAL_MEMORY_EXTENSION_NAME "VK_NV_external_memory"
+
+typedef struct VkExternalMemoryImageCreateInfoNV {
+    VkStructureType                      sType;
+    const void*                          pNext;
+    VkExternalMemoryHandleTypeFlagsNV    handleTypes;
+} VkExternalMemoryImageCreateInfoNV;
+
+typedef struct VkExportMemoryAllocateInfoNV {
+    VkStructureType                      sType;
+    const void*                          pNext;
+    VkExternalMemoryHandleTypeFlagsNV    handleTypes;
+} VkExportMemoryAllocateInfoNV;
+
+
+
+#ifdef VK_USE_PLATFORM_WIN32_KHR
+#define VK_NV_external_memory_win32 1
+#define VK_NV_EXTERNAL_MEMORY_WIN32_SPEC_VERSION 1
+#define VK_NV_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME "VK_NV_external_memory_win32"
+
+typedef struct VkImportMemoryWin32HandleInfoNV {
+    VkStructureType                      sType;
+    const void*                          pNext;
+    VkExternalMemoryHandleTypeFlagsNV    handleType;
+    HANDLE                               handle;
+} VkImportMemoryWin32HandleInfoNV;
+
+typedef struct VkExportMemoryWin32HandleInfoNV {
+    VkStructureType               sType;
+    const void*                   pNext;
+    const SECURITY_ATTRIBUTES*    pAttributes;
+    DWORD                         dwAccess;
+} VkExportMemoryWin32HandleInfoNV;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkGetMemoryWin32HandleNV)(VkDevice device, VkDeviceMemory memory, VkExternalMemoryHandleTypeFlagsNV handleType, HANDLE* pHandle);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkGetMemoryWin32HandleNV(
+    VkDevice                                    device,
+    VkDeviceMemory                              memory,
+    VkExternalMemoryHandleTypeFlagsNV           handleType,
+    HANDLE*                                     pHandle);
+#endif
+#endif /* VK_USE_PLATFORM_WIN32_KHR */
+
+#ifdef VK_USE_PLATFORM_WIN32_KHR
+#define VK_NV_win32_keyed_mutex 1
+#define VK_NV_WIN32_KEYED_MUTEX_SPEC_VERSION 1
+#define VK_NV_WIN32_KEYED_MUTEX_EXTENSION_NAME "VK_NV_win32_keyed_mutex"
+
+typedef struct VkWin32KeyedMutexAcquireReleaseInfoNV {
+    VkStructureType          sType;
+    const void*              pNext;
+    uint32_t                 acquireCount;
+    const VkDeviceMemory*    pAcquireSyncs;
+    const uint64_t*          pAcquireKeys;
+    const uint32_t*          pAcquireTimeoutMilliseconds;
+    uint32_t                 releaseCount;
+    const VkDeviceMemory*    pReleaseSyncs;
+    const uint64_t*          pReleaseKeys;
+} VkWin32KeyedMutexAcquireReleaseInfoNV;
+
+
+#endif /* VK_USE_PLATFORM_WIN32_KHR */
+
+#define VK_KHX_device_group 1
+#define VK_MAX_DEVICE_GROUP_SIZE_KHX      32
+#define VK_KHX_DEVICE_GROUP_SPEC_VERSION  1
+#define VK_KHX_DEVICE_GROUP_EXTENSION_NAME "VK_KHX_device_group"
+
+
+typedef enum VkPeerMemoryFeatureFlagBitsKHX {
+    VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT_KHX = 0x00000001,
+    VK_PEER_MEMORY_FEATURE_COPY_DST_BIT_KHX = 0x00000002,
+    VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT_KHX = 0x00000004,
+    VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT_KHX = 0x00000008,
+    VK_PEER_MEMORY_FEATURE_FLAG_BITS_MAX_ENUM_KHX = 0x7FFFFFFF
+} VkPeerMemoryFeatureFlagBitsKHX;
+typedef VkFlags VkPeerMemoryFeatureFlagsKHX;
+
+typedef enum VkMemoryAllocateFlagBitsKHX {
+    VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT_KHX = 0x00000001,
+    VK_MEMORY_ALLOCATE_FLAG_BITS_MAX_ENUM_KHX = 0x7FFFFFFF
+} VkMemoryAllocateFlagBitsKHX;
+typedef VkFlags VkMemoryAllocateFlagsKHX;
+
+typedef enum VkDeviceGroupPresentModeFlagBitsKHX {
+    VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHX = 0x00000001,
+    VK_DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHX = 0x00000002,
+    VK_DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHX = 0x00000004,
+    VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHX = 0x00000008,
+    VK_DEVICE_GROUP_PRESENT_MODE_FLAG_BITS_MAX_ENUM_KHX = 0x7FFFFFFF
+} VkDeviceGroupPresentModeFlagBitsKHX;
+typedef VkFlags VkDeviceGroupPresentModeFlagsKHX;
+
+typedef struct VkMemoryAllocateFlagsInfoKHX {
+    VkStructureType             sType;
+    const void*                 pNext;
+    VkMemoryAllocateFlagsKHX    flags;
+    uint32_t                    deviceMask;
+} VkMemoryAllocateFlagsInfoKHX;
+
+typedef struct VkBindBufferMemoryInfoKHX {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkBuffer           buffer;
+    VkDeviceMemory     memory;
+    VkDeviceSize       memoryOffset;
+    uint32_t           deviceIndexCount;
+    const uint32_t*    pDeviceIndices;
+} VkBindBufferMemoryInfoKHX;
+
+typedef struct VkBindImageMemoryInfoKHX {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkImage            image;
+    VkDeviceMemory     memory;
+    VkDeviceSize       memoryOffset;
+    uint32_t           deviceIndexCount;
+    const uint32_t*    pDeviceIndices;
+    uint32_t           SFRRectCount;
+    const VkRect2D*    pSFRRects;
+} VkBindImageMemoryInfoKHX;
+
+typedef struct VkDeviceGroupRenderPassBeginInfoKHX {
+    VkStructureType    sType;
+    const void*        pNext;
+    uint32_t           deviceMask;
+    uint32_t           deviceRenderAreaCount;
+    const VkRect2D*    pDeviceRenderAreas;
+} VkDeviceGroupRenderPassBeginInfoKHX;
+
+typedef struct VkDeviceGroupCommandBufferBeginInfoKHX {
+    VkStructureType    sType;
+    const void*        pNext;
+    uint32_t           deviceMask;
+} VkDeviceGroupCommandBufferBeginInfoKHX;
+
+typedef struct VkDeviceGroupSubmitInfoKHX {
+    VkStructureType    sType;
+    const void*        pNext;
+    uint32_t           waitSemaphoreCount;
+    const uint32_t*    pWaitSemaphoreDeviceIndices;
+    uint32_t           commandBufferCount;
+    const uint32_t*    pCommandBufferDeviceMasks;
+    uint32_t           signalSemaphoreCount;
+    const uint32_t*    pSignalSemaphoreDeviceIndices;
+} VkDeviceGroupSubmitInfoKHX;
+
+typedef struct VkDeviceGroupBindSparseInfoKHX {
+    VkStructureType    sType;
+    const void*        pNext;
+    uint32_t           resourceDeviceIndex;
+    uint32_t           memoryDeviceIndex;
+} VkDeviceGroupBindSparseInfoKHX;
+
+typedef struct VkDeviceGroupPresentCapabilitiesKHX {
+    VkStructureType                     sType;
+    const void*                         pNext;
+    uint32_t                            presentMask[VK_MAX_DEVICE_GROUP_SIZE_KHX];
+    VkDeviceGroupPresentModeFlagsKHX    modes;
+} VkDeviceGroupPresentCapabilitiesKHX;
+
+typedef struct VkImageSwapchainCreateInfoKHX {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkSwapchainKHR     swapchain;
+} VkImageSwapchainCreateInfoKHX;
+
+typedef struct VkBindImageMemorySwapchainInfoKHX {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkSwapchainKHR     swapchain;
+    uint32_t           imageIndex;
+} VkBindImageMemorySwapchainInfoKHX;
+
+typedef struct VkAcquireNextImageInfoKHX {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkSwapchainKHR     swapchain;
+    uint64_t           timeout;
+    VkSemaphore        semaphore;
+    VkFence            fence;
+    uint32_t           deviceMask;
+} VkAcquireNextImageInfoKHX;
+
+typedef struct VkDeviceGroupPresentInfoKHX {
+    VkStructureType                        sType;
+    const void*                            pNext;
+    uint32_t                               swapchainCount;
+    const uint32_t*                        pDeviceMasks;
+    VkDeviceGroupPresentModeFlagBitsKHX    mode;
+} VkDeviceGroupPresentInfoKHX;
+
+typedef struct VkDeviceGroupSwapchainCreateInfoKHX {
+    VkStructureType                     sType;
+    const void*                         pNext;
+    VkDeviceGroupPresentModeFlagsKHX    modes;
+} VkDeviceGroupSwapchainCreateInfoKHX;
+
+
+typedef void (VKAPI_PTR *PFN_vkGetDeviceGroupPeerMemoryFeaturesKHX)(VkDevice device, uint32_t heapIndex, uint32_t localDeviceIndex, uint32_t remoteDeviceIndex, VkPeerMemoryFeatureFlagsKHX* pPeerMemoryFeatures);
+typedef VkResult (VKAPI_PTR *PFN_vkBindBufferMemory2KHX)(VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfoKHX* pBindInfos);
+typedef VkResult (VKAPI_PTR *PFN_vkBindImageMemory2KHX)(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfoKHX* pBindInfos);
+typedef void (VKAPI_PTR *PFN_vkCmdSetDeviceMaskKHX)(VkCommandBuffer commandBuffer, uint32_t deviceMask);
+typedef VkResult (VKAPI_PTR *PFN_vkGetDeviceGroupPresentCapabilitiesKHX)(VkDevice device, VkDeviceGroupPresentCapabilitiesKHX* pDeviceGroupPresentCapabilities);
+typedef VkResult (VKAPI_PTR *PFN_vkGetDeviceGroupSurfacePresentModesKHX)(VkDevice device, VkSurfaceKHR surface, VkDeviceGroupPresentModeFlagsKHX* pModes);
+typedef VkResult (VKAPI_PTR *PFN_vkAcquireNextImage2KHX)(VkDevice device, const VkAcquireNextImageInfoKHX* pAcquireInfo, uint32_t* pImageIndex);
+typedef void (VKAPI_PTR *PFN_vkCmdDispatchBaseKHX)(VkCommandBuffer commandBuffer, uint32_t baseGroupX, uint32_t baseGroupY, uint32_t baseGroupZ, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDevicePresentRectanglesKHX)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pRectCount, VkRect2D* pRects);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkGetDeviceGroupPeerMemoryFeaturesKHX(
+    VkDevice                                    device,
+    uint32_t                                    heapIndex,
+    uint32_t                                    localDeviceIndex,
+    uint32_t                                    remoteDeviceIndex,
+    VkPeerMemoryFeatureFlagsKHX*                pPeerMemoryFeatures);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkBindBufferMemory2KHX(
+    VkDevice                                    device,
+    uint32_t                                    bindInfoCount,
+    const VkBindBufferMemoryInfoKHX*            pBindInfos);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkBindImageMemory2KHX(
+    VkDevice                                    device,
+    uint32_t                                    bindInfoCount,
+    const VkBindImageMemoryInfoKHX*             pBindInfos);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdSetDeviceMaskKHX(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    deviceMask);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetDeviceGroupPresentCapabilitiesKHX(
+    VkDevice                                    device,
+    VkDeviceGroupPresentCapabilitiesKHX*        pDeviceGroupPresentCapabilities);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetDeviceGroupSurfacePresentModesKHX(
+    VkDevice                                    device,
+    VkSurfaceKHR                                surface,
+    VkDeviceGroupPresentModeFlagsKHX*           pModes);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImage2KHX(
+    VkDevice                                    device,
+    const VkAcquireNextImageInfoKHX*            pAcquireInfo,
+    uint32_t*                                   pImageIndex);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdDispatchBaseKHX(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    baseGroupX,
+    uint32_t                                    baseGroupY,
+    uint32_t                                    baseGroupZ,
+    uint32_t                                    groupCountX,
+    uint32_t                                    groupCountY,
+    uint32_t                                    groupCountZ);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDevicePresentRectanglesKHX(
+    VkPhysicalDevice                            physicalDevice,
+    VkSurfaceKHR                                surface,
+    uint32_t*                                   pRectCount,
+    VkRect2D*                                   pRects);
+#endif
+
+#define VK_EXT_validation_flags 1
+#define VK_EXT_VALIDATION_FLAGS_SPEC_VERSION 1
+#define VK_EXT_VALIDATION_FLAGS_EXTENSION_NAME "VK_EXT_validation_flags"
+
+
+typedef enum VkValidationCheckEXT {
+    VK_VALIDATION_CHECK_ALL_EXT = 0,
+    VK_VALIDATION_CHECK_SHADERS_EXT = 1,
+    VK_VALIDATION_CHECK_BEGIN_RANGE_EXT = VK_VALIDATION_CHECK_ALL_EXT,
+    VK_VALIDATION_CHECK_END_RANGE_EXT = VK_VALIDATION_CHECK_SHADERS_EXT,
+    VK_VALIDATION_CHECK_RANGE_SIZE_EXT = (VK_VALIDATION_CHECK_SHADERS_EXT - VK_VALIDATION_CHECK_ALL_EXT + 1),
+    VK_VALIDATION_CHECK_MAX_ENUM_EXT = 0x7FFFFFFF
+} VkValidationCheckEXT;
+
+typedef struct VkValidationFlagsEXT {
+    VkStructureType          sType;
+    const void*              pNext;
+    uint32_t                 disabledValidationCheckCount;
+    VkValidationCheckEXT*    pDisabledValidationChecks;
+} VkValidationFlagsEXT;
+
+
+
+#ifdef VK_USE_PLATFORM_VI_NN
+#define VK_NN_vi_surface 1
+#define VK_NN_VI_SURFACE_SPEC_VERSION     1
+#define VK_NN_VI_SURFACE_EXTENSION_NAME   "VK_NN_vi_surface"
+
+typedef VkFlags VkViSurfaceCreateFlagsNN;
+
+typedef struct VkViSurfaceCreateInfoNN {
+    VkStructureType             sType;
+    const void*                 pNext;
+    VkViSurfaceCreateFlagsNN    flags;
+    void*                       window;
+} VkViSurfaceCreateInfoNN;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateViSurfaceNN)(VkInstance instance, const VkViSurfaceCreateInfoNN* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateViSurfaceNN(
+    VkInstance                                  instance,
+    const VkViSurfaceCreateInfoNN*              pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSurfaceKHR*                               pSurface);
+#endif
+#endif /* VK_USE_PLATFORM_VI_NN */
+
+#define VK_EXT_shader_subgroup_ballot 1
+#define VK_EXT_SHADER_SUBGROUP_BALLOT_SPEC_VERSION 1
+#define VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME "VK_EXT_shader_subgroup_ballot"
+
+
+#define VK_EXT_shader_subgroup_vote 1
+#define VK_EXT_SHADER_SUBGROUP_VOTE_SPEC_VERSION 1
+#define VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME "VK_EXT_shader_subgroup_vote"
+
+
+#define VK_KHX_device_group_creation 1
+#define VK_KHX_DEVICE_GROUP_CREATION_SPEC_VERSION 1
+#define VK_KHX_DEVICE_GROUP_CREATION_EXTENSION_NAME "VK_KHX_device_group_creation"
+
+typedef struct VkPhysicalDeviceGroupPropertiesKHX {
+    VkStructureType     sType;
+    void*               pNext;
+    uint32_t            physicalDeviceCount;
+    VkPhysicalDevice    physicalDevices[VK_MAX_DEVICE_GROUP_SIZE_KHX];
+    VkBool32            subsetAllocation;
+} VkPhysicalDeviceGroupPropertiesKHX;
+
+typedef struct VkDeviceGroupDeviceCreateInfoKHX {
+    VkStructureType            sType;
+    const void*                pNext;
+    uint32_t                   physicalDeviceCount;
+    const VkPhysicalDevice*    pPhysicalDevices;
+} VkDeviceGroupDeviceCreateInfoKHX;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkEnumeratePhysicalDeviceGroupsKHX)(VkInstance instance, uint32_t* pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupPropertiesKHX* pPhysicalDeviceGroupProperties);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkEnumeratePhysicalDeviceGroupsKHX(
+    VkInstance                                  instance,
+    uint32_t*                                   pPhysicalDeviceGroupCount,
+    VkPhysicalDeviceGroupPropertiesKHX*         pPhysicalDeviceGroupProperties);
+#endif
+
+#define VK_NVX_device_generated_commands 1
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkObjectTableNVX)
+VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkIndirectCommandsLayoutNVX)
+
+#define VK_NVX_DEVICE_GENERATED_COMMANDS_SPEC_VERSION 3
+#define VK_NVX_DEVICE_GENERATED_COMMANDS_EXTENSION_NAME "VK_NVX_device_generated_commands"
+
+
+typedef enum VkIndirectCommandsTokenTypeNVX {
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_PIPELINE_NVX = 0,
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_DESCRIPTOR_SET_NVX = 1,
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_INDEX_BUFFER_NVX = 2,
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_VERTEX_BUFFER_NVX = 3,
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_PUSH_CONSTANT_NVX = 4,
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_DRAW_INDEXED_NVX = 5,
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_DRAW_NVX = 6,
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_DISPATCH_NVX = 7,
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_BEGIN_RANGE_NVX = VK_INDIRECT_COMMANDS_TOKEN_TYPE_PIPELINE_NVX,
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_END_RANGE_NVX = VK_INDIRECT_COMMANDS_TOKEN_TYPE_DISPATCH_NVX,
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_RANGE_SIZE_NVX = (VK_INDIRECT_COMMANDS_TOKEN_TYPE_DISPATCH_NVX - VK_INDIRECT_COMMANDS_TOKEN_TYPE_PIPELINE_NVX + 1),
+    VK_INDIRECT_COMMANDS_TOKEN_TYPE_MAX_ENUM_NVX = 0x7FFFFFFF
+} VkIndirectCommandsTokenTypeNVX;
+
+typedef enum VkObjectEntryTypeNVX {
+    VK_OBJECT_ENTRY_TYPE_DESCRIPTOR_SET_NVX = 0,
+    VK_OBJECT_ENTRY_TYPE_PIPELINE_NVX = 1,
+    VK_OBJECT_ENTRY_TYPE_INDEX_BUFFER_NVX = 2,
+    VK_OBJECT_ENTRY_TYPE_VERTEX_BUFFER_NVX = 3,
+    VK_OBJECT_ENTRY_TYPE_PUSH_CONSTANT_NVX = 4,
+    VK_OBJECT_ENTRY_TYPE_BEGIN_RANGE_NVX = VK_OBJECT_ENTRY_TYPE_DESCRIPTOR_SET_NVX,
+    VK_OBJECT_ENTRY_TYPE_END_RANGE_NVX = VK_OBJECT_ENTRY_TYPE_PUSH_CONSTANT_NVX,
+    VK_OBJECT_ENTRY_TYPE_RANGE_SIZE_NVX = (VK_OBJECT_ENTRY_TYPE_PUSH_CONSTANT_NVX - VK_OBJECT_ENTRY_TYPE_DESCRIPTOR_SET_NVX + 1),
+    VK_OBJECT_ENTRY_TYPE_MAX_ENUM_NVX = 0x7FFFFFFF
+} VkObjectEntryTypeNVX;
+
+
+typedef enum VkIndirectCommandsLayoutUsageFlagBitsNVX {
+    VK_INDIRECT_COMMANDS_LAYOUT_USAGE_UNORDERED_SEQUENCES_BIT_NVX = 0x00000001,
+    VK_INDIRECT_COMMANDS_LAYOUT_USAGE_SPARSE_SEQUENCES_BIT_NVX = 0x00000002,
+    VK_INDIRECT_COMMANDS_LAYOUT_USAGE_EMPTY_EXECUTIONS_BIT_NVX = 0x00000004,
+    VK_INDIRECT_COMMANDS_LAYOUT_USAGE_INDEXED_SEQUENCES_BIT_NVX = 0x00000008,
+    VK_INDIRECT_COMMANDS_LAYOUT_USAGE_FLAG_BITS_MAX_ENUM_NVX = 0x7FFFFFFF
+} VkIndirectCommandsLayoutUsageFlagBitsNVX;
+typedef VkFlags VkIndirectCommandsLayoutUsageFlagsNVX;
+
+typedef enum VkObjectEntryUsageFlagBitsNVX {
+    VK_OBJECT_ENTRY_USAGE_GRAPHICS_BIT_NVX = 0x00000001,
+    VK_OBJECT_ENTRY_USAGE_COMPUTE_BIT_NVX = 0x00000002,
+    VK_OBJECT_ENTRY_USAGE_FLAG_BITS_MAX_ENUM_NVX = 0x7FFFFFFF
+} VkObjectEntryUsageFlagBitsNVX;
+typedef VkFlags VkObjectEntryUsageFlagsNVX;
+
+typedef struct VkDeviceGeneratedCommandsFeaturesNVX {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkBool32           computeBindingPointSupport;
+} VkDeviceGeneratedCommandsFeaturesNVX;
+
+typedef struct VkDeviceGeneratedCommandsLimitsNVX {
+    VkStructureType    sType;
+    const void*        pNext;
+    uint32_t           maxIndirectCommandsLayoutTokenCount;
+    uint32_t           maxObjectEntryCounts;
+    uint32_t           minSequenceCountBufferOffsetAlignment;
+    uint32_t           minSequenceIndexBufferOffsetAlignment;
+    uint32_t           minCommandsTokenBufferOffsetAlignment;
+} VkDeviceGeneratedCommandsLimitsNVX;
+
+typedef struct VkIndirectCommandsTokenNVX {
+    VkIndirectCommandsTokenTypeNVX    tokenType;
+    VkBuffer                          buffer;
+    VkDeviceSize                      offset;
+} VkIndirectCommandsTokenNVX;
+
+typedef struct VkIndirectCommandsLayoutTokenNVX {
+    VkIndirectCommandsTokenTypeNVX    tokenType;
+    uint32_t                          bindingUnit;
+    uint32_t                          dynamicCount;
+    uint32_t                          divisor;
+} VkIndirectCommandsLayoutTokenNVX;
+
+typedef struct VkIndirectCommandsLayoutCreateInfoNVX {
+    VkStructureType                            sType;
+    const void*                                pNext;
+    VkPipelineBindPoint                        pipelineBindPoint;
+    VkIndirectCommandsLayoutUsageFlagsNVX      flags;
+    uint32_t                                   tokenCount;
+    const VkIndirectCommandsLayoutTokenNVX*    pTokens;
+} VkIndirectCommandsLayoutCreateInfoNVX;
+
+typedef struct VkCmdProcessCommandsInfoNVX {
+    VkStructureType                      sType;
+    const void*                          pNext;
+    VkObjectTableNVX                     objectTable;
+    VkIndirectCommandsLayoutNVX          indirectCommandsLayout;
+    uint32_t                             indirectCommandsTokenCount;
+    const VkIndirectCommandsTokenNVX*    pIndirectCommandsTokens;
+    uint32_t                             maxSequencesCount;
+    VkCommandBuffer                      targetCommandBuffer;
+    VkBuffer                             sequencesCountBuffer;
+    VkDeviceSize                         sequencesCountOffset;
+    VkBuffer                             sequencesIndexBuffer;
+    VkDeviceSize                         sequencesIndexOffset;
+} VkCmdProcessCommandsInfoNVX;
+
+typedef struct VkCmdReserveSpaceForCommandsInfoNVX {
+    VkStructureType                sType;
+    const void*                    pNext;
+    VkObjectTableNVX               objectTable;
+    VkIndirectCommandsLayoutNVX    indirectCommandsLayout;
+    uint32_t                       maxSequencesCount;
+} VkCmdReserveSpaceForCommandsInfoNVX;
+
+typedef struct VkObjectTableCreateInfoNVX {
+    VkStructureType                      sType;
+    const void*                          pNext;
+    uint32_t                             objectCount;
+    const VkObjectEntryTypeNVX*          pObjectEntryTypes;
+    const uint32_t*                      pObjectEntryCounts;
+    const VkObjectEntryUsageFlagsNVX*    pObjectEntryUsageFlags;
+    uint32_t                             maxUniformBuffersPerDescriptor;
+    uint32_t                             maxStorageBuffersPerDescriptor;
+    uint32_t                             maxStorageImagesPerDescriptor;
+    uint32_t                             maxSampledImagesPerDescriptor;
+    uint32_t                             maxPipelineLayouts;
+} VkObjectTableCreateInfoNVX;
+
+typedef struct VkObjectTableEntryNVX {
+    VkObjectEntryTypeNVX          type;
+    VkObjectEntryUsageFlagsNVX    flags;
+} VkObjectTableEntryNVX;
+
+typedef struct VkObjectTablePipelineEntryNVX {
+    VkObjectEntryTypeNVX          type;
+    VkObjectEntryUsageFlagsNVX    flags;
+    VkPipeline                    pipeline;
+} VkObjectTablePipelineEntryNVX;
+
+typedef struct VkObjectTableDescriptorSetEntryNVX {
+    VkObjectEntryTypeNVX          type;
+    VkObjectEntryUsageFlagsNVX    flags;
+    VkPipelineLayout              pipelineLayout;
+    VkDescriptorSet               descriptorSet;
+} VkObjectTableDescriptorSetEntryNVX;
+
+typedef struct VkObjectTableVertexBufferEntryNVX {
+    VkObjectEntryTypeNVX          type;
+    VkObjectEntryUsageFlagsNVX    flags;
+    VkBuffer                      buffer;
+} VkObjectTableVertexBufferEntryNVX;
+
+typedef struct VkObjectTableIndexBufferEntryNVX {
+    VkObjectEntryTypeNVX          type;
+    VkObjectEntryUsageFlagsNVX    flags;
+    VkBuffer                      buffer;
+    VkIndexType                   indexType;
+} VkObjectTableIndexBufferEntryNVX;
+
+typedef struct VkObjectTablePushConstantEntryNVX {
+    VkObjectEntryTypeNVX          type;
+    VkObjectEntryUsageFlagsNVX    flags;
+    VkPipelineLayout              pipelineLayout;
+    VkShaderStageFlags            stageFlags;
+} VkObjectTablePushConstantEntryNVX;
+
+
+typedef void (VKAPI_PTR *PFN_vkCmdProcessCommandsNVX)(VkCommandBuffer commandBuffer, const VkCmdProcessCommandsInfoNVX* pProcessCommandsInfo);
+typedef void (VKAPI_PTR *PFN_vkCmdReserveSpaceForCommandsNVX)(VkCommandBuffer commandBuffer, const VkCmdReserveSpaceForCommandsInfoNVX* pReserveSpaceInfo);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateIndirectCommandsLayoutNVX)(VkDevice device, const VkIndirectCommandsLayoutCreateInfoNVX* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkIndirectCommandsLayoutNVX* pIndirectCommandsLayout);
+typedef void (VKAPI_PTR *PFN_vkDestroyIndirectCommandsLayoutNVX)(VkDevice device, VkIndirectCommandsLayoutNVX indirectCommandsLayout, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkCreateObjectTableNVX)(VkDevice device, const VkObjectTableCreateInfoNVX* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkObjectTableNVX* pObjectTable);
+typedef void (VKAPI_PTR *PFN_vkDestroyObjectTableNVX)(VkDevice device, VkObjectTableNVX objectTable, const VkAllocationCallbacks* pAllocator);
+typedef VkResult (VKAPI_PTR *PFN_vkRegisterObjectsNVX)(VkDevice device, VkObjectTableNVX objectTable, uint32_t objectCount, const VkObjectTableEntryNVX* const*    ppObjectTableEntries, const uint32_t* pObjectIndices);
+typedef VkResult (VKAPI_PTR *PFN_vkUnregisterObjectsNVX)(VkDevice device, VkObjectTableNVX objectTable, uint32_t objectCount, const VkObjectEntryTypeNVX* pObjectEntryTypes, const uint32_t* pObjectIndices);
+typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX)(VkPhysicalDevice physicalDevice, VkDeviceGeneratedCommandsFeaturesNVX* pFeatures, VkDeviceGeneratedCommandsLimitsNVX* pLimits);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkCmdProcessCommandsNVX(
+    VkCommandBuffer                             commandBuffer,
+    const VkCmdProcessCommandsInfoNVX*          pProcessCommandsInfo);
+
+VKAPI_ATTR void VKAPI_CALL vkCmdReserveSpaceForCommandsNVX(
+    VkCommandBuffer                             commandBuffer,
+    const VkCmdReserveSpaceForCommandsInfoNVX*  pReserveSpaceInfo);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateIndirectCommandsLayoutNVX(
+    VkDevice                                    device,
+    const VkIndirectCommandsLayoutCreateInfoNVX* pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkIndirectCommandsLayoutNVX*                pIndirectCommandsLayout);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyIndirectCommandsLayoutNVX(
+    VkDevice                                    device,
+    VkIndirectCommandsLayoutNVX                 indirectCommandsLayout,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateObjectTableNVX(
+    VkDevice                                    device,
+    const VkObjectTableCreateInfoNVX*           pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkObjectTableNVX*                           pObjectTable);
+
+VKAPI_ATTR void VKAPI_CALL vkDestroyObjectTableNVX(
+    VkDevice                                    device,
+    VkObjectTableNVX                            objectTable,
+    const VkAllocationCallbacks*                pAllocator);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkRegisterObjectsNVX(
+    VkDevice                                    device,
+    VkObjectTableNVX                            objectTable,
+    uint32_t                                    objectCount,
+    const VkObjectTableEntryNVX* const*         ppObjectTableEntries,
+    const uint32_t*                             pObjectIndices);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkUnregisterObjectsNVX(
+    VkDevice                                    device,
+    VkObjectTableNVX                            objectTable,
+    uint32_t                                    objectCount,
+    const VkObjectEntryTypeNVX*                 pObjectEntryTypes,
+    const uint32_t*                             pObjectIndices);
+
+VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX(
+    VkPhysicalDevice                            physicalDevice,
+    VkDeviceGeneratedCommandsFeaturesNVX*       pFeatures,
+    VkDeviceGeneratedCommandsLimitsNVX*         pLimits);
+#endif
+
+#define VK_NV_clip_space_w_scaling 1
+#define VK_NV_CLIP_SPACE_W_SCALING_SPEC_VERSION 1
+#define VK_NV_CLIP_SPACE_W_SCALING_EXTENSION_NAME "VK_NV_clip_space_w_scaling"
+
+typedef struct VkViewportWScalingNV {
+    float    xcoeff;
+    float    ycoeff;
+} VkViewportWScalingNV;
+
+typedef struct VkPipelineViewportWScalingStateCreateInfoNV {
+    VkStructureType                sType;
+    const void*                    pNext;
+    VkBool32                       viewportWScalingEnable;
+    uint32_t                       viewportCount;
+    const VkViewportWScalingNV*    pViewportWScalings;
+} VkPipelineViewportWScalingStateCreateInfoNV;
+
+
+typedef void (VKAPI_PTR *PFN_vkCmdSetViewportWScalingNV)(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewportWScalingNV* pViewportWScalings);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkCmdSetViewportWScalingNV(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    firstViewport,
+    uint32_t                                    viewportCount,
+    const VkViewportWScalingNV*                 pViewportWScalings);
+#endif
+
+#define VK_EXT_direct_mode_display 1
+#define VK_EXT_DIRECT_MODE_DISPLAY_SPEC_VERSION 1
+#define VK_EXT_DIRECT_MODE_DISPLAY_EXTENSION_NAME "VK_EXT_direct_mode_display"
+
+typedef VkResult (VKAPI_PTR *PFN_vkReleaseDisplayEXT)(VkPhysicalDevice physicalDevice, VkDisplayKHR display);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkReleaseDisplayEXT(
+    VkPhysicalDevice                            physicalDevice,
+    VkDisplayKHR                                display);
+#endif
+
+#ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT
+#define VK_EXT_acquire_xlib_display 1
+#include <X11/extensions/Xrandr.h>
+
+#define VK_EXT_ACQUIRE_XLIB_DISPLAY_SPEC_VERSION 1
+#define VK_EXT_ACQUIRE_XLIB_DISPLAY_EXTENSION_NAME "VK_EXT_acquire_xlib_display"
+
+typedef VkResult (VKAPI_PTR *PFN_vkAcquireXlibDisplayEXT)(VkPhysicalDevice physicalDevice, Display* dpy, VkDisplayKHR display);
+typedef VkResult (VKAPI_PTR *PFN_vkGetRandROutputDisplayEXT)(VkPhysicalDevice physicalDevice, Display* dpy, RROutput rrOutput, VkDisplayKHR* pDisplay);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkAcquireXlibDisplayEXT(
+    VkPhysicalDevice                            physicalDevice,
+    Display*                                    dpy,
+    VkDisplayKHR                                display);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetRandROutputDisplayEXT(
+    VkPhysicalDevice                            physicalDevice,
+    Display*                                    dpy,
+    RROutput                                    rrOutput,
+    VkDisplayKHR*                               pDisplay);
+#endif
+#endif /* VK_USE_PLATFORM_XLIB_XRANDR_EXT */
+
+#define VK_EXT_display_surface_counter 1
+#define VK_EXT_DISPLAY_SURFACE_COUNTER_SPEC_VERSION 1
+#define VK_EXT_DISPLAY_SURFACE_COUNTER_EXTENSION_NAME "VK_EXT_display_surface_counter"
+#define VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES2_EXT VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_EXT
+
+
+typedef enum VkSurfaceCounterFlagBitsEXT {
+    VK_SURFACE_COUNTER_VBLANK_EXT = 0x00000001,
+    VK_SURFACE_COUNTER_FLAG_BITS_MAX_ENUM_EXT = 0x7FFFFFFF
+} VkSurfaceCounterFlagBitsEXT;
+typedef VkFlags VkSurfaceCounterFlagsEXT;
+
+typedef struct VkSurfaceCapabilities2EXT {
+    VkStructureType                  sType;
+    void*                            pNext;
+    uint32_t                         minImageCount;
+    uint32_t                         maxImageCount;
+    VkExtent2D                       currentExtent;
+    VkExtent2D                       minImageExtent;
+    VkExtent2D                       maxImageExtent;
+    uint32_t                         maxImageArrayLayers;
+    VkSurfaceTransformFlagsKHR       supportedTransforms;
+    VkSurfaceTransformFlagBitsKHR    currentTransform;
+    VkCompositeAlphaFlagsKHR         supportedCompositeAlpha;
+    VkImageUsageFlags                supportedUsageFlags;
+    VkSurfaceCounterFlagsEXT         supportedSurfaceCounters;
+} VkSurfaceCapabilities2EXT;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceCapabilities2EXT)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkSurfaceCapabilities2EXT* pSurfaceCapabilities);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceCapabilities2EXT(
+    VkPhysicalDevice                            physicalDevice,
+    VkSurfaceKHR                                surface,
+    VkSurfaceCapabilities2EXT*                  pSurfaceCapabilities);
+#endif
+
+#define VK_EXT_display_control 1
+#define VK_EXT_DISPLAY_CONTROL_SPEC_VERSION 1
+#define VK_EXT_DISPLAY_CONTROL_EXTENSION_NAME "VK_EXT_display_control"
+
+
+typedef enum VkDisplayPowerStateEXT {
+    VK_DISPLAY_POWER_STATE_OFF_EXT = 0,
+    VK_DISPLAY_POWER_STATE_SUSPEND_EXT = 1,
+    VK_DISPLAY_POWER_STATE_ON_EXT = 2,
+    VK_DISPLAY_POWER_STATE_BEGIN_RANGE_EXT = VK_DISPLAY_POWER_STATE_OFF_EXT,
+    VK_DISPLAY_POWER_STATE_END_RANGE_EXT = VK_DISPLAY_POWER_STATE_ON_EXT,
+    VK_DISPLAY_POWER_STATE_RANGE_SIZE_EXT = (VK_DISPLAY_POWER_STATE_ON_EXT - VK_DISPLAY_POWER_STATE_OFF_EXT + 1),
+    VK_DISPLAY_POWER_STATE_MAX_ENUM_EXT = 0x7FFFFFFF
+} VkDisplayPowerStateEXT;
+
+typedef enum VkDeviceEventTypeEXT {
+    VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT = 0,
+    VK_DEVICE_EVENT_TYPE_BEGIN_RANGE_EXT = VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT,
+    VK_DEVICE_EVENT_TYPE_END_RANGE_EXT = VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT,
+    VK_DEVICE_EVENT_TYPE_RANGE_SIZE_EXT = (VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT - VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT + 1),
+    VK_DEVICE_EVENT_TYPE_MAX_ENUM_EXT = 0x7FFFFFFF
+} VkDeviceEventTypeEXT;
+
+typedef enum VkDisplayEventTypeEXT {
+    VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT = 0,
+    VK_DISPLAY_EVENT_TYPE_BEGIN_RANGE_EXT = VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT,
+    VK_DISPLAY_EVENT_TYPE_END_RANGE_EXT = VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT,
+    VK_DISPLAY_EVENT_TYPE_RANGE_SIZE_EXT = (VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT - VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT + 1),
+    VK_DISPLAY_EVENT_TYPE_MAX_ENUM_EXT = 0x7FFFFFFF
+} VkDisplayEventTypeEXT;
+
+typedef struct VkDisplayPowerInfoEXT {
+    VkStructureType           sType;
+    const void*               pNext;
+    VkDisplayPowerStateEXT    powerState;
+} VkDisplayPowerInfoEXT;
+
+typedef struct VkDeviceEventInfoEXT {
+    VkStructureType         sType;
+    const void*             pNext;
+    VkDeviceEventTypeEXT    deviceEvent;
+} VkDeviceEventInfoEXT;
+
+typedef struct VkDisplayEventInfoEXT {
+    VkStructureType          sType;
+    const void*              pNext;
+    VkDisplayEventTypeEXT    displayEvent;
+} VkDisplayEventInfoEXT;
+
+typedef struct VkSwapchainCounterCreateInfoEXT {
+    VkStructureType             sType;
+    const void*                 pNext;
+    VkSurfaceCounterFlagsEXT    surfaceCounters;
+} VkSwapchainCounterCreateInfoEXT;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkDisplayPowerControlEXT)(VkDevice device, VkDisplayKHR display, const VkDisplayPowerInfoEXT* pDisplayPowerInfo);
+typedef VkResult (VKAPI_PTR *PFN_vkRegisterDeviceEventEXT)(VkDevice device, const VkDeviceEventInfoEXT* pDeviceEventInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence);
+typedef VkResult (VKAPI_PTR *PFN_vkRegisterDisplayEventEXT)(VkDevice device, VkDisplayKHR display, const VkDisplayEventInfoEXT* pDisplayEventInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence);
+typedef VkResult (VKAPI_PTR *PFN_vkGetSwapchainCounterEXT)(VkDevice device, VkSwapchainKHR swapchain, VkSurfaceCounterFlagBitsEXT counter, uint64_t* pCounterValue);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkDisplayPowerControlEXT(
+    VkDevice                                    device,
+    VkDisplayKHR                                display,
+    const VkDisplayPowerInfoEXT*                pDisplayPowerInfo);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkRegisterDeviceEventEXT(
+    VkDevice                                    device,
+    const VkDeviceEventInfoEXT*                 pDeviceEventInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkFence*                                    pFence);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkRegisterDisplayEventEXT(
+    VkDevice                                    device,
+    VkDisplayKHR                                display,
+    const VkDisplayEventInfoEXT*                pDisplayEventInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkFence*                                    pFence);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetSwapchainCounterEXT(
+    VkDevice                                    device,
+    VkSwapchainKHR                              swapchain,
+    VkSurfaceCounterFlagBitsEXT                 counter,
+    uint64_t*                                   pCounterValue);
+#endif
+
+#define VK_GOOGLE_display_timing 1
+#define VK_GOOGLE_DISPLAY_TIMING_SPEC_VERSION 1
+#define VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME "VK_GOOGLE_display_timing"
+
+typedef struct VkRefreshCycleDurationGOOGLE {
+    uint64_t    refreshDuration;
+} VkRefreshCycleDurationGOOGLE;
+
+typedef struct VkPastPresentationTimingGOOGLE {
+    uint32_t    presentID;
+    uint64_t    desiredPresentTime;
+    uint64_t    actualPresentTime;
+    uint64_t    earliestPresentTime;
+    uint64_t    presentMargin;
+} VkPastPresentationTimingGOOGLE;
+
+typedef struct VkPresentTimeGOOGLE {
+    uint32_t    presentID;
+    uint64_t    desiredPresentTime;
+} VkPresentTimeGOOGLE;
+
+typedef struct VkPresentTimesInfoGOOGLE {
+    VkStructureType               sType;
+    const void*                   pNext;
+    uint32_t                      swapchainCount;
+    const VkPresentTimeGOOGLE*    pTimes;
+} VkPresentTimesInfoGOOGLE;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkGetRefreshCycleDurationGOOGLE)(VkDevice device, VkSwapchainKHR swapchain, VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties);
+typedef VkResult (VKAPI_PTR *PFN_vkGetPastPresentationTimingGOOGLE)(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pPresentationTimingCount, VkPastPresentationTimingGOOGLE* pPresentationTimings);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkGetRefreshCycleDurationGOOGLE(
+    VkDevice                                    device,
+    VkSwapchainKHR                              swapchain,
+    VkRefreshCycleDurationGOOGLE*               pDisplayTimingProperties);
+
+VKAPI_ATTR VkResult VKAPI_CALL vkGetPastPresentationTimingGOOGLE(
+    VkDevice                                    device,
+    VkSwapchainKHR                              swapchain,
+    uint32_t*                                   pPresentationTimingCount,
+    VkPastPresentationTimingGOOGLE*             pPresentationTimings);
+#endif
+
+#define VK_NV_sample_mask_override_coverage 1
+#define VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION 1
+#define VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME "VK_NV_sample_mask_override_coverage"
+
+
+#define VK_NV_geometry_shader_passthrough 1
+#define VK_NV_GEOMETRY_SHADER_PASSTHROUGH_SPEC_VERSION 1
+#define VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME "VK_NV_geometry_shader_passthrough"
+
+
+#define VK_NV_viewport_array2 1
+#define VK_NV_VIEWPORT_ARRAY2_SPEC_VERSION 1
+#define VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME "VK_NV_viewport_array2"
+
+
+#define VK_NVX_multiview_per_view_attributes 1
+#define VK_NVX_MULTIVIEW_PER_VIEW_ATTRIBUTES_SPEC_VERSION 1
+#define VK_NVX_MULTIVIEW_PER_VIEW_ATTRIBUTES_EXTENSION_NAME "VK_NVX_multiview_per_view_attributes"
+
+typedef struct VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVX {
+    VkStructureType    sType;
+    void*              pNext;
+    VkBool32           perViewPositionAllComponents;
+} VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVX;
+
+
+
+#define VK_NV_viewport_swizzle 1
+#define VK_NV_VIEWPORT_SWIZZLE_SPEC_VERSION 1
+#define VK_NV_VIEWPORT_SWIZZLE_EXTENSION_NAME "VK_NV_viewport_swizzle"
+
+
+typedef enum VkViewportCoordinateSwizzleNV {
+    VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_X_NV = 0,
+    VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_X_NV = 1,
+    VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_Y_NV = 2,
+    VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_Y_NV = 3,
+    VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_Z_NV = 4,
+    VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_Z_NV = 5,
+    VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_W_NV = 6,
+    VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_W_NV = 7,
+    VK_VIEWPORT_COORDINATE_SWIZZLE_BEGIN_RANGE_NV = VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_X_NV,
+    VK_VIEWPORT_COORDINATE_SWIZZLE_END_RANGE_NV = VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_W_NV,
+    VK_VIEWPORT_COORDINATE_SWIZZLE_RANGE_SIZE_NV = (VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_W_NV - VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_X_NV + 1),
+    VK_VIEWPORT_COORDINATE_SWIZZLE_MAX_ENUM_NV = 0x7FFFFFFF
+} VkViewportCoordinateSwizzleNV;
+
+typedef VkFlags VkPipelineViewportSwizzleStateCreateFlagsNV;
+
+typedef struct VkViewportSwizzleNV {
+    VkViewportCoordinateSwizzleNV    x;
+    VkViewportCoordinateSwizzleNV    y;
+    VkViewportCoordinateSwizzleNV    z;
+    VkViewportCoordinateSwizzleNV    w;
+} VkViewportSwizzleNV;
+
+typedef struct VkPipelineViewportSwizzleStateCreateInfoNV {
+    VkStructureType                                sType;
+    const void*                                    pNext;
+    VkPipelineViewportSwizzleStateCreateFlagsNV    flags;
+    uint32_t                                       viewportCount;
+    const VkViewportSwizzleNV*                     pViewportSwizzles;
+} VkPipelineViewportSwizzleStateCreateInfoNV;
+
+
+
+#define VK_EXT_discard_rectangles 1
+#define VK_EXT_DISCARD_RECTANGLES_SPEC_VERSION 1
+#define VK_EXT_DISCARD_RECTANGLES_EXTENSION_NAME "VK_EXT_discard_rectangles"
+
+
+typedef enum VkDiscardRectangleModeEXT {
+    VK_DISCARD_RECTANGLE_MODE_INCLUSIVE_EXT = 0,
+    VK_DISCARD_RECTANGLE_MODE_EXCLUSIVE_EXT = 1,
+    VK_DISCARD_RECTANGLE_MODE_BEGIN_RANGE_EXT = VK_DISCARD_RECTANGLE_MODE_INCLUSIVE_EXT,
+    VK_DISCARD_RECTANGLE_MODE_END_RANGE_EXT = VK_DISCARD_RECTANGLE_MODE_EXCLUSIVE_EXT,
+    VK_DISCARD_RECTANGLE_MODE_RANGE_SIZE_EXT = (VK_DISCARD_RECTANGLE_MODE_EXCLUSIVE_EXT - VK_DISCARD_RECTANGLE_MODE_INCLUSIVE_EXT + 1),
+    VK_DISCARD_RECTANGLE_MODE_MAX_ENUM_EXT = 0x7FFFFFFF
+} VkDiscardRectangleModeEXT;
+
+typedef VkFlags VkPipelineDiscardRectangleStateCreateFlagsEXT;
+
+typedef struct VkPhysicalDeviceDiscardRectanglePropertiesEXT {
+    VkStructureType    sType;
+    void*              pNext;
+    uint32_t           maxDiscardRectangles;
+} VkPhysicalDeviceDiscardRectanglePropertiesEXT;
+
+typedef struct VkPipelineDiscardRectangleStateCreateInfoEXT {
+    VkStructureType                                  sType;
+    const void*                                      pNext;
+    VkPipelineDiscardRectangleStateCreateFlagsEXT    flags;
+    VkDiscardRectangleModeEXT                        discardRectangleMode;
+    uint32_t                                         discardRectangleCount;
+    const VkRect2D*                                  pDiscardRectangles;
+} VkPipelineDiscardRectangleStateCreateInfoEXT;
+
+
+typedef void (VKAPI_PTR *PFN_vkCmdSetDiscardRectangleEXT)(VkCommandBuffer commandBuffer, uint32_t firstDiscardRectangle, uint32_t discardRectangleCount, const VkRect2D* pDiscardRectangles);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkCmdSetDiscardRectangleEXT(
+    VkCommandBuffer                             commandBuffer,
+    uint32_t                                    firstDiscardRectangle,
+    uint32_t                                    discardRectangleCount,
+    const VkRect2D*                             pDiscardRectangles);
+#endif
+
+#define VK_EXT_swapchain_colorspace 1
+#define VK_EXT_SWAPCHAIN_COLOR_SPACE_SPEC_VERSION 3
+#define VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME "VK_EXT_swapchain_colorspace"
+
+
+#define VK_EXT_hdr_metadata 1
+#define VK_EXT_HDR_METADATA_SPEC_VERSION  1
+#define VK_EXT_HDR_METADATA_EXTENSION_NAME "VK_EXT_hdr_metadata"
+
+typedef struct VkXYColorEXT {
+    float    x;
+    float    y;
+} VkXYColorEXT;
+
+typedef struct VkHdrMetadataEXT {
+    VkStructureType    sType;
+    const void*        pNext;
+    VkXYColorEXT       displayPrimaryRed;
+    VkXYColorEXT       displayPrimaryGreen;
+    VkXYColorEXT       displayPrimaryBlue;
+    VkXYColorEXT       whitePoint;
+    float              maxLuminance;
+    float              minLuminance;
+    float              maxContentLightLevel;
+    float              maxFrameAverageLightLevel;
+} VkHdrMetadataEXT;
+
+
+typedef void (VKAPI_PTR *PFN_vkSetHdrMetadataEXT)(VkDevice device, uint32_t swapchainCount, const VkSwapchainKHR* pSwapchains, const VkHdrMetadataEXT* pMetadata);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR void VKAPI_CALL vkSetHdrMetadataEXT(
+    VkDevice                                    device,
+    uint32_t                                    swapchainCount,
+    const VkSwapchainKHR*                       pSwapchains,
+    const VkHdrMetadataEXT*                     pMetadata);
+#endif
+
+#ifdef VK_USE_PLATFORM_IOS_MVK
+#define VK_MVK_ios_surface 1
+#define VK_MVK_IOS_SURFACE_SPEC_VERSION   2
+#define VK_MVK_IOS_SURFACE_EXTENSION_NAME "VK_MVK_ios_surface"
+
+typedef VkFlags VkIOSSurfaceCreateFlagsMVK;
+
+typedef struct VkIOSSurfaceCreateInfoMVK {
+    VkStructureType               sType;
+    const void*                   pNext;
+    VkIOSSurfaceCreateFlagsMVK    flags;
+    const void*                   pView;
+} VkIOSSurfaceCreateInfoMVK;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateIOSSurfaceMVK)(VkInstance instance, const VkIOSSurfaceCreateInfoMVK* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateIOSSurfaceMVK(
+    VkInstance                                  instance,
+    const VkIOSSurfaceCreateInfoMVK*            pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSurfaceKHR*                               pSurface);
+#endif
+#endif /* VK_USE_PLATFORM_IOS_MVK */
+
+#ifdef VK_USE_PLATFORM_MACOS_MVK
+#define VK_MVK_macos_surface 1
+#define VK_MVK_MACOS_SURFACE_SPEC_VERSION 2
+#define VK_MVK_MACOS_SURFACE_EXTENSION_NAME "VK_MVK_macos_surface"
+
+typedef VkFlags VkMacOSSurfaceCreateFlagsMVK;
+
+typedef struct VkMacOSSurfaceCreateInfoMVK {
+    VkStructureType                 sType;
+    const void*                     pNext;
+    VkMacOSSurfaceCreateFlagsMVK    flags;
+    const void*                     pView;
+} VkMacOSSurfaceCreateInfoMVK;
+
+
+typedef VkResult (VKAPI_PTR *PFN_vkCreateMacOSSurfaceMVK)(VkInstance instance, const VkMacOSSurfaceCreateInfoMVK* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface);
+
+#ifndef VK_NO_PROTOTYPES
+VKAPI_ATTR VkResult VKAPI_CALL vkCreateMacOSSurfaceMVK(
+    VkInstance                                  instance,
+    const VkMacOSSurfaceCreateInfoMVK*          pCreateInfo,
+    const VkAllocationCallbacks*                pAllocator,
+    VkSurfaceKHR*                               pSurface);
+#endif
+#endif /* VK_USE_PLATFORM_MACOS_MVK */
+
+#define VK_EXT_sampler_filter_minmax 1
+#define VK_EXT_SAMPLER_FILTER_MINMAX_SPEC_VERSION 1
+#define VK_EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME "VK_EXT_sampler_filter_minmax"
+
+
+typedef enum VkSamplerReductionModeEXT {
+    VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT = 0,
+    VK_SAMPLER_REDUCTION_MODE_MIN_EXT = 1,
+    VK_SAMPLER_REDUCTION_MODE_MAX_EXT = 2,
+    VK_SAMPLER_REDUCTION_MODE_BEGIN_RANGE_EXT = VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT,
+    VK_SAMPLER_REDUCTION_MODE_END_RANGE_EXT = VK_SAMPLER_REDUCTION_MODE_MAX_EXT,
+    VK_SAMPLER_REDUCTION_MODE_RANGE_SIZE_EXT = (VK_SAMPLER_REDUCTION_MODE_MAX_EXT - VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT + 1),
+    VK_SAMPLER_REDUCTION_MODE_MAX_ENUM_EXT = 0x7FFFFFFF
+} VkSamplerReductionModeEXT;
+
+typedef struct VkSamplerReductionModeCreateInfoEXT {
+    VkStructureType              sType;
+    const void*                  pNext;
+    VkSamplerReductionModeEXT    reductionMode;
+} VkSamplerReductionModeCreateInfoEXT;
+
+typedef struct VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT {
+    VkStructureType    sType;
+    void*              pNext;
+    VkBool32           filterMinmaxSingleComponentFormats;
+    VkBool32           filterMinmaxImageComponentMapping;
+} VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT;
+
+
+
+#define VK_AMD_gpu_shader_int16 1
+#define VK_AMD_GPU_SHADER_INT16_SPEC_VERSION 1
+#define VK_AMD_GPU_SHADER_INT16_EXTENSION_NAME "VK_AMD_gpu_shader_int16"
+
+
+#define VK_AMD_mixed_attachment_samples 1
+#define VK_AMD_MIXED_ATTACHMENT_SAMPLES_SPEC_VERSION 1
+#define VK_AMD_MIXED_ATTACHMENT_SAMPLES_EXTENSION_NAME "VK_AMD_mixed_attachment_samples"
+
+
+#define VK_EXT_shader_stencil_export 1
+#define VK_EXT_SHADER_STENCIL_EXPORT_SPEC_VERSION 1
+#define VK_EXT_SHADER_STENCIL_EXPORT_EXTENSION_NAME "VK_EXT_shader_stencil_export"
+
+
+#define VK_EXT_blend_operation_advanced 1
+#define VK_EXT_BLEND_OPERATION_ADVANCED_SPEC_VERSION 2
+#define VK_EXT_BLEND_OPERATION_ADVANCED_EXTENSION_NAME "VK_EXT_blend_operation_advanced"
+
+
+typedef enum VkBlendOverlapEXT {
+    VK_BLEND_OVERLAP_UNCORRELATED_EXT = 0,
+    VK_BLEND_OVERLAP_DISJOINT_EXT = 1,
+    VK_BLEND_OVERLAP_CONJOINT_EXT = 2,
+    VK_BLEND_OVERLAP_BEGIN_RANGE_EXT = VK_BLEND_OVERLAP_UNCORRELATED_EXT,
+    VK_BLEND_OVERLAP_END_RANGE_EXT = VK_BLEND_OVERLAP_CONJOINT_EXT,
+    VK_BLEND_OVERLAP_RANGE_SIZE_EXT = (VK_BLEND_OVERLAP_CONJOINT_EXT - VK_BLEND_OVERLAP_UNCORRELATED_EXT + 1),
+    VK_BLEND_OVERLAP_MAX_ENUM_EXT = 0x7FFFFFFF
+} VkBlendOverlapEXT;
+
+typedef struct VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT {
+    VkStructureType    sType;
+    void*              pNext;
+    VkBool32           advancedBlendCoherentOperations;
+} VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT;
+
+typedef struct VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT {
+    VkStructureType    sType;
+    void*              pNext;
+    uint32_t           advancedBlendMaxColorAttachments;
+    VkBool32           advancedBlendIndependentBlend;
+    VkBool32           advancedBlendNonPremultipliedSrcColor;
+    VkBool32           advancedBlendNonPremultipliedDstColor;
+    VkBool32           advancedBlendCorrelatedOverlap;
+    VkBool32           advancedBlendAllOperations;
+} VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT;
+
+typedef struct VkPipelineColorBlendAdvancedStateCreateInfoEXT {
+    VkStructureType      sType;
+    const void*          pNext;
+    VkBool32             srcPremultiplied;
+    VkBool32             dstPremultiplied;
+    VkBlendOverlapEXT    blendOverlap;
+} VkPipelineColorBlendAdvancedStateCreateInfoEXT;
+
+
+
+#define VK_NV_fragment_coverage_to_color 1
+#define VK_NV_FRAGMENT_COVERAGE_TO_COLOR_SPEC_VERSION 1
+#define VK_NV_FRAGMENT_COVERAGE_TO_COLOR_EXTENSION_NAME "VK_NV_fragment_coverage_to_color"
+
+typedef VkFlags VkPipelineCoverageToColorStateCreateFlagsNV;
+
+typedef struct VkPipelineCoverageToColorStateCreateInfoNV {
+    VkStructureType                                sType;
+    const void*                                    pNext;
+    VkPipelineCoverageToColorStateCreateFlagsNV    flags;
+    VkBool32                                       coverageToColorEnable;
+    uint32_t                                       coverageToColorLocation;
+} VkPipelineCoverageToColorStateCreateInfoNV;
+
+
+
+#define VK_NV_framebuffer_mixed_samples 1
+#define VK_NV_FRAMEBUFFER_MIXED_SAMPLES_SPEC_VERSION 1
+#define VK_NV_FRAMEBUFFER_MIXED_SAMPLES_EXTENSION_NAME "VK_NV_framebuffer_mixed_samples"
+
+
+typedef enum VkCoverageModulationModeNV {
+    VK_COVERAGE_MODULATION_MODE_NONE_NV = 0,
+    VK_COVERAGE_MODULATION_MODE_RGB_NV = 1,
+    VK_COVERAGE_MODULATION_MODE_ALPHA_NV = 2,
+    VK_COVERAGE_MODULATION_MODE_RGBA_NV = 3,
+    VK_COVERAGE_MODULATION_MODE_BEGIN_RANGE_NV = VK_COVERAGE_MODULATION_MODE_NONE_NV,
+    VK_COVERAGE_MODULATION_MODE_END_RANGE_NV = VK_COVERAGE_MODULATION_MODE_RGBA_NV,
+    VK_COVERAGE_MODULATION_MODE_RANGE_SIZE_NV = (VK_COVERAGE_MODULATION_MODE_RGBA_NV - VK_COVERAGE_MODULATION_MODE_NONE_NV + 1),
+    VK_COVERAGE_MODULATION_MODE_MAX_ENUM_NV = 0x7FFFFFFF
+} VkCoverageModulationModeNV;
+
+typedef VkFlags VkPipelineCoverageModulationStateCreateFlagsNV;
+
+typedef struct VkPipelineCoverageModulationStateCreateInfoNV {
+    VkStructureType                                   sType;
+    const void*                                       pNext;
+    VkPipelineCoverageModulationStateCreateFlagsNV    flags;
+    VkCoverageModulationModeNV                        coverageModulationMode;
+    VkBool32                                          coverageModulationTableEnable;
+    uint32_t                                          coverageModulationTableCount;
+    const float*                                      pCoverageModulationTable;
+} VkPipelineCoverageModulationStateCreateInfoNV;
+
+
+
+#define VK_NV_fill_rectangle 1
+#define VK_NV_FILL_RECTANGLE_SPEC_VERSION 1
+#define VK_NV_FILL_RECTANGLE_EXTENSION_NAME "VK_NV_fill_rectangle"
+
+
+#define VK_EXT_post_depth_coverage 1
+#define VK_EXT_POST_DEPTH_COVERAGE_SPEC_VERSION 1
+#define VK_EXT_POST_DEPTH_COVERAGE_EXTENSION_NAME "VK_EXT_post_depth_coverage"
+
+
+#define VK_EXT_shader_viewport_index_layer 1
+#define VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION 1
+#define VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME "VK_EXT_shader_viewport_index_layer"
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/video/kmsdrm/SDL_kmsdrmdyn.c b/src/video/kmsdrm/SDL_kmsdrmdyn.c
new file mode 100644
index 0000000..9530b2a
--- /dev/null
+++ b/src/video/kmsdrm/SDL_kmsdrmdyn.c
@@ -0,0 +1,171 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_DRIVER_KMSDRM
+
+#define DEBUG_DYNAMIC_KMSDRM 0
+
+#include "SDL_kmsdrmdyn.h"
+
+#if DEBUG_DYNAMIC_KMSDRM
+#include "SDL_log.h"
+#endif
+
+#ifdef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC
+
+#include "SDL_name.h"
+#include "SDL_loadso.h"
+
+typedef struct
+{
+    void *lib;
+    const char *libname;
+} kmsdrmdynlib;
+
+#ifndef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC
+#define SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC NULL
+#endif
+#ifndef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM
+#define SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM NULL
+#endif
+
+static kmsdrmdynlib kmsdrmlibs[] = {
+    {NULL, SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC},
+    {NULL, SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM}
+};
+
+static void *
+KMSDRM_GetSym(const char *fnname, int *pHasModule)
+{
+    int i;
+    void *fn = NULL;
+    for (i = 0; i < SDL_TABLESIZE(kmsdrmlibs); i++) {
+        if (kmsdrmlibs[i].lib != NULL) {
+            fn = SDL_LoadFunction(kmsdrmlibs[i].lib, fnname);
+            if (fn != NULL)
+                break;
+        }
+    }
+
+#if DEBUG_DYNAMIC_KMSDRM
+    if (fn != NULL)
+        SDL_Log("KMSDRM: Found '%s' in %s (%p)\n", fnname, kmsdrmlibs[i].libname, fn);
+    else
+        SDL_Log("KMSDRM: Symbol '%s' NOT FOUND!\n", fnname);
+#endif
+
+    if (fn == NULL)
+        *pHasModule = 0;  /* kill this module. */
+
+    return fn;
+}
+
+#endif /* SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC */
+
+/* Define all the function pointers and wrappers... */
+#define SDL_KMSDRM_MODULE(modname) int SDL_KMSDRM_HAVE_##modname = 0;
+#define SDL_KMSDRM_SYM(rc,fn,params) SDL_DYNKMSDRMFN_##fn KMSDRM_##fn = NULL;
+#define SDL_KMSDRM_SYM_CONST(type,name) SDL_DYNKMSDRMCONST_##name KMSDRM_##name = NULL;
+#include "SDL_kmsdrmsym.h"
+
+static int kmsdrm_load_refcount = 0;
+
+void
+SDL_KMSDRM_UnloadSymbols(void)
+{
+    /* Don't actually unload if more than one module is using the libs... */
+    if (kmsdrm_load_refcount > 0) {
+        if (--kmsdrm_load_refcount == 0) {
+#ifdef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC
+            int i;
+#endif
+
+            /* set all the function pointers to NULL. */
+#define SDL_KMSDRM_MODULE(modname) SDL_KMSDRM_HAVE_##modname = 0;
+#define SDL_KMSDRM_SYM(rc,fn,params) KMSDRM_##fn = NULL;
+#define SDL_KMSDRM_SYM_CONST(type,name) KMSDRM_##name = NULL;
+#include "SDL_kmsdrmsym.h"
+
+
+#ifdef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC
+            for (i = 0; i < SDL_TABLESIZE(kmsdrmlibs); i++) {
+                if (kmsdrmlibs[i].lib != NULL) {
+                    SDL_UnloadObject(kmsdrmlibs[i].lib);
+                    kmsdrmlibs[i].lib = NULL;
+                }
+            }
+#endif
+        }
+    }
+}
+
+/* returns non-zero if all needed symbols were loaded. */
+int
+SDL_KMSDRM_LoadSymbols(void)
+{
+    int rc = 1;                 /* always succeed if not using Dynamic KMSDRM stuff. */
+
+    /* deal with multiple modules needing these symbols... */
+    if (kmsdrm_load_refcount++ == 0) {
+#ifdef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC
+        int i;
+        int *thismod = NULL;
+        for (i = 0; i < SDL_TABLESIZE(kmsdrmlibs); i++) {
+            if (kmsdrmlibs[i].libname != NULL) {
+                kmsdrmlibs[i].lib = SDL_LoadObject(kmsdrmlibs[i].libname);
+            }
+        }
+
+#define SDL_KMSDRM_MODULE(modname) SDL_KMSDRM_HAVE_##modname = 1; /* default yes */
+#include "SDL_kmsdrmsym.h"
+
+#define SDL_KMSDRM_MODULE(modname) thismod = &SDL_KMSDRM_HAVE_##modname;
+#define SDL_KMSDRM_SYM(rc,fn,params) KMSDRM_##fn = (SDL_DYNKMSDRMFN_##fn) KMSDRM_GetSym(#fn,thismod);
+#define SDL_KMSDRM_SYM_CONST(type,name) KMSDRM_##name = *(SDL_DYNKMSDRMCONST_##name*) KMSDRM_GetSym(#name,thismod);
+#include "SDL_kmsdrmsym.h"
+
+        if ((SDL_KMSDRM_HAVE_LIBDRM) && (SDL_KMSDRM_HAVE_GBM)) {
+            /* all required symbols loaded. */
+            SDL_ClearError();
+        } else {
+            /* in case something got loaded... */
+            SDL_KMSDRM_UnloadSymbols();
+            rc = 0;
+        }
+
+#else  /* no dynamic KMSDRM */
+
+#define SDL_KMSDRM_MODULE(modname) SDL_KMSDRM_HAVE_##modname = 1; /* default yes */
+#define SDL_KMSDRM_SYM(rc,fn,params) KMSDRM_##fn = fn;
+#define SDL_KMSDRM_SYM_CONST(type,name) KMSDRM_##name = name;
+#include "SDL_kmsdrmsym.h"
+
+#endif
+    }
+
+    return rc;
+}
+
+#endif /* SDL_VIDEO_DRIVER_KMSDRM */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/mir/SDL_mirdyn.h b/src/video/kmsdrm/SDL_kmsdrmdyn.h
similarity index 68%
copy from src/video/mir/SDL_mirdyn.h
copy to src/video/kmsdrm/SDL_kmsdrmdyn.h
index a3638cf..2e92762 100644
--- a/src/video/mir/SDL_mirdyn.h
+++ b/src/video/kmsdrm/SDL_kmsdrmdyn.h
@@ -19,35 +19,35 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_mirdyn_h
-#define _SDL_mirdyn_h
+#ifndef SDL_kmsdrmdyn_h_
+#define SDL_kmsdrmdyn_h_
 
 #include "../../SDL_internal.h"
 
-#include <EGL/egl.h>
-#include <mir_toolkit/mir_client_library.h>
-#include <xkbcommon/xkbcommon.h>
+#include <xf86drm.h>
+#include <xf86drmMode.h>
+#include <gbm.h>
 
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-int SDL_MIR_LoadSymbols(void);
-void SDL_MIR_UnloadSymbols(void);
+int SDL_KMSDRM_LoadSymbols(void);
+void SDL_KMSDRM_UnloadSymbols(void);
 
 /* Declare all the function pointers and wrappers... */
-#define SDL_MIR_SYM(rc,fn,params) \
-    typedef rc (*SDL_DYNMIRFN_##fn) params; \
-    extern SDL_DYNMIRFN_##fn MIR_##fn;
-#define SDL_MIR_SYM_CONST(type, name) \
-    typedef type SDL_DYMMIRCONST_##name; \
-    extern SDL_DYMMIRCONST_##name MIR_##name;
-#include "SDL_mirsym.h"
+#define SDL_KMSDRM_SYM(rc,fn,params) \
+    typedef rc (*SDL_DYNKMSDRMFN_##fn) params; \
+    extern SDL_DYNKMSDRMFN_##fn KMSDRM_##fn;
+#define SDL_KMSDRM_SYM_CONST(type, name) \
+    typedef type SDL_DYNKMSDRMCONST_##name; \
+    extern SDL_DYNKMSDRMCONST_##name KMSDRM_##name;
+#include "SDL_kmsdrmsym.h"
 
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* !defined _SDL_mirdyn_h */
+#endif /* SDL_kmsdrmdyn_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/raspberry/SDL_rpievents.c b/src/video/kmsdrm/SDL_kmsdrmevents.c
similarity index 80%
copy from src/video/raspberry/SDL_rpievents.c
copy to src/video/kmsdrm/SDL_kmsdrmevents.c
index 4104568..4e1e0ca 100644
--- a/src/video/raspberry/SDL_rpievents.c
+++ b/src/video/kmsdrm/SDL_kmsdrmevents.c
@@ -21,25 +21,22 @@
 
 #include "../../SDL_internal.h"
 
-#if SDL_VIDEO_DRIVER_RPI
+#if SDL_VIDEO_DRIVER_KMSDRM
 
-#include "../../events/SDL_sysevents.h"
-#include "../../events/SDL_events_c.h"
-#include "../../events/SDL_keyboard_c.h"
-#include "SDL_rpivideo.h"
-#include "SDL_rpievents_c.h"
+#include "SDL_kmsdrmvideo.h"
+#include "SDL_kmsdrmevents.h"
 
 #ifdef SDL_INPUT_LINUXEV
 #include "../../core/linux/SDL_evdev.h"
 #endif
 
-void RPI_PumpEvents(_THIS)
+void KMSDRM_PumpEvents(_THIS)
 {
 #ifdef SDL_INPUT_LINUXEV
     SDL_EVDEV_Poll();
 #endif
-    
+
 }
 
-#endif /* SDL_VIDEO_DRIVER_RPI */
+#endif /* SDL_VIDEO_DRIVER_KMSDRM */
 
diff --git a/src/thread/windows/SDL_systhread_c.h b/src/video/kmsdrm/SDL_kmsdrmevents.h
similarity index 82%
copy from src/thread/windows/SDL_systhread_c.h
copy to src/video/kmsdrm/SDL_kmsdrmevents.h
index 90866a7..f2354ba 100644
--- a/src/thread/windows/SDL_systhread_c.h
+++ b/src/video/kmsdrm/SDL_kmsdrmevents.h
@@ -18,15 +18,14 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../../SDL_internal.h"
-
-#ifndef _SDL_systhread_c_h
-#define _SDL_systhread_c_h
 
-#include "../../core/windows/SDL_windows.h"
+#include "../../SDL_internal.h"
 
-typedef HANDLE SYS_ThreadHandle;
+#ifndef SDL_kmsdrmevents_h_
+#define SDL_kmsdrmevents_h_
 
-#endif /* _SDL_systhread_c_h */
+extern void KMSDRM_PumpEvents(_THIS);
+extern void KMSDRM_EventInit(_THIS);
+extern void KMSDRM_EventQuit(_THIS);
 
-/* vi: set ts=4 sw=4 expandtab: */
+#endif /* SDL_kmsdrmevents_h_ */
diff --git a/src/video/kmsdrm/SDL_kmsdrmmouse.c b/src/video/kmsdrm/SDL_kmsdrmmouse.c
new file mode 100644
index 0000000..f44402a
--- /dev/null
+++ b/src/video/kmsdrm/SDL_kmsdrmmouse.c
@@ -0,0 +1,422 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_DRIVER_KMSDRM
+
+#include "SDL_kmsdrmvideo.h"
+#include "SDL_kmsdrmmouse.h"
+#include "SDL_kmsdrmdyn.h"
+
+#include "../../events/SDL_mouse_c.h"
+#include "../../events/default_cursor.h"
+
+static SDL_Cursor *KMSDRM_CreateDefaultCursor(void);
+static SDL_Cursor *KMSDRM_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y);
+static int KMSDRM_ShowCursor(SDL_Cursor * cursor);
+static void KMSDRM_MoveCursor(SDL_Cursor * cursor);
+static void KMSDRM_FreeCursor(SDL_Cursor * cursor);
+static void KMSDRM_WarpMouse(SDL_Window * window, int x, int y);
+static int KMSDRM_WarpMouseGlobal(int x, int y);
+
+static SDL_Cursor *
+KMSDRM_CreateDefaultCursor(void)
+{
+    return SDL_CreateCursor(default_cdata, default_cmask, DEFAULT_CWIDTH, DEFAULT_CHEIGHT, DEFAULT_CHOTX, DEFAULT_CHOTY);
+}
+
+/* Create a cursor from a surface */
+static SDL_Cursor *
+KMSDRM_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y)
+{
+    SDL_VideoDevice *dev = SDL_GetVideoDevice();
+    SDL_VideoData *vdata = ((SDL_VideoData *)dev->driverdata);
+    SDL_PixelFormat *pixlfmt = surface->format;
+    KMSDRM_CursorData *curdata;
+    SDL_Cursor *cursor;
+    int i, ret;
+    uint32_t bo_format, bo_stride;
+    char *buffer = NULL;
+    size_t bufsize;
+
+    switch(pixlfmt->format) {
+    case SDL_PIXELFORMAT_RGB332:
+        bo_format = GBM_FORMAT_RGB332;
+        break;
+    case SDL_PIXELFORMAT_ARGB4444:
+        bo_format = GBM_FORMAT_ARGB4444;
+        break;
+    case SDL_PIXELFORMAT_RGBA4444:
+        bo_format = GBM_FORMAT_RGBA4444;
+        break;
+    case SDL_PIXELFORMAT_ABGR4444:
+        bo_format = GBM_FORMAT_ABGR4444;
+        break;
+    case SDL_PIXELFORMAT_BGRA4444:
+        bo_format = GBM_FORMAT_BGRA4444;
+        break;
+    case SDL_PIXELFORMAT_ARGB1555:
+        bo_format = GBM_FORMAT_ARGB1555;
+        break;
+    case SDL_PIXELFORMAT_RGBA5551:
+        bo_format = GBM_FORMAT_RGBA5551;
+        break;
+    case SDL_PIXELFORMAT_ABGR1555:
+        bo_format = GBM_FORMAT_ABGR1555;
+        break;
+    case SDL_PIXELFORMAT_BGRA5551:
+        bo_format = GBM_FORMAT_BGRA5551;
+        break;
+    case SDL_PIXELFORMAT_RGB565:
+        bo_format = GBM_FORMAT_RGB565;
+        break;
+    case SDL_PIXELFORMAT_BGR565:
+        bo_format = GBM_FORMAT_BGR565;
+        break;
+    case SDL_PIXELFORMAT_RGB888:
+    case SDL_PIXELFORMAT_RGB24:
+        bo_format = GBM_FORMAT_RGB888;
+        break;
+    case SDL_PIXELFORMAT_BGR888:
+    case SDL_PIXELFORMAT_BGR24:
+        bo_format = GBM_FORMAT_BGR888;
+        break;
+    case SDL_PIXELFORMAT_RGBX8888:
+        bo_format = GBM_FORMAT_RGBX8888;
+        break;
+    case SDL_PIXELFORMAT_BGRX8888:
+        bo_format = GBM_FORMAT_BGRX8888;
+        break;
+    case SDL_PIXELFORMAT_ARGB8888:
+        bo_format = GBM_FORMAT_ARGB8888;
+        break;
+    case SDL_PIXELFORMAT_RGBA8888:
+        bo_format = GBM_FORMAT_RGBA8888;
+        break;
+    case SDL_PIXELFORMAT_ABGR8888:
+        bo_format = GBM_FORMAT_ABGR8888;
+        break;
+    case SDL_PIXELFORMAT_BGRA8888:
+        bo_format = GBM_FORMAT_BGRA8888;
+        break;
+    case SDL_PIXELFORMAT_ARGB2101010:
+        bo_format = GBM_FORMAT_ARGB2101010;
+        break;
+    default:
+        SDL_SetError("Unsupported pixel format for cursor");
+        return NULL;
+    }
+
+    if (!KMSDRM_gbm_device_is_format_supported(vdata->gbm, bo_format, GBM_BO_USE_CURSOR | GBM_BO_USE_WRITE)) {
+        SDL_SetError("Unsupported pixel format for cursor");
+        return NULL;
+    }
+
+    cursor = (SDL_Cursor *) SDL_calloc(1, sizeof(*cursor));
+    if (cursor == NULL) {
+        SDL_OutOfMemory();
+        return NULL;
+    }
+    curdata = (KMSDRM_CursorData *) SDL_calloc(1, sizeof(*curdata));
+    if (curdata == NULL) {
+        SDL_OutOfMemory();
+        SDL_free(cursor);
+        return NULL;
+    }
+
+    curdata->hot_x = hot_x;
+    curdata->hot_y = hot_y;
+    curdata->w = surface->w;
+    curdata->h = surface->h;
+
+    curdata->bo = KMSDRM_gbm_bo_create(vdata->gbm, surface->w, surface->h, bo_format,
+                                       GBM_BO_USE_CURSOR | GBM_BO_USE_WRITE);
+    if (curdata->bo == NULL) {
+        SDL_SetError("Could not create GBM cursor BO");
+        goto cleanup;
+    }
+
+    bo_stride = KMSDRM_gbm_bo_get_stride(curdata->bo);
+    bufsize = bo_stride * surface->h;
+
+    if (surface->pitch != bo_stride) {
+        /* pitch doesn't match stride, must be copied to temp buffer  */
+        buffer = SDL_malloc(bufsize);
+        if (buffer == NULL) {
+            SDL_OutOfMemory();
+            goto cleanup;
+        }
+
+        if (SDL_MUSTLOCK(surface)) {
+            if (SDL_LockSurface(surface) < 0) {
+                /* Could not lock surface */
+                goto cleanup;
+            }
+        }
+
+        /* Copy to temporary buffer */
+        for (i = 0; i < surface->h; i++) {
+            SDL_memcpy(buffer + (i * bo_stride),
+                       ((char *)surface->pixels) + (i * surface->pitch),
+                       surface->w * pixlfmt->BytesPerPixel);
+        }
+
+        if (SDL_MUSTLOCK(surface)) {
+            SDL_UnlockSurface(surface);
+        }
+
+        if (KMSDRM_gbm_bo_write(curdata->bo, buffer, bufsize)) {
+            SDL_SetError("Could not write to GBM cursor BO");
+            goto cleanup;
+        }
+
+        /* Free temporary buffer */
+        SDL_free(buffer);
+        buffer = NULL;
+    } else {
+        /* surface matches BO format */
+        if (SDL_MUSTLOCK(surface)) {
+            if (SDL_LockSurface(surface) < 0) {
+                /* Could not lock surface */
+                goto cleanup;
+            }
+        }
+
+        ret = KMSDRM_gbm_bo_write(curdata->bo, surface->pixels, bufsize);
+
+        if (SDL_MUSTLOCK(surface)) {
+            SDL_UnlockSurface(surface);
+        }
+
+        if (ret) {
+            SDL_SetError("Could not write to GBM cursor BO");
+            goto cleanup;
+        }
+    }
+
+    cursor->driverdata = curdata;
+
+    return cursor;
+
+cleanup:
+    if (buffer != NULL) {
+        SDL_free(buffer);
+    }
+    if (cursor != NULL) {
+        SDL_free(cursor);
+    }
+    if (curdata != NULL) {
+        if (curdata->bo != NULL) {
+            KMSDRM_gbm_bo_destroy(curdata->bo);
+        }
+        SDL_free(curdata);
+    }
+    return NULL;
+}
+
+/* Show the specified cursor, or hide if cursor is NULL */
+static int
+KMSDRM_ShowCursor(SDL_Cursor * cursor)
+{
+    SDL_VideoDevice *dev = SDL_GetVideoDevice();
+    SDL_VideoData *vdata = ((SDL_VideoData *)dev->driverdata);
+    SDL_Mouse *mouse;
+    KMSDRM_CursorData *curdata;
+    SDL_VideoDisplay *display = NULL;
+    SDL_DisplayData *ddata = NULL;
+    int ret;
+    uint32_t bo_handle;
+
+    mouse = SDL_GetMouse();
+    if (mouse == NULL) {
+        return SDL_SetError("No mouse.");
+    }
+
+    if (mouse->focus != NULL) {
+        display = SDL_GetDisplayForWindow(mouse->focus);
+        if (display != NULL) {
+            ddata = (SDL_DisplayData*) display->driverdata;
+        }
+    }
+
+    if (cursor == NULL) {
+        /* Hide current cursor */
+        if ( mouse->cur_cursor != NULL && mouse->cur_cursor->driverdata != NULL) {
+            curdata = (KMSDRM_CursorData *) mouse->cur_cursor->driverdata;
+
+            if (curdata->crtc_id != 0) {
+                ret = KMSDRM_drmModeSetCursor(vdata->drm_fd, curdata->crtc_id, 0, 0, 0);
+                if (ret) {
+                    SDL_SetError("Could not hide current cursor with drmModeSetCursor().");
+                    return ret;
+                }
+                /* Mark previous cursor as not-displayed */
+                curdata->crtc_id = 0;
+
+                return 0;
+            }
+        }
+        /* otherwise if possible, hide global cursor */
+        if (ddata != NULL && ddata->crtc_id != 0) {
+            ret = KMSDRM_drmModeSetCursor(vdata->drm_fd, ddata->crtc_id, 0, 0, 0);
+            if (ret) {
+                SDL_SetError("Could not hide display's cursor with drmModeSetCursor().");
+                return ret;
+            }
+            return 0;
+        }
+
+        return SDL_SetError("Couldn't find cursor to hide.");
+    }
+    /* If cursor != NULL, show new cursor on display */
+    if (display == NULL) {
+        return SDL_SetError("Could not get display for mouse.");
+    }
+    if (ddata == NULL) {
+        return SDL_SetError("Could not get display driverdata.");
+    }
+
+    curdata = (KMSDRM_CursorData *) cursor->driverdata;
+    if (curdata == NULL || curdata->bo == NULL) {
+        return SDL_SetError("Cursor not initialized properly.");
+    }
+
+    bo_handle = KMSDRM_gbm_bo_get_handle(curdata->bo).u32;
+    if (curdata->hot_x == 0 && curdata->hot_y == 0) {
+        ret = KMSDRM_drmModeSetCursor(vdata->drm_fd, ddata->crtc_id, bo_handle,
+                                      curdata->w, curdata->h);
+    } else {
+        ret = KMSDRM_drmModeSetCursor2(vdata->drm_fd, ddata->crtc_id, bo_handle,
+                                       curdata->w, curdata->h,
+                                       curdata->hot_x, curdata->hot_y);
+    }
+    if (ret) {
+        SDL_SetError("drmModeSetCursor failed.");
+        return ret;
+    }
+
+    curdata->crtc_id = ddata->crtc_id;
+
+    return 0;
+}
+
+/* Free a window manager cursor */
+static void
+KMSDRM_FreeCursor(SDL_Cursor * cursor)
+{
+    KMSDRM_CursorData *curdata;
+    int drm_fd;
+
+    if (cursor != NULL) {
+        curdata = (KMSDRM_CursorData *) cursor->driverdata;
+
+        if (curdata != NULL) {
+            if (curdata->bo != NULL) {
+                if (curdata->crtc_id != 0) {
+                    drm_fd = KMSDRM_gbm_device_get_fd(KMSDRM_gbm_bo_get_device(curdata->bo));
+                    /* Hide the cursor if previously shown on a CRTC */
+                    KMSDRM_drmModeSetCursor(drm_fd, curdata->crtc_id, 0, 0, 0);
+                    curdata->crtc_id = 0;
+                }
+                KMSDRM_gbm_bo_destroy(curdata->bo);
+                curdata->bo = NULL;
+            }
+            SDL_free(cursor->driverdata);
+        }
+        SDL_free(cursor);
+    }
+}
+
+/* Warp the mouse to (x,y) */
+static void
+KMSDRM_WarpMouse(SDL_Window * window, int x, int y)
+{
+    /* Only one global/fullscreen window is supported */
+    KMSDRM_WarpMouseGlobal(x, y);
+}
+
+/* Warp the mouse to (x,y) */
+static int
+KMSDRM_WarpMouseGlobal(int x, int y)
+{
+    KMSDRM_CursorData *curdata;
+    SDL_Mouse *mouse = SDL_GetMouse();
+
+    if (mouse != NULL && mouse->cur_cursor != NULL && mouse->cur_cursor->driverdata != NULL) {
+        curdata = (KMSDRM_CursorData *) mouse->cur_cursor->driverdata;
+        if (curdata->bo != NULL) {
+            if (curdata->crtc_id != 0) {
+                int ret, drm_fd;
+                drm_fd = KMSDRM_gbm_device_get_fd(KMSDRM_gbm_bo_get_device(curdata->bo));
+                ret = KMSDRM_drmModeMoveCursor(drm_fd, curdata->crtc_id, x, y);
+
+                if (ret) {
+                    SDL_SetError("drmModeMoveCursor() failed.");
+                }
+
+                return ret;
+            } else {
+                return SDL_SetError("Cursor is not currently shown.");
+            }
+        } else {
+            return SDL_SetError("Cursor not initialized properly.");
+        }
+    } else {
+        return SDL_SetError("No mouse or current cursor.");
+    }
+}
+
+void
+KMSDRM_InitMouse(_THIS)
+{
+    /* FIXME: Using UDEV it should be possible to scan all mice
+     * but there's no point in doing so as there's no multimice support...yet!
+     */
+    SDL_Mouse *mouse = SDL_GetMouse();
+
+    mouse->CreateCursor = KMSDRM_CreateCursor;
+    mouse->ShowCursor = KMSDRM_ShowCursor;
+    mouse->MoveCursor = KMSDRM_MoveCursor;
+    mouse->FreeCursor = KMSDRM_FreeCursor;
+    mouse->WarpMouse = KMSDRM_WarpMouse;
+    mouse->WarpMouseGlobal = KMSDRM_WarpMouseGlobal;
+
+    SDL_SetDefaultCursor(KMSDRM_CreateDefaultCursor());
+}
+
+void
+KMSDRM_QuitMouse(_THIS)
+{
+    /* TODO: ? */
+}
+
+/* This is called when a mouse motion event occurs */
+static void
+KMSDRM_MoveCursor(SDL_Cursor * cursor)
+{
+    SDL_Mouse *mouse = SDL_GetMouse();
+    KMSDRM_WarpMouse(mouse->focus, mouse->x, mouse->y);
+}
+
+#endif /* SDL_VIDEO_DRIVER_KMSDRM */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/dummy/SDL_nullevents.c b/src/video/kmsdrm/SDL_kmsdrmmouse.h
similarity index 74%
copy from src/video/dummy/SDL_nullevents.c
copy to src/video/kmsdrm/SDL_kmsdrmmouse.h
index a5a9443..05c7288 100644
--- a/src/video/dummy/SDL_nullevents.c
+++ b/src/video/kmsdrm/SDL_kmsdrmmouse.h
@@ -18,24 +18,25 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../../SDL_internal.h"
-
-#if SDL_VIDEO_DRIVER_DUMMY
 
-/* Being a null driver, there's no event stream. We just define stubs for
-   most of the API. */
+#include "../../SDL_internal.h"
 
-#include "../../events/SDL_events_c.h"
+#ifndef SDL_KMSDRM_mouse_h_
+#define SDL_KMSDRM_mouse_h_
 
-#include "SDL_nullvideo.h"
-#include "SDL_nullevents_c.h"
+#include <gbm.h>
 
-void
-DUMMY_PumpEvents(_THIS)
+typedef struct _KMSDRM_CursorData
 {
-    /* do nothing. */
-}
+    struct gbm_bo *bo;
+    uint32_t       crtc_id;
+    int            hot_x, hot_y;
+    int            w, h;
+} KMSDRM_CursorData;
+
+extern void KMSDRM_InitMouse(_THIS);
+extern void KMSDRM_QuitMouse(_THIS);
 
-#endif /* SDL_VIDEO_DRIVER_DUMMY */
+#endif /* SDL_KMSDRM_mouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/kmsdrm/SDL_kmsdrmopengles.c b/src/video/kmsdrm/SDL_kmsdrmopengles.c
new file mode 100644
index 0000000..7063e5f
--- /dev/null
+++ b/src/video/kmsdrm/SDL_kmsdrmopengles.c
@@ -0,0 +1,139 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_DRIVER_KMSDRM && SDL_VIDEO_OPENGL_EGL
+
+#include "SDL_log.h"
+
+#include "SDL_kmsdrmvideo.h"
+#include "SDL_kmsdrmopengles.h"
+#include "SDL_kmsdrmdyn.h"
+
+#ifndef EGL_PLATFORM_GBM_MESA
+#define EGL_PLATFORM_GBM_MESA 0x31D7
+#endif
+
+/* EGL implementation of SDL OpenGL support */
+
+int
+KMSDRM_GLES_LoadLibrary(_THIS, const char *path) {
+    return SDL_EGL_LoadLibrary(_this, path, ((SDL_VideoData *)_this->driverdata)->gbm, EGL_PLATFORM_GBM_MESA);
+}
+
+SDL_EGL_CreateContext_impl(KMSDRM)
+
+int KMSDRM_GLES_SetSwapInterval(_THIS, int interval) {
+    if (!_this->egl_data) {
+        return SDL_SetError("EGL not initialized");
+    }
+
+    if (interval == 0 || interval == 1) {
+        _this->egl_data->egl_swapinterval = interval;
+    } else {
+        return SDL_SetError("Only swap intervals of 0 or 1 are supported");
+    }
+
+    return 0;
+}
+
+int
+KMSDRM_GLES_SwapWindow(_THIS, SDL_Window * window) {
+    SDL_WindowData *wdata = ((SDL_WindowData *) window->driverdata);
+    SDL_DisplayData *displaydata = (SDL_DisplayData *) SDL_GetDisplayForWindow(window)->driverdata;
+    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);
+    KMSDRM_FBInfo *fb_info;
+    int ret;
+
+    /* Do we still need to wait for a flip? */
+    int timeout = 0;
+    if (_this->egl_data->egl_swapinterval == 1) {
+        timeout = -1;
+    }
+    if (!KMSDRM_WaitPageFlip(_this, wdata, timeout)) {
+        return 0;
+    }
+
+    /* Release previously displayed buffer (which is now the backbuffer) and lock a new one */
+    if (wdata->next_bo != NULL) {
+        KMSDRM_gbm_surface_release_buffer(wdata->gs, wdata->current_bo);
+        /* SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Released GBM surface %p", (void *)wdata->next_bo); */
+
+        wdata->current_bo = wdata->next_bo;
+        wdata->next_bo = NULL;
+    }
+
+    if (!(_this->egl_data->eglSwapBuffers(_this->egl_data->egl_display, wdata->egl_surface))) {
+        SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "eglSwapBuffers failed.");
+        return 0;
+    }
+
+    if (wdata->current_bo == NULL) {
+        wdata->current_bo = KMSDRM_gbm_surface_lock_front_buffer(wdata->gs);
+        if (wdata->current_bo == NULL) {
+            return 0;
+        }
+    }
+
+    wdata->next_bo = KMSDRM_gbm_surface_lock_front_buffer(wdata->gs);
+    if (wdata->next_bo == NULL) {
+        SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Could not lock GBM surface front buffer");
+        return 0;
+    /* } else {
+        SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Locked GBM surface %p", (void *)wdata->next_bo); */
+    }
+
+    fb_info = KMSDRM_FBFromBO(_this, wdata->next_bo);
+    if (fb_info == NULL) {
+        return 0;
+    }
+    if (_this->egl_data->egl_swapinterval == 0) {
+        /* Swap buffers instantly, possible tearing */
+        /* SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "drmModeSetCrtc(%d, %u, %u, 0, 0, &%u, 1, &%ux%u@%u)",
+            vdata->drm_fd, displaydata->crtc_id, fb_info->fb_id, vdata->saved_conn_id,
+            displaydata->cur_mode.hdisplay, displaydata->cur_mode.vdisplay, displaydata->cur_mode.vrefresh); */
+        ret = KMSDRM_drmModeSetCrtc(vdata->drm_fd, displaydata->crtc_id, fb_info->fb_id,
+                                    0, 0, &vdata->saved_conn_id, 1, &displaydata->cur_mode);
+        if(ret != 0) {
+            SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Could not pageflip with drmModeSetCrtc: %d", ret);
+        }
+    } else {
+        /* Queue page flip at vsync */
+        /* SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "drmModePageFlip(%d, %u, %u, DRM_MODE_PAGE_FLIP_EVENT, &wdata->waiting_for_flip)",
+            vdata->drm_fd, displaydata->crtc_id, fb_info->fb_id); */
+        ret = KMSDRM_drmModePageFlip(vdata->drm_fd, displaydata->crtc_id, fb_info->fb_id,
+                                     DRM_MODE_PAGE_FLIP_EVENT, &wdata->waiting_for_flip);
+        if (ret == 0) {
+            wdata->waiting_for_flip = SDL_TRUE;
+        } else {
+            SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "Could not queue pageflip: %d", ret);
+        }
+    }
+
+    return 0;
+}
+
+SDL_EGL_MakeCurrent_impl(KMSDRM)
+
+#endif /* SDL_VIDEO_DRIVER_KMSDRM && SDL_VIDEO_OPENGL_EGL */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/raspberry/SDL_rpiopengles.h b/src/video/kmsdrm/SDL_kmsdrmopengles.h
similarity index 56%
copy from src/video/raspberry/SDL_rpiopengles.h
copy to src/video/kmsdrm/SDL_kmsdrmopengles.h
index 83c8000..7bbb11d 100644
--- a/src/video/raspberry/SDL_rpiopengles.h
+++ b/src/video/kmsdrm/SDL_kmsdrmopengles.h
@@ -20,29 +20,29 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_rpiopengles_h
-#define _SDL_rpiopengles_h
+#ifndef SDL_kmsdrmopengles_h_
+#define SDL_kmsdrmopengles_h_
 
-#if SDL_VIDEO_DRIVER_RPI && SDL_VIDEO_OPENGL_EGL
+#if SDL_VIDEO_DRIVER_KMSDRM && SDL_VIDEO_OPENGL_EGL
 
 #include "../SDL_sysvideo.h"
 #include "../SDL_egl_c.h"
 
 /* OpenGLES functions */
-#define RPI_GLES_GetAttribute SDL_EGL_GetAttribute
-#define RPI_GLES_GetProcAddress SDL_EGL_GetProcAddress
-#define RPI_GLES_UnloadLibrary SDL_EGL_UnloadLibrary
-#define RPI_GLES_SetSwapInterval SDL_EGL_SetSwapInterval
-#define RPI_GLES_GetSwapInterval SDL_EGL_GetSwapInterval
-#define RPI_GLES_DeleteContext SDL_EGL_DeleteContext
+#define KMSDRM_GLES_GetAttribute SDL_EGL_GetAttribute
+#define KMSDRM_GLES_GetProcAddress SDL_EGL_GetProcAddress
+#define KMSDRM_GLES_UnloadLibrary SDL_EGL_UnloadLibrary
+#define KMSDRM_GLES_DeleteContext SDL_EGL_DeleteContext
+#define KMSDRM_GLES_GetSwapInterval SDL_EGL_GetSwapInterval
 
-extern int RPI_GLES_LoadLibrary(_THIS, const char *path);
-extern SDL_GLContext RPI_GLES_CreateContext(_THIS, SDL_Window * window);
-extern void RPI_GLES_SwapWindow(_THIS, SDL_Window * window);
-extern int RPI_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
+extern int KMSDRM_GLES_SetSwapInterval(_THIS, int interval);
+extern int KMSDRM_GLES_LoadLibrary(_THIS, const char *path);
+extern SDL_GLContext KMSDRM_GLES_CreateContext(_THIS, SDL_Window * window);
+extern int KMSDRM_GLES_SwapWindow(_THIS, SDL_Window * window);
+extern int KMSDRM_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 
-#endif /* SDL_VIDEO_DRIVER_RPI && SDL_VIDEO_OPENGL_EGL */
+#endif /* SDL_VIDEO_DRIVER_KMSDRM && SDL_VIDEO_OPENGL_EGL */
 
-#endif /* _SDL_rpiopengles_h */
+#endif /* SDL_kmsdrmopengles_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/kmsdrm/SDL_kmsdrmsym.h b/src/video/kmsdrm/SDL_kmsdrmsym.h
new file mode 100644
index 0000000..72c07a9
--- /dev/null
+++ b/src/video/kmsdrm/SDL_kmsdrmsym.h
@@ -0,0 +1,99 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+/* *INDENT-OFF* */
+
+#ifndef SDL_KMSDRM_MODULE
+#define SDL_KMSDRM_MODULE(modname)
+#endif
+
+#ifndef SDL_KMSDRM_SYM
+#define SDL_KMSDRM_SYM(rc,fn,params)
+#endif
+
+#ifndef SDL_KMSDRM_SYM_CONST
+#define SDL_KMSDRM_SYM_CONST(type, name)
+#endif
+
+
+SDL_KMSDRM_MODULE(LIBDRM)
+SDL_KMSDRM_SYM(void,drmModeFreeResources,(drmModeResPtr ptr))
+SDL_KMSDRM_SYM(void,drmModeFreeFB,(drmModeFBPtr ptr))
+SDL_KMSDRM_SYM(void,drmModeFreeCrtc,(drmModeCrtcPtr ptr))
+SDL_KMSDRM_SYM(void,drmModeFreeConnector,(drmModeConnectorPtr ptr))
+SDL_KMSDRM_SYM(void,drmModeFreeEncoder,(drmModeEncoderPtr ptr))
+SDL_KMSDRM_SYM(drmModeResPtr,drmModeGetResources,(int fd))
+SDL_KMSDRM_SYM(int,drmModeAddFB,(int fd, uint32_t width, uint32_t height, uint8_t depth,
+                                 uint8_t bpp, uint32_t pitch, uint32_t bo_handle,
+                                 uint32_t *buf_id))
+SDL_KMSDRM_SYM(int,drmModeRmFB,(int fd, uint32_t bufferId))
+SDL_KMSDRM_SYM(drmModeFBPtr,drmModeGetFB,(int fd, uint32_t buf))
+SDL_KMSDRM_SYM(drmModeCrtcPtr,drmModeGetCrtc,(int fd, uint32_t crtcId))
+SDL_KMSDRM_SYM(int,drmModeSetCrtc,(int fd, uint32_t crtcId, uint32_t bufferId,
+                                   uint32_t x, uint32_t y, uint32_t *connectors, int count,
+                                   drmModeModeInfoPtr mode))
+SDL_KMSDRM_SYM(int,drmModeSetCursor,(int fd, uint32_t crtcId, uint32_t bo_handle,
+                                     uint32_t width, uint32_t height))
+SDL_KMSDRM_SYM(int,drmModeSetCursor2,(int fd, uint32_t crtcId, uint32_t bo_handle,
+                                      uint32_t width, uint32_t height,
+                                      int32_t hot_x, int32_t hot_y))
+SDL_KMSDRM_SYM(int,drmModeMoveCursor,(int fd, uint32_t crtcId, int x, int y))
+SDL_KMSDRM_SYM(drmModeEncoderPtr,drmModeGetEncoder,(int fd, uint32_t encoder_id))
+SDL_KMSDRM_SYM(drmModeConnectorPtr,drmModeGetConnector,(int fd, uint32_t connector_id))
+SDL_KMSDRM_SYM(int,drmHandleEvent,(int fd,drmEventContextPtr evctx))
+SDL_KMSDRM_SYM(int,drmModePageFlip,(int fd, uint32_t crtc_id, uint32_t fb_id,
+                                    uint32_t flags, void *user_data))
+
+
+SDL_KMSDRM_MODULE(GBM)
+SDL_KMSDRM_SYM(int,gbm_device_get_fd,(struct gbm_device *gbm))
+SDL_KMSDRM_SYM(int,gbm_device_is_format_supported,(struct gbm_device *gbm,
+                                                   uint32_t format, uint32_t usage))
+SDL_KMSDRM_SYM(void,gbm_device_destroy,(struct gbm_device *gbm))
+SDL_KMSDRM_SYM(struct gbm_device *,gbm_create_device,(int fd))
+SDL_KMSDRM_SYM(unsigned int,gbm_bo_get_width,(struct gbm_bo *bo))
+SDL_KMSDRM_SYM(unsigned int,gbm_bo_get_height,(struct gbm_bo *bo))
+SDL_KMSDRM_SYM(uint32_t,gbm_bo_get_stride,(struct gbm_bo *bo))
+SDL_KMSDRM_SYM(union gbm_bo_handle,gbm_bo_get_handle,(struct gbm_bo *bo))
+SDL_KMSDRM_SYM(int,gbm_bo_write,(struct gbm_bo *bo, const void *buf, size_t count))
+SDL_KMSDRM_SYM(struct gbm_device *,gbm_bo_get_device,(struct gbm_bo *bo))
+SDL_KMSDRM_SYM(void,gbm_bo_set_user_data,(struct gbm_bo *bo, void *data,
+                                          void (*destroy_user_data)(struct gbm_bo *, void *)))
+SDL_KMSDRM_SYM(void *,gbm_bo_get_user_data,(struct gbm_bo *bo))
+SDL_KMSDRM_SYM(void,gbm_bo_destroy,(struct gbm_bo *bo))
+SDL_KMSDRM_SYM(struct gbm_bo *,gbm_bo_create,(struct gbm_device *gbm,
+                                              uint32_t width, uint32_t height,
+                                              uint32_t format, uint32_t usage))
+SDL_KMSDRM_SYM(struct gbm_surface *,gbm_surface_create,(struct gbm_device *gbm,
+                                                        uint32_t width, uint32_t height,
+                                                        uint32_t format, uint32_t flags))
+SDL_KMSDRM_SYM(void,gbm_surface_destroy,(struct gbm_surface *surf))
+SDL_KMSDRM_SYM(struct gbm_bo *,gbm_surface_lock_front_buffer,(struct gbm_surface *surf))
+SDL_KMSDRM_SYM(void,gbm_surface_release_buffer,(struct gbm_surface *surf, struct gbm_bo *bo))
+
+
+#undef SDL_KMSDRM_MODULE
+#undef SDL_KMSDRM_SYM
+#undef SDL_KMSDRM_SYM_CONST
+
+/* *INDENT-ON* */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/kmsdrm/SDL_kmsdrmvideo.c b/src/video/kmsdrm/SDL_kmsdrmvideo.c
new file mode 100644
index 0000000..63376f2
--- /dev/null
+++ b/src/video/kmsdrm/SDL_kmsdrmvideo.c
@@ -0,0 +1,650 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_DRIVER_KMSDRM
+
+/* SDL internals */
+#include "../SDL_sysvideo.h"
+#include "SDL_syswm.h"
+#include "SDL_log.h"
+#include "../../events/SDL_mouse_c.h"
+#include "../../events/SDL_keyboard_c.h"
+
+#ifdef SDL_INPUT_LINUXEV
+#include "../../core/linux/SDL_evdev.h"
+#endif
+
+/* KMS/DRM declarations */
+#include "SDL_kmsdrmvideo.h"
+#include "SDL_kmsdrmevents.h"
+#include "SDL_kmsdrmopengles.h"
+#include "SDL_kmsdrmmouse.h"
+#include "SDL_kmsdrmdyn.h"
+
+#define KMSDRM_DRI_CARD_0 "/dev/dri/card0"
+
+static int
+KMSDRM_Available(void)
+{
+    int available = 0;
+
+    int drm_fd = open(KMSDRM_DRI_CARD_0, O_RDWR | O_CLOEXEC);
+    if (drm_fd >= 0) {
+        if (SDL_KMSDRM_LoadSymbols()) {
+            drmModeRes *resources = KMSDRM_drmModeGetResources(drm_fd);
+            if (resources != NULL) {
+                available = 1;
+                KMSDRM_drmModeFreeResources(resources);
+            }
+            SDL_KMSDRM_UnloadSymbols();
+        }
+        close(drm_fd);
+    }
+
+    return available;
+}
+
+static void
+KMSDRM_Destroy(SDL_VideoDevice * device)
+{
+    if (device->driverdata != NULL) {
+        SDL_free(device->driverdata);
+        device->driverdata = NULL;
+    }
+
+    SDL_free(device);
+    SDL_KMSDRM_UnloadSymbols();
+}
+
+static SDL_VideoDevice *
+KMSDRM_Create(int devindex)
+{
+    SDL_VideoDevice *device;
+    SDL_VideoData *vdata;
+
+    if (devindex < 0 || devindex > 99) {
+        SDL_SetError("devindex (%d) must be between 0 and 99.\n", devindex);
+        return NULL;
+    }
+
+    if (!SDL_KMSDRM_LoadSymbols()) {
+        return NULL;
+    }
+
+    /* Initialize SDL_VideoDevice structure */
+    device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice));
+    if (device == NULL) {
+        SDL_OutOfMemory();
+        return NULL;
+    }
+
+    /* Initialize internal data */
+    vdata = (SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData));
+    if (vdata == NULL) {
+        SDL_OutOfMemory();
+        goto cleanup;
+    }
+    vdata->devindex = devindex;
+    vdata->drm_fd = -1;
+
+    device->driverdata = vdata;
+
+    /* Setup amount of available displays and current display */
+    device->num_displays = 0;
+
+    /* Set device free function */
+    device->free = KMSDRM_Destroy;
+
+    /* Setup all functions which we can handle */
+    device->VideoInit = KMSDRM_VideoInit;
+    device->VideoQuit = KMSDRM_VideoQuit;
+    device->GetDisplayModes = KMSDRM_GetDisplayModes;
+    device->SetDisplayMode = KMSDRM_SetDisplayMode;
+    device->CreateSDLWindow = KMSDRM_CreateWindow;
+    device->CreateSDLWindowFrom = KMSDRM_CreateWindowFrom;
+    device->SetWindowTitle = KMSDRM_SetWindowTitle;
+    device->SetWindowIcon = KMSDRM_SetWindowIcon;
+    device->SetWindowPosition = KMSDRM_SetWindowPosition;
+    device->SetWindowSize = KMSDRM_SetWindowSize;
+    device->ShowWindow = KMSDRM_ShowWindow;
+    device->HideWindow = KMSDRM_HideWindow;
+    device->RaiseWindow = KMSDRM_RaiseWindow;
+    device->MaximizeWindow = KMSDRM_MaximizeWindow;
+    device->MinimizeWindow = KMSDRM_MinimizeWindow;
+    device->RestoreWindow = KMSDRM_RestoreWindow;
+    device->SetWindowGrab = KMSDRM_SetWindowGrab;
+    device->DestroyWindow = KMSDRM_DestroyWindow;
+    device->GetWindowWMInfo = KMSDRM_GetWindowWMInfo;
+#if SDL_VIDEO_OPENGL_EGL
+    device->GL_LoadLibrary = KMSDRM_GLES_LoadLibrary;
+    device->GL_GetProcAddress = KMSDRM_GLES_GetProcAddress;
+    device->GL_UnloadLibrary = KMSDRM_GLES_UnloadLibrary;
+    device->GL_CreateContext = KMSDRM_GLES_CreateContext;
+    device->GL_MakeCurrent = KMSDRM_GLES_MakeCurrent;
+    device->GL_SetSwapInterval = KMSDRM_GLES_SetSwapInterval;
+    device->GL_GetSwapInterval = KMSDRM_GLES_GetSwapInterval;
+    device->GL_SwapWindow = KMSDRM_GLES_SwapWindow;
+    device->GL_DeleteContext = KMSDRM_GLES_DeleteContext;
+#endif
+
+    device->PumpEvents = KMSDRM_PumpEvents;
+
+    return device;
+
+cleanup:
+    if (device != NULL)
+        SDL_free(device);
+    if (vdata != NULL)
+        SDL_free(vdata);
+    return NULL;
+}
+
+VideoBootStrap KMSDRM_bootstrap = {
+    "KMSDRM",
+    "KMS/DRM Video Driver",
+    KMSDRM_Available,
+    KMSDRM_Create
+};
+
+
+static void
+KMSDRM_FBDestroyCallback(struct gbm_bo *bo, void *data)
+{
+    KMSDRM_FBInfo *fb_info = (KMSDRM_FBInfo *)data;
+
+    if (fb_info && fb_info->drm_fd > 0 && fb_info->fb_id != 0) {
+        KMSDRM_drmModeRmFB(fb_info->drm_fd, fb_info->fb_id);
+        SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Delete DRM FB %u", fb_info->fb_id);
+    }
+
+    free(fb_info);
+}
+
+KMSDRM_FBInfo *
+KMSDRM_FBFromBO(_THIS, struct gbm_bo *bo)
+{
+    uint32_t w, h, stride, handle;
+    int ret;
+    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);
+    KMSDRM_FBInfo *fb_info;
+
+    fb_info = (KMSDRM_FBInfo *)KMSDRM_gbm_bo_get_user_data(bo);
+    if (fb_info != NULL) {
+        /* Have a previously used framebuffer, return it */
+        return fb_info;
+    }
+
+    /* Here a new DRM FB must be created */
+    fb_info = (KMSDRM_FBInfo *)SDL_calloc(1, sizeof(KMSDRM_FBInfo));
+    if (fb_info == NULL) {
+        SDL_OutOfMemory();
+        return NULL;
+    }
+    fb_info->drm_fd = vdata->drm_fd;
+
+    w  = KMSDRM_gbm_bo_get_width(bo);
+    h = KMSDRM_gbm_bo_get_height(bo);
+    stride = KMSDRM_gbm_bo_get_stride(bo);
+    handle = KMSDRM_gbm_bo_get_handle(bo).u32;
+
+    ret = KMSDRM_drmModeAddFB(vdata->drm_fd, w, h, 24, 32, stride, handle, &fb_info->fb_id);
+    if (ret < 0) {
+       free(fb_info);
+       return NULL;
+    }
+    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "New DRM FB (%u): %ux%u, stride %u from BO %p", fb_info->fb_id, w, h, stride, (void *)bo);
+
+    /* Associate our DRM framebuffer with this buffer object */
+    KMSDRM_gbm_bo_set_user_data(bo, fb_info, KMSDRM_FBDestroyCallback);
+    return fb_info;
+}
+
+SDL_bool
+KMSDRM_WaitPageFlip(_THIS, SDL_WindowData *wdata, int timeout) {
+    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);
+
+    while (wdata->waiting_for_flip) {
+        vdata->drm_pollfd.revents = 0;
+        if (poll(&vdata->drm_pollfd, 1, timeout) < 0) {
+            SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "DRM poll error");
+            return SDL_FALSE;
+        }
+
+        if (vdata->drm_pollfd.revents & (POLLHUP | POLLERR)) {
+            SDL_LogError(SDL_LOG_CATEGORY_VIDEO, "DRM poll hup or error");
+            return SDL_FALSE;
+        }
+
+        if (vdata->drm_pollfd.revents & POLLIN) {
+            /* Page flip? If so, drmHandleEvent will unset wdata->waiting_for_flip */
+            KMSDRM_drmHandleEvent(vdata->drm_fd, &vdata->drm_evctx);
+        } else {
+            /* Timed out and page flip didn't happen */
+            SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Dropping frame while waiting_for_flip");
+            return SDL_FALSE;
+        }
+    }
+    return SDL_TRUE;
+}
+
+static void
+KMSDRM_FlipHandler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data)
+{
+    *((SDL_bool *) data) = SDL_FALSE;
+}
+
+
+/*****************************************************************************/
+/* SDL Video and Display initialization/handling functions                   */
+/* _this is a SDL_VideoDevice *                                              */
+/*****************************************************************************/
+int
+KMSDRM_VideoInit(_THIS)
+{
+    int i;
+    int ret = 0;
+    char *devname;
+    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);
+    drmModeRes *resources = NULL;
+    drmModeConnector *connector = NULL;
+    drmModeEncoder *encoder = NULL;
+    SDL_DisplayMode current_mode;
+    SDL_VideoDisplay display;
+
+    /* Allocate display internal data */
+    SDL_DisplayData *data = (SDL_DisplayData *) SDL_calloc(1, sizeof(SDL_DisplayData));
+    if (data == NULL) {
+        return SDL_OutOfMemory();
+    }
+
+    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "KMSDRM_VideoInit()");
+
+    /* Open /dev/dri/cardNN */
+    devname = (char *) SDL_calloc(1, 16);
+    if (devname == NULL) {
+        ret = SDL_OutOfMemory();
+        goto cleanup;
+    }
+    SDL_snprintf(devname, 16, "/dev/dri/card%d", vdata->devindex);
+    vdata->drm_fd = open(devname, O_RDWR | O_CLOEXEC);
+    SDL_free(devname);
+
+    if (vdata->drm_fd < 0) {
+        ret = SDL_SetError("Could not open /dev/dri/card%d.", vdata->devindex);
+        goto cleanup;
+    }
+    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Opened DRM FD (%d)", vdata->drm_fd);
+
+    vdata->gbm = KMSDRM_gbm_create_device(vdata->drm_fd);
+    if (vdata->gbm == NULL) {
+        ret = SDL_SetError("Couldn't create gbm device.");
+        goto cleanup;
+    }
+
+    /* Find the first available connector with modes */
+    resources = KMSDRM_drmModeGetResources(vdata->drm_fd);
+    if (!resources) {
+        ret = SDL_SetError("drmModeGetResources(%d) failed", vdata->drm_fd);
+        goto cleanup;
+    }
+
+    for (i = 0; i < resources->count_connectors; i++) {
+        connector = KMSDRM_drmModeGetConnector(vdata->drm_fd, resources->connectors[i]);
+        if (connector == NULL)
+            continue;
+
+        if (connector->connection == DRM_MODE_CONNECTED &&
+            connector->count_modes > 0) {
+            SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Found connector %d with %d modes.",
+                         connector->connector_id, connector->count_modes);
+            vdata->saved_conn_id = connector->connector_id;
+            break;
+        }
+
+        KMSDRM_drmModeFreeConnector(connector);
+        connector = NULL;
+    }
+
+    if (i == resources->count_connectors) {
+        ret = SDL_SetError("No currently active connector found.");
+        goto cleanup;
+    }
+
+    for (i = 0; i < resources->count_encoders; i++) {
+        encoder = KMSDRM_drmModeGetEncoder(vdata->drm_fd, resources->encoders[i]);
+
+        if (encoder == NULL)
+            continue;
+
+        if (encoder->encoder_id == connector->encoder_id) {
+            SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Found encoder %d.", encoder->encoder_id);
+            data->encoder_id = encoder->encoder_id;
+            break;
+        }
+
+        KMSDRM_drmModeFreeEncoder(encoder);
+        encoder = NULL;
+    }
+
+    if (i == resources->count_encoders) {
+        ret = SDL_SetError("No connected encoder found.");
+        goto cleanup;
+    }
+
+    vdata->saved_crtc = KMSDRM_drmModeGetCrtc(vdata->drm_fd, encoder->crtc_id);
+    if (vdata->saved_crtc == NULL) {
+        ret = SDL_SetError("No CRTC found.");
+        goto cleanup;
+    }
+    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Saved crtc_id %u, fb_id %u, (%u,%u), %ux%u",
+                 vdata->saved_crtc->crtc_id, vdata->saved_crtc->buffer_id, vdata->saved_crtc->x,
+                 vdata->saved_crtc->y, vdata->saved_crtc->width, vdata->saved_crtc->height);
+    data->crtc_id = encoder->crtc_id;
+    data->cur_mode = vdata->saved_crtc->mode;
+
+    SDL_zero(current_mode);
+
+    current_mode.w = vdata->saved_crtc->mode.hdisplay;
+    current_mode.h = vdata->saved_crtc->mode.vdisplay;
+    current_mode.refresh_rate = vdata->saved_crtc->mode.vrefresh;
+
+    /* FIXME ?
+    drmModeFB *fb = drmModeGetFB(vdata->drm_fd, vdata->saved_crtc->buffer_id);
+    current_mode.format = drmToSDLPixelFormat(fb->bpp, fb->depth);
+    drmModeFreeFB(fb);
+    */
+    current_mode.format = SDL_PIXELFORMAT_ARGB8888;
+
+    current_mode.driverdata = NULL;
+
+    SDL_zero(display);
+    display.desktop_mode = current_mode;
+    display.current_mode = current_mode;
+
+    display.driverdata = data;
+    /* SDL_VideoQuit will later SDL_free(display.driverdata) */
+    SDL_AddVideoDisplay(&display);
+
+    /* Setup page flip handler */
+    vdata->drm_pollfd.fd = vdata->drm_fd;
+    vdata->drm_pollfd.events = POLLIN;
+    vdata->drm_evctx.version = DRM_EVENT_CONTEXT_VERSION;
+    vdata->drm_evctx.page_flip_handler = KMSDRM_FlipHandler;
+
+#ifdef SDL_INPUT_LINUXEV
+    SDL_EVDEV_Init();
+#endif
+
+    KMSDRM_InitMouse(_this);
+
+cleanup:
+    if (encoder != NULL)
+        KMSDRM_drmModeFreeEncoder(encoder);
+    if (connector != NULL)
+        KMSDRM_drmModeFreeConnector(connector);
+    if (resources != NULL)
+        KMSDRM_drmModeFreeResources(resources);
+
+    if (ret != 0) {
+        /* Error (complete) cleanup */
+        SDL_free(data);
+        if(vdata->saved_crtc != NULL) {
+            KMSDRM_drmModeFreeCrtc(vdata->saved_crtc);
+            vdata->saved_crtc = NULL;
+        }
+        if (vdata->gbm != NULL) {
+            KMSDRM_gbm_device_destroy(vdata->gbm);
+            vdata->gbm = NULL;
+        }
+        if (vdata->drm_fd >= 0) {
+            close(vdata->drm_fd);
+            vdata->drm_fd = -1;
+        }
+    }
+    return ret;
+}
+
+void
+KMSDRM_VideoQuit(_THIS)
+{
+    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);
+
+    SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "KMSDRM_VideoQuit()");
+
+    if (_this->gl_config.driver_loaded) {
+        SDL_GL_UnloadLibrary();
+    }
+
+    if(vdata->saved_crtc != NULL) {
+        if(vdata->drm_fd > 0 && vdata->saved_conn_id > 0) {
+            /* Restore saved CRTC settings */
+            drmModeCrtc *crtc = vdata->saved_crtc;
+            if(KMSDRM_drmModeSetCrtc(vdata->drm_fd, crtc->crtc_id, crtc->buffer_id,
+                                     crtc->x, crtc->y, &vdata->saved_conn_id, 1,
+                                     &crtc->mode) != 0) {
+                SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "Could not restore original CRTC mode");
+            }
+        }
+        KMSDRM_drmModeFreeCrtc(vdata->saved_crtc);
+        vdata->saved_crtc = NULL;
+    }
+    if (vdata->gbm != NULL) {
+        KMSDRM_gbm_device_destroy(vdata->gbm);
+        vdata->gbm = NULL;
+    }
+    if (vdata->drm_fd >= 0) {
+        close(vdata->drm_fd);
+        SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "Closed DRM FD %d", vdata->drm_fd);
+        vdata->drm_fd = -1;
+    }
+#ifdef SDL_INPUT_LINUXEV
+    SDL_EVDEV_Quit();
+#endif
+}
+
+void
+KMSDRM_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
+{
+    /* Only one display mode available, the current one */
+    SDL_AddDisplayMode(display, &display->current_mode);
+}
+
+int
+KMSDRM_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode)
+{
+    return 0;
+}
+
+int
+KMSDRM_CreateWindow(_THIS, SDL_Window * window)
+{
+    SDL_WindowData *wdata;
+    SDL_VideoDisplay *display;
+    SDL_VideoData *vdata = ((SDL_VideoData *)_this->driverdata);
+    Uint32 surface_fmt, surface_flags;
+
+    /* Allocate window internal data */
+    wdata = (SDL_WindowData *) SDL_calloc(1, sizeof(SDL_WindowData));
+    if (wdata == NULL) {
+        SDL_OutOfMemory();
+        goto error;
+    }
+
+    wdata->waiting_for_flip = SDL_FALSE;
+    display = SDL_GetDisplayForWindow(window);
+
+    /* Windows have one size for now */
+    window->w = display->desktop_mode.w;
+    window->h = display->desktop_mode.h;
+
+    /* Maybe you didn't ask for a fullscreen OpenGL window, but that's what you get */
+    window->flags |= (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL);
+
+    surface_fmt = GBM_FORMAT_XRGB8888;
+    surface_flags = GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING;
+
+    if (!KMSDRM_gbm_device_is_format_supported(vdata->gbm, surface_fmt, surface_flags)) {
+        SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "GBM surface format not supported. Trying anyway.");
+    }
+    wdata->gs = KMSDRM_gbm_surface_create(vdata->gbm, window->w, window->h, surface_fmt, surface_flags);
+
+#if SDL_VIDEO_OPENGL_EGL
+    if (!_this->egl_data) {
+        if (SDL_GL_LoadLibrary(NULL) < 0) {
+            goto error;
+        }
+    }
+    wdata->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) wdata->gs);
+
+    if (wdata->egl_surface == EGL_NO_SURFACE) {
+        SDL_SetError("Could not create EGL window surface");
+        goto error;
+    }
+#endif /* SDL_VIDEO_OPENGL_EGL */
+
+    /* Setup driver data for this window */
+    window->driverdata = wdata;
+
+    /* One window, it always has focus */
+    SDL_SetMouseFocus(window);
+    SDL_SetKeyboardFocus(window);
+
+    /* Window has been successfully created */
+    return 0;
+
+error:
+    if (wdata != NULL) {
+#if SDL_VIDEO_OPENGL_EGL
+        if (wdata->egl_surface != EGL_NO_SURFACE)
+            SDL_EGL_DestroySurface(_this, wdata->egl_surface);
+#endif /* SDL_VIDEO_OPENGL_EGL */
+        if (wdata->gs != NULL)
+            KMSDRM_gbm_surface_destroy(wdata->gs);
+        SDL_free(wdata);
+    }
+    return -1;
+}
+
+void
+KMSDRM_DestroyWindow(_THIS, SDL_Window * window)
+{
+    SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
+    if(data) {
+        /* Wait for any pending page flips and unlock buffer */
+        KMSDRM_WaitPageFlip(_this, data, -1);
+        if (data->next_bo != NULL) {
+            KMSDRM_gbm_surface_release_buffer(data->gs, data->next_bo);
+            data->next_bo = NULL;
+        }
+        if (data->current_bo != NULL) {
+            KMSDRM_gbm_surface_release_buffer(data->gs, data->current_bo);
+            data->current_bo = NULL;
+        }
+#if SDL_VIDEO_OPENGL_EGL
+        SDL_EGL_MakeCurrent(_this, EGL_NO_SURFACE, EGL_NO_CONTEXT);
+        if (data->egl_surface != EGL_NO_SURFACE) {
+            SDL_EGL_DestroySurface(_this, data->egl_surface);
+        }
+#endif /* SDL_VIDEO_OPENGL_EGL */
+        if (data->gs != NULL) {
+            KMSDRM_gbm_surface_destroy(data->gs);
+            data->gs = NULL;
+        }
+        SDL_free(data);
+        window->driverdata = NULL;
+    }
+}
+
+int
+KMSDRM_CreateWindowFrom(_THIS, SDL_Window * window, const void *data)
+{
+    return -1;
+}
+
+void
+KMSDRM_SetWindowTitle(_THIS, SDL_Window * window)
+{
+}
+void
+KMSDRM_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon)
+{
+}
+void
+KMSDRM_SetWindowPosition(_THIS, SDL_Window * window)
+{
+}
+void
+KMSDRM_SetWindowSize(_THIS, SDL_Window * window)
+{
+}
+void
+KMSDRM_ShowWindow(_THIS, SDL_Window * window)
+{
+}
+void
+KMSDRM_HideWindow(_THIS, SDL_Window * window)
+{
+}
+void
+KMSDRM_RaiseWindow(_THIS, SDL_Window * window)
+{
+}
+void
+KMSDRM_MaximizeWindow(_THIS, SDL_Window * window)
+{
+}
+void
+KMSDRM_MinimizeWindow(_THIS, SDL_Window * window)
+{
+}
+void
+KMSDRM_RestoreWindow(_THIS, SDL_Window * window)
+{
+}
+void
+KMSDRM_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed)
+{
+
+}
+
+/*****************************************************************************/
+/* SDL Window Manager function                                               */
+/*****************************************************************************/
+SDL_bool
+KMSDRM_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info)
+{
+    if (info->version.major <= SDL_MAJOR_VERSION) {
+        return SDL_TRUE;
+    } else {
+        SDL_SetError("application not compiled with SDL %d.%d\n",
+                     SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
+        return SDL_FALSE;
+    }
+
+    /* Failed to get window manager information */
+    return SDL_FALSE;
+}
+
+#endif /* SDL_VIDEO_DRIVER_KMSDRM */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/kmsdrm/SDL_kmsdrmvideo.h b/src/video/kmsdrm/SDL_kmsdrmvideo.h
new file mode 100644
index 0000000..307c475
--- /dev/null
+++ b/src/video/kmsdrm/SDL_kmsdrmvideo.h
@@ -0,0 +1,121 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+
+#ifndef __SDL_KMSDRMVIDEO_H__
+#define __SDL_KMSDRMVIDEO_H__
+
+#include "../SDL_sysvideo.h"
+
+#include <fcntl.h>
+#include <unistd.h>
+#include <poll.h>
+#include <xf86drm.h>
+#include <xf86drmMode.h>
+#include <gbm.h>
+#if SDL_VIDEO_OPENGL_EGL
+#include <EGL/egl.h>
+#endif
+
+typedef struct SDL_VideoData
+{
+    int devindex;               /* device index that was passed on creation */
+    int drm_fd;                 /* DRM file desc */
+    struct gbm_device *gbm;
+    drmEventContext drm_evctx;  /* DRM event context */
+    struct pollfd drm_pollfd;   /* pollfd containing DRM file desc */
+    drmModeCrtc *saved_crtc;    /* Saved CRTC to restore on quit */
+    uint32_t saved_conn_id;     /* Saved DRM connector ID */
+} SDL_VideoData;
+
+
+typedef struct SDL_DisplayData
+{
+    uint32_t encoder_id;
+    uint32_t crtc_id;
+    drmModeModeInfo cur_mode;
+} SDL_DisplayData;
+
+
+typedef struct SDL_WindowData
+{
+    struct gbm_surface *gs;
+    struct gbm_bo *current_bo;
+    struct gbm_bo *next_bo;
+    SDL_bool waiting_for_flip;
+#if SDL_VIDEO_OPENGL_EGL
+    EGLSurface egl_surface;
+#endif
+} SDL_WindowData;
+
+typedef struct KMSDRM_FBInfo
+{
+    int drm_fd;         /* DRM file desc */
+    uint32_t fb_id;     /* DRM framebuffer ID */
+} KMSDRM_FBInfo;
+
+/* Helper functions */
+KMSDRM_FBInfo *KMSDRM_FBFromBO(_THIS, struct gbm_bo *bo);
+SDL_bool KMSDRM_WaitPageFlip(_THIS, SDL_WindowData *wdata, int timeout);
+
+/****************************************************************************/
+/* SDL_VideoDevice functions declaration                                    */
+/****************************************************************************/
+
+/* Display and window functions */
+int KMSDRM_VideoInit(_THIS);
+void KMSDRM_VideoQuit(_THIS);
+void KMSDRM_GetDisplayModes(_THIS, SDL_VideoDisplay * display);
+int KMSDRM_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode);
+int KMSDRM_CreateWindow(_THIS, SDL_Window * window);
+int KMSDRM_CreateWindowFrom(_THIS, SDL_Window * window, const void *data);
+void KMSDRM_SetWindowTitle(_THIS, SDL_Window * window);
+void KMSDRM_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon);
+void KMSDRM_SetWindowPosition(_THIS, SDL_Window * window);
+void KMSDRM_SetWindowSize(_THIS, SDL_Window * window);
+void KMSDRM_ShowWindow(_THIS, SDL_Window * window);
+void KMSDRM_HideWindow(_THIS, SDL_Window * window);
+void KMSDRM_RaiseWindow(_THIS, SDL_Window * window);
+void KMSDRM_MaximizeWindow(_THIS, SDL_Window * window);
+void KMSDRM_MinimizeWindow(_THIS, SDL_Window * window);
+void KMSDRM_RestoreWindow(_THIS, SDL_Window * window);
+void KMSDRM_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed);
+void KMSDRM_DestroyWindow(_THIS, SDL_Window * window);
+
+/* Window manager function */
+SDL_bool KMSDRM_GetWindowWMInfo(_THIS, SDL_Window * window,
+                             struct SDL_SysWMinfo *info);
+
+/* OpenGL/OpenGL ES functions */
+int KMSDRM_GLES_LoadLibrary(_THIS, const char *path);
+void *KMSDRM_GLES_GetProcAddress(_THIS, const char *proc);
+void KMSDRM_GLES_UnloadLibrary(_THIS);
+SDL_GLContext KMSDRM_GLES_CreateContext(_THIS, SDL_Window * window);
+int KMSDRM_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
+int KMSDRM_GLES_SetSwapInterval(_THIS, int interval);
+int KMSDRM_GLES_GetSwapInterval(_THIS);
+int KMSDRM_GLES_SwapWindow(_THIS, SDL_Window * window);
+void KMSDRM_GLES_DeleteContext(_THIS, SDL_GLContext context);
+
+#endif /* __SDL_KMSDRMVIDEO_H__ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/mir/SDL_mirdyn.c b/src/video/mir/SDL_mirdyn.c
index 6bbe537..e50c41f 100644
--- a/src/video/mir/SDL_mirdyn.c
+++ b/src/video/mir/SDL_mirdyn.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/mir/SDL_mirdyn.h b/src/video/mir/SDL_mirdyn.h
index a3638cf..6a6e54c 100644
--- a/src/video/mir/SDL_mirdyn.h
+++ b/src/video/mir/SDL_mirdyn.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_mirdyn_h
-#define _SDL_mirdyn_h
+#ifndef SDL_mirdyn_h_
+#define SDL_mirdyn_h_
 
 #include "../../SDL_internal.h"
 
@@ -48,6 +48,6 @@ void SDL_MIR_UnloadSymbols(void);
 }
 #endif
 
-#endif /* !defined _SDL_mirdyn_h */
+#endif /* !defined SDL_mirdyn_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/mir/SDL_mirevents.c b/src/video/mir/SDL_mirevents.c
index e369868..84817c6 100644
--- a/src/video/mir/SDL_mirevents.c
+++ b/src/video/mir/SDL_mirevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -141,7 +141,7 @@ HandleTouchMotion(int device_id, int source_id, float x, float y, float pressure
 }
 
 static void
-HandleMouseScroll(SDL_Window* sdl_window, int hscroll, int vscroll)
+HandleMouseScroll(SDL_Window* sdl_window, float hscroll, float vscroll)
 {
     SDL_SendMouseWheel(sdl_window, 0, hscroll, vscroll, SDL_MOUSEWHEEL_NORMAL);
 }
@@ -205,7 +205,7 @@ HandleMouseEvent(MirPointerEvent const* pointer, SDL_Window* sdl_window)
             break;
         case mir_pointer_action_motion: {
             int x, y;
-            int hscroll, vscroll;
+            float hscroll, vscroll;
             SDL_Mouse* mouse = SDL_GetMouse();
             x = MIR_mir_pointer_event_axis_value(pointer, mir_pointer_axis_x);
             y = MIR_mir_pointer_event_axis_value(pointer, mir_pointer_axis_y);
@@ -237,7 +237,7 @@ HandleMouseEvent(MirPointerEvent const* pointer, SDL_Window* sdl_window)
 }
 
 static void
-MIR_HandleInput(MirInputEvent const* input_event, SDL_Window* window)
+HandleInput(MirInputEvent const* input_event, SDL_Window* window)
 {
     switch (MIR_mir_input_event_get_type(input_event)) {
         case (mir_input_event_type_key):
@@ -257,7 +257,7 @@ MIR_HandleInput(MirInputEvent const* input_event, SDL_Window* window)
 }
 
 static void
-MIR_HandleResize(MirResizeEvent const* resize_event, SDL_Window* window)
+HandleResize(MirResizeEvent const* resize_event, SDL_Window* window)
 {
     int new_w = MIR_mir_resize_event_get_width (resize_event);
     int new_h = MIR_mir_resize_event_get_height(resize_event);
@@ -270,23 +270,23 @@ MIR_HandleResize(MirResizeEvent const* resize_event, SDL_Window* window)
 }
 
 static void
-MIR_HandleSurface(MirSurfaceEvent const* surface_event, SDL_Window* window)
+HandleWindow(MirWindowEvent const* event, SDL_Window* window)
 {
-    MirSurfaceAttrib attrib = MIR_mir_surface_event_get_attribute(surface_event);
-    int value               = MIR_mir_surface_event_get_attribute_value(surface_event);
+    MirWindowAttrib attrib = MIR_mir_window_event_get_attribute(event);
+    int value              = MIR_mir_window_event_get_attribute_value(event);
 
-    if (attrib == mir_surface_attrib_focus) {
-        if (value == mir_surface_focused) {
+    if (attrib == mir_window_attrib_focus) {
+        if (value == mir_window_focus_state_focused) {
             SDL_SetKeyboardFocus(window);
         }
-        else if (value == mir_surface_unfocused) {
+        else if (value == mir_window_focus_state_unfocused) {
             SDL_SetKeyboardFocus(NULL);
         }
     }
 }
 
 void
-MIR_HandleEvent(MirSurface* surface, MirEvent const* ev, void* context)
+MIR_HandleEvent(MirWindow* mirwindow, MirEvent const* ev, void* context)
 {
     MirEventType event_type = MIR_mir_event_get_type(ev);
     SDL_Window* window      = (SDL_Window*)context;
@@ -294,13 +294,13 @@ MIR_HandleEvent(MirSurface* surface, MirEvent const* ev, void* context)
     if (window) {
         switch (event_type) {
             case (mir_event_type_input):
-                MIR_HandleInput(MIR_mir_event_get_input_event(ev), window);
+                HandleInput(MIR_mir_event_get_input_event(ev), window);
                 break;
             case (mir_event_type_resize):
-                MIR_HandleResize(MIR_mir_event_get_resize_event(ev), window);
+                HandleResize(MIR_mir_event_get_resize_event(ev), window);
                 break;
-            case (mir_event_type_surface):
-                MIR_HandleSurface(MIR_mir_event_get_surface_event(ev), window);
+            case (mir_event_type_window):
+                HandleWindow(MIR_mir_event_get_window_event(ev), window);
                 break;
             default:
                 break;
diff --git a/src/video/mir/SDL_mirevents.h b/src/video/mir/SDL_mirevents.h
index 121c4b3..b87bff8 100644
--- a/src/video/mir/SDL_mirevents.h
+++ b/src/video/mir/SDL_mirevents.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,15 +23,15 @@
   Contributed by Brandon Schaefer, <brandon.schaefer at canonical.com>
 */
 
-#ifndef _SDL_mirevents_h
-#define _SDL_mirevents_h
+#ifndef SDL_mirevents_h_
+#define SDL_mirevents_h_
 
 #include <mir_toolkit/mir_client_library.h>
 
 extern void
-MIR_HandleEvent(MirSurface* surface, MirEvent const* ev, void* context);
+MIR_HandleEvent(MirWindow*, MirEvent const* ev, void* context);
 
-#endif /* _SDL_mirevents_h */
+#endif /* SDL_mirevents_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
 
diff --git a/src/video/mir/SDL_mirframebuffer.c b/src/video/mir/SDL_mirframebuffer.c
index 775bc07..d804f3e 100644
--- a/src/video/mir/SDL_mirframebuffer.c
+++ b/src/video/mir/SDL_mirframebuffer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -42,7 +42,7 @@ MIR_CreateWindowFramebuffer(_THIS, SDL_Window* window, Uint32* format,
     mir_data->software = SDL_TRUE;
 
     if (MIR_CreateWindow(_this, window) < 0)
-        return SDL_SetError("Failed to created a mir window.");
+        return SDL_SetError("Failed to create a mir window.");
 
     *format = MIR_GetSDLPixelFormat(mir_data->pixel_format);
     if (*format == SDL_PIXELFORMAT_UNKNOWN)
@@ -70,7 +70,7 @@ MIR_UpdateWindowFramebuffer(_THIS, SDL_Window* window,
     char* s_dest;
     char* pixels;
 
-    bs = MIR_mir_surface_get_buffer_stream(mir_window->surface);
+    bs = MIR_mir_window_get_buffer_stream(mir_window->window);
     MIR_mir_buffer_stream_get_graphics_region(bs, &region);
 
     s_dest = region.vaddr;
diff --git a/src/video/mir/SDL_mirframebuffer.h b/src/video/mir/SDL_mirframebuffer.h
index 22a579c..b632ee7 100644
--- a/src/video/mir/SDL_mirframebuffer.h
+++ b/src/video/mir/SDL_mirframebuffer.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,8 +23,8 @@
   Contributed by Brandon Schaefer, <brandon.schaefer at canonical.com>
 */
 
-#ifndef _SDL_mirframebuffer_h
-#define _SDL_mirframebuffer_h
+#ifndef SDL_mirframebuffer_h_
+#define SDL_mirframebuffer_h_
 
 #include "../SDL_sysvideo.h"
 
@@ -41,7 +41,7 @@ MIR_UpdateWindowFramebuffer(_THIS, SDL_Window* sdl_window,
 extern void
 MIR_DestroyWindowFramebuffer(_THIS, SDL_Window* sdl_window);
 
-#endif /* _SDL_mirframebuffer_h */
+#endif /* SDL_mirframebuffer_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
 
diff --git a/src/video/mir/SDL_mirmouse.c b/src/video/mir/SDL_mirmouse.c
index 1a22b28..0acffe6 100644
--- a/src/video/mir/SDL_mirmouse.c
+++ b/src/video/mir/SDL_mirmouse.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -41,6 +41,7 @@ typedef struct
 {
     MirCursorConfiguration* conf;
     MirBufferStream*        stream;
+    char const*             name;
 } MIR_Cursor;
 
 static SDL_Cursor*
@@ -55,6 +56,7 @@ MIR_CreateDefaultCursor()
         if (mir_cursor) {
             mir_cursor->conf   = NULL;
             mir_cursor->stream = NULL;
+            mir_cursor->name   = NULL;
             cursor->driverdata = mir_cursor;
         }
         else {
@@ -137,12 +139,8 @@ static SDL_Cursor*
 MIR_CreateSystemCursor(SDL_SystemCursor id)
 {
     char const* cursor_name = NULL;
-    SDL_Cursor* cursor      = MIR_CreateDefaultCursor();
-    MIR_Cursor* mir_cursor  = (MIR_Cursor*)cursor->driverdata;
-
-    if (!cursor) {
-        return NULL;
-    }
+    SDL_Cursor* cursor;
+    MIR_Cursor* mir_cursor;
 
     switch(id) {
         case SDL_SYSTEM_CURSOR_ARROW:
@@ -188,7 +186,13 @@ MIR_CreateSystemCursor(SDL_SystemCursor id)
             return NULL;
     }
 
-    mir_cursor->conf = MIR_mir_cursor_configuration_from_name(cursor_name);
+    cursor = MIR_CreateDefaultCursor();
+    if (!cursor) {
+        return NULL;
+    }
+
+    mir_cursor = (MIR_Cursor*)cursor->driverdata;
+    mir_cursor->name = cursor_name;
 
     return cursor;
 }
@@ -220,18 +224,25 @@ MIR_ShowCursor(SDL_Cursor* cursor)
     MIR_Window* mir_window  = mir_data->current_window;
 
     if (cursor && cursor->driverdata) {
-        if (mir_window && MIR_mir_surface_is_valid(mir_window->surface)) {
+        if (mir_window && MIR_mir_window_is_valid(mir_window->window)) {
             MIR_Cursor* mir_cursor = (MIR_Cursor*)cursor->driverdata;
 
+            if (mir_cursor->name != NULL) {
+                MirWindowSpec* spec = MIR_mir_create_window_spec(mir_data->connection);
+                MIR_mir_window_spec_set_cursor_name(spec, mir_cursor->name);
+                MIR_mir_window_apply_spec(mir_window->window, spec);
+                MIR_mir_window_spec_release(spec);
+            }
+
             if (mir_cursor->conf) {
-                MIR_mir_surface_configure_cursor(mir_window->surface, mir_cursor->conf);
+                MIR_mir_window_configure_cursor(mir_window->window, mir_cursor->conf);
             }
         }
     }
-    else if(mir_window && MIR_mir_surface_is_valid(mir_window->surface)) {
-        MIR_mir_surface_configure_cursor(mir_window->surface, NULL);
+    else if(mir_window && MIR_mir_window_is_valid(mir_window->window)) {
+        MIR_mir_window_configure_cursor(mir_window->window, NULL);
     }
-    
+
     return 0;
 }
 
@@ -273,17 +284,6 @@ MIR_InitMouse()
 void
 MIR_FiniMouse()
 {
-    SDL_Mouse* mouse = SDL_GetMouse();
-
-    MIR_FreeCursor(mouse->def_cursor);
-    mouse->def_cursor = NULL;
-
-    mouse->CreateCursor         = NULL;
-    mouse->ShowCursor           = NULL;
-    mouse->FreeCursor           = NULL;
-    mouse->WarpMouse            = NULL;
-    mouse->CreateSystemCursor   = NULL;
-    mouse->SetRelativeMouseMode = NULL;
 }
 
 #endif /* SDL_VIDEO_DRIVER_MIR */
diff --git a/src/video/mir/SDL_mirmouse.h b/src/video/mir/SDL_mirmouse.h
index 94dd085..63cc8c7 100644
--- a/src/video/mir/SDL_mirmouse.h
+++ b/src/video/mir/SDL_mirmouse.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,8 +23,8 @@
   Contributed by Brandon Schaefer, <brandon.schaefer at canonical.com>
 */
 
-#ifndef _SDL_mirmouse_h
-#define _SDL_mirmouse_h
+#ifndef SDL_mirmouse_h_
+#define SDL_mirmouse_h_
 
 extern void
 MIR_InitMouse();
@@ -32,6 +32,6 @@ MIR_InitMouse();
 extern void
 MIR_FiniMouse();
 
-#endif /* _SDL_mirmouse_h */
+#endif /* SDL_mirmouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/mir/SDL_miropengl.c b/src/video/mir/SDL_miropengl.c
index 23fabb2..64b17a8 100644
--- a/src/video/mir/SDL_miropengl.c
+++ b/src/video/mir/SDL_miropengl.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -31,12 +31,12 @@
 
 #include "SDL_mirdyn.h"
 
-void
+int
 MIR_GL_SwapWindow(_THIS, SDL_Window* window)
 {
     MIR_Window* mir_wind = window->driverdata;
 
-    SDL_EGL_SwapBuffers(_this, mir_wind->egl_surface);
+    return SDL_EGL_SwapBuffers(_this, mir_wind->egl_surface);
 }
 
 int
@@ -66,31 +66,13 @@ MIR_GL_LoadLibrary(_THIS, const char* path)
 {
     MIR_Data* mir_data = _this->driverdata;
 
-    SDL_EGL_LoadLibrary(_this, path, MIR_mir_connection_get_egl_native_display(mir_data->connection));
+    SDL_EGL_LoadLibrary(_this, path, MIR_mir_connection_get_egl_native_display(mir_data->connection), 0);
 
     SDL_EGL_ChooseConfig(_this);
 
     return 0;
 }
 
-void
-MIR_GL_UnloadLibrary(_THIS)
-{
-    SDL_EGL_UnloadLibrary(_this);
-}
-
-void*
-MIR_GL_GetProcAddress(_THIS, const char* proc)
-{
-    void* proc_addr = SDL_EGL_GetProcAddress(_this, proc);
-
-    if (!proc_addr) {
-        SDL_SetError("Failed to find proc address!");
-    }
-
-    return proc_addr;
-}
-
 #endif /* SDL_VIDEO_DRIVER_MIR */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/mir/SDL_miropengl.h b/src/video/mir/SDL_miropengl.h
index 96bb40a..538b9a9 100644
--- a/src/video/mir/SDL_miropengl.h
+++ b/src/video/mir/SDL_miropengl.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,8 +23,8 @@
   Contributed by Brandon Schaefer, <brandon.schaefer at canonical.com>
 */
 
-#ifndef _SDL_miropengl_h
-#define _SDL_miropengl_h
+#ifndef SDL_miropengl_h_
+#define SDL_miropengl_h_
 
 #include "SDL_mirwindow.h"
 
@@ -33,8 +33,10 @@
 #define MIR_GL_DeleteContext   SDL_EGL_DeleteContext
 #define MIR_GL_GetSwapInterval SDL_EGL_GetSwapInterval
 #define MIR_GL_SetSwapInterval SDL_EGL_SetSwapInterval
+#define MIR_GL_UnloadLibrary   SDL_EGL_UnloadLibrary
+#define MIR_GL_GetProcAddress  SDL_EGL_GetProcAddress
 
-extern void
+extern int
 MIR_GL_SwapWindow(_THIS, SDL_Window* window);
 
 extern int
@@ -46,13 +48,6 @@ MIR_GL_CreateContext(_THIS, SDL_Window* window);
 extern int
 MIR_GL_LoadLibrary(_THIS, const char* path);
 
-extern void
-MIR_GL_UnloadLibrary(_THIS);
-
-extern void*
-MIR_GL_GetProcAddress(_THIS, const char* proc);
-
-#endif /* _SDL_miropengl_h */
+#endif /* SDL_miropengl_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
-
diff --git a/src/video/mir/SDL_mirsym.h b/src/video/mir/SDL_mirsym.h
index 4f97ed9..79f3075 100644
--- a/src/video/mir/SDL_mirsym.h
+++ b/src/video/mir/SDL_mirsym.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -34,28 +34,30 @@
 #endif
 
 SDL_MIR_MODULE(MIR_CLIENT)
-SDL_MIR_SYM(MirSurface *,mir_surface_create_sync,(MirSurfaceSpec* spec))
+SDL_MIR_SYM(MirWindow *,mir_create_window_sync,(MirWindowSpec* spec))
 SDL_MIR_SYM(MirEGLNativeWindowType,mir_buffer_stream_get_egl_native_window,(MirBufferStream *surface))
-SDL_MIR_SYM(void,mir_buffer_stream_get_graphics_region,(MirBufferStream *stream, MirGraphicsRegion *graphics_region))
+SDL_MIR_SYM(bool,mir_buffer_stream_get_graphics_region,(MirBufferStream *stream, MirGraphicsRegion *graphics_region))
 SDL_MIR_SYM(void,mir_buffer_stream_swap_buffers_sync,(MirBufferStream *stream))
-SDL_MIR_SYM(void,mir_surface_set_event_handler,(MirSurface *surface, mir_surface_event_callback callback, void* context))
-SDL_MIR_SYM(MirSurfaceSpec*,mir_connection_create_spec_for_normal_surface,(MirConnection *connection, int width, int height, MirPixelFormat format))
-SDL_MIR_SYM(MirSurfaceSpec*,mir_connection_create_spec_for_changes,(MirConnection *connection))
-SDL_MIR_SYM(void,mir_surface_spec_set_buffer_usage,(MirSurfaceSpec *spec, MirBufferUsage usage))
-SDL_MIR_SYM(void,mir_surface_spec_set_name,(MirSurfaceSpec *spec, char const *name))
-SDL_MIR_SYM(void,mir_surface_spec_release,(MirSurfaceSpec *spec))
-SDL_MIR_SYM(void,mir_surface_spec_set_width,(MirSurfaceSpec *spec, unsigned width))
-SDL_MIR_SYM(void,mir_surface_spec_set_height,(MirSurfaceSpec *spec, unsigned height))
-SDL_MIR_SYM(void,mir_surface_spec_set_min_width,(MirSurfaceSpec *spec, unsigned min_width))
-SDL_MIR_SYM(void,mir_surface_spec_set_min_height,(MirSurfaceSpec *spec, unsigned min_height))
-SDL_MIR_SYM(void,mir_surface_spec_set_max_width,(MirSurfaceSpec *spec, unsigned max_width))
-SDL_MIR_SYM(void,mir_surface_spec_set_max_height,(MirSurfaceSpec *spec, unsigned max_height))
-SDL_MIR_SYM(void,mir_surface_spec_set_type,(MirSurfaceSpec *spec, MirSurfaceType type))
-SDL_MIR_SYM(void,mir_surface_spec_set_state,(MirSurfaceSpec *spec, MirSurfaceState state))
-SDL_MIR_SYM(void,mir_surface_spec_set_pointer_confinement,(MirSurfaceSpec *spec, MirPointerConfinementState state))
-SDL_MIR_SYM(void,mir_surface_apply_spec,(MirSurface *surface, MirSurfaceSpec *spec))
-SDL_MIR_SYM(void,mir_surface_get_parameters,(MirSurface *surface, MirSurfaceParameters *params))
-SDL_MIR_SYM(MirBufferStream*,mir_surface_get_buffer_stream,(MirSurface *surface))
+SDL_MIR_SYM(void,mir_window_set_event_handler,(MirWindow* window, MirWindowEventCallback callback, void* context))
+SDL_MIR_SYM(MirWindowSpec*,mir_create_normal_window_spec,(MirConnection *connection, int width, int height))
+SDL_MIR_SYM(MirWindowSpec*,mir_create_window_spec,(MirConnection *connection))
+SDL_MIR_SYM(void,mir_window_spec_set_buffer_usage,(MirWindowSpec *spec, MirBufferUsage usage))
+SDL_MIR_SYM(void,mir_window_spec_set_name,(MirWindowSpec *spec, char const *name))
+SDL_MIR_SYM(void,mir_window_spec_release,(MirWindowSpec *spec))
+SDL_MIR_SYM(void,mir_window_spec_set_width,(MirWindowSpec *spec, unsigned width))
+SDL_MIR_SYM(void,mir_window_spec_set_height,(MirWindowSpec *spec, unsigned height))
+SDL_MIR_SYM(void,mir_window_spec_set_min_width,(MirWindowSpec *spec, unsigned min_width))
+SDL_MIR_SYM(void,mir_window_spec_set_min_height,(MirWindowSpec *spec, unsigned min_height))
+SDL_MIR_SYM(void,mir_window_spec_set_max_width,(MirWindowSpec *spec, unsigned max_width))
+SDL_MIR_SYM(void,mir_window_spec_set_max_height,(MirWindowSpec *spec, unsigned max_height))
+SDL_MIR_SYM(void,mir_window_spec_set_type,(MirWindowSpec *spec, MirWindowType type))
+SDL_MIR_SYM(void,mir_window_spec_set_state,(MirWindowSpec *spec, MirWindowState state))
+SDL_MIR_SYM(void,mir_window_spec_set_pointer_confinement,(MirWindowSpec *spec, MirPointerConfinementState state))
+SDL_MIR_SYM(void,mir_window_spec_set_pixel_format,(MirWindowSpec *spec, MirPixelFormat pixel_format))
+SDL_MIR_SYM(void,mir_window_spec_set_cursor_name,(MirWindowSpec *spec, char const* cursor_name))
+SDL_MIR_SYM(void,mir_window_apply_spec,(MirWindow* window, MirWindowSpec* spec))
+SDL_MIR_SYM(void,mir_window_get_parameters,(MirWindow *window, MirWindowParameters *params))
+SDL_MIR_SYM(MirBufferStream*,mir_window_get_buffer_stream,(MirWindow* window))
 SDL_MIR_SYM(MirCursorConfiguration*,mir_cursor_configuration_from_buffer_stream,(MirBufferStream const* stream, int hot_x, int hot_y))
 SDL_MIR_SYM(MirBufferStream*,mir_connection_create_buffer_stream_sync,(MirConnection *connection, int w, int h, MirPixelFormat format, MirBufferUsage usage))
 SDL_MIR_SYM(MirKeyboardAction,mir_keyboard_event_action,(MirKeyboardEvent const *event))
@@ -76,7 +78,7 @@ SDL_MIR_SYM(MirResizeEvent const*,mir_event_get_resize_event,(MirEvent const *ev
 SDL_MIR_SYM(MirKeyboardEvent const*,mir_input_event_get_keyboard_event,(MirInputEvent const *event))
 SDL_MIR_SYM(MirPointerEvent const*,mir_input_event_get_pointer_event,(MirInputEvent const *event))
 SDL_MIR_SYM(MirTouchEvent const*,mir_input_event_get_touch_event,(MirInputEvent const *event))
-SDL_MIR_SYM(MirSurfaceEvent const*,mir_event_get_surface_event,(MirEvent const *event))
+SDL_MIR_SYM(MirWindowEvent const*,mir_event_get_window_event,(MirEvent const *event))
 SDL_MIR_SYM(unsigned int,mir_touch_event_point_count,(MirTouchEvent const *event))
 SDL_MIR_SYM(void,mir_connection_get_available_surface_formats,(MirConnection* connection, MirPixelFormat* formats, unsigned const int format_size, unsigned int *num_valid_formats))
 SDL_MIR_SYM(MirEGLNativeDisplayType,mir_connection_get_egl_native_display,(MirConnection *connection))
@@ -84,24 +86,23 @@ SDL_MIR_SYM(bool,mir_connection_is_valid,(MirConnection *connection))
 SDL_MIR_SYM(void,mir_connection_release,(MirConnection *connection))
 SDL_MIR_SYM(MirPixelFormat,mir_connection_get_egl_pixel_format,(MirConnection* connection, void* egldisplay, void* eglconfig))
 SDL_MIR_SYM(MirConnection *,mir_connect_sync,(char const *server, char const *app_name))
-SDL_MIR_SYM(char const *,mir_surface_get_error_message,(MirSurface *surface))
-SDL_MIR_SYM(bool,mir_surface_is_valid,(MirSurface *surface))
-SDL_MIR_SYM(void,mir_surface_release_sync,(MirSurface *surface))
+SDL_MIR_SYM(char const *,mir_window_get_error_message,(MirWindow *window))
+SDL_MIR_SYM(bool,mir_window_is_valid,(MirWindow *window))
+SDL_MIR_SYM(void,mir_window_release_sync,(MirWindow* window))
 SDL_MIR_SYM(void,mir_buffer_stream_release_sync,(MirBufferStream *stream))
-SDL_MIR_SYM(MirCursorConfiguration*,mir_cursor_configuration_from_name,(char const* cursor_name))
-SDL_MIR_SYM(MirWaitHandle*,mir_surface_configure_cursor,(MirSurface* surface, MirCursorConfiguration const* conf))
+SDL_MIR_SYM(void,mir_window_configure_cursor,(MirWindow* window, MirCursorConfiguration const* conf))
 SDL_MIR_SYM(void,mir_cursor_configuration_destroy,(MirCursorConfiguration* conf))
 SDL_MIR_SYM(int,mir_resize_event_get_width,(MirResizeEvent const* resize_event))
 SDL_MIR_SYM(int,mir_resize_event_get_height,(MirResizeEvent const* resize_event))
 SDL_MIR_SYM(char const*,mir_connection_get_error_message,(MirConnection* connection))
-SDL_MIR_SYM(MirSurfaceAttrib,mir_surface_event_get_attribute,(MirSurfaceEvent const* surface_event))
-SDL_MIR_SYM(int,mir_surface_event_get_attribute_value,(MirSurfaceEvent const* surface_event))
-SDL_MIR_SYM(void,mir_wait_for,(MirWaitHandle* handle))
+SDL_MIR_SYM(MirWindowAttrib,mir_window_event_get_attribute,(MirWindowEvent const* event))
+SDL_MIR_SYM(int,mir_window_event_get_attribute_value,(MirWindowEvent const* window_event))
 SDL_MIR_SYM(MirDisplayConfig*,mir_connection_create_display_configuration,(MirConnection* connection))
 SDL_MIR_SYM(void,mir_display_config_release,(MirDisplayConfig* config))
 SDL_MIR_SYM(int,mir_display_config_get_num_outputs,(MirDisplayConfig const* config))
 SDL_MIR_SYM(MirOutput*,mir_display_config_get_mutable_output,(MirDisplayConfig* config, size_t index))
 SDL_MIR_SYM(int,mir_output_get_num_modes,(MirOutput const* output))
+SDL_MIR_SYM(MirOutputMode const*,mir_output_get_current_mode,(MirOutput const* output))
 SDL_MIR_SYM(MirPixelFormat,mir_output_get_current_pixel_format,(MirOutput const* output))
 SDL_MIR_SYM(int,mir_output_get_position_x,(MirOutput const* output))
 SDL_MIR_SYM(int,mir_output_get_position_y,(MirOutput const* output))
@@ -115,7 +116,7 @@ SDL_MIR_SYM(MirOutputMode const*,mir_output_get_mode,(MirOutput const* output, s
 SDL_MIR_SYM(int,mir_output_mode_get_width,(MirOutputMode const* mode))
 SDL_MIR_SYM(int,mir_output_mode_get_height,(MirOutputMode const* mode))
 SDL_MIR_SYM(double,mir_output_mode_get_refresh_rate,(MirOutputMode const* mode))
-SDL_MIR_SYM(MirOutputGammaSupported,mir_output_is_gamma_supported,(MirOutput const* output))
+SDL_MIR_SYM(bool,mir_output_is_gamma_supported,(MirOutput const* output))
 SDL_MIR_SYM(uint32_t,mir_output_get_gamma_size,(MirOutput const* output))
 SDL_MIR_SYM(void,mir_output_get_gamma,(MirOutput const* output, uint16_t* red, uint16_t* green, uint16_t* blue, uint32_t size))
 SDL_MIR_SYM(void,mir_output_set_gamma,(MirOutput* output, uint16_t const* red, uint16_t const* green, uint16_t const* blue, uint32_t size))
diff --git a/src/video/mir/SDL_mirvideo.c b/src/video/mir/SDL_mirvideo.c
index 6a8f9e4..35cb405 100644
--- a/src/video/mir/SDL_mirvideo.c
+++ b/src/video/mir/SDL_mirvideo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,6 +27,8 @@
 
 #if SDL_VIDEO_DRIVER_MIR
 
+#include "SDL_log.h"
+
 #include "SDL_mirwindow.h"
 #include "SDL_video.h"
 
@@ -34,6 +36,7 @@
 #include "SDL_mirmouse.h"
 #include "SDL_miropengl.h"
 #include "SDL_mirvideo.h"
+#include "SDL_mirvulkan.h"
 
 #include "SDL_mirdyn.h"
 
@@ -98,7 +101,19 @@ MIR_Available()
     int available = 0;
 
     if (SDL_MIR_LoadSymbols()) {
-        /* !!! FIXME: try to make a MirConnection here. */
+
+        /* Lets ensure we can connect to the mir server */
+        MirConnection* connection = MIR_mir_connect_sync(NULL, __PRETTY_FUNCTION__);
+
+        if (!MIR_mir_connection_is_valid(connection)) {
+            SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "Unable to connect to the mir server %s",
+                MIR_mir_connection_get_error_message(connection));
+
+            return available;
+        }
+
+        MIR_mir_connection_release(connection);
+
         available = 1;
         SDL_MIR_UnloadSymbols();
     }
@@ -165,7 +180,7 @@ MIR_CreateDevice(int device_index)
     device->GL_GetProcAddress  = MIR_GL_GetProcAddress;
 
     /* mirwindow */
-    device->CreateWindow         = MIR_CreateWindow;
+    device->CreateSDLWindow         = MIR_CreateWindow;
     device->DestroyWindow        = MIR_DestroyWindow;
     device->GetWindowWMInfo      = MIR_GetWindowWMInfo;
     device->SetWindowFullscreen  = MIR_SetWindowFullscreen;
@@ -182,7 +197,7 @@ MIR_CreateDevice(int device_index)
     device->SetWindowGammaRamp   = MIR_SetWindowGammaRamp;
     device->GetWindowGammaRamp   = MIR_GetWindowGammaRamp;
 
-    device->CreateWindowFrom     = NULL;
+    device->CreateSDLWindowFrom     = NULL;
     device->SetWindowIcon        = NULL;
     device->RaiseWindow          = NULL;
     device->SetWindowBordered    = NULL;
@@ -218,6 +233,13 @@ MIR_CreateDevice(int device_index)
 
     device->ShowMessageBox = NULL;
 
+#if SDL_VIDEO_VULKAN
+    device->Vulkan_LoadLibrary = MIR_Vulkan_LoadLibrary;
+    device->Vulkan_UnloadLibrary = MIR_Vulkan_UnloadLibrary;
+    device->Vulkan_GetInstanceExtensions = MIR_Vulkan_GetInstanceExtensions;
+    device->Vulkan_CreateSurface = MIR_Vulkan_CreateSurface;
+#endif
+
     return device;
 }
 
@@ -255,7 +277,7 @@ MIR_InitDisplayFromOutput(_THIS, MirOutput* output)
 
     MirPixelFormat format = MIR_mir_output_get_current_pixel_format(output);
     int num_modes         = MIR_mir_output_get_num_modes(output);
-    SDL_DisplayMode current_mode = MIR_ConvertModeToSDLMode(mir_output_get_current_mode(output), format);
+    SDL_DisplayMode current_mode = MIR_ConvertModeToSDLMode(MIR_mir_output_get_current_mode(output), format);
 
     SDL_zero(display);
 
diff --git a/src/video/mir/SDL_mirvideo.h b/src/video/mir/SDL_mirvideo.h
index 71ef4ec..c29890b 100644
--- a/src/video/mir/SDL_mirvideo.h
+++ b/src/video/mir/SDL_mirvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,11 +23,12 @@
   Contributed by Brandon Schaefer, <brandon.schaefer at canonical.com>
 */
 
-#ifndef _SDL_mirvideo_h_
-#define _SDL_mirvideo_h_
+#ifndef SDL_mirvideo_h__
+#define SDL_mirvideo_h__
 
 #include <EGL/egl.h>
 #include <mir_toolkit/mir_client_library.h>
+#include "SDL_stdinc.h"
 
 typedef struct MIR_Window MIR_Window;
 
@@ -43,6 +44,6 @@ typedef struct
 extern Uint32
 MIR_GetSDLPixelFormat(MirPixelFormat format);
 
-#endif /* _SDL_mirvideo_h_ */
+#endif /* SDL_mirvideo_h__ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/mir/SDL_mirvulkan.c b/src/video/mir/SDL_mirvulkan.c
new file mode 100644
index 0000000..72abe8f
--- /dev/null
+++ b/src/video/mir/SDL_mirvulkan.c
@@ -0,0 +1,175 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.c.
+ */
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_MIR
+
+#include "SDL_mirvideo.h"
+#include "SDL_mirwindow.h"
+#include "SDL_assert.h"
+
+#include "SDL_loadso.h"
+#include "SDL_mirvulkan.h"
+#include "SDL_syswm.h"
+
+int MIR_Vulkan_LoadLibrary(_THIS, const char *path)
+{
+    VkExtensionProperties *extensions = NULL;
+    Uint32 extensionCount = 0;
+    SDL_bool hasSurfaceExtension = SDL_FALSE;
+    SDL_bool hasMIRSurfaceExtension = SDL_FALSE;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
+    if(_this->vulkan_config.loader_handle)
+        return SDL_SetError("Vulkan already loaded");
+
+    /* Load the Vulkan loader library */
+    if(!path)
+        path = SDL_getenv("SDL_VULKAN_LIBRARY");
+    if(!path)
+        path = "libvulkan.so.1";
+    _this->vulkan_config.loader_handle = SDL_LoadObject(path);
+    if(!_this->vulkan_config.loader_handle)
+        return -1;
+    SDL_strlcpy(_this->vulkan_config.loader_path, path,
+                SDL_arraysize(_this->vulkan_config.loader_path));
+    vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction(
+        _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr");
+    if(!vkGetInstanceProcAddr)
+        goto fail;
+    _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr;
+    _this->vulkan_config.vkEnumerateInstanceExtensionProperties =
+        (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)(
+            VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties");
+    if(!_this->vulkan_config.vkEnumerateInstanceExtensionProperties)
+        goto fail;
+    extensions = SDL_Vulkan_CreateInstanceExtensionsList(
+        (PFN_vkEnumerateInstanceExtensionProperties)
+            _this->vulkan_config.vkEnumerateInstanceExtensionProperties,
+        &extensionCount);
+    if(!extensions)
+        goto fail;
+    for(Uint32 i = 0; i < extensionCount; i++)
+    {
+        if(SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasSurfaceExtension = SDL_TRUE;
+        else if(SDL_strcmp(VK_KHR_MIR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasMIRSurfaceExtension = SDL_TRUE;
+    }
+    SDL_free(extensions);
+    if(!hasSurfaceExtension)
+    {
+        SDL_SetError("Installed Vulkan doesn't implement the "
+                     VK_KHR_SURFACE_EXTENSION_NAME " extension");
+        goto fail;
+    }
+    else if(!hasMIRSurfaceExtension)
+    {
+        SDL_SetError("Installed Vulkan doesn't implement the "
+                     VK_KHR_MIR_SURFACE_EXTENSION_NAME "extension");
+        goto fail;
+    }
+    return 0;
+
+fail:
+    SDL_UnloadObject(_this->vulkan_config.loader_handle);
+    _this->vulkan_config.loader_handle = NULL;
+    return -1;
+}
+
+void MIR_Vulkan_UnloadLibrary(_THIS)
+{
+    if(_this->vulkan_config.loader_handle)
+    {
+        SDL_UnloadObject(_this->vulkan_config.loader_handle);
+        _this->vulkan_config.loader_handle = NULL;
+    }
+}
+
+SDL_bool MIR_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names)
+{
+    static const char *const extensionsForMir[] = {
+        VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_MIR_SURFACE_EXTENSION_NAME
+    };
+    if(!_this->vulkan_config.loader_handle)
+    {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+    return SDL_Vulkan_GetInstanceExtensions_Helper(
+            count, names, SDL_arraysize(extensionsForMir),
+            extensionsForMir);
+}
+
+SDL_bool MIR_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface)
+{
+    MIR_Window *windowData = (MIR_Window *)window->driverdata;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr =
+        (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr;
+    PFN_vkCreateMirSurfaceKHR vkCreateMirSurfaceKHR =
+        (PFN_vkCreateMirSurfaceKHR)vkGetInstanceProcAddr(
+                                            (VkInstance)instance,
+                                            "vkCreateMirSurfaceKHR");
+    VkMirSurfaceCreateInfoKHR createInfo = {};
+    VkResult result;
+
+    if(!_this->vulkan_config.loader_handle)
+    {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+
+    if(!vkCreateMirSurfaceKHR)
+    {
+        SDL_SetError(VK_KHR_MIR_SURFACE_EXTENSION_NAME
+                     " extension is not enabled in the Vulkan instance.");
+        return SDL_FALSE;
+    }
+    createInfo.sType = VK_STRUCTURE_TYPE_MIR_SURFACE_CREATE_INFO_KHR;
+    createInfo.pNext = NULL;
+    createInfo.flags = 0;
+    createInfo.connection = windowData->mir_data->connection;
+    createInfo.mirSurface = windowData->window;
+    result = vkCreateMirSurfaceKHR(instance, &createInfo,
+                                       NULL, surface);
+    if(result != VK_SUCCESS)
+    {
+        SDL_SetError("vkCreateMirSurfaceKHR failed: %s",
+                     SDL_Vulkan_GetResultString(result));
+        return SDL_FALSE;
+    }
+    return SDL_TRUE;
+}
+
+#endif
+
+/* vim: set ts=4 sw=4 expandtab: */
diff --git a/src/video/emscripten/SDL_emscriptenvideo.h b/src/video/mir/SDL_mirvulkan.h
similarity index 56%
copy from src/video/emscripten/SDL_emscriptenvideo.h
copy to src/video/mir/SDL_mirvulkan.h
index 7618ab6..4b3981c 100644
--- a/src/video/emscripten/SDL_emscriptenvideo.h
+++ b/src/video/mir/SDL_mirvulkan.h
@@ -18,37 +18,35 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../../SDL_internal.h"
-
-#ifndef _SDL_emscriptenvideo_h
-#define _SDL_emscriptenvideo_h
 
-#include "../SDL_sysvideo.h"
-#include "../../events/SDL_touch_c.h"
-#include <emscripten/emscripten.h>
-#include <emscripten/html5.h>
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.h.
+ */
 
-#include <EGL/egl.h>
+#include "../../SDL_internal.h"
 
-typedef struct SDL_WindowData
-{
-#if SDL_VIDEO_OPENGL_EGL
-    EGLSurface egl_surface;
-#endif
-    SDL_Window *window;
-    SDL_Surface *surface;
+#ifndef SDL_mirvulkan_h_
+#define SDL_mirvulkan_h_
 
-    float pixel_ratio;
+#include "../SDL_vulkan_internal.h"
+#include "../SDL_sysvideo.h"
 
-    SDL_bool external_size;
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_MIR
 
-    int requested_fullscreen_mode;
-    SDL_bool fullscreen_resize;
+int MIR_Vulkan_LoadLibrary(_THIS, const char *path);
+void MIR_Vulkan_UnloadLibrary(_THIS);
+SDL_bool MIR_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names);
+SDL_bool MIR_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface);
 
-    SDL_bool finger_touching;  /* for mapping touch events to mice */
-    SDL_FingerID first_finger;
-} SDL_WindowData;
+#endif
 
-#endif /* _SDL_emscriptenvideo_h */
+#endif /* SDL_mirvulkan_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/mir/SDL_mirwindow.c b/src/video/mir/SDL_mirwindow.c
index 1bf9016..183114b 100644
--- a/src/video/mir/SDL_mirwindow.c
+++ b/src/video/mir/SDL_mirwindow.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -36,18 +36,18 @@
 
 #include "SDL_mirdyn.h"
 
-int
-IsSurfaceValid(MIR_Window* mir_window)
+static int
+IsMirWindowValid(MIR_Window* mir_window)
 {
-    if (!MIR_mir_surface_is_valid(mir_window->surface)) {
-        const char* error = MIR_mir_surface_get_error_message(mir_window->surface);
-        return SDL_SetError("Failed to created a mir surface: %s", error);
+    if (!MIR_mir_window_is_valid(mir_window->window)) {
+        const char* error = MIR_mir_window_get_error_message(mir_window->window);
+        return SDL_SetError("Failed to create a mir surface: %s", error);
     }
 
-    return 0;
+    return 1;
 }
 
-MirPixelFormat
+static MirPixelFormat
 FindValidPixelFormat(MIR_Data* mir_data)
 {
     unsigned int pf_size = 32;
@@ -81,7 +81,7 @@ MIR_CreateWindow(_THIS, SDL_Window* window)
     MirPixelFormat pixel_format;
     MirBufferUsage buffer_usage;
 
-    MirSurfaceSpec* spec;
+    MirWindowSpec* spec;
 
     mir_window = SDL_calloc(1, sizeof(MIR_Window));
     if (!mir_window)
@@ -117,36 +117,36 @@ MIR_CreateWindow(_THIS, SDL_Window* window)
     if (mir_data->software)
         buffer_usage = mir_buffer_usage_software;
 
-    spec = MIR_mir_connection_create_spec_for_normal_surface(mir_data->connection,
-                                                             window->w,
-                                                             window->h,
-                                                             pixel_format);
+    spec = MIR_mir_create_normal_window_spec(mir_data->connection,
+                                             window->w,
+                                             window->h);
 
-    MIR_mir_surface_spec_set_buffer_usage(spec, buffer_usage);
-    MIR_mir_surface_spec_set_name(spec, "Mir surface");
+    MIR_mir_window_spec_set_buffer_usage(spec, buffer_usage);
+    MIR_mir_window_spec_set_name(spec, "Mir surface");
+    MIR_mir_window_spec_set_pixel_format(spec, pixel_format);
 
     if (window->flags & SDL_WINDOW_INPUT_FOCUS)
         SDL_SetKeyboardFocus(window);
 
-    mir_window->surface = MIR_mir_surface_create_sync(spec);
-    MIR_mir_surface_set_event_handler(mir_window->surface, MIR_HandleEvent, window);
+    mir_window->window = MIR_mir_create_window_sync(spec);
+    MIR_mir_window_set_event_handler(mir_window->window, MIR_HandleEvent, window);
 
-    MIR_mir_surface_spec_release(spec);
+    MIR_mir_window_spec_release(spec);
 
-    if (!MIR_mir_surface_is_valid(mir_window->surface)) {
-        return SDL_SetError("Failed to created a mir surface: %s",
-            MIR_mir_surface_get_error_message(mir_window->surface));
+    if (!MIR_mir_window_is_valid(mir_window->window)) {
+        return SDL_SetError("Failed to create a mir surface: %s",
+            MIR_mir_window_get_error_message(mir_window->window));
     }
 
     if (window->flags & SDL_WINDOW_OPENGL) {
         EGLNativeWindowType egl_native_window =
                         (EGLNativeWindowType)MIR_mir_buffer_stream_get_egl_native_window(
-                                                       MIR_mir_surface_get_buffer_stream(mir_window->surface));
+                                                       MIR_mir_window_get_buffer_stream(mir_window->window));
 
         mir_window->egl_surface = SDL_EGL_CreateSurface(_this, egl_native_window);
 
         if (mir_window->egl_surface == EGL_NO_SURFACE) {
-            return SDL_SetError("Failed to created a window surface %p",
+            return SDL_SetError("Failed to create a window surface %p",
                                 _this->egl_data->egl_display);
         }
     }
@@ -167,7 +167,7 @@ MIR_DestroyWindow(_THIS, SDL_Window* window)
 
     if (mir_data) {
         SDL_EGL_DestroySurface(_this, mir_window->egl_surface);
-        MIR_mir_surface_release_sync(mir_window->surface);
+        MIR_mir_window_release_sync(mir_window->window);
 
         mir_data->current_window = NULL;
 
@@ -185,7 +185,8 @@ MIR_GetWindowWMInfo(_THIS, SDL_Window* window, SDL_SysWMinfo* info)
 
         info->subsystem = SDL_SYSWM_MIR;
         info->info.mir.connection = mir_window->mir_data->connection;
-        info->info.mir.surface = mir_window->surface;
+        // Cannot change this to window due to it being in the public API
+        info->info.mir.surface = mir_window->window;
 
         return SDL_TRUE;
     }
@@ -193,153 +194,104 @@ MIR_GetWindowWMInfo(_THIS, SDL_Window* window, SDL_SysWMinfo* info)
     return SDL_FALSE;
 }
 
+static void
+UpdateMirWindowState(MIR_Data* mir_data, MIR_Window* mir_window, MirWindowState window_state)
+{
+    if (IsMirWindowValid(mir_window)) {
+        MirWindowSpec* spec = MIR_mir_create_window_spec(mir_data->connection);
+        MIR_mir_window_spec_set_state(spec, window_state);
+
+        MIR_mir_window_apply_spec(mir_window->window, spec);
+        MIR_mir_window_spec_release(spec);
+    }
+}
+
 void
 MIR_SetWindowFullscreen(_THIS, SDL_Window* window,
                         SDL_VideoDisplay* display,
                         SDL_bool fullscreen)
 {
-    MIR_Data*   mir_data   = _this->driverdata;
-    MIR_Window* mir_window = window->driverdata;
-    MirSurfaceSpec* spec;
-    MirSurfaceState state;
+    if (IsMirWindowValid(window->driverdata)) {
+        MirWindowState state;
 
-    if (IsSurfaceValid(mir_window) < 0)
-        return;
+        if (fullscreen) {
+            state = mir_window_state_fullscreen;
+        }
+        else {
+            state = mir_window_state_restored;
+        }
 
-    if (fullscreen) {
-        state = mir_surface_state_fullscreen;
-    } else {
-        state = mir_surface_state_restored;
+        UpdateMirWindowState(_this->driverdata, window->driverdata, state);
     }
-
-    spec = MIR_mir_connection_create_spec_for_changes(mir_data->connection);
-    MIR_mir_surface_spec_set_state(spec, state);
-
-    MIR_mir_surface_apply_spec(mir_window->surface, spec);
-    MIR_mir_surface_spec_release(spec);
 }
 
 void
 MIR_MaximizeWindow(_THIS, SDL_Window* window)
 {
-    MIR_Data*   mir_data   = _this->driverdata;
-    MIR_Window* mir_window = window->driverdata;
-    MirSurfaceSpec* spec;
-
-    if (IsSurfaceValid(mir_window) < 0)
-        return;
-
-    spec = MIR_mir_connection_create_spec_for_changes(mir_data->connection);
-    MIR_mir_surface_spec_set_state(spec, mir_surface_state_maximized);
-
-    MIR_mir_surface_apply_spec(mir_window->surface, spec);
-    MIR_mir_surface_spec_release(spec);
+    UpdateMirWindowState(_this->driverdata, window->driverdata, mir_window_state_maximized);
 }
 
 void
 MIR_MinimizeWindow(_THIS, SDL_Window* window)
 {
-    MIR_Data*   mir_data   = _this->driverdata;
-    MIR_Window* mir_window = window->driverdata;
-    MirSurfaceSpec* spec;
-
-    if (IsSurfaceValid(mir_window) < 0)
-        return;
-
-    spec = MIR_mir_connection_create_spec_for_changes(mir_data->connection);
-    MIR_mir_surface_spec_set_state(spec, mir_surface_state_minimized);
-
-    MIR_mir_surface_apply_spec(mir_window->surface, spec);
-    MIR_mir_surface_spec_release(spec);
+    UpdateMirWindowState(_this->driverdata, window->driverdata, mir_window_state_minimized);
 }
 
 void
 MIR_RestoreWindow(_THIS, SDL_Window * window)
 {
-    MIR_Data*   mir_data   = _this->driverdata;
-    MIR_Window* mir_window = window->driverdata;
-    MirSurfaceSpec* spec;
-
-    if (IsSurfaceValid(mir_window) < 0)
-        return;
-
-    spec = MIR_mir_connection_create_spec_for_changes(mir_data->connection);
-    MIR_mir_surface_spec_set_state(spec, mir_surface_state_restored);
-
-    MIR_mir_surface_apply_spec(mir_window->surface, spec);
-    MIR_mir_surface_spec_release(spec);
+    UpdateMirWindowState(_this->driverdata, window->driverdata, mir_window_state_restored);
 }
 
 void
 MIR_HideWindow(_THIS, SDL_Window* window)
 {
-    MIR_Data*   mir_data   = _this->driverdata;
-    MIR_Window* mir_window = window->driverdata;
-    MirSurfaceSpec* spec;
-
-    if (IsSurfaceValid(mir_window) < 0)
-        return;
-
-    spec = MIR_mir_connection_create_spec_for_changes(mir_data->connection);
-    MIR_mir_surface_spec_set_state(spec, mir_surface_state_hidden);
-
-    MIR_mir_surface_apply_spec(mir_window->surface, spec);
-    MIR_mir_surface_spec_release(spec);
+    UpdateMirWindowState(_this->driverdata, window->driverdata, mir_window_state_hidden);
 }
 
 void
 MIR_SetWindowSize(_THIS, SDL_Window* window)
 {
-    MIR_Data*   mir_data   = _this->driverdata;
+    MIR_Data* mir_data     = _this->driverdata;
     MIR_Window* mir_window = window->driverdata;
-    MirSurfaceSpec* spec;
 
-    if (IsSurfaceValid(mir_window) < 0)
-        return;
-
-    /* You cannot set the x/y of a mir window! So only update w/h */
-    spec = MIR_mir_connection_create_spec_for_changes(mir_data->connection);
-    MIR_mir_surface_spec_set_width (spec, window->w);
-    MIR_mir_surface_spec_set_height(spec, window->h);
+    if (IsMirWindowValid(mir_window)) {
+        MirWindowSpec* spec = MIR_mir_create_window_spec(mir_data->connection);
+        MIR_mir_window_spec_set_width (spec, window->w);
+        MIR_mir_window_spec_set_height(spec, window->h);
 
-    MIR_mir_surface_apply_spec(mir_window->surface, spec);
-    MIR_mir_surface_spec_release(spec);
+        MIR_mir_window_apply_spec(mir_window->window, spec);
+    }
 }
 
 void
 MIR_SetWindowMinimumSize(_THIS, SDL_Window* window)
 {
-    MIR_Data*   mir_data   = _this->driverdata;
+    MIR_Data* mir_data     = _this->driverdata;
     MIR_Window* mir_window = window->driverdata;
-    MirSurfaceSpec* spec;
-
-    if (IsSurfaceValid(mir_window) < 0)
-        return;
 
-    spec = MIR_mir_connection_create_spec_for_changes(mir_data->connection);
-    MIR_mir_surface_spec_set_min_width (spec, window->min_w);
-    MIR_mir_surface_spec_set_min_height(spec, window->min_h);
+    if (IsMirWindowValid(mir_window)) {
+        MirWindowSpec* spec = MIR_mir_create_window_spec(mir_data->connection);
+        MIR_mir_window_spec_set_min_width (spec, window->min_w);
+        MIR_mir_window_spec_set_min_height(spec, window->min_h);
 
-    MIR_mir_surface_apply_spec(mir_window->surface, spec);
-    MIR_mir_surface_spec_release(spec);
+        MIR_mir_window_apply_spec(mir_window->window, spec);
+    }
 }
 
 void
 MIR_SetWindowMaximumSize(_THIS, SDL_Window* window)
 {
-    MIR_Data*   mir_data   = _this->driverdata;
+    MIR_Data* mir_data     = _this->driverdata;
     MIR_Window* mir_window = window->driverdata;
-    MirSurfaceSpec* spec;
 
-    if (IsSurfaceValid(mir_window) < 0)
-        return;
-
-    spec = MIR_mir_connection_create_spec_for_changes(mir_data->connection);
-    MIR_mir_surface_spec_set_max_width (spec, window->max_w);
-    MIR_mir_surface_spec_set_max_height(spec, window->max_h);
+    if (IsMirWindowValid(mir_window)) {
+        MirWindowSpec* spec = MIR_mir_create_window_spec(mir_data->connection);
+        MIR_mir_window_spec_set_max_width (spec, window->max_w);
+        MIR_mir_window_spec_set_max_height(spec, window->max_h);
 
-    MIR_mir_surface_apply_spec(mir_window->surface, spec);
-    MIR_mir_surface_spec_release(spec);
+        MIR_mir_window_apply_spec(mir_window->window, spec);
+    }
 }
 
 void
@@ -348,16 +300,16 @@ MIR_SetWindowTitle(_THIS, SDL_Window* window)
     MIR_Data*   mir_data   = _this->driverdata;
     MIR_Window* mir_window = window->driverdata;
     char const* title = window->title ? window->title : "";
-    MirSurfaceSpec* spec;
+    MirWindowSpec* spec;
 
-    if (IsSurfaceValid(mir_window) < 0)
+    if (IsMirWindowValid(mir_window) < 0)
         return;
 
-    spec = MIR_mir_connection_create_spec_for_changes(mir_data->connection);
-    MIR_mir_surface_spec_set_name(spec, title);
+    spec = MIR_mir_create_window_spec(mir_data->connection);
+    MIR_mir_window_spec_set_name(spec, title);
 
-    MIR_mir_surface_apply_spec(mir_window->surface, spec);
-    MIR_mir_surface_spec_release(spec);
+    MIR_mir_window_apply_spec(mir_window->window, spec);
+    MIR_mir_window_spec_release(spec);
 }
 
 void
@@ -366,16 +318,16 @@ MIR_SetWindowGrab(_THIS, SDL_Window* window, SDL_bool grabbed)
     MIR_Data*   mir_data   = _this->driverdata;
     MIR_Window* mir_window = window->driverdata;
     MirPointerConfinementState confined = mir_pointer_unconfined;
-    MirSurfaceSpec* spec;
+    MirWindowSpec* spec;
 
     if (grabbed)
-        confined = mir_pointer_confined_to_surface;
+        confined = mir_pointer_confined_to_window;
 
-    spec = MIR_mir_connection_create_spec_for_changes(mir_data->connection);
-    MIR_mir_surface_spec_set_pointer_confinement(spec, confined);
+    spec = MIR_mir_create_window_spec(mir_data->connection);
+    MIR_mir_window_spec_set_pointer_confinement(spec, confined);
 
-    MIR_mir_surface_apply_spec(mir_window->surface, spec);
-    MIR_mir_surface_spec_release(spec);
+    MIR_mir_window_apply_spec(mir_window->window, spec);
+    MIR_mir_window_spec_release(spec);
 }
 
 int
diff --git a/src/video/mir/SDL_mirwindow.h b/src/video/mir/SDL_mirwindow.h
index c4084aa..a5f1ed8 100644
--- a/src/video/mir/SDL_mirwindow.h
+++ b/src/video/mir/SDL_mirwindow.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,8 +23,8 @@
   Contributed by Brandon Schaefer, <brandon.schaefer at canonical.com>
 */
 
-#ifndef _SDL_mirwindow_h
-#define _SDL_mirwindow_h
+#ifndef SDL_mirwindow_h_
+#define SDL_mirwindow_h_
 
 #include "../SDL_sysvideo.h"
 #include "SDL_syswm.h"
@@ -35,7 +35,7 @@ struct MIR_Window {
     SDL_Window* sdl_window;
     MIR_Data*   mir_data;
 
-    MirSurface* surface;
+    MirWindow*  window;
     EGLSurface  egl_surface;
 };
 
@@ -87,7 +87,7 @@ MIR_SetWindowGammaRamp(_THIS, SDL_Window* window, Uint16 const* ramp);
 extern int
 MIR_GetWindowGammaRamp(_THIS, SDL_Window* window, Uint16* ramp);
 
-#endif /* _SDL_mirwindow_h */
+#endif /* SDL_mirwindow_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
 
diff --git a/src/video/nacl/SDL_naclevents.c b/src/video/nacl/SDL_naclevents.c
index d6ebbdf..7cc66dd 100644
--- a/src/video/nacl/SDL_naclevents.c
+++ b/src/video/nacl/SDL_naclevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -298,7 +298,7 @@ static Uint8 SDL_NACL_translate_mouse_button(int32_t button) {
             return SDL_BUTTON_MIDDLE;
         case PP_INPUTEVENT_MOUSEBUTTON_RIGHT:
             return SDL_BUTTON_RIGHT;
-            
+
         case PP_INPUTEVENT_MOUSEBUTTON_NONE:
         default:
             return 0;
@@ -314,14 +314,14 @@ SDL_NACL_translate_keycode(int keycode)
         scancode = NACL_Keycodes[keycode];
     }
     if (scancode == SDL_SCANCODE_UNKNOWN) {
-        SDL_Log("The key you just pressed is not recognized by SDL. To help get this fixed, please report this to the SDL mailing list <sdl at libsdl.org> NACL KeyCode %d \n", keycode);
+        SDL_Log("The key you just pressed is not recognized by SDL. To help get this fixed, please report this to the SDL forums/mailing list <https://discourse.libsdl.org/> NACL KeyCode %d", keycode);
     }
     return scancode;
 }
 
 void NACL_PumpEvents(_THIS) {
   PSEvent* ps_event;
-  PP_Resource event;  
+  PP_Resource event;
   PP_InputEvent_Type type;
   PP_InputEvent_Modifier modifiers;
   struct PP_Rect rect;
@@ -329,11 +329,11 @@ void NACL_PumpEvents(_THIS) {
   struct PP_Point location;
   struct PP_Var var;
   const char *str;
-  char text[64];
+  char text[SDL_TEXTINPUTEVENT_TEXT_SIZE];
   Uint32 str_len;
   SDL_VideoData *driverdata = (SDL_VideoData *) _this->driverdata;
   SDL_Mouse *mouse = SDL_GetMouse();
-  
+
   if (driverdata->window) {
     while ((ps_event = PSEventTryAcquire()) != NULL) {
         event = ps_event->as_resource;
@@ -344,9 +344,9 @@ void NACL_PumpEvents(_THIS) {
                 NACL_SetScreenResolution(rect.size.width, rect.size.height, SDL_PIXELFORMAT_UNKNOWN);
                 // FIXME: Rebuild context? See life.c UpdateContext
                 break;
-            
+
             /* From HandleInputEvent, contains an input resource. */
-            case PSE_INSTANCE_HANDLEINPUT: 
+            case PSE_INSTANCE_HANDLEINPUT:
                 type = driverdata->ppb_input_event->GetType(event);
                 modifiers = driverdata->ppb_input_event->GetModifiers(event);
                 switch(type) {
@@ -359,35 +359,35 @@ void NACL_PumpEvents(_THIS) {
                     case PP_INPUTEVENT_TYPE_WHEEL:
                         /* FIXME: GetTicks provides high resolution scroll events */
                         fp = driverdata->ppb_wheel_input_event->GetDelta(event);
-                        SDL_SendMouseWheel(mouse->focus, mouse->mouseID, (int) fp.x, (int) fp.y, SDL_MOUSEWHEEL_NORMAL);
+                        SDL_SendMouseWheel(mouse->focus, mouse->mouseID, fp.x, fp.y, SDL_MOUSEWHEEL_NORMAL);
                         break;
-                        
+
                     case PP_INPUTEVENT_TYPE_MOUSEENTER:
                     case PP_INPUTEVENT_TYPE_MOUSELEAVE:
                         /* FIXME: Mouse Focus */
                         break;
-                        
-                        
-                    case PP_INPUTEVENT_TYPE_MOUSEMOVE: 
+
+
+                    case PP_INPUTEVENT_TYPE_MOUSEMOVE:
                         location = driverdata->ppb_mouse_input_event->GetPosition(event);
                         SDL_SendMouseMotion(mouse->focus, mouse->mouseID, SDL_FALSE, location.x, location.y);
                         break;
-                  
+
                     case PP_INPUTEVENT_TYPE_TOUCHSTART:
                     case PP_INPUTEVENT_TYPE_TOUCHMOVE:
                     case PP_INPUTEVENT_TYPE_TOUCHEND:
                     case PP_INPUTEVENT_TYPE_TOUCHCANCEL:
                         /* FIXME: Touch events */
                         break;
-                      
+
                     case PP_INPUTEVENT_TYPE_KEYDOWN:
                         SDL_SendKeyboardKey(SDL_PRESSED, SDL_NACL_translate_keycode(driverdata->ppb_keyboard_input_event->GetKeyCode(event)));
                         break;
-                        
+
                     case PP_INPUTEVENT_TYPE_KEYUP:
                         SDL_SendKeyboardKey(SDL_RELEASED, SDL_NACL_translate_keycode(driverdata->ppb_keyboard_input_event->GetKeyCode(event)));
                         break;
-                        
+
                     case PP_INPUTEVENT_TYPE_CHAR:
                         var = driverdata->ppb_keyboard_input_event->GetCharacterText(event);
                         str = driverdata->ppb_var->VarToUtf8(var, &str_len);
@@ -397,17 +397,17 @@ void NACL_PumpEvents(_THIS) {
                         }
                         SDL_strlcpy(text, str, str_len );
                         text[str_len] = '\0';
-                        
+
                         SDL_SendKeyboardText(text);
                         /* FIXME: Do we have to handle ref counting? driverdata->ppb_var->Release(var);*/
                         break;
-                        
+
                     default:
                         break;
                 }
                 break;
-                
-        
+
+
             /* From HandleMessage, contains a PP_Var. */
             case PSE_INSTANCE_HANDLEMESSAGE:
                 break;
@@ -419,7 +419,7 @@ void NACL_PumpEvents(_THIS) {
             /* When the 3D context is lost, no resource. */
             case PSE_GRAPHICS3D_GRAPHICS3DCONTEXTLOST:
                 break;
-                
+
             /* When the mouse lock is lost. */
             case PSE_MOUSELOCK_MOUSELOCKLOST:
                 break;
@@ -427,7 +427,7 @@ void NACL_PumpEvents(_THIS) {
             default:
                 break;
         }
-        
+
         PSEventRelease(ps_event);
     }
   }
diff --git a/src/video/nacl/SDL_naclevents_c.h b/src/video/nacl/SDL_naclevents_c.h
index 3255578..6129b45 100644
--- a/src/video/nacl/SDL_naclevents_c.h
+++ b/src/video/nacl/SDL_naclevents_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,11 +20,11 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_naclevents_c_h
-#define _SDL_naclevents_c_h
+#ifndef SDL_naclevents_c_h_
+#define SDL_naclevents_c_h_
 
 #include "SDL_naclvideo.h"
 
 extern void NACL_PumpEvents(_THIS);
 
-#endif /* _SDL_naclevents_c_h */
+#endif /* SDL_naclevents_c_h_ */
diff --git a/src/video/nacl/SDL_naclglue.c b/src/video/nacl/SDL_naclglue.c
index 79f5b0f..a0fa7eb 100644
--- a/src/video/nacl/SDL_naclglue.c
+++ b/src/video/nacl/SDL_naclglue.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/nacl/SDL_naclopengles.c b/src/video/nacl/SDL_naclopengles.c
index e112451..d7ddc24 100644
--- a/src/video/nacl/SDL_naclopengles.c
+++ b/src/video/nacl/SDL_naclopengles.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -141,7 +141,7 @@ int
 NACL_GLES_SetSwapInterval(_THIS, int interval)
 {
     /* STUB */
-    return 0;
+    return SDL_Unsupported();
 }
 
 int
@@ -151,12 +151,15 @@ NACL_GLES_GetSwapInterval(_THIS)
     return 0;
 }
 
-void
+int
 NACL_GLES_SwapWindow(_THIS, SDL_Window * window)
 {
     SDL_VideoData *driverdata = (SDL_VideoData *) _this->driverdata;
     struct PP_CompletionCallback callback = { NULL, 0, PP_COMPLETIONCALLBACK_FLAG_NONE };
-    driverdata->ppb_graphics->SwapBuffers((PP_Resource) SDL_GL_GetCurrentContext(), callback );
+    if (driverdata->ppb_graphics->SwapBuffers((PP_Resource) SDL_GL_GetCurrentContext(), callback ) != 0) {
+        return SDL_SetError("SwapBuffers failed");
+    }
+    return 0;
 }
 
 void
diff --git a/src/video/nacl/SDL_naclopengles.h b/src/video/nacl/SDL_naclopengles.h
index 1845e81..befdd4d 100644
--- a/src/video/nacl/SDL_naclopengles.h
+++ b/src/video/nacl/SDL_naclopengles.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_naclgl_h
-#define _SDL_naclgl_h
+#ifndef SDL_naclopengles_h_
+#define SDL_naclopengles_h_
 
 extern int NACL_GLES_LoadLibrary(_THIS, const char *path);
 extern void *NACL_GLES_GetProcAddress(_THIS, const char *proc);
@@ -30,9 +30,9 @@ extern SDL_GLContext NACL_GLES_CreateContext(_THIS, SDL_Window * window);
 extern int NACL_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 extern int NACL_GLES_SetSwapInterval(_THIS, int interval);
 extern int NACL_GLES_GetSwapInterval(_THIS);
-extern void NACL_GLES_SwapWindow(_THIS, SDL_Window * window);
+extern int NACL_GLES_SwapWindow(_THIS, SDL_Window * window);
 extern void NACL_GLES_DeleteContext(_THIS, SDL_GLContext context);
 
-#endif /* _SDL_naclgl_h */
+#endif /* SDL_naclopengles_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/nacl/SDL_naclvideo.c b/src/video/nacl/SDL_naclvideo.c
index 467155c..3d35d5c 100644
--- a/src/video/nacl/SDL_naclvideo.c
+++ b/src/video/nacl/SDL_naclvideo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -81,7 +81,7 @@ static int NACL_Available(void) {
 static void NACL_DeleteDevice(SDL_VideoDevice *device) {
     SDL_VideoData *driverdata = (SDL_VideoData*) device->driverdata;
     driverdata->ppb_core->ReleaseResource((PP_Resource) driverdata->ppb_message_loop);
-    SDL_free(device->driverdata);
+    /* device->driverdata is not freed because it points to static memory */
     SDL_free(device);
 }
 
@@ -107,7 +107,7 @@ static SDL_VideoDevice *NACL_CreateDevice(int devindex) {
     device->VideoQuit = NACL_VideoQuit;
     device->PumpEvents = NACL_PumpEvents;
     
-    device->CreateWindow = NACL_CreateWindow;
+    device->CreateSDLWindow = NACL_CreateWindow;
     device->SetWindowTitle = NACL_SetWindowTitle;
     device->DestroyWindow = NACL_DestroyWindow;
     
diff --git a/src/video/nacl/SDL_naclvideo.h b/src/video/nacl/SDL_naclvideo.h
index 174a6e7..6ee18b9 100644
--- a/src/video/nacl/SDL_naclvideo.h
+++ b/src/video/nacl/SDL_naclvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_naclvideo_h
-#define _SDL_naclvideo_h
+#ifndef SDL_naclvideo_h_
+#define SDL_naclvideo_h_
 
 #include "../SDL_sysvideo.h"
 #include "ppapi_simple/ps_interface.h"
@@ -64,4 +64,4 @@ typedef struct SDL_VideoData {
 extern void NACL_SetScreenResolution(int width, int height, Uint32 format);
 
 
-#endif /* _SDL_naclvideo_h */
+#endif /* SDL_naclvideo_h_ */
diff --git a/src/video/nacl/SDL_naclwindow.c b/src/video/nacl/SDL_naclwindow.c
index 32d1e6d..3649df1 100644
--- a/src/video/nacl/SDL_naclwindow.c
+++ b/src/video/nacl/SDL_naclwindow.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/nacl/SDL_naclwindow.h b/src/video/nacl/SDL_naclwindow.h
index 617bfc3..487fbdb 100644
--- a/src/video/nacl/SDL_naclwindow.h
+++ b/src/video/nacl/SDL_naclwindow.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,13 +20,13 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_naclwindow_h
-#define _SDL_naclwindow_h
+#ifndef SDL_naclwindow_h_
+#define SDL_naclwindow_h_
 
 extern int NACL_CreateWindow(_THIS, SDL_Window * window);
 extern void NACL_SetWindowTitle(_THIS, SDL_Window * window);
 extern void NACL_DestroyWindow(_THIS, SDL_Window * window);
 
-#endif /* _SDL_naclwindow_h */
+#endif /* SDL_naclwindow_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/pandora/SDL_pandora.c b/src/video/pandora/SDL_pandora.c
index 7afa543..a1c48a3 100644
--- a/src/video/pandora/SDL_pandora.c
+++ b/src/video/pandora/SDL_pandora.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -102,8 +102,8 @@ PND_create()
     device->VideoQuit = PND_videoquit;
     device->GetDisplayModes = PND_getdisplaymodes;
     device->SetDisplayMode = PND_setdisplaymode;
-    device->CreateWindow = PND_createwindow;
-    device->CreateWindowFrom = PND_createwindowfrom;
+    device->CreateSDLWindow = PND_createwindow;
+    device->CreateSDLWindowFrom = PND_createwindowfrom;
     device->SetWindowTitle = PND_setwindowtitle;
     device->SetWindowIcon = PND_setwindowicon;
     device->SetWindowPosition = PND_setwindowposition;
@@ -116,7 +116,9 @@ PND_create()
     device->RestoreWindow = PND_restorewindow;
     device->SetWindowGrab = PND_setwindowgrab;
     device->DestroyWindow = PND_destroywindow;
+#if 0
     device->GetWindowWMInfo = PND_getwindowwminfo;
+#endif
     device->GL_LoadLibrary = PND_gl_loadlibrary;
     device->GL_GetProcAddress = PND_gl_getprocaddres;
     device->GL_UnloadLibrary = PND_gl_unloadlibrary;
@@ -298,13 +300,14 @@ PND_destroywindow(_THIS, SDL_Window * window)
 /*****************************************************************************/
 /* SDL Window Manager function                                               */
 /*****************************************************************************/
+#if 0
 SDL_bool
 PND_getwindowwminfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info)
 {
     if (info->version.major <= SDL_MAJOR_VERSION) {
         return SDL_TRUE;
     } else {
-        SDL_SetError("application not compiled with SDL %d.%d\n",
+        SDL_SetError("application not compiled with SDL %d.%d",
                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
@@ -312,6 +315,7 @@ PND_getwindowwminfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info)
     /* Failed to get window manager information */
     return SDL_FALSE;
 }
+#endif
 
 /*****************************************************************************/
 /* SDL OpenGL/OpenGL ES functions                                            */
@@ -637,7 +641,7 @@ PND_gl_createcontext(_THIS, SDL_Window * window)
 
 
     if (wdata->gles_surface == 0) {
-        SDL_SetError("Error : eglCreateWindowSurface failed;\n");
+        SDL_SetError("Error : eglCreateWindowSurface failed;");
         return NULL;
     }
 
@@ -774,15 +778,14 @@ PND_gl_getswapinterval(_THIS)
     return ((SDL_VideoData *) _this->driverdata)->swapinterval;
 }
 
-void
+int
 PND_gl_swapwindow(_THIS, SDL_Window * window)
 {
     SDL_VideoData *phdata = (SDL_VideoData *) _this->driverdata;
     SDL_WindowData *wdata = (SDL_WindowData *) window->driverdata;
 
     if (phdata->egl_initialized != SDL_TRUE) {
-        SDL_SetError("PND: GLES initialization failed, no OpenGL ES support");
-        return;
+        return SDL_SetError("PND: GLES initialization failed, no OpenGL ES support");
     }
 
     /* Many applications do not uses glFinish(), so we call it for them */
@@ -792,6 +795,7 @@ PND_gl_swapwindow(_THIS, SDL_Window * window)
     eglWaitGL();
 
     eglSwapBuffers(phdata->egl_display, wdata->gles_surface);
+    return 0;
 }
 
 void
diff --git a/src/video/pandora/SDL_pandora.h b/src/video/pandora/SDL_pandora.h
index 859b7ee..d4dd9bc 100644
--- a/src/video/pandora/SDL_pandora.h
+++ b/src/video/pandora/SDL_pandora.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -92,7 +92,7 @@ SDL_GLContext PND_gl_createcontext(_THIS, SDL_Window * window);
 int PND_gl_makecurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 int PND_gl_setswapinterval(_THIS, int interval);
 int PND_gl_getswapinterval(_THIS);
-void PND_gl_swapwindow(_THIS, SDL_Window * window);
+int PND_gl_swapwindow(_THIS, SDL_Window * window);
 void PND_gl_deletecontext(_THIS, SDL_GLContext context);
 
 
diff --git a/src/video/pandora/SDL_pandora_events.c b/src/video/pandora/SDL_pandora_events.c
index d22d0c7..4f58154 100644
--- a/src/video/pandora/SDL_pandora_events.c
+++ b/src/video/pandora/SDL_pandora_events.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/pandora/SDL_pandora_events.h b/src/video/pandora/SDL_pandora_events.h
index e9f8d7c..be6dbbb 100644
--- a/src/video/pandora/SDL_pandora_events.h
+++ b/src/video/pandora/SDL_pandora_events.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/psp/SDL_pspevents.c b/src/video/psp/SDL_pspevents.c
index 7126727..83ff880 100644
--- a/src/video/psp/SDL_pspevents.c
+++ b/src/video/psp/SDL_pspevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -260,12 +260,12 @@ void PSP_EventInit(_THIS)
 #endif
     /* Start thread to read data */
     if((event_sem =  SDL_CreateSemaphore(1)) == NULL) {
-        SDL_SetError("Can't create input semaphore\n");
+        SDL_SetError("Can't create input semaphore");
         return;
     }
     running = 1;
     if((thread = SDL_CreateThreadInternal(EventUpdate, "PSPInputThread", 4096, NULL)) == NULL) {
-        SDL_SetError("Can't create input thread\n");
+        SDL_SetError("Can't create input thread");
         return;
     }
 }
diff --git a/src/video/psp/SDL_pspevents_c.h b/src/video/psp/SDL_pspevents_c.h
index e1929d2..e17ddd3 100644
--- a/src/video/psp/SDL_pspevents_c.h
+++ b/src/video/psp/SDL_pspevents_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/psp/SDL_pspgl.c b/src/video/psp/SDL_pspgl.c
index e4f81e9..dbcf20c 100644
--- a/src/video/psp/SDL_pspgl.c
+++ b/src/video/psp/SDL_pspgl.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -47,10 +47,6 @@
 int
 PSP_GL_LoadLibrary(_THIS, const char *path)
 {
-  if (!_this->gl_config.driver_loaded) {
-        _this->gl_config.driver_loaded = 1;
-  }
-
   return 0;
 }
 
@@ -174,10 +170,13 @@ PSP_GL_GetSwapInterval(_THIS)
     return _this->gl_data->swapinterval;
 }
 
-void
+int
 PSP_GL_SwapWindow(_THIS, SDL_Window * window)
 {
-    eglSwapBuffers(_this->gl_data->display, _this->gl_data->surface);
+    if (!eglSwapBuffers(_this->gl_data->display, _this->gl_data->surface)) {
+        return SDL_SetError("eglSwapBuffers() failed");
+    }
+    return 0;
 }
 
 void
diff --git a/src/video/psp/SDL_pspgl_c.h b/src/video/psp/SDL_pspgl_c.h
index 308b027..ea1deab 100644
--- a/src/video/psp/SDL_pspgl_c.h
+++ b/src/video/psp/SDL_pspgl_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_pspgl_c_h
-#define _SDL_pspgl_c_h
+#ifndef SDL_pspgl_c_h_
+#define SDL_pspgl_c_h_
 
 
 #include <GLES/egl.h>
@@ -40,7 +40,7 @@ extern void * PSP_GL_GetProcAddress(_THIS, const char *proc);
 extern int PSP_GL_MakeCurrent(_THIS,SDL_Window * window, SDL_GLContext context);
 extern void PSP_GL_SwapBuffers(_THIS);
 
-extern void PSP_GL_SwapWindow(_THIS, SDL_Window * window);
+extern int PSP_GL_SwapWindow(_THIS, SDL_Window * window);
 extern SDL_GLContext PSP_GL_CreateContext(_THIS, SDL_Window * window);
 
 extern int PSP_GL_LoadLibrary(_THIS, const char *path);
@@ -49,4 +49,6 @@ extern int PSP_GL_SetSwapInterval(_THIS, int interval);
 extern int PSP_GL_GetSwapInterval(_THIS);
 
 
-#endif /* _SDL_pspgl_c_h */
+#endif /* SDL_pspgl_c_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/psp/SDL_pspmouse.c b/src/video/psp/SDL_pspmouse.c
index b7c3d2b..f5ac2b4 100644
--- a/src/video/psp/SDL_pspmouse.c
+++ b/src/video/psp/SDL_pspmouse.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/psp/SDL_pspmouse_c.h b/src/video/psp/SDL_pspmouse_c.h
index 2a3df68..3fede5b 100644
--- a/src/video/psp/SDL_pspmouse_c.h
+++ b/src/video/psp/SDL_pspmouse_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/psp/SDL_pspvideo.c b/src/video/psp/SDL_pspvideo.c
index 381e489..95ec796 100644
--- a/src/video/psp/SDL_pspvideo.c
+++ b/src/video/psp/SDL_pspvideo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -113,8 +113,8 @@ PSP_Create()
     device->VideoQuit = PSP_VideoQuit;
     device->GetDisplayModes = PSP_GetDisplayModes;
     device->SetDisplayMode = PSP_SetDisplayMode;
-    device->CreateWindow = PSP_CreateWindow;
-    device->CreateWindowFrom = PSP_CreateWindowFrom;
+    device->CreateSDLWindow = PSP_CreateWindow;
+    device->CreateSDLWindowFrom = PSP_CreateWindowFrom;
     device->SetWindowTitle = PSP_SetWindowTitle;
     device->SetWindowIcon = PSP_SetWindowIcon;
     device->SetWindowPosition = PSP_SetWindowPosition;
@@ -127,7 +127,9 @@ PSP_Create()
     device->RestoreWindow = PSP_RestoreWindow;
     device->SetWindowGrab = PSP_SetWindowGrab;
     device->DestroyWindow = PSP_DestroyWindow;
+#if 0
     device->GetWindowWMInfo = PSP_GetWindowWMInfo;
+#endif
     device->GL_LoadLibrary = PSP_GL_LoadLibrary;
     device->GL_GetProcAddress = PSP_GL_GetProcAddress;
     device->GL_UnloadLibrary = PSP_GL_UnloadLibrary;
@@ -291,13 +293,14 @@ PSP_DestroyWindow(_THIS, SDL_Window * window)
 /*****************************************************************************/
 /* SDL Window Manager function                                               */
 /*****************************************************************************/
+#if 0
 SDL_bool
 PSP_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info)
 {
     if (info->version.major <= SDL_MAJOR_VERSION) {
         return SDL_TRUE;
     } else {
-        SDL_SetError("application not compiled with SDL %d.%d\n",
+        SDL_SetError("Application not compiled with SDL %d.%d",
                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
@@ -305,6 +308,7 @@ PSP_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info)
     /* Failed to get window manager information */
     return SDL_FALSE;
 }
+#endif
 
 
 /* TO Write Me */
diff --git a/src/video/psp/SDL_pspvideo.h b/src/video/psp/SDL_pspvideo.h
index f5705a9..58391cc 100644
--- a/src/video/psp/SDL_pspvideo.h
+++ b/src/video/psp/SDL_pspvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_pspvideo_h
-#define _SDL_pspvideo_h
+#ifndef SDL_pspvideo_h_
+#define SDL_pspvideo_h_
 
 #include <GLES/egl.h>
 
@@ -88,7 +88,7 @@ SDL_GLContext PSP_GL_CreateContext(_THIS, SDL_Window * window);
 int PSP_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 int PSP_GL_SetSwapInterval(_THIS, int interval);
 int PSP_GL_GetSwapInterval(_THIS);
-void PSP_GL_SwapWindow(_THIS, SDL_Window * window);
+int PSP_GL_SwapWindow(_THIS, SDL_Window * window);
 void PSP_GL_DeleteContext(_THIS, SDL_GLContext context);
 
 /* PSP on screen keyboard */
@@ -97,6 +97,6 @@ void PSP_ShowScreenKeyboard(_THIS, SDL_Window *window);
 void PSP_HideScreenKeyboard(_THIS, SDL_Window *window);
 SDL_bool PSP_IsScreenKeyboardShown(_THIS, SDL_Window *window);
 
-#endif /* _SDL_pspvideo_h */
+#endif /* SDL_pspvideo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/qnx/gl.c b/src/video/qnx/gl.c
new file mode 100644
index 0000000..19e1bd4
--- /dev/null
+++ b/src/video/qnx/gl.c
@@ -0,0 +1,285 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 2017 BlackBerry Limited
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+#include "sdl_qnx.h"
+
+static EGLDisplay   egl_disp;
+
+/**
+ * Detertmines the pixel format to use based on the current display and EGL
+ * configuration.
+ * @param   egl_conf    EGL configuration to use
+ * @return  A SCREEN_FORMAT* constant for the pixel format to use
+ */
+static int
+chooseFormat(EGLConfig egl_conf)
+{
+    EGLint buffer_bit_depth;
+    EGLint alpha_bit_depth;
+
+    eglGetConfigAttrib(egl_disp, egl_conf, EGL_BUFFER_SIZE, &buffer_bit_depth);
+    eglGetConfigAttrib(egl_disp, egl_conf, EGL_ALPHA_SIZE, &alpha_bit_depth);
+
+    switch (buffer_bit_depth) {
+        case 32:
+            return SCREEN_FORMAT_RGBX8888;
+        case 24:
+            return SCREEN_FORMAT_RGB888;
+        case 16:
+            switch (alpha_bit_depth) {
+                case 4:
+                    return SCREEN_FORMAT_RGBX4444;
+                case 1:
+                    return SCREEN_FORMAT_RGBA5551;
+                default:
+                    return SCREEN_FORMAT_RGB565;
+            }
+        default:
+            return 0;
+    }
+}
+
+/**
+ * Enumerates the supported EGL configurations and chooses a suitable one.
+ * @param[out]  pconf   The chosen configuration
+ * @param[out]  pformat The chosen pixel format
+ * @return 0 if successful, -1 on error
+ */
+int
+glGetConfig(EGLConfig *pconf, int *pformat)
+{
+    EGLConfig egl_conf = (EGLConfig)0;
+    EGLConfig *egl_configs;
+    EGLint egl_num_configs;
+    EGLint val;
+    EGLBoolean rc;
+    EGLint i;
+
+    // Determine the numbfer of configurations.
+    rc = eglGetConfigs(egl_disp, NULL, 0, &egl_num_configs);
+    if (rc != EGL_TRUE) {
+        return -1;
+    }
+
+    if (egl_num_configs == 0) {
+        return -1;
+    }
+
+    // Allocate enough memory for all configurations.
+    egl_configs = malloc(egl_num_configs * sizeof(*egl_configs));
+    if (egl_configs == NULL) {
+        return -1;
+    }
+
+    // Get the list of configurations.
+    rc = eglGetConfigs(egl_disp, egl_configs, egl_num_configs,
+                       &egl_num_configs);
+    if (rc != EGL_TRUE) {
+        free(egl_configs);
+        return -1;
+    }
+
+    // Find a good configuration.
+    for (i = 0; i < egl_num_configs; i++) {
+        eglGetConfigAttrib(egl_disp, egl_configs[i], EGL_SURFACE_TYPE, &val);
+        if (!(val & EGL_WINDOW_BIT)) {
+            continue;
+        }
+
+        eglGetConfigAttrib(egl_disp, egl_configs[i], EGL_RENDERABLE_TYPE, &val);
+        if (!(val & EGL_OPENGL_ES2_BIT)) {
+            continue;
+        }
+
+        eglGetConfigAttrib(egl_disp, egl_configs[i], EGL_DEPTH_SIZE, &val);
+        if (val == 0) {
+            continue;
+        }
+
+        egl_conf = egl_configs[i];
+        break;
+    }
+
+    free(egl_configs);
+    *pconf = egl_conf;
+    *pformat = chooseFormat(egl_conf);
+
+    return 0;
+}
+
+/**
+ * Initializes the EGL library.
+ * @param   _THIS
+ * @param   name    unused
+ * @return  0 if successful, -1 on error
+ */
+int
+glLoadLibrary(_THIS, const char *name)
+{
+    EGLNativeDisplayType    disp_id = EGL_DEFAULT_DISPLAY;
+
+    egl_disp = eglGetDisplay(disp_id);
+    if (egl_disp == EGL_NO_DISPLAY) {
+        return -1;
+    }
+
+    if (eglInitialize(egl_disp, NULL, NULL) == EGL_FALSE) {
+        return -1;
+    }
+
+    return 0;
+}
+
+/**
+ * Finds the address of an EGL extension function.
+ * @param   proc    Function name
+ * @return  Function address
+ */
+void *
+glGetProcAddress(_THIS, const char *proc)
+{
+    return eglGetProcAddress(proc);
+}
+
+/**
+ * Associates the given window with the necessary EGL structures for drawing and
+ * displaying content.
+ * @param   _THIS
+ * @param   window  The SDL window to create the context for
+ * @return  A pointer to the created context, if successful, NULL on error
+ */
+SDL_GLContext
+glCreateContext(_THIS, SDL_Window *window)
+{
+    window_impl_t   *impl = (window_impl_t *)window->driverdata;
+    EGLContext      context;
+    EGLSurface      surface;
+
+    struct {
+        EGLint client_version[2];
+        EGLint none;
+    } egl_ctx_attr = {
+        .client_version = { EGL_CONTEXT_CLIENT_VERSION, 2 },
+        .none = EGL_NONE
+    };
+
+    struct {
+        EGLint render_buffer[2];
+        EGLint none;
+    } egl_surf_attr = {
+        .render_buffer = { EGL_RENDER_BUFFER, EGL_BACK_BUFFER },
+        .none = EGL_NONE
+    };
+
+    context = eglCreateContext(egl_disp, impl->conf, EGL_NO_CONTEXT,
+                               (EGLint *)&egl_ctx_attr);
+    if (context == EGL_NO_CONTEXT) {
+        return NULL;
+    }
+
+    surface = eglCreateWindowSurface(egl_disp, impl->conf, impl->window,
+                                     (EGLint *)&egl_surf_attr);
+    if (surface == EGL_NO_SURFACE) {
+        return NULL;
+    }
+
+    eglMakeCurrent(egl_disp, surface, surface, context);
+
+    impl->surface = surface;
+    return context;
+}
+
+/**
+ * Sets a new value for the number of frames to display before swapping buffers.
+ * @param   _THIS
+ * @param   interval    New interval value
+ * @return  0 if successful, -1 on error
+ */
+int
+glSetSwapInterval(_THIS, int interval)
+{
+    if (eglSwapInterval(egl_disp, interval) != EGL_TRUE) {
+        return -1;
+    }
+
+    return 0;
+}
+
+/**
+ * Swaps the EGL buffers associated with the given window
+ * @param   _THIS
+ * @param   window  Window to swap buffers for
+ * @return  0 if successful, -1 on error
+ */
+int
+glSwapWindow(_THIS, SDL_Window *window)
+{
+    /* !!! FIXME: should we migrate this all over to use SDL_egl.c? */
+    window_impl_t   *impl = (window_impl_t *)window->driverdata;
+    return eglSwapBuffers(egl_disp, impl->surface) == EGL_TRUE ? 0 : -1;
+}
+
+/**
+ * Makes the given context the current one for drawing operations.
+ * @param   _THIS
+ * @param   window  SDL window associated with the context (maybe NULL)
+ * @param   context The context to activate
+ * @return  0 if successful, -1 on error
+ */
+int
+glMakeCurrent(_THIS, SDL_Window *window, SDL_GLContext context)
+{
+    window_impl_t   *impl;
+    EGLSurface      surface = NULL;
+
+    if (window) {
+        impl = (window_impl_t *)window->driverdata;
+        surface = impl->surface;
+    }
+
+    if (eglMakeCurrent(egl_disp, surface, surface, context) != EGL_TRUE) {
+        return -1;
+    }
+
+    return 0;
+}
+
+/**
+ * Destroys a context.
+ * @param   _THIS
+ * @param   context The context to destroy
+ */
+void
+glDeleteContext(_THIS, SDL_GLContext context)
+{
+    eglDestroyContext(egl_disp, context);
+}
+
+/**
+ * Terminates access to the EGL library.
+ * @param   _THIS
+ */
+void
+glUnloadLibrary(_THIS)
+{
+    eglTerminate(egl_disp);
+}
diff --git a/src/video/qnx/keyboard.c b/src/video/qnx/keyboard.c
new file mode 100644
index 0000000..86c6395
--- /dev/null
+++ b/src/video/qnx/keyboard.c
@@ -0,0 +1,133 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 2017 BlackBerry Limited
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+#include "../../events/SDL_keyboard_c.h"
+#include "SDL_scancode.h"
+#include "SDL_events.h"
+#include "sdl_qnx.h"
+#include <sys/keycodes.h>
+
+/**
+ * A map thta translates Screen key names to SDL scan codes.
+ * This map is incomplete, but should include most major keys.
+ */
+static int key_to_sdl[] = {
+    [KEYCODE_SPACE] = SDL_SCANCODE_SPACE,
+    [KEYCODE_APOSTROPHE] = SDL_SCANCODE_APOSTROPHE,
+    [KEYCODE_COMMA] = SDL_SCANCODE_COMMA,
+    [KEYCODE_MINUS] = SDL_SCANCODE_MINUS,
+    [KEYCODE_PERIOD] = SDL_SCANCODE_PERIOD,
+    [KEYCODE_SLASH] = SDL_SCANCODE_SLASH,
+    [KEYCODE_ZERO] = SDL_SCANCODE_0,
+    [KEYCODE_ONE] = SDL_SCANCODE_1,
+    [KEYCODE_TWO] = SDL_SCANCODE_2,
+    [KEYCODE_THREE] = SDL_SCANCODE_3,
+    [KEYCODE_FOUR] = SDL_SCANCODE_4,
+    [KEYCODE_FIVE] = SDL_SCANCODE_5,
+    [KEYCODE_SIX] = SDL_SCANCODE_6,
+    [KEYCODE_SEVEN] = SDL_SCANCODE_7,
+    [KEYCODE_EIGHT] = SDL_SCANCODE_8,
+    [KEYCODE_NINE] = SDL_SCANCODE_9,
+    [KEYCODE_SEMICOLON] = SDL_SCANCODE_SEMICOLON,
+    [KEYCODE_EQUAL] = SDL_SCANCODE_EQUALS,
+    [KEYCODE_LEFT_BRACKET] = SDL_SCANCODE_LEFTBRACKET,
+    [KEYCODE_BACK_SLASH] = SDL_SCANCODE_BACKSLASH,
+    [KEYCODE_RIGHT_BRACKET] = SDL_SCANCODE_RIGHTBRACKET,
+    [KEYCODE_GRAVE] = SDL_SCANCODE_GRAVE,
+    [KEYCODE_A] = SDL_SCANCODE_A,
+    [KEYCODE_B] = SDL_SCANCODE_B,
+    [KEYCODE_C] = SDL_SCANCODE_C,
+    [KEYCODE_D] = SDL_SCANCODE_D,
+    [KEYCODE_E] = SDL_SCANCODE_E,
+    [KEYCODE_F] = SDL_SCANCODE_F,
+    [KEYCODE_G] = SDL_SCANCODE_G,
+    [KEYCODE_H] = SDL_SCANCODE_H,
+    [KEYCODE_I] = SDL_SCANCODE_I,
+    [KEYCODE_J] = SDL_SCANCODE_J,
+    [KEYCODE_K] = SDL_SCANCODE_K,
+    [KEYCODE_L] = SDL_SCANCODE_L,
+    [KEYCODE_M] = SDL_SCANCODE_M,
+    [KEYCODE_N] = SDL_SCANCODE_N,
+    [KEYCODE_O] = SDL_SCANCODE_O,
+    [KEYCODE_P] = SDL_SCANCODE_P,
+    [KEYCODE_Q] = SDL_SCANCODE_Q,
+    [KEYCODE_R] = SDL_SCANCODE_R,
+    [KEYCODE_S] = SDL_SCANCODE_S,
+    [KEYCODE_T] = SDL_SCANCODE_T,
+    [KEYCODE_U] = SDL_SCANCODE_U,
+    [KEYCODE_V] = SDL_SCANCODE_V,
+    [KEYCODE_W] = SDL_SCANCODE_W,
+    [KEYCODE_X] = SDL_SCANCODE_X,
+    [KEYCODE_Y] = SDL_SCANCODE_Y,
+    [KEYCODE_Z] = SDL_SCANCODE_Z,
+    [KEYCODE_UP] = SDL_SCANCODE_UP,
+    [KEYCODE_DOWN] = SDL_SCANCODE_DOWN,
+    [KEYCODE_LEFT] = SDL_SCANCODE_LEFT,
+    [KEYCODE_PG_UP] = SDL_SCANCODE_PAGEUP,
+    [KEYCODE_PG_DOWN] = SDL_SCANCODE_PAGEDOWN,
+    [KEYCODE_RIGHT] = SDL_SCANCODE_RIGHT,
+    [KEYCODE_RETURN] = SDL_SCANCODE_RETURN,
+    [KEYCODE_TAB] = SDL_SCANCODE_TAB,
+    [KEYCODE_ESCAPE] = SDL_SCANCODE_ESCAPE,
+};
+
+/**
+ * Called from the event dispatcher when a keyboard event is encountered.
+ * Translates the event such that it can be handled by SDL.
+ * @param   event   Screen keyboard event
+ */
+void
+handleKeyboardEvent(screen_event_t event)
+{
+    int             val;
+    SDL_Scancode    scancode;
+
+    // Get the key value.
+    if (screen_get_event_property_iv(event, SCREEN_PROPERTY_SYM, &val) < 0) {
+        return;
+    }
+
+    // Skip unrecognized keys.
+    if ((val < 0) || (val >= SDL_TABLESIZE(key_to_sdl))) {
+        return;
+    }
+
+    // Translate to an SDL scan code.
+    scancode = key_to_sdl[val];
+    if (scancode == 0) {
+        return;
+    }
+
+    // Get event flags (key state).
+    if (screen_get_event_property_iv(event, SCREEN_PROPERTY_FLAGS, &val) < 0) {
+        return;
+    }
+
+    // Propagate the event to SDL.
+    // FIXME:
+    // Need to handle more key states (such as key combinations).
+    if (val & KEY_DOWN) {
+        SDL_SendKeyboardKey(SDL_PRESSED, scancode);
+    } else {
+        SDL_SendKeyboardKey(SDL_RELEASED, scancode);
+    }
+}
diff --git a/src/video/emscripten/SDL_emscriptenvideo.h b/src/video/qnx/sdl_qnx.h
similarity index 54%
copy from src/video/emscripten/SDL_emscriptenvideo.h
copy to src/video/qnx/sdl_qnx.h
index 7618ab6..65e0798 100644
--- a/src/video/emscripten/SDL_emscriptenvideo.h
+++ b/src/video/qnx/sdl_qnx.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 2017 BlackBerry Limited
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,37 +18,31 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../../SDL_internal.h"
 
-#ifndef _SDL_emscriptenvideo_h
-#define _SDL_emscriptenvideo_h
+#ifndef __SDL_QNX_H__
+#define __SDL_QNX_H__
 
 #include "../SDL_sysvideo.h"
-#include "../../events/SDL_touch_c.h"
-#include <emscripten/emscripten.h>
-#include <emscripten/html5.h>
-
+#include <screen/screen.h>
 #include <EGL/egl.h>
 
-typedef struct SDL_WindowData
+typedef struct
 {
-#if SDL_VIDEO_OPENGL_EGL
-    EGLSurface egl_surface;
-#endif
-    SDL_Window *window;
-    SDL_Surface *surface;
-
-    float pixel_ratio;
-
-    SDL_bool external_size;
+    screen_window_t window;
+    EGLSurface      surface;
+    EGLConfig       conf;
+} window_impl_t;
+
+extern void handleKeyboardEvent(screen_event_t event);
+
+extern int glGetConfig(EGLConfig *pconf, int *pformat);
+extern int glLoadLibrary(_THIS, const char *name);
+void *glGetProcAddress(_THIS, const char *proc);
+extern SDL_GLContext glCreateContext(_THIS, SDL_Window *window);
+extern int glSetSwapInterval(_THIS, int interval);
+extern int glSwapWindow(_THIS, SDL_Window *window);
+extern int glMakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
+extern void glDeleteContext(_THIS, SDL_GLContext context);
+extern void glUnloadLibrary(_THIS);
 
-    int requested_fullscreen_mode;
-    SDL_bool fullscreen_resize;
-
-    SDL_bool finger_touching;  /* for mapping touch events to mice */
-    SDL_FingerID first_finger;
-} SDL_WindowData;
-
-#endif /* _SDL_emscriptenvideo_h */
-
-/* vi: set ts=4 sw=4 expandtab: */
+#endif
diff --git a/src/video/qnx/video.c b/src/video/qnx/video.c
new file mode 100644
index 0000000..ff8223c
--- /dev/null
+++ b/src/video/qnx/video.c
@@ -0,0 +1,364 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 2017 BlackBerry Limited
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "../../SDL_internal.h"
+#include "../SDL_sysvideo.h"
+#include "sdl_qnx.h"
+
+static screen_context_t context;
+static screen_event_t   event;
+
+/**
+ * Initializes the QNX video plugin.
+ * Creates the Screen context and event handles used for all window operations
+ * by the plugin.
+ * @param   _THIS
+ * @return  0 if successful, -1 on error
+ */
+static int
+videoInit(_THIS)
+{
+    SDL_VideoDisplay display;
+
+    if (screen_create_context(&context, 0) < 0) {
+        return -1;
+    }
+
+    if (screen_create_event(&event) < 0) {
+        return -1;
+    }
+
+    SDL_zero(display);
+
+    if (SDL_AddVideoDisplay(&display) < 0) {
+        return -1;
+    }
+
+    _this->num_displays = 1;
+    return 0;
+}
+
+static void
+videoQuit(_THIS)
+{
+}
+
+/**
+ * Creates a new native Screen window and associates it with the given SDL
+ * window.
+ * @param   _THIS
+ * @param   window  SDL window to initialize
+ * @return  0 if successful, -1 on error
+ */
+static int
+createWindow(_THIS, SDL_Window *window)
+{
+    window_impl_t   *impl;
+    int             size[2];
+    int             numbufs;
+    int             format;
+    int             usage;
+
+    impl = SDL_calloc(1, sizeof(*impl));
+    if (impl == NULL) {
+        return -1;
+    }
+
+    // Create a native window.
+    if (screen_create_window(&impl->window, context) < 0) {
+        goto fail;
+    }
+
+    // Set the native window's size to match the SDL window.
+    size[0] = window->w;
+    size[1] = window->h;
+
+    if (screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_SIZE,
+                                      size) < 0) {
+        goto fail;
+    }
+
+    if (screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_SOURCE_SIZE,
+                                      size) < 0) {
+        goto fail;
+    }
+
+    // Create window buffer(s).
+    if (window->flags & SDL_WINDOW_OPENGL) {
+        if (glGetConfig(&impl->conf, &format) < 0) {
+            goto fail;
+        }
+        numbufs = 2;
+
+        usage = SCREEN_USAGE_OPENGL_ES2;
+        if (screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_USAGE,
+                                          &usage) < 0) {
+            return -1;
+        }
+    } else {
+        format = SCREEN_FORMAT_RGBX8888;
+        numbufs = 1;
+    }
+
+    // Set pixel format.
+    if (screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_FORMAT,
+                                      &format) < 0) {
+        goto fail;
+    }
+
+    // Create buffer(s).
+    if (screen_create_window_buffers(impl->window, numbufs) < 0) {
+        goto fail;
+    }
+
+    window->driverdata = impl;
+    return 0;
+
+fail:
+    if (impl->window) {
+        screen_destroy_window(impl->window);
+    }
+
+    SDL_free(impl);
+    return -1;
+}
+
+/**
+ * Gets a pointer to the Screen buffer associated with the given window. Note
+ * that the buffer is actually created in createWindow().
+ * @param       _THIS
+ * @param       window  SDL window to get the buffer for
+ * @param[out]  pixles  Holds a pointer to the window's buffer
+ * @param[out]  format  Holds the pixel format for the buffer
+ * @param[out]  pitch   Holds the number of bytes per line
+ * @return  0 if successful, -1 on error
+ */
+static int
+createWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format,
+                        void ** pixels, int *pitch)
+{
+    window_impl_t   *impl = (window_impl_t *)window->driverdata;
+    screen_buffer_t buffer;
+
+    // Get a pointer to the buffer's memory.
+    if (screen_get_window_property_pv(impl->window, SCREEN_PROPERTY_BUFFERS,
+                                      (void **)&buffer) < 0) {
+        return -1;
+    }
+
+    if (screen_get_buffer_property_pv(buffer, SCREEN_PROPERTY_POINTER,
+                                      pixels) < 0) {
+        return -1;
+    }
+
+    // Set format and pitch.
+    if (screen_get_buffer_property_iv(buffer, SCREEN_PROPERTY_STRIDE,
+                                      pitch) < 0) {
+        return -1;
+    }
+
+    *format = SDL_PIXELFORMAT_RGB888;
+    return 0;
+}
+
+/**
+ * Informs the window manager that the window needs to be updated.
+ * @param   _THIS
+ * @param   window      The window to update
+ * @param   rects       An array of reectangular areas to update
+ * @param   numrects    Rect array length
+ * @return  0 if successful, -1 on error
+ */
+static int
+updateWindowFramebuffer(_THIS, SDL_Window *window, const SDL_Rect *rects,
+                        int numrects)
+{
+    window_impl_t   *impl = (window_impl_t *)window->driverdata;
+    screen_buffer_t buffer;
+
+    if (screen_get_window_property_pv(impl->window, SCREEN_PROPERTY_BUFFERS,
+                                      (void **)&buffer) < 0) {
+        return -1;
+    }
+
+    screen_post_window(impl->window, buffer, numrects, (int *)rects, 0);
+    screen_flush_context(context, 0);
+    return 0;
+}
+
+/**
+ * Runs the main event loop.
+ * @param   _THIS
+ */
+static void
+pumpEvents(_THIS)
+{
+    int             type;
+
+    for (;;) {
+        if (screen_get_event(context, event, 0) < 0) {
+            break;
+        }
+
+        if (screen_get_event_property_iv(event, SCREEN_PROPERTY_TYPE, &type)
+            < 0) {
+            break;
+        }
+
+        if (type == SCREEN_EVENT_NONE) {
+            break;
+        }
+
+        switch (type) {
+        case SCREEN_EVENT_KEYBOARD:
+            handleKeyboardEvent(event);
+            break;
+
+        default:
+            break;
+        }
+    }
+}
+
+/**
+ * Updates the size of the native window using the geometry of the SDL window.
+ * @param   _THIS
+ * @param   window  SDL window to update
+ */
+static void
+setWindowSize(_THIS, SDL_Window *window)
+{
+    window_impl_t   *impl = (window_impl_t *)window->driverdata;
+    int             size[2];
+
+    size[0] = window->w;
+    size[1] = window->h;
+
+    screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_SIZE, size);
+    screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_SOURCE_SIZE,
+                                  size);
+}
+
+/**
+ * Makes the native window associated with the given SDL window visible.
+ * @param   _THIS
+ * @param   window  SDL window to update
+ */
+static void
+showWindow(_THIS, SDL_Window *window)
+{
+    window_impl_t   *impl = (window_impl_t *)window->driverdata;
+    const int       visible = 1;
+
+    screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_VISIBLE,
+                                  &visible);
+}
+
+/**
+ * Makes the native window associated with the given SDL window invisible.
+ * @param   _THIS
+ * @param   window  SDL window to update
+ */
+static void
+hideWindow(_THIS, SDL_Window *window)
+{
+    window_impl_t   *impl = (window_impl_t *)window->driverdata;
+    const int       visible = 0;
+
+    screen_set_window_property_iv(impl->window, SCREEN_PROPERTY_VISIBLE,
+        &visible);
+}
+
+/**
+ * Destroys the native window associated with the given SDL window.
+ * @param   _THIS
+ * @param   window  SDL window that is being destroyed
+ */
+static void
+destroyWindow(_THIS, SDL_Window *window)
+{
+    window_impl_t   *impl = (window_impl_t *)window->driverdata;
+
+    if (impl) {
+        screen_destroy_window(impl->window);
+        window->driverdata = NULL;
+    }
+}
+
+/**
+ * Frees the plugin object created by createDevice().
+ * @param   device  Plugin object to free
+ */
+static void
+deleteDevice(SDL_VideoDevice *device)
+{
+    SDL_free(device);
+}
+
+/**
+ * Creates the QNX video plugin used by SDL.
+ * @param   devindex    Unused
+ * @return  Initialized device if successful, NULL otherwise
+ */
+static SDL_VideoDevice *
+createDevice(int devindex)
+{
+    SDL_VideoDevice *device;
+
+    device = (SDL_VideoDevice *)SDL_calloc(1, sizeof(SDL_VideoDevice));
+    if (device == NULL) {
+        return NULL;
+    }
+
+    device->driverdata = NULL;
+    device->VideoInit = videoInit;
+    device->VideoQuit = videoQuit;
+    device->CreateSDLWindow = createWindow;
+    device->CreateWindowFramebuffer = createWindowFramebuffer;
+    device->UpdateWindowFramebuffer = updateWindowFramebuffer;
+    device->SetWindowSize = setWindowSize;
+    device->ShowWindow = showWindow;
+    device->HideWindow = hideWindow;
+    device->PumpEvents = pumpEvents;
+    device->DestroyWindow = destroyWindow;
+
+    device->GL_LoadLibrary = glLoadLibrary;
+    device->GL_GetProcAddress = glGetProcAddress;
+    device->GL_CreateContext = glCreateContext;
+    device->GL_SetSwapInterval = glSetSwapInterval;
+    device->GL_SwapWindow = glSwapWindow;
+    device->GL_MakeCurrent = glMakeCurrent;
+    device->GL_DeleteContext = glDeleteContext;
+    device->GL_UnloadLibrary = glUnloadLibrary;
+
+    device->free = deleteDevice;
+    return device;
+}
+
+static int
+available()
+{
+    return 1;
+}
+
+VideoBootStrap QNX_bootstrap = {
+    "qnx", "QNX Screen",
+    available, createDevice
+};
diff --git a/src/video/raspberry/SDL_rpievents.c b/src/video/raspberry/SDL_rpievents.c
index 4104568..79a8b7a 100644
--- a/src/video/raspberry/SDL_rpievents.c
+++ b/src/video/raspberry/SDL_rpievents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/raspberry/SDL_rpievents_c.h b/src/video/raspberry/SDL_rpievents_c.h
index 54fc196..bcb8433 100644
--- a/src/video/raspberry/SDL_rpievents_c.h
+++ b/src/video/raspberry/SDL_rpievents_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_rpievents_c_h
-#define _SDL_rpievents_c_h
+#ifndef SDL_rpievents_c_h_
+#define SDL_rpievents_c_h_
 
 #include "SDL_rpivideo.h"
 
@@ -28,4 +28,4 @@ void RPI_PumpEvents(_THIS);
 void RPI_EventInit(_THIS);
 void RPI_EventQuit(_THIS);
 
-#endif /* _SDL_rpievents_c_h */
+#endif /* SDL_rpievents_c_h_ */
diff --git a/src/video/raspberry/SDL_rpimouse.c b/src/video/raspberry/SDL_rpimouse.c
index ae9bdfd..026fbd2 100644
--- a/src/video/raspberry/SDL_rpimouse.c
+++ b/src/video/raspberry/SDL_rpimouse.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/raspberry/SDL_rpimouse.h b/src/video/raspberry/SDL_rpimouse.h
index 6a4e705..f0ba4a4 100644
--- a/src/video/raspberry/SDL_rpimouse.h
+++ b/src/video/raspberry/SDL_rpimouse.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_RPI_mouse_h
-#define _SDL_RPI_mouse_h
+#ifndef SDL_RPI_mouse_h_
+#define SDL_RPI_mouse_h_
 
 #include "../SDL_sysvideo.h"
 
@@ -38,6 +38,6 @@ struct _RPI_CursorData
 extern void RPI_InitMouse(_THIS);
 extern void RPI_QuitMouse(_THIS);
 
-#endif /* _SDL_RPI_mouse_h */
+#endif /* SDL_RPI_mouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/raspberry/SDL_rpiopengles.c b/src/video/raspberry/SDL_rpiopengles.c
index 0881dbd..5b23a3f 100644
--- a/src/video/raspberry/SDL_rpiopengles.c
+++ b/src/video/raspberry/SDL_rpiopengles.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,9 +27,17 @@
 
 /* EGL implementation of SDL OpenGL support */
 
+void
+RPI_GLES_DefaultProfileConfig(_THIS, int *mask, int *major, int *minor)
+{
+    *mask = SDL_GL_CONTEXT_PROFILE_ES;
+    *major = 2;
+    *minor = 0;
+}
+
 int
 RPI_GLES_LoadLibrary(_THIS, const char *path) {
-    return SDL_EGL_LoadLibrary(_this, path, EGL_DEFAULT_DISPLAY);
+    return SDL_EGL_LoadLibrary(_this, path, EGL_DEFAULT_DISPLAY, 0);
 }
 
 SDL_EGL_CreateContext_impl(RPI)
diff --git a/src/video/raspberry/SDL_rpiopengles.h b/src/video/raspberry/SDL_rpiopengles.h
index 83c8000..fca8a49 100644
--- a/src/video/raspberry/SDL_rpiopengles.h
+++ b/src/video/raspberry/SDL_rpiopengles.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_rpiopengles_h
-#define _SDL_rpiopengles_h
+#ifndef SDL_rpiopengles_h_
+#define SDL_rpiopengles_h_
 
 #if SDL_VIDEO_DRIVER_RPI && SDL_VIDEO_OPENGL_EGL
 
@@ -38,11 +38,12 @@
 
 extern int RPI_GLES_LoadLibrary(_THIS, const char *path);
 extern SDL_GLContext RPI_GLES_CreateContext(_THIS, SDL_Window * window);
-extern void RPI_GLES_SwapWindow(_THIS, SDL_Window * window);
+extern int RPI_GLES_SwapWindow(_THIS, SDL_Window * window);
 extern int RPI_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
+extern void RPI_GLES_DefaultProfileConfig(_THIS, int *mask, int *major, int *minor);
 
 #endif /* SDL_VIDEO_DRIVER_RPI && SDL_VIDEO_OPENGL_EGL */
 
-#endif /* _SDL_rpiopengles_h */
+#endif /* SDL_rpiopengles_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/raspberry/SDL_rpivideo.c b/src/video/raspberry/SDL_rpivideo.c
index 67dc77b..1e1f569 100644
--- a/src/video/raspberry/SDL_rpivideo.c
+++ b/src/video/raspberry/SDL_rpivideo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -59,11 +59,8 @@ RPI_Available(void)
 static void
 RPI_Destroy(SDL_VideoDevice * device)
 {
-    /*    SDL_VideoData *phdata = (SDL_VideoData *) device->driverdata; */
-
-    if (device->driverdata != NULL) {
-        device->driverdata = NULL;
-    }
+    SDL_free(device->driverdata);
+    SDL_free(device);
 }
 
 static SDL_VideoDevice *
@@ -100,8 +97,8 @@ RPI_Create()
     device->VideoQuit = RPI_VideoQuit;
     device->GetDisplayModes = RPI_GetDisplayModes;
     device->SetDisplayMode = RPI_SetDisplayMode;
-    device->CreateWindow = RPI_CreateWindow;
-    device->CreateWindowFrom = RPI_CreateWindowFrom;
+    device->CreateSDLWindow = RPI_CreateWindow;
+    device->CreateSDLWindowFrom = RPI_CreateWindowFrom;
     device->SetWindowTitle = RPI_SetWindowTitle;
     device->SetWindowIcon = RPI_SetWindowIcon;
     device->SetWindowPosition = RPI_SetWindowPosition;
@@ -114,7 +111,9 @@ RPI_Create()
     device->RestoreWindow = RPI_RestoreWindow;
     device->SetWindowGrab = RPI_SetWindowGrab;
     device->DestroyWindow = RPI_DestroyWindow;
+#if 0
     device->GetWindowWMInfo = RPI_GetWindowWMInfo;
+#endif
     device->GL_LoadLibrary = RPI_GLES_LoadLibrary;
     device->GL_GetProcAddress = RPI_GLES_GetProcAddress;
     device->GL_UnloadLibrary = RPI_GLES_UnloadLibrary;
@@ -124,6 +123,7 @@ RPI_Create()
     device->GL_GetSwapInterval = RPI_GLES_GetSwapInterval;
     device->GL_SwapWindow = RPI_GLES_SwapWindow;
     device->GL_DeleteContext = RPI_GLES_DeleteContext;
+    device->GL_DefaultProfileConfig = RPI_GLES_DefaultProfileConfig;
 
     device->PumpEvents = RPI_PumpEvents;
 
@@ -183,7 +183,9 @@ RPI_VideoInit(_THIS)
     SDL_AddVideoDisplay(&display);
 
 #ifdef SDL_INPUT_LINUXEV    
-    SDL_EVDEV_Init();
+    if (SDL_EVDEV_Init() < 0) {
+        return -1;
+    }
 #endif    
     
     RPI_InitMouse(_this);
@@ -368,13 +370,14 @@ RPI_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed)
 /*****************************************************************************/
 /* SDL Window Manager function                                               */
 /*****************************************************************************/
+#if 0
 SDL_bool
 RPI_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info)
 {
     if (info->version.major <= SDL_MAJOR_VERSION) {
         return SDL_TRUE;
     } else {
-        SDL_SetError("application not compiled with SDL %d.%d\n",
+        SDL_SetError("application not compiled with SDL %d.%d",
                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
@@ -382,6 +385,7 @@ RPI_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info)
     /* Failed to get window manager information */
     return SDL_FALSE;
 }
+#endif
 
 #endif /* SDL_VIDEO_DRIVER_RPI */
 
diff --git a/src/video/raspberry/SDL_rpivideo.h b/src/video/raspberry/SDL_rpivideo.h
index 74dcf94..ba1f0b2 100644
--- a/src/video/raspberry/SDL_rpivideo.h
+++ b/src/video/raspberry/SDL_rpivideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,7 +25,7 @@
 #include "../../SDL_internal.h"
 #include "../SDL_sysvideo.h"
 
-#include "bcm_host.h"
+#include <bcm_host.h>
 #include "GLES/gl.h"
 #include "EGL/egl.h"
 #include "EGL/eglext.h"
@@ -90,7 +90,7 @@ SDL_GLContext RPI_GLES_CreateContext(_THIS, SDL_Window * window);
 int RPI_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 int RPI_GLES_SetSwapInterval(_THIS, int interval);
 int RPI_GLES_GetSwapInterval(_THIS);
-void RPI_GLES_SwapWindow(_THIS, SDL_Window * window);
+int RPI_GLES_SwapWindow(_THIS, SDL_Window * window);
 void RPI_GLES_DeleteContext(_THIS, SDL_GLContext context);
 
 #endif /* __SDL_RPIVIDEO_H__ */
diff --git a/src/video/sdlgenblit.pl b/src/video/sdlgenblit.pl
index 9ebffaf..f52461a 100755
--- a/src/video/sdlgenblit.pl
+++ b/src/video/sdlgenblit.pl
@@ -92,7 +92,7 @@ sub open_file {
 /* DO NOT EDIT!  This file is generated by sdlgenblit.pl */
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken\@libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken\@libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/uikit/SDL_uikitappdelegate.h b/src/video/uikit/SDL_uikitappdelegate.h
index edf09f5..3ee825e 100644
--- a/src/video/uikit/SDL_uikitappdelegate.h
+++ b/src/video/uikit/SDL_uikitappdelegate.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -36,6 +36,12 @@
 
 - (void)hideLaunchScreen;
 
+/* This property is marked as optional, and is only intended to be used when
+ * the app's UI is storyboard-based. SDL is not storyboard-based, however
+ * several major third-party ad APIs (e.g. Google admob) incorrectly assume this
+ * property always exists, and will crash if it doesn't. */
+ at property (nonatomic) UIWindow *window;
+
 @end
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitappdelegate.m b/src/video/uikit/SDL_uikitappdelegate.m
index c94c78a..d3ea75c 100644
--- a/src/video/uikit/SDL_uikitappdelegate.m
+++ b/src/video/uikit/SDL_uikitappdelegate.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -69,7 +69,7 @@ int main(int argc, char **argv)
     return exit_status;
 }
 
-static void
+static void SDLCALL
 SDL_IdleTimerDisabledChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
 {
     BOOL disable = (hint && *hint != '0');
@@ -422,14 +422,24 @@ SDL_LoadLaunchImageNamed(NSString *name, int screenh)
     return YES;
 }
 
-- (void)applicationWillTerminate:(UIApplication *)application
+- (UIWindow *)window
 {
-    SDL_SendAppEvent(SDL_APP_TERMINATING);
+    SDL_VideoDevice *_this = SDL_GetVideoDevice();
+    if (_this) {
+        SDL_Window *window = NULL;
+        for (window = _this->windows; window != NULL; window = window->next) {
+            SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
+            if (data != nil) {
+                return data.uiwindow;
+            }
+        }
+    }
+    return nil;
 }
 
-- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
+- (void)setWindow:(UIWindow *)window
 {
-    SDL_SendAppEvent(SDL_APP_LOWMEMORY);
+    /* Do nothing. */
 }
 
 #if !TARGET_OS_TV
@@ -462,41 +472,34 @@ SDL_LoadLaunchImageNamed(NSString *name, int screenh)
 }
 #endif
 
+- (void)applicationWillTerminate:(UIApplication *)application
+{
+    SDL_OnApplicationWillTerminate();
+}
+
+- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
+{
+    SDL_OnApplicationDidReceiveMemoryWarning();
+}
+
 - (void)applicationWillResignActive:(UIApplication*)application
 {
-    SDL_VideoDevice *_this = SDL_GetVideoDevice();
-    if (_this) {
-        SDL_Window *window;
-        for (window = _this->windows; window != nil; window = window->next) {
-            SDL_SendWindowEvent(window, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
-            SDL_SendWindowEvent(window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
-        }
-    }
-    SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
+    SDL_OnApplicationWillResignActive();
 }
 
 - (void)applicationDidEnterBackground:(UIApplication*)application
 {
-    SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
+    SDL_OnApplicationDidEnterBackground();
 }
 
 - (void)applicationWillEnterForeground:(UIApplication*)application
 {
-    SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND);
+    SDL_OnApplicationWillEnterForeground();
 }
 
 - (void)applicationDidBecomeActive:(UIApplication*)application
 {
-    SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
-
-    SDL_VideoDevice *_this = SDL_GetVideoDevice();
-    if (_this) {
-        SDL_Window *window;
-        for (window = _this->windows; window != nil; window = window->next) {
-            SDL_SendWindowEvent(window, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
-            SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESTORED, 0, 0);
-        }
-    }
+    SDL_OnApplicationDidBecomeActive();
 }
 
 - (void)sendDropFileForURL:(NSURL *)url
@@ -510,23 +513,24 @@ SDL_LoadLaunchImageNamed(NSString *name, int screenh)
     SDL_SendDropComplete(NULL);
 }
 
-#if TARGET_OS_TV
-/* TODO: Use this on iOS 9+ as well? */
+#if TARGET_OS_TV || (defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_9_0)
+
 - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
 {
     /* TODO: Handle options */
     [self sendDropFileForURL:url];
     return YES;
 }
-#endif /* TARGET_OS_TV */
 
-#if !TARGET_OS_TV
+#else
+
 - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
 {
     [self sendDropFileForURL:url];
     return YES;
 }
-#endif /* !TARGET_OS_TV */
+
+#endif
 
 @end
 
diff --git a/src/video/uikit/SDL_uikitclipboard.h b/src/video/uikit/SDL_uikitclipboard.h
index 7d1c35f..b888238 100644
--- a/src/video/uikit/SDL_uikitclipboard.h
+++ b/src/video/uikit/SDL_uikitclipboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,8 +18,8 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#ifndef _SDL_uikitclipboard_h
-#define _SDL_uikitclipboard_h
+#ifndef SDL_uikitclipboard_h_
+#define SDL_uikitclipboard_h_
 
 #include "../SDL_sysvideo.h"
 
@@ -30,6 +30,6 @@ extern SDL_bool UIKit_HasClipboardText(_THIS);
 extern void UIKit_InitClipboard(_THIS);
 extern void UIKit_QuitClipboard(_THIS);
 
-#endif /* _SDL_uikitclipboard_h */
+#endif /* SDL_uikitclipboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitclipboard.m b/src/video/uikit/SDL_uikitclipboard.m
index 050d588..7ce4d3c 100644
--- a/src/video/uikit/SDL_uikitclipboard.m
+++ b/src/video/uikit/SDL_uikitclipboard.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/uikit/SDL_uikitevents.h b/src/video/uikit/SDL_uikitevents.h
index 9b1d60c..e5b15ad 100644
--- a/src/video/uikit/SDL_uikitevents.h
+++ b/src/video/uikit/SDL_uikitevents.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,13 +18,13 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#ifndef _SDL_uikitevents_h
-#define _SDL_uikitevents_h
+#ifndef SDL_uikitevents_h_
+#define SDL_uikitevents_h_
 
 #include "../SDL_sysvideo.h"
 
 extern void UIKit_PumpEvents(_THIS);
 
-#endif /* _SDL_uikitevents_h */
+#endif /* SDL_uikitevents_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitevents.m b/src/video/uikit/SDL_uikitevents.m
index 7083e20..2b21773 100644
--- a/src/video/uikit/SDL_uikitevents.m
+++ b/src/video/uikit/SDL_uikitevents.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/uikit/SDL_uikitmessagebox.h b/src/video/uikit/SDL_uikitmessagebox.h
index 5280724..7e4fbc4 100644
--- a/src/video/uikit/SDL_uikitmessagebox.h
+++ b/src/video/uikit/SDL_uikitmessagebox.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -22,7 +22,7 @@
 
 #if SDL_VIDEO_DRIVER_UIKIT
 
-extern SDL_bool UIKit_ShowingMessageBox();
+extern SDL_bool UIKit_ShowingMessageBox(void);
 
 extern int UIKit_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid);
 
diff --git a/src/video/uikit/SDL_uikitmessagebox.m b/src/video/uikit/SDL_uikitmessagebox.m
index 5778032..3c7ac46 100644
--- a/src/video/uikit/SDL_uikitmessagebox.m
+++ b/src/video/uikit/SDL_uikitmessagebox.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -31,7 +31,7 @@
 static SDL_bool s_showingMessageBox = SDL_FALSE;
 
 SDL_bool
-UIKit_ShowingMessageBox()
+UIKit_ShowingMessageBox(void)
 {
     return s_showingMessageBox;
 }
diff --git a/src/video/uikit/SDL_uikitmetalview.h b/src/video/uikit/SDL_uikitmetalview.h
new file mode 100644
index 0000000..a26c356
--- /dev/null
+++ b/src/video/uikit/SDL_uikitmetalview.h
@@ -0,0 +1,55 @@
+/*
+ Simple DirectMedia Layer
+ Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+ 
+ This software is provided 'as-is', without any express or implied
+ warranty.  In no event will the authors be held liable for any damages
+ arising from the use of this software.
+ 
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+ 
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+ */
+
+/*
+ * @author Mark Callow, www.edgewise-consulting.com.
+ *
+ * Thanks to Alex Szpakowski, @slime73 on GitHub, for his gist showing
+ * how to add a CAMetalLayer backed view.
+ */
+
+#ifndef SDL_uikitmetalview_h_
+#define SDL_uikitmetalview_h_
+
+#import "../SDL_sysvideo.h"
+#import "SDL_uikitwindow.h"
+
+#import <UIKit/UIKit.h>
+#import <Metal/Metal.h>
+#import <QuartzCore/CAMetalLayer.h>
+
+#define METALVIEW_TAG 255
+
+ at interface SDL_uikitmetalview : UIView
+
+- (instancetype)initWithFrame:(CGRect)frame
+                        scale:(CGFloat)scale
+                        tag:(int)tag;
+
+ at end
+
+SDL_uikitmetalview* UIKit_Mtl_AddMetalView(SDL_Window* window);
+
+void UIKit_Mtl_GetDrawableSize(SDL_Window * window, int * w, int * h);
+
+#endif /* SDL_uikitmetalview_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitmetalview.m b/src/video/uikit/SDL_uikitmetalview.m
new file mode 100644
index 0000000..17dca69
--- /dev/null
+++ b/src/video/uikit/SDL_uikitmetalview.m
@@ -0,0 +1,147 @@
+/*
+ Simple DirectMedia Layer
+ Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+ 
+ This software is provided 'as-is', without any express or implied
+ warranty.  In no event will the authors be held liable for any damages
+ arising from the use of this software.
+ 
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+ 
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+ */
+
+/*
+ * @author Mark Callow, www.edgewise-consulting.com.
+ *
+ * Thanks to Alex Szpakowski, @slime73 on GitHub, for his gist showing
+ * how to add a CAMetalLayer backed view.
+ */
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_UIKIT
+
+#import "../SDL_sysvideo.h"
+#import "SDL_uikitwindow.h"
+#import "SDL_uikitmetalview.h"
+
+#include "SDL_assert.h"
+
+ at implementation SDL_uikitmetalview
+
+/* Returns a Metal-compatible layer. */
++ (Class)layerClass
+{
+    return [CAMetalLayer class];
+}
+
+- (instancetype)initWithFrame:(CGRect)frame
+                        scale:(CGFloat)scale
+                          tag:(int)tag
+{
+    if ((self = [super initWithFrame:frame])) {
+        /* Resize properly when rotated. */
+        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
+
+        /* Set the appropriate scale (for retina display support) */
+        self.contentScaleFactor = scale;
+        self.tag = tag;
+
+        [self updateDrawableSize];
+    }
+
+    return self;
+}
+
+/* Set the size of the metal drawables when the view is resized. */
+- (void)layoutSubviews
+{
+    [super layoutSubviews];
+    [self updateDrawableSize];
+}
+
+- (void)updateDrawableSize
+{
+    CGSize size  = self.bounds.size;
+    size.width  *= self.contentScaleFactor;
+    size.height *= self.contentScaleFactor;
+
+    ((CAMetalLayer *) self.layer).drawableSize = size;
+}
+
+ at end
+
+SDL_uikitmetalview*
+UIKit_Mtl_AddMetalView(SDL_Window* window)
+{
+    SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
+    SDL_uikitview *view = (SDL_uikitview*)data.uiwindow.rootViewController.view;
+    CGFloat scale = 1.0;
+
+    if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) {
+        /* Set the scale to the natural scale factor of the screen - the
+         * backing dimensions of the Metal view will match the pixel
+         * dimensions of the screen rather than the dimensions in points.
+         */
+#ifdef __IPHONE_8_0
+        if ([data.uiwindow.screen respondsToSelector:@selector(nativeScale)]) {
+            scale = data.uiwindow.screen.nativeScale;
+        } else
+#endif
+        {
+            scale = data.uiwindow.screen.scale;
+        }
+    }
+    SDL_uikitmetalview *metalview
+         = [[SDL_uikitmetalview alloc] initWithFrame:view.frame
+                                          scale:scale
+                                            tag:METALVIEW_TAG];
+#if 1
+    [view addSubview:metalview];
+#else
+    /* Sets this view as the controller's view, and adds the view to
+     * the window hierarchy.
+     *
+     * Left here for information. Not used because I suspect that for correct
+     * operation it will be necesary to copy everything from the window's
+     * current SDL_uikitview instance to the SDL_uikitview portion of the
+     * SDL_metalview. The latter would be derived from SDL_uikitview rather
+     * than UIView. */
+    [metalview setSDLWindow:window];
+#endif
+
+    return metalview;
+}
+
+void
+UIKit_Mtl_GetDrawableSize(SDL_Window * window, int * w, int * h)
+{
+    @autoreleasepool {
+        SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
+        SDL_uikitview *view = (SDL_uikitview*)data.uiwindow.rootViewController.view;
+        SDL_uikitmetalview* metalview = [view viewWithTag:METALVIEW_TAG];
+        if (metalview) {
+            CAMetalLayer *layer = (CAMetalLayer*)metalview.layer;
+            assert(layer != NULL);
+            if (w) {
+                *w = layer.drawableSize.width;
+            }
+            if (h) {
+                *h = layer.drawableSize.height;
+            }
+        } else {
+            SDL_GetWindowSize(window, w, h);
+        }
+    }
+}
+
+#endif
diff --git a/src/video/uikit/SDL_uikitmodes.h b/src/video/uikit/SDL_uikitmodes.h
index b936df6..4620eea 100644
--- a/src/video/uikit/SDL_uikitmodes.h
+++ b/src/video/uikit/SDL_uikitmodes.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_uikitmodes_h
-#define _SDL_uikitmodes_h
+#ifndef SDL_uikitmodes_h_
+#define SDL_uikitmodes_h_
 
 #include "SDL_uikitvideo.h"
 
@@ -45,6 +45,6 @@ extern int UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMo
 extern void UIKit_QuitModes(_THIS);
 extern int UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect);
 
-#endif /* _SDL_uikitmodes_h */
+#endif /* SDL_uikitmodes_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitmodes.m b/src/video/uikit/SDL_uikitmodes.m
index cd3b8d0..0798166 100644
--- a/src/video/uikit/SDL_uikitmodes.m
+++ b/src/video/uikit/SDL_uikitmodes.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -68,21 +68,33 @@ UIKit_FreeDisplayModeData(SDL_DisplayMode * mode)
     }
 }
 
+static NSUInteger
+UIKit_GetDisplayModeRefreshRate(UIScreen *uiscreen)
+{
+#ifdef __IPHONE_10_3
+    if ([uiscreen respondsToSelector:@selector(maximumFramesPerSecond)]) {
+        return uiscreen.maximumFramesPerSecond;
+    }
+#endif
+    return 0;
+}
+
 static int
 UIKit_AddSingleDisplayMode(SDL_VideoDisplay * display, int w, int h,
-    UIScreenMode * uiscreenmode)
+    UIScreen * uiscreen, UIScreenMode * uiscreenmode)
 {
     SDL_DisplayMode mode;
     SDL_zero(mode);
 
-    mode.format = SDL_PIXELFORMAT_ABGR8888;
-    mode.refresh_rate = 0;
     if (UIKit_AllocateDisplayModeData(&mode, uiscreenmode) < 0) {
         return -1;
     }
 
+    mode.format = SDL_PIXELFORMAT_ABGR8888;
+    mode.refresh_rate = (int) UIKit_GetDisplayModeRefreshRate(uiscreen);
     mode.w = w;
     mode.h = h;
+
     if (SDL_AddDisplayMode(display, &mode)) {
         return 0;
     } else {
@@ -92,16 +104,16 @@ UIKit_AddSingleDisplayMode(SDL_VideoDisplay * display, int w, int h,
 }
 
 static int
-UIKit_AddDisplayMode(SDL_VideoDisplay * display, int w, int h,
+UIKit_AddDisplayMode(SDL_VideoDisplay * display, int w, int h, UIScreen * uiscreen,
                      UIScreenMode * uiscreenmode, SDL_bool addRotation)
 {
-    if (UIKit_AddSingleDisplayMode(display, w, h, uiscreenmode) < 0) {
+    if (UIKit_AddSingleDisplayMode(display, w, h, uiscreen, uiscreenmode) < 0) {
         return -1;
     }
 
     if (addRotation) {
         /* Add the rotated version */
-        if (UIKit_AddSingleDisplayMode(display, h, w, uiscreenmode) < 0) {
+        if (UIKit_AddSingleDisplayMode(display, h, w, uiscreen, uiscreenmode) < 0) {
             return -1;
         }
     }
@@ -112,7 +124,11 @@ UIKit_AddDisplayMode(SDL_VideoDisplay * display, int w, int h,
 static int
 UIKit_AddDisplay(UIScreen *uiscreen)
 {
+    UIScreenMode *uiscreenmode = uiscreen.currentMode;
     CGSize size = uiscreen.bounds.size;
+    SDL_VideoDisplay display;
+    SDL_DisplayMode mode;
+    SDL_zero(mode);
 
     /* Make sure the width/height are oriented correctly */
     if (UIKit_IsDisplayLandscape(uiscreen) != (size.width > size.height)) {
@@ -121,15 +137,11 @@ UIKit_AddDisplay(UIScreen *uiscreen)
         size.height = height;
     }
 
-    SDL_VideoDisplay display;
-    SDL_DisplayMode mode;
-    SDL_zero(mode);
     mode.format = SDL_PIXELFORMAT_ABGR8888;
+    mode.refresh_rate = (int) UIKit_GetDisplayModeRefreshRate(uiscreen);
     mode.w = (int) size.width;
     mode.h = (int) size.height;
 
-    UIScreenMode *uiscreenmode = uiscreen.currentMode;
-
     if (UIKit_AllocateDisplayModeData(&mode, uiscreenmode) < 0) {
         return -1;
     }
@@ -220,7 +232,7 @@ UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
                 h = tmp;
             }
 
-            UIKit_AddDisplayMode(display, w, h, uimode, addRotation);
+            UIKit_AddDisplayMode(display, w, h, data.uiscreen, uimode, addRotation);
         }
     }
 }
@@ -261,6 +273,7 @@ UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect)
     @autoreleasepool {
         int displayIndex = (int) (display - _this->displays);
         SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata;
+        CGRect frame = data.uiscreen.bounds;
 
         /* the default function iterates displays to make a fake offset,
          as if all the displays were side-by-side, which is fine for iOS. */
@@ -268,9 +281,7 @@ UIKit_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect)
             return -1;
         }
 
-        CGRect frame = data.uiscreen.bounds;
-
-#if !TARGET_OS_TV
+#if !TARGET_OS_TV && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
         if (!UIKit_IsSystemVersionAtLeast(7.0)) {
             frame = [data.uiscreen applicationFrame];
         }
diff --git a/src/video/uikit/SDL_uikitopengles.h b/src/video/uikit/SDL_uikitopengles.h
index b52e429..0244964 100644
--- a/src/video/uikit/SDL_uikitopengles.h
+++ b/src/video/uikit/SDL_uikitopengles.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,8 +18,8 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#ifndef _SDL_uikitopengles
-#define _SDL_uikitopengles
+#ifndef SDL_uikitopengles_
+#define SDL_uikitopengles_
 
 #include "../SDL_sysvideo.h"
 
@@ -27,14 +27,14 @@ extern int UIKit_GL_MakeCurrent(_THIS, SDL_Window * window,
                                 SDL_GLContext context);
 extern void UIKit_GL_GetDrawableSize(_THIS, SDL_Window * window,
                                      int * w, int * h);
-extern void UIKit_GL_SwapWindow(_THIS, SDL_Window * window);
+extern int UIKit_GL_SwapWindow(_THIS, SDL_Window * window);
 extern SDL_GLContext UIKit_GL_CreateContext(_THIS, SDL_Window * window);
 extern void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context);
 extern void *UIKit_GL_GetProcAddress(_THIS, const char *proc);
 extern int UIKit_GL_LoadLibrary(_THIS, const char *path);
 
-extern void UIKit_GL_RestoreCurrentContext();
+extern void UIKit_GL_RestoreCurrentContext(void);
 
-#endif
+#endif /* SDL_uikitopengles_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitopengles.m b/src/video/uikit/SDL_uikitopengles.m
index 461ff9b..9e3b13f 100644
--- a/src/video/uikit/SDL_uikitopengles.m
+++ b/src/video/uikit/SDL_uikitopengles.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -111,7 +111,7 @@ UIKit_GL_LoadLibrary(_THIS, const char *path)
     return 0;
 }
 
-void UIKit_GL_SwapWindow(_THIS, SDL_Window * window)
+int UIKit_GL_SwapWindow(_THIS, SDL_Window * window)
 {
     @autoreleasepool {
         SDLEAGLContext *context = (__bridge SDLEAGLContext *) SDL_GL_GetCurrentContext();
@@ -127,6 +127,7 @@ void UIKit_GL_SwapWindow(_THIS, SDL_Window * window)
          * We don't pump events here because we don't want iOS application events
          * (low memory, terminate, etc.) to happen inside low level rendering. */
     }
+    return 0;
 }
 
 SDL_GLContext
@@ -227,7 +228,7 @@ UIKit_GL_DeleteContext(_THIS, SDL_GLContext context)
 }
 
 void
-UIKit_GL_RestoreCurrentContext()
+UIKit_GL_RestoreCurrentContext(void)
 {
     @autoreleasepool {
         /* Some iOS system functionality (such as Dictation on the on-screen
diff --git a/src/video/uikit/SDL_uikitopenglview.h b/src/video/uikit/SDL_uikitopenglview.h
index 86fb5e1..716c94d 100644
--- a/src/video/uikit/SDL_uikitopenglview.h
+++ b/src/video/uikit/SDL_uikitopenglview.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/uikit/SDL_uikitopenglview.m b/src/video/uikit/SDL_uikitopenglview.m
index aae7ee8..21a2825 100644
--- a/src/video/uikit/SDL_uikitopenglview.m
+++ b/src/video/uikit/SDL_uikitopenglview.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/uikit/SDL_uikitvideo.h b/src/video/uikit/SDL_uikitvideo.h
index aafb714..736888c 100644
--- a/src/video/uikit/SDL_uikitvideo.h
+++ b/src/video/uikit/SDL_uikitvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,8 +18,8 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#ifndef _SDL_uikitvideo_h
-#define _SDL_uikitvideo_h
+#ifndef SDL_uikitvideo_h_
+#define SDL_uikitvideo_h_
 
 #include "../SDL_sysvideo.h"
 
@@ -41,6 +41,6 @@ void UIKit_SuspendScreenSaver(_THIS);
 
 SDL_bool UIKit_IsSystemVersionAtLeast(double version);
 
-#endif /* _SDL_uikitvideo_h */
+#endif /* SDL_uikitvideo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitvideo.m b/src/video/uikit/SDL_uikitvideo.m
index 88d4617..f679427 100644
--- a/src/video/uikit/SDL_uikitvideo.m
+++ b/src/video/uikit/SDL_uikitvideo.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -37,6 +37,7 @@
 #include "SDL_uikitwindow.h"
 #include "SDL_uikitopengles.h"
 #include "SDL_uikitclipboard.h"
+#include "SDL_uikitvulkan.h"
 
 #define UIKITVID_DRIVER_NAME "uikit"
 
@@ -90,7 +91,7 @@ UIKit_CreateDevice(int devindex)
         device->SetDisplayMode = UIKit_SetDisplayMode;
         device->PumpEvents = UIKit_PumpEvents;
         device->SuspendScreenSaver = UIKit_SuspendScreenSaver;
-        device->CreateWindow = UIKit_CreateWindow;
+        device->CreateSDLWindow = UIKit_CreateWindow;
         device->SetWindowTitle = UIKit_SetWindowTitle;
         device->ShowWindow = UIKit_ShowWindow;
         device->HideWindow = UIKit_HideWindow;
@@ -101,13 +102,13 @@ UIKit_CreateDevice(int devindex)
         device->GetWindowWMInfo = UIKit_GetWindowWMInfo;
         device->GetDisplayUsableBounds = UIKit_GetDisplayUsableBounds;
 
-    #if SDL_IPHONE_KEYBOARD
+#if SDL_IPHONE_KEYBOARD
         device->HasScreenKeyboardSupport = UIKit_HasScreenKeyboardSupport;
         device->ShowScreenKeyboard = UIKit_ShowScreenKeyboard;
         device->HideScreenKeyboard = UIKit_HideScreenKeyboard;
         device->IsScreenKeyboardShown = UIKit_IsScreenKeyboardShown;
         device->SetTextInputRect = UIKit_SetTextInputRect;
-    #endif
+#endif
 
         device->SetClipboardText = UIKit_SetClipboardText;
         device->GetClipboardText = UIKit_GetClipboardText;
@@ -123,6 +124,15 @@ UIKit_CreateDevice(int devindex)
         device->GL_LoadLibrary      = UIKit_GL_LoadLibrary;
         device->free = UIKit_DeleteDevice;
 
+#if SDL_VIDEO_VULKAN
+        device->Vulkan_LoadLibrary = UIKit_Vulkan_LoadLibrary;
+        device->Vulkan_UnloadLibrary = UIKit_Vulkan_UnloadLibrary;
+        device->Vulkan_GetInstanceExtensions
+                                     = UIKit_Vulkan_GetInstanceExtensions;
+        device->Vulkan_CreateSurface = UIKit_Vulkan_CreateSurface;
+        device->Vulkan_GetDrawableSize = UIKit_Vulkan_GetDrawableSize;
+#endif
+
         device->gl_config.accelerated = 1;
 
         return device;
@@ -176,18 +186,39 @@ UIKit_IsSystemVersionAtLeast(double version)
 CGRect
 UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen)
 {
+    CGRect frame = screen.bounds;
+
 #if !TARGET_OS_TV && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0)
     BOOL hasiOS7 = UIKit_IsSystemVersionAtLeast(7.0);
 
-    if (hasiOS7 || (window->flags & (SDL_WINDOW_BORDERLESS|SDL_WINDOW_FULLSCREEN))) {
-        /* The view should always show behind the status bar in iOS 7+. */
-        return screen.bounds;
-    } else {
-        return screen.applicationFrame;
+    /* The view should always show behind the status bar in iOS 7+. */
+    if (!hasiOS7 && !(window->flags & (SDL_WINDOW_BORDERLESS|SDL_WINDOW_FULLSCREEN))) {
+        frame = screen.applicationFrame;
     }
-#else
-    return screen.bounds;
 #endif
+
+#if !TARGET_OS_TV
+    /* iOS 10 seems to have a bug where, in certain conditions, putting the
+     * device to sleep with the a landscape-only app open, re-orienting the
+     * device to portrait, and turning it back on will result in the screen
+     * bounds returning portrait orientation despite the app being in landscape.
+     * This is a workaround until a better solution can be found.
+     * https://bugzilla.libsdl.org/show_bug.cgi?id=3505
+     * https://bugzilla.libsdl.org/show_bug.cgi?id=3465
+     * https://forums.developer.apple.com/thread/65337 */
+    if (UIKit_IsSystemVersionAtLeast(8.0)) {
+        UIInterfaceOrientation orient = [UIApplication sharedApplication].statusBarOrientation;
+        BOOL isLandscape = UIInterfaceOrientationIsLandscape(orient);
+
+        if (isLandscape != (frame.size.width > frame.size.height)) {
+            float height = frame.size.width;
+            frame.size.width = frame.size.height;
+            frame.size.height = height;
+        }
+    }
+#endif
+
+    return frame;
 }
 
 /*
diff --git a/src/video/uikit/SDL_uikitview.h b/src/video/uikit/SDL_uikitview.h
index 18fa78f..0f49701 100644
--- a/src/video/uikit/SDL_uikitview.h
+++ b/src/video/uikit/SDL_uikitview.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/uikit/SDL_uikitview.m b/src/video/uikit/SDL_uikitview.m
index c7d9f51..d4f9e6e 100644
--- a/src/video/uikit/SDL_uikitview.m
+++ b/src/video/uikit/SDL_uikitview.m
@@ -1,6 +1,6 @@
  /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -42,6 +42,25 @@
 - (instancetype)initWithFrame:(CGRect)frame
 {
     if ((self = [super initWithFrame:frame])) {
+        /* Apple TV Remote touchpad swipe gestures. */
+#if TARGET_OS_TV
+        UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
+        swipeUp.direction = UISwipeGestureRecognizerDirectionUp;
+        [self addGestureRecognizer:swipeUp];
+
+        UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
+        swipeDown.direction = UISwipeGestureRecognizerDirectionDown;
+        [self addGestureRecognizer:swipeDown];
+
+        UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
+        swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
+        [self addGestureRecognizer:swipeLeft];
+
+        UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
+        swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
+        [self addGestureRecognizer:swipeRight];
+#endif
+
         self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
         self.autoresizesSubviews = YES;
 
@@ -264,6 +283,35 @@
 }
 #endif /* TARGET_OS_TV || defined(__IPHONE_9_1) */
 
+#if TARGET_OS_TV
+-(void)swipeGesture:(UISwipeGestureRecognizer *)gesture
+{
+    /* Swipe gestures don't trigger begin states. */
+    if (gesture.state == UIGestureRecognizerStateEnded) {
+        /* Send arrow key presses for now, as we don't have an external API
+         * which better maps to swipe gestures. */
+        switch (gesture.direction) {
+        case UISwipeGestureRecognizerDirectionUp:
+            SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_UP);
+            SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_UP);
+            break;
+        case UISwipeGestureRecognizerDirectionDown:
+            SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_DOWN);
+            SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_DOWN);
+            break;
+        case UISwipeGestureRecognizerDirectionLeft:
+            SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_LEFT);
+            SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_LEFT);
+            break;
+        case UISwipeGestureRecognizerDirectionRight:
+            SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_RIGHT);
+            SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_RIGHT);
+            break;
+        }
+    }
+}
+#endif /* TARGET_OS_TV */
+
 @end
 
 #endif /* SDL_VIDEO_DRIVER_UIKIT */
diff --git a/src/video/uikit/SDL_uikitviewcontroller.h b/src/video/uikit/SDL_uikitviewcontroller.h
index 8608524..4704e08 100644
--- a/src/video/uikit/SDL_uikitviewcontroller.h
+++ b/src/video/uikit/SDL_uikitviewcontroller.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/uikit/SDL_uikitviewcontroller.m b/src/video/uikit/SDL_uikitviewcontroller.m
index e6e903e..745e223 100644
--- a/src/video/uikit/SDL_uikitviewcontroller.m
+++ b/src/video/uikit/SDL_uikitviewcontroller.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -40,7 +40,7 @@
 #endif
 
 #if TARGET_OS_TV
-static void
+static void SDLCALL
 SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
 {
     @autoreleasepool {
@@ -58,6 +58,7 @@ SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char
 
 #if SDL_IPHONE_KEYBOARD
     UITextField *textField;
+    BOOL rotatingOrientation;
 #endif
 }
 
@@ -70,6 +71,7 @@ SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char
 
 #if SDL_IPHONE_KEYBOARD
         [self initKeyboard];
+        rotatingOrientation = FALSE;
 #endif
 
 #if TARGET_OS_TV
@@ -112,7 +114,22 @@ SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char
 - (void)startAnimation
 {
     displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(doLoop:)];
-    [displayLink setFrameInterval:animationInterval];
+
+#ifdef __IPHONE_10_3
+    SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
+
+    if ([displayLink respondsToSelector:@selector(preferredFramesPerSecond)]
+        && data != nil && data.uiwindow != nil
+        && [data.uiwindow.screen respondsToSelector:@selector(maximumFramesPerSecond)]) {
+        displayLink.preferredFramesPerSecond = data.uiwindow.screen.maximumFramesPerSecond / animationInterval;
+    } else
+#endif
+    {
+#if __IPHONE_OS_VERSION_MIN_REQUIRED < 100300
+        [displayLink setFrameInterval:animationInterval];
+#endif
+    }
+
     [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
 }
 
@@ -153,10 +170,12 @@ SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char
     return UIKit_GetSupportedOrientations(window);
 }
 
+#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orient
 {
     return ([self supportedInterfaceOrientations] & (1 << orient)) != 0;
 }
+#endif
 
 - (BOOL)prefersStatusBarHidden
 {
@@ -211,6 +230,29 @@ SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char
     }
 }
 
+/* willRotateToInterfaceOrientation and didRotateFromInterfaceOrientation are deprecated in iOS 8+ in favor of viewWillTransitionToSize */
+#if TARGET_OS_TV || __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000
+- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
+{
+    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
+    rotatingOrientation = TRUE;
+    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {}
+                                 completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
+                                     rotatingOrientation = FALSE;
+                                 }];
+}
+#else
+- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
+    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
+    rotatingOrientation = TRUE;
+}
+
+- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
+    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
+    rotatingOrientation = FALSE;
+}
+#endif /* TARGET_OS_TV || __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000 */
+
 - (void)deinitKeyboard
 {
 #if !TARGET_OS_TV
@@ -239,7 +281,7 @@ SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char
 - (void)keyboardWillShow:(NSNotification *)notification
 {
 #if !TARGET_OS_TV
-    CGRect kbrect = [[notification userInfo][UIKeyboardFrameBeginUserInfoKey] CGRectValue];
+    CGRect kbrect = [[notification userInfo][UIKeyboardFrameEndUserInfoKey] CGRectValue];
 
     /* The keyboard rect is in the coordinate space of the screen/window, but we
      * want its height in the coordinate space of the view. */
@@ -251,7 +293,9 @@ SDL_AppleTVControllerUIHintChanged(void *userdata, const char *name, const char
 
 - (void)keyboardWillHide:(NSNotification *)notification
 {
-    SDL_StopTextInput();
+    if (!rotatingOrientation) {
+        SDL_StopTextInput();
+    }
     [self setKeyboardHeight:0];
 }
 
diff --git a/src/video/emscripten/SDL_emscriptenvideo.h b/src/video/uikit/SDL_uikitvulkan.h
similarity index 54%
copy from src/video/emscripten/SDL_emscriptenvideo.h
copy to src/video/uikit/SDL_uikitvulkan.h
index 7618ab6..e5376b7 100644
--- a/src/video/emscripten/SDL_emscriptenvideo.h
+++ b/src/video/uikit/SDL_uikitvulkan.h
@@ -18,37 +18,37 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../../SDL_internal.h"
 
-#ifndef _SDL_emscriptenvideo_h
-#define _SDL_emscriptenvideo_h
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.h.
+ */
 
-#include "../SDL_sysvideo.h"
-#include "../../events/SDL_touch_c.h"
-#include <emscripten/emscripten.h>
-#include <emscripten/html5.h>
+#include "../../SDL_internal.h"
 
-#include <EGL/egl.h>
+#ifndef SDL_uikitvulkan_h_
+#define SDL_uikitvulkan_h_
 
-typedef struct SDL_WindowData
-{
-#if SDL_VIDEO_OPENGL_EGL
-    EGLSurface egl_surface;
-#endif
-    SDL_Window *window;
-    SDL_Surface *surface;
+#include "../SDL_vulkan_internal.h"
+#include "../SDL_sysvideo.h"
 
-    float pixel_ratio;
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_UIKIT
 
-    SDL_bool external_size;
+int UIKit_Vulkan_LoadLibrary(_THIS, const char *path);
+void UIKit_Vulkan_UnloadLibrary(_THIS);
+SDL_bool UIKit_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names);
+SDL_bool UIKit_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface);
 
-    int requested_fullscreen_mode;
-    SDL_bool fullscreen_resize;
+void UIKit_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h);
 
-    SDL_bool finger_touching;  /* for mapping touch events to mice */
-    SDL_FingerID first_finger;
-} SDL_WindowData;
+#endif
 
-#endif /* _SDL_emscriptenvideo_h */
+#endif /* SDL_uikitvulkan_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitvulkan.m b/src/video/uikit/SDL_uikitvulkan.m
new file mode 100644
index 0000000..514a051
--- /dev/null
+++ b/src/video/uikit/SDL_uikitvulkan.m
@@ -0,0 +1,222 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.c.
+ */
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_UIKIT
+
+#include "SDL_uikitvideo.h"
+#include "SDL_uikitwindow.h"
+#include "SDL_assert.h"
+
+#include "SDL_loadso.h"
+#include "SDL_uikitvulkan.h"
+#include "SDL_uikitmetalview.h"
+#include "SDL_syswm.h"
+
+#include <dlfcn.h>
+
+#define DEFAULT_MOLTENVK  "libMoltenVK.dylib"
+/* Since libSDL is static, could use RTLD_SELF. Using RTLD_DEFAULT is future
+ * proofing. */
+#define DEFAULT_HANDLE RTLD_DEFAULT
+
+int UIKit_Vulkan_LoadLibrary(_THIS, const char *path)
+{
+    VkExtensionProperties *extensions = NULL;
+    Uint32 extensionCount = 0;
+    SDL_bool hasSurfaceExtension = SDL_FALSE;
+    SDL_bool hasIOSSurfaceExtension = SDL_FALSE;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
+
+    if (_this->vulkan_config.loader_handle) {
+        return SDL_SetError("MoltenVK/Vulkan already loaded");
+    }
+
+    /* Load the Vulkan loader library */
+    if (!path) {
+        path = SDL_getenv("SDL_VULKAN_LIBRARY");
+    }
+
+    if (!path) {
+        /* MoltenVK framework, currently, v0.17.0, has a static library and is
+         * the recommended way to use the package. There is likely no object to
+         * load. */
+        vkGetInstanceProcAddr =
+        (PFN_vkGetInstanceProcAddr)dlsym(DEFAULT_HANDLE,
+                                         "vkGetInstanceProcAddr");
+    }
+
+    if (vkGetInstanceProcAddr) {
+        _this->vulkan_config.loader_handle = DEFAULT_HANDLE;
+    } else {
+        if (!path) {
+            /* Look for the .dylib packaged with the application instead. */
+            path = DEFAULT_MOLTENVK;
+        }
+
+        _this->vulkan_config.loader_handle = SDL_LoadObject(path);
+        if (!_this->vulkan_config.loader_handle) {
+            return -1;
+        }
+        SDL_strlcpy(_this->vulkan_config.loader_path, path,
+                    SDL_arraysize(_this->vulkan_config.loader_path));
+        vkGetInstanceProcAddr =
+            (PFN_vkGetInstanceProcAddr)SDL_LoadFunction(
+                                    _this->vulkan_config.loader_handle,
+                                    "vkGetInstanceProcAddr");
+    }
+
+    if (!vkGetInstanceProcAddr) {
+        SDL_SetError("Failed to find %s in either executable or %s: %s",
+                     "vkGetInstanceProcAddr",
+                     DEFAULT_MOLTENVK,
+                     (const char *) dlerror());
+        goto fail;
+    }
+
+    _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr;
+    _this->vulkan_config.vkEnumerateInstanceExtensionProperties =
+        (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)(
+            VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties");
+
+    if (!_this->vulkan_config.vkEnumerateInstanceExtensionProperties) {
+        SDL_SetError("No vkEnumerateInstanceExtensionProperties found.");
+        goto fail;
+    }
+
+    extensions = SDL_Vulkan_CreateInstanceExtensionsList(
+        (PFN_vkEnumerateInstanceExtensionProperties)
+            _this->vulkan_config.vkEnumerateInstanceExtensionProperties,
+        &extensionCount);
+
+    if (!extensions) {
+        goto fail;
+    }
+
+    for (Uint32 i = 0; i < extensionCount; i++) {
+        if (SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) {
+            hasSurfaceExtension = SDL_TRUE;
+        } else if (SDL_strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0) {
+            hasIOSSurfaceExtension = SDL_TRUE;
+        }
+    }
+
+    SDL_free(extensions);
+
+    if (!hasSurfaceExtension) {
+        SDL_SetError("Installed MoltenVK/Vulkan doesn't implement the "
+                     VK_KHR_SURFACE_EXTENSION_NAME " extension");
+        goto fail;
+    } else if (!hasIOSSurfaceExtension) {
+        SDL_SetError("Installed MoltenVK/Vulkan doesn't implement the "
+                     VK_MVK_IOS_SURFACE_EXTENSION_NAME "extension");
+        goto fail;
+    }
+
+    return 0;
+
+fail:
+    _this->vulkan_config.loader_handle = NULL;
+    return -1;
+}
+
+void UIKit_Vulkan_UnloadLibrary(_THIS)
+{
+    if (_this->vulkan_config.loader_handle) {
+        if (_this->vulkan_config.loader_handle != DEFAULT_HANDLE) {
+            SDL_UnloadObject(_this->vulkan_config.loader_handle);
+        }
+        _this->vulkan_config.loader_handle = NULL;
+    }
+}
+
+SDL_bool UIKit_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names)
+{
+    static const char *const extensionsForUIKit[] = {
+        VK_KHR_SURFACE_EXTENSION_NAME, VK_MVK_IOS_SURFACE_EXTENSION_NAME
+    };
+    if (!_this->vulkan_config.loader_handle) {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+
+    return SDL_Vulkan_GetInstanceExtensions_Helper(
+            count, names, SDL_arraysize(extensionsForUIKit),
+            extensionsForUIKit);
+}
+
+SDL_bool UIKit_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface)
+{
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr =
+        (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr;
+    PFN_vkCreateIOSSurfaceMVK vkCreateIOSSurfaceMVK =
+        (PFN_vkCreateIOSSurfaceMVK)vkGetInstanceProcAddr(
+                                            (VkInstance)instance,
+                                            "vkCreateIOSSurfaceMVK");
+    VkIOSSurfaceCreateInfoMVK createInfo = {};
+    VkResult result;
+
+    if (!_this->vulkan_config.loader_handle) {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+
+    if (!vkCreateIOSSurfaceMVK) {
+        SDL_SetError(VK_MVK_IOS_SURFACE_EXTENSION_NAME
+                     " extension is not enabled in the Vulkan instance.");
+        return SDL_FALSE;
+    }
+
+    createInfo.sType = VK_STRUCTURE_TYPE_IOS_SURFACE_CREATE_INFO_MVK;
+    createInfo.pNext = NULL;
+    createInfo.flags = 0;
+    createInfo.pView = (__bridge void *)UIKit_Mtl_AddMetalView(window);
+    result = vkCreateIOSSurfaceMVK(instance, &createInfo,
+                                       NULL, surface);
+    if (result != VK_SUCCESS) {
+        SDL_SetError("vkCreateIOSSurfaceMVK failed: %s",
+                     SDL_Vulkan_GetResultString(result));
+        return SDL_FALSE;
+    }
+
+    return SDL_TRUE;
+}
+
+void UIKit_Vulkan_GetDrawableSize(_THIS, SDL_Window *window, int *w, int *h)
+{
+    UIKit_Mtl_GetDrawableSize(window, w, h);
+}
+
+#endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitwindow.h b/src/video/uikit/SDL_uikitwindow.h
index ed08c55..ba1d3a1 100644
--- a/src/video/uikit/SDL_uikitwindow.h
+++ b/src/video/uikit/SDL_uikitwindow.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -18,8 +18,8 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#ifndef _SDL_uikitwindow_h
-#define _SDL_uikitwindow_h
+#ifndef SDL_uikitwindow_h_
+#define SDL_uikitwindow_h_
 
 #include "../SDL_sysvideo.h"
 #import "SDL_uikitvideo.h"
@@ -51,6 +51,6 @@ extern NSUInteger UIKit_GetSupportedOrientations(SDL_Window * window);
 
 @end
 
-#endif /* _SDL_uikitwindow_h */
+#endif /* SDL_uikitwindow_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitwindow.m b/src/video/uikit/SDL_uikitwindow.m
index 35c549b..35c5200 100644
--- a/src/video/uikit/SDL_uikitwindow.m
+++ b/src/video/uikit/SDL_uikitwindow.m
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -107,6 +107,14 @@ static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bo
 
 #if !TARGET_OS_TV
     if (displaydata.uiscreen == [UIScreen mainScreen]) {
+        /* SDL_CreateWindow sets the window w&h to the display's bounds if the
+         * fullscreen flag is set. But the display bounds orientation might not
+         * match what we want, and GetSupportedOrientations call below uses the
+         * window w&h. They're overridden below anyway, so we'll just set them
+         * to the requested size for the purposes of determining orientation. */
+        window->w = window->windowed.w;
+        window->h = window->windowed.h;
+
         NSUInteger orients = UIKit_GetSupportedOrientations(window);
         BOOL supportsLandscape = (orients & UIInterfaceOrientationMaskLandscape) != 0;
         BOOL supportsPortrait = (orients & (UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskPortraitUpsideDown)) != 0;
@@ -360,7 +368,7 @@ UIKit_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
 
             return SDL_TRUE;
         } else {
-            SDL_SetError("Application not compiled with SDL %d.%d\n",
+            SDL_SetError("Application not compiled with SDL %d.%d",
                          SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
             return SDL_FALSE;
         }
diff --git a/src/video/uikit/keyinfotable.h b/src/video/uikit/keyinfotable.h
index 962dbd9..f817cfd 100644
--- a/src/video/uikit/keyinfotable.h
+++ b/src/video/uikit/keyinfotable.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/vivante/SDL_vivanteopengles.c b/src/video/vivante/SDL_vivanteopengles.c
index 687cc6a..7341a48 100644
--- a/src/video/vivante/SDL_vivanteopengles.c
+++ b/src/video/vivante/SDL_vivanteopengles.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -34,7 +34,7 @@ VIVANTE_GLES_LoadLibrary(_THIS, const char *path)
 
     displaydata = SDL_GetDisplayDriverData(0);
 
-    return SDL_EGL_LoadLibrary(_this, path, displaydata->native_display);
+    return SDL_EGL_LoadLibrary(_this, path, displaydata->native_display, 0);
 }
 
 SDL_EGL_CreateContext_impl(VIVANTE)
diff --git a/src/video/vivante/SDL_vivanteopengles.h b/src/video/vivante/SDL_vivanteopengles.h
index f47bf77..49163b5 100644
--- a/src/video/vivante/SDL_vivanteopengles.h
+++ b/src/video/vivante/SDL_vivanteopengles.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_vivanteopengles_h
-#define _SDL_vivanteopengles_h
+#ifndef SDL_vivanteopengles_h_
+#define SDL_vivanteopengles_h_
 
 #if SDL_VIDEO_DRIVER_VIVANTE && SDL_VIDEO_OPENGL_EGL
 
@@ -38,11 +38,11 @@
 
 extern int VIVANTE_GLES_LoadLibrary(_THIS, const char *path);
 extern SDL_GLContext VIVANTE_GLES_CreateContext(_THIS, SDL_Window * window);
-extern void VIVANTE_GLES_SwapWindow(_THIS, SDL_Window * window);
+extern int VIVANTE_GLES_SwapWindow(_THIS, SDL_Window * window);
 extern int VIVANTE_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 
 #endif /* SDL_VIDEO_DRIVER_VIVANTE && SDL_VIDEO_OPENGL_EGL */
 
-#endif /* _SDL_vivanteopengles_h */
+#endif /* SDL_vivanteopengles_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/vivante/SDL_vivanteplatform.c b/src/video/vivante/SDL_vivanteplatform.c
index 7623341..d1b46a4 100644
--- a/src/video/vivante/SDL_vivanteplatform.c
+++ b/src/video/vivante/SDL_vivanteplatform.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/vivante/SDL_vivanteplatform.h b/src/video/vivante/SDL_vivanteplatform.h
index 6e11cce..23cb406 100644
--- a/src/video/vivante/SDL_vivanteplatform.h
+++ b/src/video/vivante/SDL_vivanteplatform.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_vivanteplatform_h
-#define _SDL_vivanteplatform_h
+#ifndef SDL_vivanteplatform_h_
+#define SDL_vivanteplatform_h_
 
 #if SDL_VIDEO_DRIVER_VIVANTE
 
@@ -40,6 +40,6 @@ extern void VIVANTE_CleanupPlatform(_THIS);
 
 #endif /* SDL_VIDEO_DRIVER_VIVANTE */
 
-#endif /* _SDL_vivanteplatform_h */
+#endif /* SDL_vivanteplatform_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/vivante/SDL_vivantevideo.c b/src/video/vivante/SDL_vivantevideo.c
index 0372de5..79b36c2 100644
--- a/src/video/vivante/SDL_vivantevideo.c
+++ b/src/video/vivante/SDL_vivantevideo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -88,7 +88,7 @@ VIVANTE_Create()
     device->VideoQuit = VIVANTE_VideoQuit;
     device->GetDisplayModes = VIVANTE_GetDisplayModes;
     device->SetDisplayMode = VIVANTE_SetDisplayMode;
-    device->CreateWindow = VIVANTE_CreateWindow;
+    device->CreateSDLWindow = VIVANTE_CreateWindow;
     device->SetWindowTitle = VIVANTE_SetWindowTitle;
     device->SetWindowPosition = VIVANTE_SetWindowPosition;
     device->SetWindowSize = VIVANTE_SetWindowSize;
@@ -376,7 +376,7 @@ VIVANTE_GetWindowWMInfo(_THIS, SDL_Window * window, struct SDL_SysWMinfo *info)
         info->info.vivante.window = data->native_window;
         return SDL_TRUE;
     } else {
-        SDL_SetError("Application not compiled with SDL %d.%d\n",
+        SDL_SetError("Application not compiled with SDL %d.%d",
                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
diff --git a/src/video/vivante/SDL_vivantevideo.h b/src/video/vivante/SDL_vivantevideo.h
index b99c733..53c84da 100644
--- a/src/video/vivante/SDL_vivantevideo.h
+++ b/src/video/vivante/SDL_vivantevideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_vivantevideo_h
-#define _SDL_vivantevideo_h
+#ifndef SDL_vivantevideo_h_
+#define SDL_vivantevideo_h_
 
 #include "../../SDL_internal.h"
 #include "../SDL_sysvideo.h"
@@ -86,6 +86,6 @@ SDL_bool VIVANTE_GetWindowWMInfo(_THIS, SDL_Window * window,
 /* Event functions */
 void VIVANTE_PumpEvents(_THIS);
 
-#endif /* _SDL_vivantevideo_h */
+#endif /* SDL_vivantevideo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/wayland/SDL_waylandclipboard.c b/src/video/wayland/SDL_waylandclipboard.c
new file mode 100644
index 0000000..b623328
--- /dev/null
+++ b/src/video/wayland/SDL_waylandclipboard.c
@@ -0,0 +1,123 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_DRIVER_WAYLAND
+
+#include "SDL_waylanddatamanager.h"
+#include "SDL_waylandevents_c.h"
+
+int
+Wayland_SetClipboardText(_THIS, const char *text)
+{
+    SDL_VideoData *video_data = NULL;
+    SDL_WaylandDataDevice *data_device = NULL;
+    
+    int status = 0;
+ 
+    if (_this == NULL || _this->driverdata == NULL) {
+        status = SDL_SetError("Video driver uninitialized");
+    } else {
+        video_data = _this->driverdata;
+        /* TODO: Support more than one seat */ 
+        data_device = Wayland_get_data_device(video_data->input);
+        if (text[0] != '\0') {
+            SDL_WaylandDataSource* source = Wayland_data_source_create(_this);
+            Wayland_data_source_add_data(source, TEXT_MIME, text,
+                                         strlen(text) + 1); 
+
+            status = Wayland_data_device_set_selection(data_device, source);
+            if (status != 0) {
+                Wayland_data_source_destroy(source);
+            }
+        } else {
+            status = Wayland_data_device_clear_selection(data_device);
+        }
+    }
+
+    return status;
+}
+
+char *
+Wayland_GetClipboardText(_THIS)
+{
+    SDL_VideoData *video_data = NULL;
+    SDL_WaylandDataDevice *data_device = NULL;
+
+    char *text = NULL;
+
+    void *buffer = NULL;
+    size_t length = 0;
+ 
+    if (_this == NULL || _this->driverdata == NULL) {
+        SDL_SetError("Video driver uninitialized");
+    } else {
+        video_data = _this->driverdata;
+        /* TODO: Support more than one seat */ 
+        data_device = Wayland_get_data_device(video_data->input);
+        if (data_device->selection_offer != NULL) {
+            buffer = Wayland_data_offer_receive(data_device->selection_offer,
+                                                &length, TEXT_MIME, SDL_TRUE);
+            if (length > 0) {
+                text = (char*) buffer;
+            } 
+        } else if (data_device->selection_source != NULL) {
+            buffer = Wayland_data_source_get_data(data_device->selection_source,
+                                                  &length, TEXT_MIME, SDL_TRUE);
+            if (length > 0) {
+                text = (char*) buffer;
+            } 
+        }
+    }
+
+    if (text == NULL) {
+        text = SDL_strdup("");
+    }
+
+    return text;
+}
+
+SDL_bool
+Wayland_HasClipboardText(_THIS)
+{
+    SDL_VideoData *video_data = NULL;
+    SDL_WaylandDataDevice *data_device = NULL;
+
+    SDL_bool result = SDL_FALSE;    
+    if (_this == NULL || _this->driverdata == NULL) {
+        SDL_SetError("Video driver uninitialized");
+    } else {
+        video_data = _this->driverdata;
+        data_device = Wayland_get_data_device(video_data->input);
+        if (data_device != NULL && Wayland_data_offer_has_mime(
+                data_device->selection_offer, TEXT_MIME)) {
+            result = SDL_TRUE;
+        } else if(data_device != NULL && Wayland_data_source_has_mime(
+                data_device->selection_source, TEXT_MIME)) {
+            result = SDL_TRUE;
+        }
+    }
+    return result;
+}
+
+#endif /* SDL_VIDEO_DRIVER_WAYLAND */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/power/uikit/SDL_syspower.h b/src/video/wayland/SDL_waylandclipboard.h
similarity index 74%
copy from src/power/uikit/SDL_syspower.h
copy to src/video/wayland/SDL_waylandclipboard.h
index 4cfa5c9..8bd7b5c 100644
--- a/src/power/uikit/SDL_syspower.h
+++ b/src/video/wayland/SDL_waylandclipboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,13 +20,13 @@
 */
 #include "../../SDL_internal.h"
 
-#if SDL_POWER_UIKIT
+#ifndef SDL_waylandclipboard_h_
+#define SDL_waylandclipboard_h_
 
-#include "SDL_power.h"
+extern int Wayland_SetClipboardText(_THIS, const char *text);
+extern char *Wayland_GetClipboardText(_THIS);
+extern SDL_bool Wayland_HasClipboardText(_THIS);
 
-void SDL_UIKit_UpdateBatteryMonitoring(void);
-SDL_bool SDL_GetPowerInfo_UIKit(SDL_PowerState * state, int *seconds, int *percent);
-
-#endif /* SDL_POWER_UIKIT */
+#endif /* SDL_waylandclipboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/wayland/SDL_waylanddatamanager.c b/src/video/wayland/SDL_waylanddatamanager.c
new file mode 100644
index 0000000..e10d291
--- /dev/null
+++ b/src/video/wayland/SDL_waylanddatamanager.c
@@ -0,0 +1,468 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_DRIVER_WAYLAND
+
+#include <fcntl.h>
+#include <unistd.h>
+#include <limits.h>
+#include <signal.h>
+
+#include "SDL_stdinc.h"
+#include "SDL_assert.h"
+#include "../../core/unix/SDL_poll.h"
+
+#include "SDL_waylandvideo.h"
+#include "SDL_waylanddatamanager.h"
+
+#include "SDL_waylanddyn.h"
+
+static ssize_t
+write_pipe(int fd, const void* buffer, size_t total_length, size_t *pos)
+{
+    int ready = 0;
+    ssize_t bytes_written = 0;
+    ssize_t length = total_length - *pos;
+
+    sigset_t sig_set;
+    sigset_t old_sig_set;
+    struct timespec zerotime = {0};
+
+    ready = SDL_IOReady(fd, SDL_TRUE, 1 * 1000);
+
+    sigemptyset(&sig_set);
+    sigaddset(&sig_set, SIGPIPE);  
+
+    pthread_sigmask(SIG_BLOCK, &sig_set, &old_sig_set); 
+
+    if (ready == 0) {
+        bytes_written = SDL_SetError("Pipe timeout");
+    } else if (ready < 0) {
+        bytes_written = SDL_SetError("Pipe select error");
+    } else {
+        if (length > 0) {
+            bytes_written = write(fd, buffer + *pos, SDL_min(length, PIPE_BUF));
+        }
+
+        if (bytes_written > 0) {
+            *pos += bytes_written;
+        }
+    }
+
+    sigtimedwait(&sig_set, 0, &zerotime);
+    pthread_sigmask(SIG_SETMASK, &old_sig_set, NULL);
+
+    return bytes_written;
+}
+
+static ssize_t
+read_pipe(int fd, void** buffer, size_t* total_length, SDL_bool null_terminate)
+{
+    int ready = 0;
+    void* output_buffer = NULL;
+    char temp[PIPE_BUF];
+    size_t new_buffer_length = 0;
+    ssize_t bytes_read = 0;
+    size_t pos = 0;
+
+    ready = SDL_IOReady(fd, SDL_FALSE, 1 * 1000);
+  
+    if (ready == 0) {
+        bytes_read = SDL_SetError("Pipe timeout");
+    } else if (ready < 0) {
+        bytes_read = SDL_SetError("Pipe select error");
+    } else {
+        bytes_read = read(fd, temp, sizeof(temp));
+    }
+
+    if (bytes_read > 0) {
+        pos = *total_length;
+        *total_length += bytes_read;
+
+        if (null_terminate == SDL_TRUE) {
+            new_buffer_length = *total_length + 1;
+        } else {
+            new_buffer_length = *total_length;
+        }
+
+        if (*buffer == NULL) {
+            output_buffer = SDL_malloc(new_buffer_length);
+        } else {
+            output_buffer = SDL_realloc(*buffer, new_buffer_length);
+        }           
+        
+        if (output_buffer == NULL) {
+            bytes_read = SDL_OutOfMemory();
+        } else {
+            SDL_memcpy(output_buffer + pos, temp, bytes_read);
+
+            if (null_terminate == SDL_TRUE) {
+                SDL_memset(output_buffer + (new_buffer_length - 1), 0, 1);
+            }
+            
+            *buffer = output_buffer;
+        }
+    }
+
+    return bytes_read;
+}
+
+#define MIME_LIST_SIZE 4
+
+static const char* mime_conversion_list[MIME_LIST_SIZE][2] = {
+    {"text/plain", TEXT_MIME},
+    {"TEXT", TEXT_MIME},
+    {"UTF8_STRING", TEXT_MIME},
+    {"STRING", TEXT_MIME}
+};
+
+const char*
+Wayland_convert_mime_type(const char *mime_type)
+{
+    const char *found = mime_type;
+
+    size_t index = 0;
+
+    for (index = 0; index < MIME_LIST_SIZE; ++index) {
+        if (strcmp(mime_conversion_list[index][0], mime_type) == 0) {
+            found = mime_conversion_list[index][1];
+            break;
+        }
+    }
+    
+    return found;
+}
+
+static SDL_MimeDataList*
+mime_data_list_find(struct wl_list* list, 
+                    const char* mime_type)
+{
+    SDL_MimeDataList *found = NULL;
+
+    SDL_MimeDataList *mime_list = NULL;
+    wl_list_for_each(mime_list, list, link) { 
+        if (strcmp(mime_list->mime_type, mime_type) == 0) {
+            found = mime_list;
+            break;
+        }
+    }    
+    return found;
+}
+
+static int
+mime_data_list_add(struct wl_list* list, 
+                   const char* mime_type,
+                   void* buffer, size_t length)
+{
+    int status = 0;
+    size_t mime_type_length = 0;
+
+    SDL_MimeDataList *mime_data = NULL;
+
+    mime_data = mime_data_list_find(list, mime_type);
+
+    if (mime_data == NULL) {
+        mime_data = SDL_calloc(1, sizeof(*mime_data));
+        if (mime_data == NULL) {
+            status = SDL_OutOfMemory();
+        } else {
+            WAYLAND_wl_list_insert(list, &(mime_data->link));
+
+            mime_type_length = strlen(mime_type) + 1;
+            mime_data->mime_type = SDL_malloc(mime_type_length);
+            if (mime_data->mime_type == NULL) {
+                status = SDL_OutOfMemory();
+            } else {
+                SDL_memcpy(mime_data->mime_type, mime_type, mime_type_length);
+            }
+        }
+    }
+    
+    if (mime_data != NULL && buffer != NULL && length > 0) {
+        if (mime_data->data != NULL) {
+            SDL_free(mime_data->data);
+        }
+        mime_data->data = buffer;
+        mime_data->length = length;
+    }
+
+    return status;
+}
+
+static void
+mime_data_list_free(struct wl_list *list)
+{
+    SDL_MimeDataList *mime_data = NULL; 
+    SDL_MimeDataList *next = NULL;
+
+    wl_list_for_each_safe(mime_data, next, list, link) {
+        if (mime_data->data != NULL) {
+            SDL_free(mime_data->data);
+        }        
+        if (mime_data->mime_type != NULL) {
+            SDL_free(mime_data->mime_type);
+        }
+        SDL_free(mime_data);       
+    } 
+}
+
+ssize_t 
+Wayland_data_source_send(SDL_WaylandDataSource *source,  
+                         const char *mime_type, int fd)
+{
+    size_t written_bytes = 0;
+    ssize_t status = 0;
+    SDL_MimeDataList *mime_data = NULL;
+ 
+    mime_type = Wayland_convert_mime_type(mime_type);
+    mime_data = mime_data_list_find(&source->mimes,
+                                                      mime_type);
+
+    if (mime_data == NULL || mime_data->data == NULL) {
+        status = SDL_SetError("Invalid mime type");
+        close(fd);
+    } else {
+        while (write_pipe(fd, mime_data->data, mime_data->length,
+                          &written_bytes) > 0);
+        close(fd);
+        status = written_bytes;
+    }
+    return status;
+}
+
+int Wayland_data_source_add_data(SDL_WaylandDataSource *source,
+                                 const char *mime_type,
+                                 const void *buffer,
+                                 size_t length) 
+{
+    int status = 0;
+    if (length > 0) {
+        void *internal_buffer = SDL_malloc(length);
+        if (internal_buffer == NULL) {
+            status = SDL_OutOfMemory();
+        } else {
+            SDL_memcpy(internal_buffer, buffer, length);
+            status = mime_data_list_add(&source->mimes, mime_type, 
+                                        internal_buffer, length);
+        }
+    }
+    return status;
+}
+
+SDL_bool 
+Wayland_data_source_has_mime(SDL_WaylandDataSource *source,
+                             const char *mime_type)
+{
+    SDL_bool found = SDL_FALSE;
+
+    if (source != NULL) {
+        found = mime_data_list_find(&source->mimes, mime_type) != NULL;
+    }
+    return found;
+}
+
+void* 
+Wayland_data_source_get_data(SDL_WaylandDataSource *source,
+                             size_t *length, const char* mime_type,
+                             SDL_bool null_terminate)
+{
+    SDL_MimeDataList *mime_data = NULL;
+    void *buffer = NULL;
+    *length = 0;
+
+    if (source == NULL) {
+        SDL_SetError("Invalid data source");
+    } else {
+        mime_data = mime_data_list_find(&source->mimes, mime_type);
+        if (mime_data != NULL && mime_data->length > 0) {
+            buffer = SDL_malloc(mime_data->length);
+            if (buffer == NULL) {
+                *length = SDL_OutOfMemory();
+            } else {
+                *length = mime_data->length;
+                SDL_memcpy(buffer, mime_data->data, mime_data->length);
+            }
+       }
+    }
+
+    return buffer;
+}
+
+void
+Wayland_data_source_destroy(SDL_WaylandDataSource *source)
+{
+    if (source != NULL) {
+        wl_data_source_destroy(source->source);
+        mime_data_list_free(&source->mimes);
+        SDL_free(source);
+    }
+}
+
+void* 
+Wayland_data_offer_receive(SDL_WaylandDataOffer *offer,
+                           size_t *length, const char* mime_type,
+                           SDL_bool null_terminate)
+{
+    SDL_WaylandDataDevice *data_device = NULL;
+ 
+    int pipefd[2];
+    void *buffer = NULL;
+    *length = 0;
+
+    if (offer == NULL) {
+        SDL_SetError("Invalid data offer");
+    } else if ((data_device = offer->data_device) == NULL) {
+        SDL_SetError("Data device not initialized");
+    } else if (pipe2(pipefd, O_CLOEXEC|O_NONBLOCK) == -1) {
+        SDL_SetError("Could not read pipe");
+    } else {
+        wl_data_offer_receive(offer->offer, mime_type, pipefd[1]);
+
+        /* TODO: Needs pump and flush? */
+        WAYLAND_wl_display_flush(data_device->video_data->display);
+
+        close(pipefd[1]);
+        
+        while (read_pipe(pipefd[0], &buffer, length, null_terminate) > 0);
+        close(pipefd[0]);
+    }
+    return buffer;
+}
+
+int 
+Wayland_data_offer_add_mime(SDL_WaylandDataOffer *offer,
+                            const char* mime_type)
+{
+    return mime_data_list_add(&offer->mimes, mime_type, NULL, 0);
+}
+
+
+SDL_bool 
+Wayland_data_offer_has_mime(SDL_WaylandDataOffer *offer,
+                            const char *mime_type)
+{
+    SDL_bool found = SDL_FALSE;
+
+    if (offer != NULL) {
+        found = mime_data_list_find(&offer->mimes, mime_type) != NULL;
+    }
+    return found;
+}
+
+void
+Wayland_data_offer_destroy(SDL_WaylandDataOffer *offer)
+{
+    if (offer != NULL) {
+        wl_data_offer_destroy(offer->offer);
+        mime_data_list_free(&offer->mimes);
+        SDL_free(offer);
+    }
+}
+
+int
+Wayland_data_device_clear_selection(SDL_WaylandDataDevice *data_device)
+{
+    int status = 0;
+
+    if (data_device == NULL || data_device->data_device == NULL) {
+        status = SDL_SetError("Invalid Data Device");
+    } else if (data_device->selection_source != 0) {
+        wl_data_device_set_selection(data_device->data_device, NULL, 0);
+        data_device->selection_source = NULL;
+    }
+    return status;
+}
+
+int
+Wayland_data_device_set_selection(SDL_WaylandDataDevice *data_device,
+                                  SDL_WaylandDataSource *source)
+{
+    int status = 0;
+    size_t num_offers = 0;
+    size_t index = 0;
+
+    if (data_device == NULL) {
+        status = SDL_SetError("Invalid Data Device");
+    } else if (source == NULL) {
+        status = SDL_SetError("Invalid source");
+    } else {
+        SDL_MimeDataList *mime_data = NULL;
+
+        wl_list_for_each(mime_data, &(source->mimes), link) {
+            wl_data_source_offer(source->source,
+                                 mime_data->mime_type); 
+
+            /* TODO - Improve system for multiple mime types to same data */
+            for (index = 0; index < MIME_LIST_SIZE; ++index) {
+                if (strcmp(mime_conversion_list[index][1], mime_data->mime_type) == 0) {
+                    wl_data_source_offer(source->source,
+                                         mime_conversion_list[index][0]);
+               }
+            }
+            /* */
+ 
+            ++num_offers;
+        } 
+
+        if (num_offers == 0) {
+            Wayland_data_device_clear_selection(data_device);
+            status = SDL_SetError("No mime data");
+        } else {
+            /* Only set if there is a valid serial if not set it later */
+            if (data_device->selection_serial != 0) {
+                wl_data_device_set_selection(data_device->data_device,
+                                             source->source,
+                                             data_device->selection_serial); 
+            }
+            data_device->selection_source = source;
+        }
+    }
+
+    return status;
+}
+
+int
+Wayland_data_device_set_serial(SDL_WaylandDataDevice *data_device,
+                               uint32_t serial)
+{
+    int status = -1;
+    if (data_device != NULL) {
+        status = 0;
+
+        /* If there was no serial and there is a pending selection set it now. */
+        if (data_device->selection_serial == 0
+            && data_device->selection_source != NULL) {
+            wl_data_device_set_selection(data_device->data_device,
+                                         data_device->selection_source->source,
+                                         serial); 
+        }
+
+        data_device->selection_serial = serial;
+    }
+
+    return status; 
+}
+
+#endif /* SDL_VIDEO_DRIVER_WAYLAND */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/wayland/SDL_waylanddatamanager.h b/src/video/wayland/SDL_waylanddatamanager.h
new file mode 100644
index 0000000..a40ecaf
--- /dev/null
+++ b/src/video/wayland/SDL_waylanddatamanager.h
@@ -0,0 +1,103 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include "../../SDL_internal.h"
+
+#ifndef SDL_waylanddatamanager_h_
+#define SDL_waylanddatamanager_h_
+
+#include "SDL_waylandvideo.h"
+#include "SDL_waylandwindow.h"
+
+#define TEXT_MIME "text/plain;charset=utf-8"
+#define FILE_MIME "text/uri-list"
+
+typedef struct {
+    char *mime_type;
+    void *data;
+    size_t length;
+    struct wl_list link;
+} SDL_MimeDataList;
+
+typedef struct {
+    struct wl_data_source *source;
+    struct wl_list mimes;
+} SDL_WaylandDataSource;
+
+typedef struct {
+    struct wl_data_offer *offer;
+    struct wl_list mimes;
+    void *data_device;
+} SDL_WaylandDataOffer;
+
+typedef struct {
+    struct wl_data_device *data_device;
+    SDL_VideoData *video_data;
+
+    /* Drag and Drop */
+    uint32_t drag_serial;
+    SDL_WaylandDataOffer *drag_offer;
+    SDL_WaylandDataOffer *selection_offer;
+
+    /* Clipboard */
+    uint32_t selection_serial;
+    SDL_WaylandDataSource *selection_source;
+} SDL_WaylandDataDevice;
+
+extern const char* Wayland_convert_mime_type(const char *mime_type);
+
+/* Wayland Data Source - (Sending) */
+extern SDL_WaylandDataSource* Wayland_data_source_create(_THIS);
+extern ssize_t Wayland_data_source_send(SDL_WaylandDataSource *source, 
+                                        const char *mime_type, int fd);
+extern int Wayland_data_source_add_data(SDL_WaylandDataSource *source,
+                                        const char *mime_type, 
+                                        const void *buffer, 
+                                        size_t length);
+extern SDL_bool Wayland_data_source_has_mime(SDL_WaylandDataSource *source,
+                                             const char *mime_type);
+extern void* Wayland_data_source_get_data(SDL_WaylandDataSource *source,
+                                          size_t *length,
+                                          const char *mime_type,
+                                          SDL_bool null_terminate);
+extern void Wayland_data_source_destroy(SDL_WaylandDataSource *source);
+
+/* Wayland Data Offer - (Receiving) */
+extern void* Wayland_data_offer_receive(SDL_WaylandDataOffer *offer,
+                                        size_t *length,
+                                        const char *mime_type,
+                                        SDL_bool null_terminate);
+extern SDL_bool Wayland_data_offer_has_mime(SDL_WaylandDataOffer *offer,
+                                            const char *mime_type);
+extern int Wayland_data_offer_add_mime(SDL_WaylandDataOffer *offer,
+                                       const char *mime_type);
+extern void Wayland_data_offer_destroy(SDL_WaylandDataOffer *offer);
+
+/* Clipboard */
+extern int Wayland_data_device_clear_selection(SDL_WaylandDataDevice *device);
+extern int Wayland_data_device_set_selection(SDL_WaylandDataDevice *device,
+                                             SDL_WaylandDataSource *source);
+extern int Wayland_data_device_set_serial(SDL_WaylandDataDevice *device,
+                                          uint32_t serial);
+#endif /* SDL_waylanddatamanager_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
+
diff --git a/src/video/wayland/SDL_waylanddyn.c b/src/video/wayland/SDL_waylanddyn.c
index 14674fb..4a46139 100644
--- a/src/video/wayland/SDL_waylanddyn.c
+++ b/src/video/wayland/SDL_waylanddyn.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/wayland/SDL_waylanddyn.h b/src/video/wayland/SDL_waylanddyn.h
index f1f6525..fa45f92 100644
--- a/src/video/wayland/SDL_waylanddyn.h
+++ b/src/video/wayland/SDL_waylanddyn.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_waylanddyn_h
-#define _SDL_waylanddyn_h
+#ifndef SDL_waylanddyn_h_
+#define SDL_waylanddyn_h_
 
 #include "../../SDL_internal.h"
 
@@ -91,6 +91,10 @@ void SDL_WAYLAND_UnloadSymbols(void);
 #define wl_output_interface (*WAYLAND_wl_output_interface)
 #define wl_shell_interface (*WAYLAND_wl_shell_interface)
 #define wl_shm_interface (*WAYLAND_wl_shm_interface)
+#define wl_data_device_interface (*WAYLAND_wl_data_device_interface)
+#define wl_data_offer_interface (*WAYLAND_wl_data_offer_interface)
+#define wl_data_source_interface (*WAYLAND_wl_data_source_interface)
+#define wl_data_device_manager_interface (*WAYLAND_wl_data_device_manager_interface)
 
 #endif /* SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC */
 
@@ -98,6 +102,6 @@ void SDL_WAYLAND_UnloadSymbols(void);
 #include "wayland-client-protocol.h"
 #include "wayland-egl.h"
 
-#endif /* !defined _SDL_waylanddyn_h */
+#endif /* SDL_waylanddyn_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/wayland/SDL_waylandevents.c b/src/video/wayland/SDL_waylandevents.c
index 2443aef..961325f 100644
--- a/src/video/wayland/SDL_waylandevents.c
+++ b/src/video/wayland/SDL_waylandevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,6 +27,7 @@
 #include "SDL_assert.h"
 #include "SDL_log.h"
 
+#include "../../core/unix/SDL_poll.h"
 #include "../../events/SDL_sysevents.h"
 #include "../../events/SDL_events_c.h"
 #include "../../events/scancodes_xfree86.h"
@@ -51,7 +52,9 @@ struct SDL_WaylandInput {
     SDL_VideoData *display;
     struct wl_seat *seat;
     struct wl_pointer *pointer;
+    struct wl_touch *touch;
     struct wl_keyboard *keyboard;
+    SDL_WaylandDataDevice *data_device;
     struct zwp_relative_pointer_v1 *relative_pointer;
     SDL_WindowData *pointer_focus;
     SDL_WindowData *keyboard_focus;
@@ -69,20 +72,117 @@ struct SDL_WaylandInput {
     } xkb;
 };
 
+struct SDL_WaylandTouchPoint {
+    SDL_TouchID id;
+    float x;
+    float y;
+    struct wl_surface* surface;
+
+    struct SDL_WaylandTouchPoint* prev;
+    struct SDL_WaylandTouchPoint* next;
+};
+
+struct SDL_WaylandTouchPointList {
+    struct SDL_WaylandTouchPoint* head;
+    struct SDL_WaylandTouchPoint* tail;
+};
+
+static struct SDL_WaylandTouchPointList touch_points = {NULL, NULL};
+
+static void
+touch_add(SDL_TouchID id, float x, float y, struct wl_surface *surface)
+{
+    struct SDL_WaylandTouchPoint* tp = SDL_malloc(sizeof(struct SDL_WaylandTouchPoint));
+
+    tp->id = id;
+    tp->x = x;
+    tp->y = y;
+    tp->surface = surface;
+
+    if (touch_points.tail) {
+        touch_points.tail->next = tp;
+        tp->prev = touch_points.tail;
+    } else {
+        touch_points.head = tp;
+        tp->prev = NULL;
+    }
+
+    touch_points.tail = tp;
+    tp->next = NULL;
+}
+
+static void
+touch_update(SDL_TouchID id, float x, float y)
+{
+    struct SDL_WaylandTouchPoint* tp = touch_points.head;
+
+    while (tp) {
+        if (tp->id == id) {
+            tp->x = x;
+            tp->y = y;
+        }
+
+        tp = tp->next;
+    }
+}
+
+static void
+touch_del(SDL_TouchID id, float* x, float* y)
+{
+    struct SDL_WaylandTouchPoint* tp = touch_points.head;
+
+    while (tp) {
+        if (tp->id == id) {
+            *x = tp->x;
+            *y = tp->y;
+
+            if (tp->prev) {
+                tp->prev->next = tp->next;
+            } else {
+                touch_points.head = tp->next;
+            }
+
+            if (tp->next) {
+                tp->next->prev = tp->prev;
+            } else {
+                touch_points.tail = tp->prev;
+            }
+
+            SDL_free(tp);
+        }
+
+        tp = tp->next;
+    }
+}
+
+static struct wl_surface*
+touch_surface(SDL_TouchID id)
+{
+    struct SDL_WaylandTouchPoint* tp = touch_points.head;
+
+    while (tp) {
+        if (tp->id == id) {
+            return tp->surface;
+        }
+
+        tp = tp->next;
+    }
+
+    return NULL;
+}
+
 void
 Wayland_PumpEvents(_THIS)
 {
     SDL_VideoData *d = _this->driverdata;
-    struct pollfd pfd[1];
 
-    pfd[0].fd = WAYLAND_wl_display_get_fd(d->display);
-    pfd[0].events = POLLIN;
-    poll(pfd, 1, 0);
-
-    if (pfd[0].revents & POLLIN)
+    if (SDL_IOReady(WAYLAND_wl_display_get_fd(d->display), SDL_FALSE, 0)) {
         WAYLAND_wl_display_dispatch(d->display);
+    }
     else
+    {
         WAYLAND_wl_display_dispatch_pending(d->display);
+    }
 }
 
 static void
@@ -97,7 +197,7 @@ pointer_handle_enter(void *data, struct wl_pointer *pointer,
         /* enter event for a window we've just destroyed */
         return;
     }
-    
+
     /* This handler will be called twice in Wayland 1.4
      * Once for the window surface which has valid user data
      * and again for the mouse cursor surface which does not have valid user data
@@ -105,7 +205,7 @@ pointer_handle_enter(void *data, struct wl_pointer *pointer,
      */
 
     window = (SDL_WindowData *)wl_surface_get_user_data(surface);
-    
+
     if (window) {
         input->pointer_focus = window;
         SDL_SetMouseFocus(window->sdlwindow);
@@ -184,7 +284,7 @@ pointer_handle_button_common(struct SDL_WaylandInput *input, uint32_t serial,
     SDL_WindowData *window = input->pointer_focus;
     enum wl_pointer_button_state state = state_w;
     uint32_t sdl_button;
-    
+
     if  (input->pointer_focus) {
         switch (button) {
             case BTN_LEFT:
@@ -208,6 +308,8 @@ pointer_handle_button_common(struct SDL_WaylandInput *input, uint32_t serial,
             default:
                 return;
         }
+            
+        Wayland_data_device_set_serial(input->data_device, serial); 
 
         SDL_SendMouseButton(window->sdlwindow, 0,
                             state ? SDL_PRESSED : SDL_RELEASED, sdl_button);
@@ -229,16 +331,16 @@ pointer_handle_axis_common(struct SDL_WaylandInput *input,
 {
     SDL_WindowData *window = input->pointer_focus;
     enum wl_pointer_axis a = axis;
-    int x, y;
+    float x, y;
 
     if (input->pointer_focus) {
         switch (a) {
             case WL_POINTER_AXIS_VERTICAL_SCROLL:
                 x = 0;
-                y = wl_fixed_to_int(value);
+                y = (float)wl_fixed_to_double(value);
                 break;
             case WL_POINTER_AXIS_HORIZONTAL_SCROLL:
-                x = wl_fixed_to_int(value);
+                x = (float)wl_fixed_to_double(value);
                 y = 0;
                 break;
             default:
@@ -267,6 +369,69 @@ static const struct wl_pointer_listener pointer_listener = {
 };
 
 static void
+touch_handler_down(void *data, struct wl_touch *touch, unsigned int serial,
+                   unsigned int timestamp, struct wl_surface *surface,
+                   int id, wl_fixed_t fx, wl_fixed_t fy)
+{
+    float x, y;
+    SDL_WindowData* window;
+
+    window = (SDL_WindowData *)wl_surface_get_user_data(surface);
+
+    x = wl_fixed_to_double(fx) / window->sdlwindow->w;
+    y = wl_fixed_to_double(fy) / window->sdlwindow->h;
+
+    touch_add(id, x, y, surface);
+    SDL_SendTouch(1, (SDL_FingerID)id, SDL_TRUE, x, y, 1.0f);
+}
+
+static void
+touch_handler_up(void *data, struct wl_touch *touch, unsigned int serial,
+                 unsigned int timestamp, int id)
+{
+    float x = 0, y = 0;
+
+    touch_del(id, &x, &y);
+    SDL_SendTouch(1, (SDL_FingerID)id, SDL_FALSE, x, y, 0.0f);
+}
+
+static void
+touch_handler_motion(void *data, struct wl_touch *touch, unsigned int timestamp,
+                     int id, wl_fixed_t fx, wl_fixed_t fy)
+{
+    float x, y;
+    SDL_WindowData* window;
+
+    window = (SDL_WindowData *)wl_surface_get_user_data(touch_surface(id));
+
+    x = wl_fixed_to_double(fx) / window->sdlwindow->w;
+    y = wl_fixed_to_double(fy) / window->sdlwindow->h;
+
+    touch_update(id, x, y);
+    SDL_SendTouchMotion(1, (SDL_FingerID)id, x, y, 1.0f);
+}
+
+static void
+touch_handler_frame(void *data, struct wl_touch *touch)
+{
+
+}
+
+static void
+touch_handler_cancel(void *data, struct wl_touch *touch)
+{
+
+}
+
+static const struct wl_touch_listener touch_listener = {
+    touch_handler_down,
+    touch_handler_up,
+    touch_handler_motion,
+    touch_handler_frame,
+    touch_handler_cancel
+};
+
+static void
 keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard,
                        uint32_t format, int fd, uint32_t size)
 {
@@ -322,7 +487,7 @@ keyboard_handle_enter(void *data, struct wl_keyboard *keyboard,
         /* enter event for a window we've just destroyed */
         return;
     }
- 
+
     window = wl_surface_get_user_data(surface);
 
     if (window) {
@@ -373,6 +538,9 @@ keyboard_handle_key(void *data, struct wl_keyboard *keyboard,
 
         if (size > 0) {
             text[size] = 0;
+
+            Wayland_data_device_set_serial(input->data_device, serial);
+
             SDL_SendKeyboardText(text);
         }
     }
@@ -415,6 +583,18 @@ seat_handle_capabilities(void *data, struct wl_seat *seat,
         input->pointer = NULL;
     }
 
+    if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !input->touch) {
+        SDL_AddTouch(1, "wayland_touch");
+        input->touch = wl_seat_get_touch(seat);
+        wl_touch_set_user_data(input->touch, input);
+        wl_touch_add_listener(input->touch, &touch_listener,
+                                 input);
+    } else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && input->touch) {
+        SDL_DelTouch(1);
+        wl_touch_destroy(input->touch);
+        input->touch = NULL;
+    }
+
     if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !input->keyboard) {
         input->keyboard = wl_seat_get_keyboard(seat);
         wl_keyboard_set_user_data(input->keyboard, input);
@@ -430,10 +610,245 @@ static const struct wl_seat_listener seat_listener = {
     seat_handle_capabilities,
 };
 
+static void
+data_source_handle_target(void *data, struct wl_data_source *wl_data_source,
+                          const char *mime_type)
+{
+}
+
+static void
+data_source_handle_send(void *data, struct wl_data_source *wl_data_source,
+                        const char *mime_type, int32_t fd)
+{
+    Wayland_data_source_send((SDL_WaylandDataSource *)data, mime_type, fd);
+}
+                       
+static void
+data_source_handle_cancelled(void *data, struct wl_data_source *wl_data_source)
+{
+    Wayland_data_source_destroy(data);
+}
+                       
+static void
+data_source_handle_dnd_drop_performed(void *data, struct wl_data_source *wl_data_source)
+{
+}
+
+static void
+data_source_handle_dnd_finished(void *data, struct wl_data_source *wl_data_source)
+{
+}
+
+static void
+data_source_handle_action(void *data, struct wl_data_source *wl_data_source,
+                          uint32_t dnd_action)
+{
+}
+
+static const struct wl_data_source_listener data_source_listener = {
+    data_source_handle_target,
+    data_source_handle_send,
+    data_source_handle_cancelled,
+    data_source_handle_dnd_drop_performed, // Version 3
+    data_source_handle_dnd_finished,       // Version 3
+    data_source_handle_action,             // Version 3
+};
+
+SDL_WaylandDataSource*
+Wayland_data_source_create(_THIS)
+{
+    SDL_WaylandDataSource *data_source = NULL;
+    SDL_VideoData *driver_data = NULL;
+    struct wl_data_source *id = NULL;
+
+    if (_this == NULL || _this->driverdata == NULL) {
+        SDL_SetError("Video driver uninitialized");
+    } else {
+        driver_data = _this->driverdata;
+
+        if (driver_data->data_device_manager != NULL) {
+            id = wl_data_device_manager_create_data_source(
+                     driver_data->data_device_manager);
+        }
+
+        if (id == NULL) { 
+            SDL_SetError("Wayland unable to create data source");
+        } else {
+            data_source = SDL_calloc(1, sizeof *data_source);
+            if (data_source == NULL) {
+                SDL_OutOfMemory();
+                wl_data_source_destroy(id);
+            } else {
+                WAYLAND_wl_list_init(&(data_source->mimes));
+                data_source->source = id;
+                wl_data_source_set_user_data(id, data_source);
+                wl_data_source_add_listener(id, &data_source_listener,
+                                            data_source);
+            }
+        }
+    }
+    return data_source;
+}
+
+static void
+data_offer_handle_offer(void *data, struct wl_data_offer *wl_data_offer,
+                        const char *mime_type)
+{
+    SDL_WaylandDataOffer *offer = data;
+    Wayland_data_offer_add_mime(offer, mime_type);
+}
+
+static void
+data_offer_handle_source_actions(void *data, struct wl_data_offer *wl_data_offer,
+                                 uint32_t source_actions)
+{
+}
+
+static void
+data_offer_handle_actions(void *data, struct wl_data_offer *wl_data_offer,
+                          uint32_t dnd_action)
+{
+}
+
+static const struct wl_data_offer_listener data_offer_listener = {
+    data_offer_handle_offer,
+    data_offer_handle_source_actions, // Version 3
+    data_offer_handle_actions,        // Version 3
+};
+
+static void
+data_device_handle_data_offer(void *data, struct wl_data_device *wl_data_device,
+			                  struct wl_data_offer *id)
+{
+    SDL_WaylandDataOffer *data_offer = NULL;
+
+    data_offer = SDL_calloc(1, sizeof *data_offer);
+    if (data_offer == NULL) {
+        SDL_OutOfMemory();
+    } else {
+        data_offer->offer = id;
+        data_offer->data_device = data;
+        WAYLAND_wl_list_init(&(data_offer->mimes));
+        wl_data_offer_set_user_data(id, data_offer);
+        wl_data_offer_add_listener(id, &data_offer_listener, data_offer);
+    }
+}
+
+static void
+data_device_handle_enter(void *data, struct wl_data_device *wl_data_device,
+		                 uint32_t serial, struct wl_surface *surface,
+                         wl_fixed_t x, wl_fixed_t y, struct wl_data_offer *id)
+{
+    SDL_WaylandDataDevice *data_device = data;
+    SDL_bool has_mime = SDL_FALSE;
+    uint32_t dnd_action = WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE; 
+        
+    data_device->drag_serial = serial;
+
+    if (id != NULL) {
+        data_device->drag_offer = wl_data_offer_get_user_data(id);
+
+        /* TODO: SDL Support more mime types */
+        has_mime = Wayland_data_offer_has_mime(
+            data_device->drag_offer, FILE_MIME);
+
+        /* If drag_mime is NULL this will decline the offer */
+        wl_data_offer_accept(id, serial,
+                             (has_mime == SDL_TRUE) ? FILE_MIME : NULL);
+
+        /* SDL only supports "copy" style drag and drop */
+        if (has_mime == SDL_TRUE) {
+            dnd_action = WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY;
+        }
+        wl_data_offer_set_actions(data_device->drag_offer->offer,
+                                  dnd_action, dnd_action);
+    }
+}
+
+static void
+data_device_handle_leave(void *data, struct wl_data_device *wl_data_device)
+{
+    SDL_WaylandDataDevice *data_device = data;
+    SDL_WaylandDataOffer *offer = NULL;
+
+    if (data_device->selection_offer != NULL) {
+        data_device->selection_offer = NULL;
+        Wayland_data_offer_destroy(offer);
+    }
+}
+
+static void
+data_device_handle_motion(void *data, struct wl_data_device *wl_data_device,
+		                  uint32_t time, wl_fixed_t x, wl_fixed_t y)
+{
+}
+
+static void
+data_device_handle_drop(void *data, struct wl_data_device *wl_data_device)
+{
+    SDL_WaylandDataDevice *data_device = data;
+    void *buffer = NULL;
+    size_t length = 0;
+
+    const char *current_uri = NULL;
+    const char *last_char = NULL;
+    char *current_char = NULL;
+    
+    if (data_device->drag_offer != NULL) {
+        /* TODO: SDL Support more mime types */
+        buffer = Wayland_data_offer_receive(data_device->drag_offer,
+                                            &length, FILE_MIME, SDL_FALSE);
+
+        /* uri-list */
+        current_uri = (const char *)buffer;
+        last_char = (const char *)buffer + length;
+        for (current_char = buffer; current_char < last_char; ++current_char) {
+            if (*current_char == '\n' || *current_char == 0) {
+                if (*current_uri != 0 && *current_uri != '#') {
+                    *current_char = 0;
+                    SDL_SendDropFile(NULL, current_uri);
+                }
+                current_uri = (const char *)current_char + 1;
+            }
+        }
+
+        SDL_free(buffer);
+    }
+}
+
+static void
+data_device_handle_selection(void *data, struct wl_data_device *wl_data_device,
+			                 struct wl_data_offer *id)
+{    
+    SDL_WaylandDataDevice *data_device = data;
+    SDL_WaylandDataOffer *offer = NULL;
+
+    if (id != NULL) {
+        offer = wl_data_offer_get_user_data(id);
+    }
+
+    if (data_device->selection_offer != offer) {
+        Wayland_data_offer_destroy(data_device->selection_offer);
+        data_device->selection_offer = offer;
+    }
+
+    SDL_SendClipboardUpdate();
+}
+
+static const struct wl_data_device_listener data_device_listener = {
+    data_device_handle_data_offer,
+    data_device_handle_enter,
+    data_device_handle_leave,
+    data_device_handle_motion,
+    data_device_handle_drop,
+    data_device_handle_selection
+};
+
 void
 Wayland_display_add_input(SDL_VideoData *d, uint32_t id)
 {
     struct SDL_WaylandInput *input;
+    SDL_WaylandDataDevice *data_device = NULL;
 
     input = SDL_calloc(1, sizeof *input);
     if (input == NULL)
@@ -444,6 +859,27 @@ Wayland_display_add_input(SDL_VideoData *d, uint32_t id)
     input->sx_w = wl_fixed_from_int(0);
     input->sy_w = wl_fixed_from_int(0);
     d->input = input;
+    
+    if (d->data_device_manager != NULL) {
+        data_device = SDL_calloc(1, sizeof *data_device);
+        if (data_device == NULL) {
+            return;
+        }
+
+        data_device->data_device = wl_data_device_manager_get_data_device(
+            d->data_device_manager, input->seat
+        );
+        data_device->video_data = d;
+
+        if (data_device->data_device == NULL) {
+            SDL_free(data_device);
+        } else {
+            wl_data_device_set_user_data(data_device->data_device, data_device);
+            wl_data_device_add_listener(data_device->data_device,
+                                        &data_device_listener, data_device);
+            input->data_device = data_device;
+        }
+    }
 
     wl_seat_add_listener(input->seat, &seat_listener, input);
     wl_seat_set_user_data(input->seat, input);
@@ -458,12 +894,31 @@ void Wayland_display_destroy_input(SDL_VideoData *d)
     if (!input)
         return;
 
+    if (input->data_device != NULL) {
+        Wayland_data_device_clear_selection(input->data_device);
+        if (input->data_device->selection_offer != NULL) {
+            Wayland_data_offer_destroy(input->data_device->selection_offer);
+        }
+        if (input->data_device->drag_offer != NULL) {
+            Wayland_data_offer_destroy(input->data_device->drag_offer);
+        }
+        if (input->data_device->data_device != NULL) {
+            wl_data_device_release(input->data_device->data_device);
+        }
+        SDL_free(input->data_device);
+    }
+
     if (input->keyboard)
         wl_keyboard_destroy(input->keyboard);
 
     if (input->pointer)
         wl_pointer_destroy(input->pointer);
 
+    if (input->touch) {
+        SDL_DelTouch(1);
+        wl_touch_destroy(input->touch);
+    }
+
     if (input->seat)
         wl_seat_destroy(input->seat);
 
@@ -477,6 +932,15 @@ void Wayland_display_destroy_input(SDL_VideoData *d)
     d->input = NULL;
 }
 
+SDL_WaylandDataDevice* Wayland_get_data_device(struct SDL_WaylandInput *input)
+{
+    if (input == NULL) {
+        return NULL;
+    }
+
+    return input->data_device;
+}
+
 void Wayland_display_add_relative_pointer_manager(SDL_VideoData *d, uint32_t id)
 {
     d->relative_pointer_manager =
diff --git a/src/video/wayland/SDL_waylandevents_c.h b/src/video/wayland/SDL_waylandevents_c.h
index 56d12ec..ec61620 100644
--- a/src/video/wayland/SDL_waylandevents_c.h
+++ b/src/video/wayland/SDL_waylandevents_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,17 +21,22 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_waylandevents_h
-#define _SDL_waylandevents_h
+#ifndef SDL_waylandevents_h_
+#define SDL_waylandevents_h_
 
 #include "SDL_waylandvideo.h"
 #include "SDL_waylandwindow.h"
+#include "SDL_waylanddatamanager.h"
+
+struct SDL_WaylandInput;
 
 extern void Wayland_PumpEvents(_THIS);
 
 extern void Wayland_display_add_input(SDL_VideoData *d, uint32_t id);
 extern void Wayland_display_destroy_input(SDL_VideoData *d);
 
+extern SDL_WaylandDataDevice* Wayland_get_data_device(struct SDL_WaylandInput *input);
+
 extern void Wayland_display_add_pointer_constraints(SDL_VideoData *d, uint32_t id);
 extern void Wayland_display_destroy_pointer_constraints(SDL_VideoData *d);
 
@@ -41,6 +46,6 @@ extern int Wayland_input_unlock_pointer(struct SDL_WaylandInput *input);
 extern void Wayland_display_add_relative_pointer_manager(SDL_VideoData *d, uint32_t id);
 extern void Wayland_display_destroy_relative_pointer_manager(SDL_VideoData *d);
 
-#endif /* _SDL_waylandevents_h */
+#endif /* SDL_waylandevents_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/wayland/SDL_waylandmouse.c b/src/video/wayland/SDL_waylandmouse.c
index 8dfc9ee..d621aca 100644
--- a/src/video/wayland/SDL_waylandmouse.c
+++ b/src/video/wayland/SDL_waylandmouse.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,10 +23,6 @@
 
 #if SDL_VIDEO_DRIVER_WAYLAND
 
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
-
 #include <sys/types.h>
 #include <sys/mman.h>
 #include <fcntl.h>
@@ -396,23 +392,5 @@ Wayland_FiniMouse(void)
     /* This effectively assumes that nobody else
      * touches SDL_Mouse which is effectively
      * a singleton */
-
-    SDL_Mouse *mouse = SDL_GetMouse();
-
-    /* Free the current cursor if not the same pointer as
-     * the default cursor */
-    if (mouse->def_cursor != mouse->cur_cursor)
-        Wayland_FreeCursor (mouse->cur_cursor);
-
-    Wayland_FreeCursor (mouse->def_cursor);
-    mouse->def_cursor = NULL;
-    mouse->cur_cursor = NULL;
-
-    mouse->CreateCursor =  NULL;
-    mouse->CreateSystemCursor = NULL;
-    mouse->ShowCursor = NULL;
-    mouse->FreeCursor = NULL;
-    mouse->WarpMouse = NULL;
-    mouse->SetRelativeMouseMode = NULL;
 }
 #endif  /* SDL_VIDEO_DRIVER_WAYLAND */
diff --git a/src/video/wayland/SDL_waylandmouse.h b/src/video/wayland/SDL_waylandmouse.h
index 129990d..8da6dd7 100644
--- a/src/video/wayland/SDL_waylandmouse.h
+++ b/src/video/wayland/SDL_waylandmouse.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/wayland/SDL_waylandopengles.c b/src/video/wayland/SDL_waylandopengles.c
index 6803dbe..e44aa21 100644
--- a/src/video/wayland/SDL_waylandopengles.c
+++ b/src/video/wayland/SDL_waylandopengles.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -35,7 +35,7 @@ Wayland_GLES_LoadLibrary(_THIS, const char *path) {
     int ret;
     SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
     
-    ret = SDL_EGL_LoadLibrary(_this, path, (NativeDisplayType) data->display);
+    ret = SDL_EGL_LoadLibrary(_this, path, (NativeDisplayType) data->display, 0);
 
     Wayland_PumpEvents(_this);
     WAYLAND_wl_display_flush(data->display);
@@ -54,14 +54,16 @@ Wayland_GLES_CreateContext(_THIS, SDL_Window * window)
     return context;
 }
 
-void
+int
 Wayland_GLES_SwapWindow(_THIS, SDL_Window *window)
 {
-    SDL_EGL_SwapBuffers(_this, ((SDL_WindowData *) window->driverdata)->egl_surface);
+    if (SDL_EGL_SwapBuffers(_this, ((SDL_WindowData *) window->driverdata)->egl_surface) < 0) {
+        return -1;
+    }
     WAYLAND_wl_display_flush( ((SDL_VideoData*)_this->driverdata)->display );
+    return 0;
 }
 
-
 int
 Wayland_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context)
 {
diff --git a/src/video/wayland/SDL_waylandopengles.h b/src/video/wayland/SDL_waylandopengles.h
index 6c3f1f3..4d683c0 100644
--- a/src/video/wayland/SDL_waylandopengles.h
+++ b/src/video/wayland/SDL_waylandopengles.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_waylandopengles_h
-#define _SDL_waylandopengles_h
+#ifndef SDL_waylandopengles_h_
+#define SDL_waylandopengles_h_
 
 #include "../SDL_sysvideo.h"
 #include "../SDL_egl_c.h"
@@ -39,8 +39,10 @@ typedef struct SDL_PrivateGLESData
 
 extern int Wayland_GLES_LoadLibrary(_THIS, const char *path);
 extern SDL_GLContext Wayland_GLES_CreateContext(_THIS, SDL_Window * window);
-extern void Wayland_GLES_SwapWindow(_THIS, SDL_Window * window);
+extern int Wayland_GLES_SwapWindow(_THIS, SDL_Window * window);
 extern int Wayland_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 extern void Wayland_GLES_DeleteContext(_THIS, SDL_GLContext context);
 
-#endif /* _SDL_waylandopengles_h */
+#endif /* SDL_waylandopengles_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/wayland/SDL_waylandsym.h b/src/video/wayland/SDL_waylandsym.h
index aea3cb1..268f8a1 100644
--- a/src/video/wayland/SDL_waylandsym.h
+++ b/src/video/wayland/SDL_waylandsym.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -83,6 +83,10 @@ SDL_WAYLAND_INTERFACE(wl_compositor_interface)
 SDL_WAYLAND_INTERFACE(wl_output_interface)
 SDL_WAYLAND_INTERFACE(wl_shell_interface)
 SDL_WAYLAND_INTERFACE(wl_shm_interface)
+SDL_WAYLAND_INTERFACE(wl_data_device_interface)
+SDL_WAYLAND_INTERFACE(wl_data_source_interface)
+SDL_WAYLAND_INTERFACE(wl_data_offer_interface)
+SDL_WAYLAND_INTERFACE(wl_data_device_manager_interface)
 
 SDL_WAYLAND_MODULE(WAYLAND_EGL)
 SDL_WAYLAND_SYM(struct wl_egl_window *, wl_egl_window_create, (struct wl_surface *, int, int))
diff --git a/src/video/wayland/SDL_waylandtouch.c b/src/video/wayland/SDL_waylandtouch.c
index 4cae425..faeedd6 100644
--- a/src/video/wayland/SDL_waylandtouch.c
+++ b/src/video/wayland/SDL_waylandtouch.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/wayland/SDL_waylandtouch.h b/src/video/wayland/SDL_waylandtouch.h
index 5f2a058..41d5f8a 100644
--- a/src/video/wayland/SDL_waylandtouch.h
+++ b/src/video/wayland/SDL_waylandtouch.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -23,8 +23,8 @@
 
 #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH
 
-#ifndef _SDL_waylandtouch_h
-#define _SDL_waylandtouch_h
+#ifndef SDL_waylandtouch_h_
+#define SDL_waylandtouch_h_
 
 #include "SDL_waylandvideo.h"
 #include <stdint.h>
@@ -347,6 +347,6 @@ qt_windowmanager_open_url(struct qt_windowmanager *qt_windowmanager, uint32_t re
              QT_WINDOWMANAGER_OPEN_URL, remaining, url);
 }
 
-#endif /* _SDL_waylandtouch_h */
+#endif /* SDL_waylandtouch_h_ */
 
 #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */
diff --git a/src/video/wayland/SDL_waylandvideo.c b/src/video/wayland/SDL_waylandvideo.c
index 554b0ec..e3a73bd 100644
--- a/src/video/wayland/SDL_waylandvideo.c
+++ b/src/video/wayland/SDL_waylandvideo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -34,6 +34,8 @@
 #include "SDL_waylandopengles.h"
 #include "SDL_waylandmouse.h"
 #include "SDL_waylandtouch.h"
+#include "SDL_waylandclipboard.h"
+#include "SDL_waylandvulkan.h"
 
 #include <sys/types.h>
 #include <unistd.h>
@@ -166,7 +168,7 @@ Wayland_CreateDevice(int devindex)
     device->GL_GetProcAddress = Wayland_GLES_GetProcAddress;
     device->GL_DeleteContext = Wayland_GLES_DeleteContext;
 
-    device->CreateWindow = Wayland_CreateWindow;
+    device->CreateSDLWindow = Wayland_CreateWindow;
     device->ShowWindow = Wayland_ShowWindow;
     device->SetWindowFullscreen = Wayland_SetWindowFullscreen;
     device->MaximizeWindow = Wayland_MaximizeWindow;
@@ -176,6 +178,17 @@ Wayland_CreateDevice(int devindex)
     device->DestroyWindow = Wayland_DestroyWindow;
     device->SetWindowHitTest = Wayland_SetWindowHitTest;
 
+    device->SetClipboardText = Wayland_SetClipboardText;
+    device->GetClipboardText = Wayland_GetClipboardText;
+    device->HasClipboardText = Wayland_HasClipboardText;
+
+#if SDL_VIDEO_VULKAN
+    device->Vulkan_LoadLibrary = Wayland_Vulkan_LoadLibrary;
+    device->Vulkan_UnloadLibrary = Wayland_Vulkan_UnloadLibrary;
+    device->Vulkan_GetInstanceExtensions = Wayland_Vulkan_GetInstanceExtensions;
+    device->Vulkan_CreateSurface = Wayland_Vulkan_CreateSurface;
+#endif
+
     device->free = Wayland_DeleteDevice;
 
     return device;
@@ -216,6 +229,7 @@ display_handle_mode(void *data,
     SDL_DisplayMode mode;
 
     SDL_zero(mode);
+    mode.format = SDL_PIXELFORMAT_RGB888;
     mode.w = width;
     mode.h = height;
     mode.refresh_rate = refresh / 1000; // mHz to Hz
@@ -266,6 +280,7 @@ Wayland_add_display(SDL_VideoData *d, uint32_t id)
     output = wl_registry_bind(d->registry, id, &wl_output_interface, 2);
     if (!output) {
         SDL_SetError("Failed to retrieve output.");
+        SDL_free(display);
         return;
     }
 
@@ -312,6 +327,8 @@ display_handle_global(void *data, struct wl_registry *registry, uint32_t id,
         Wayland_display_add_relative_pointer_manager(d, id);
     } else if (strcmp(interface, "zwp_pointer_constraints_v1") == 0) {
         Wayland_display_add_pointer_constraints(d, id);
+    } else if (strcmp(interface, "wl_data_device_manager") == 0) {
+        d->data_device_manager = wl_registry_bind(d->registry, id, &wl_data_device_manager_interface, 3);
 #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH
     } else if (strcmp(interface, "qt_touch_extension") == 0) {
         Wayland_touch_create(d, id);
@@ -439,7 +456,7 @@ Wayland_VideoQuit(_THIS)
     }
 
     SDL_free(data->classname);
-    free(data);
+    SDL_free(data);
     _this->driverdata = NULL;
 }
 
diff --git a/src/video/wayland/SDL_waylandvideo.h b/src/video/wayland/SDL_waylandvideo.h
index ccd7ecf..60d60f0 100644
--- a/src/video/wayland/SDL_waylandvideo.h
+++ b/src/video/wayland/SDL_waylandvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_waylandvideo_h
-#define _SDL_waylandvideo_h
+#ifndef SDL_waylandvideo_h_
+#define SDL_waylandvideo_h_
 
 #include <EGL/egl.h>
 #include "wayland-util.h"
@@ -46,6 +46,7 @@ typedef struct {
     struct wl_shell *shell;
     struct zwp_relative_pointer_manager_v1 *relative_pointer_manager;
     struct zwp_pointer_constraints_v1 *pointer_constraints;
+    struct wl_data_device_manager *data_device_manager;
 
     EGLDisplay edpy;
     EGLContext context;
@@ -65,6 +66,6 @@ typedef struct {
     int relative_mouse_mode;
 } SDL_VideoData;
 
-#endif /* _SDL_waylandvideo_h */
+#endif /* SDL_waylandvideo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/wayland/SDL_waylandvulkan.c b/src/video/wayland/SDL_waylandvulkan.c
new file mode 100644
index 0000000..818c642
--- /dev/null
+++ b/src/video/wayland/SDL_waylandvulkan.c
@@ -0,0 +1,175 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.c.
+ */
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_WAYLAND
+
+#include "SDL_waylandvideo.h"
+#include "SDL_waylandwindow.h"
+#include "SDL_assert.h"
+
+#include "SDL_loadso.h"
+#include "SDL_waylandvulkan.h"
+#include "SDL_syswm.h"
+
+int Wayland_Vulkan_LoadLibrary(_THIS, const char *path)
+{
+    VkExtensionProperties *extensions = NULL;
+    Uint32 extensionCount = 0;
+    SDL_bool hasSurfaceExtension = SDL_FALSE;
+    SDL_bool hasWaylandSurfaceExtension = SDL_FALSE;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
+    if(_this->vulkan_config.loader_handle)
+        return SDL_SetError("Vulkan already loaded");
+
+    /* Load the Vulkan loader library */
+    if(!path)
+        path = SDL_getenv("SDL_VULKAN_LIBRARY");
+    if(!path)
+        path = "libvulkan.so.1";
+    _this->vulkan_config.loader_handle = SDL_LoadObject(path);
+    if(!_this->vulkan_config.loader_handle)
+        return -1;
+    SDL_strlcpy(_this->vulkan_config.loader_path, path,
+                SDL_arraysize(_this->vulkan_config.loader_path));
+    vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction(
+        _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr");
+    if(!vkGetInstanceProcAddr)
+        goto fail;
+    _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr;
+    _this->vulkan_config.vkEnumerateInstanceExtensionProperties =
+        (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)(
+            VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties");
+    if(!_this->vulkan_config.vkEnumerateInstanceExtensionProperties)
+        goto fail;
+    extensions = SDL_Vulkan_CreateInstanceExtensionsList(
+        (PFN_vkEnumerateInstanceExtensionProperties)
+            _this->vulkan_config.vkEnumerateInstanceExtensionProperties,
+        &extensionCount);
+    if(!extensions)
+        goto fail;
+    for(Uint32 i = 0; i < extensionCount; i++)
+    {
+        if(SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasSurfaceExtension = SDL_TRUE;
+        else if(SDL_strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasWaylandSurfaceExtension = SDL_TRUE;
+    }
+    SDL_free(extensions);
+    if(!hasSurfaceExtension)
+    {
+        SDL_SetError("Installed Vulkan doesn't implement the "
+                     VK_KHR_SURFACE_EXTENSION_NAME " extension");
+        goto fail;
+    }
+    else if(!hasWaylandSurfaceExtension)
+    {
+        SDL_SetError("Installed Vulkan doesn't implement the "
+                     VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME "extension");
+        goto fail;
+    }
+    return 0;
+
+fail:
+    SDL_UnloadObject(_this->vulkan_config.loader_handle);
+    _this->vulkan_config.loader_handle = NULL;
+    return -1;
+}
+
+void Wayland_Vulkan_UnloadLibrary(_THIS)
+{
+    if(_this->vulkan_config.loader_handle)
+    {
+        SDL_UnloadObject(_this->vulkan_config.loader_handle);
+        _this->vulkan_config.loader_handle = NULL;
+    }
+}
+
+SDL_bool Wayland_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names)
+{
+    static const char *const extensionsForWayland[] = {
+        VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
+    };
+    if(!_this->vulkan_config.loader_handle)
+    {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+    return SDL_Vulkan_GetInstanceExtensions_Helper(
+            count, names, SDL_arraysize(extensionsForWayland),
+            extensionsForWayland);
+}
+
+SDL_bool Wayland_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface)
+{
+    SDL_WindowData *windowData = (SDL_WindowData *)window->driverdata;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr =
+        (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr;
+    PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR =
+        (PFN_vkCreateWaylandSurfaceKHR)vkGetInstanceProcAddr(
+                                            (VkInstance)instance,
+                                            "vkCreateWaylandSurfaceKHR");
+    VkWaylandSurfaceCreateInfoKHR createInfo = {};
+    VkResult result;
+
+    if(!_this->vulkan_config.loader_handle)
+    {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+
+    if(!vkCreateWaylandSurfaceKHR)
+    {
+        SDL_SetError(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
+                     " extension is not enabled in the Vulkan instance.");
+        return SDL_FALSE;
+    }
+    createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
+    createInfo.pNext = NULL;
+    createInfo.flags = 0;
+    createInfo.display = windowData->waylandData->display;
+    createInfo.surface =  windowData->surface;
+    result = vkCreateWaylandSurfaceKHR(instance, &createInfo,
+                                       NULL, surface);
+    if(result != VK_SUCCESS)
+    {
+        SDL_SetError("vkCreateWaylandSurfaceKHR failed: %s",
+                     SDL_Vulkan_GetResultString(result));
+        return SDL_FALSE;
+    }
+    return SDL_TRUE;
+}
+
+#endif
+
+/* vim: set ts=4 sw=4 expandtab: */
diff --git a/src/video/emscripten/SDL_emscriptenvideo.h b/src/video/wayland/SDL_waylandvulkan.h
similarity index 55%
copy from src/video/emscripten/SDL_emscriptenvideo.h
copy to src/video/wayland/SDL_waylandvulkan.h
index 7618ab6..8002085 100644
--- a/src/video/emscripten/SDL_emscriptenvideo.h
+++ b/src/video/wayland/SDL_waylandvulkan.h
@@ -18,37 +18,35 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../../SDL_internal.h"
-
-#ifndef _SDL_emscriptenvideo_h
-#define _SDL_emscriptenvideo_h
 
-#include "../SDL_sysvideo.h"
-#include "../../events/SDL_touch_c.h"
-#include <emscripten/emscripten.h>
-#include <emscripten/html5.h>
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.h.
+ */
 
-#include <EGL/egl.h>
+#include "../../SDL_internal.h"
 
-typedef struct SDL_WindowData
-{
-#if SDL_VIDEO_OPENGL_EGL
-    EGLSurface egl_surface;
-#endif
-    SDL_Window *window;
-    SDL_Surface *surface;
+#ifndef SDL_waylandvulkan_h_
+#define SDL_waylandvulkan_h_
 
-    float pixel_ratio;
+#include "../SDL_vulkan_internal.h"
+#include "../SDL_sysvideo.h"
 
-    SDL_bool external_size;
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_WAYLAND
 
-    int requested_fullscreen_mode;
-    SDL_bool fullscreen_resize;
+int Wayland_Vulkan_LoadLibrary(_THIS, const char *path);
+void Wayland_Vulkan_UnloadLibrary(_THIS);
+SDL_bool Wayland_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names);
+SDL_bool Wayland_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface);
 
-    SDL_bool finger_touching;  /* for mapping touch events to mice */
-    SDL_FingerID first_finger;
-} SDL_WindowData;
+#endif
 
-#endif /* _SDL_emscriptenvideo_h */
+#endif /* SDL_waylandvulkan_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/wayland/SDL_waylandwindow.c b/src/video/wayland/SDL_waylandwindow.c
index 85fca8d..e97fd59 100644
--- a/src/video/wayland/SDL_waylandwindow.c
+++ b/src/video/wayland/SDL_waylandwindow.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -31,6 +31,7 @@
 #include "SDL_waylandvideo.h"
 #include "SDL_waylandtouch.h"
 #include "SDL_waylanddyn.h"
+#include "SDL_hints.h"
 
 static void
 handle_ping(void *data, struct wl_shell_surface *shell_surface,
@@ -128,6 +129,25 @@ SDL_bool
 Wayland_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
 {
     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
+    const Uint32 version = ((((Uint32) info->version.major) * 1000000) +
+                            (((Uint32) info->version.minor) * 10000) +
+                            (((Uint32) info->version.patch)));
+
+    /* Before 2.0.6, it was possible to build an SDL with Wayland support
+       (SDL_SysWMinfo will be large enough to hold Wayland info), but build
+       your app against SDL headers that didn't have Wayland support
+       (SDL_SysWMinfo could be smaller than Wayland needs. This would lead
+       to an app properly using SDL_GetWindowWMInfo() but we'd accidentally
+       overflow memory on the stack or heap. To protect against this, we've
+       padded out the struct unconditionally in the headers and Wayland will
+       just return an error for older apps using this function. Those apps
+       will need to be recompiled against newer headers or not use Wayland,
+       maybe by forcing SDL_VIDEODRIVER=x11. */
+    if (version < 2000006) {
+        info->subsystem = SDL_SYSWM_UNKNOWN;
+        SDL_SetError("Version must be 2.0.6 or newer");
+        return SDL_FALSE;
+    }
 
     info->info.wl.display = data->waylandData->display;
     info->info.wl.surface = data->surface;
@@ -157,6 +177,72 @@ void Wayland_ShowWindow(_THIS, SDL_Window *window)
     WAYLAND_wl_display_flush( ((SDL_VideoData*)_this->driverdata)->display );
 }
 
+#ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH
+static void SDLCALL
+QtExtendedSurface_OnHintChanged(void *userdata, const char *name,
+        const char *oldValue, const char *newValue)
+{
+    struct qt_extended_surface *qt_extended_surface = userdata;
+
+    if (name == NULL) {
+        return;
+    }
+
+    if (strcmp(name, SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION) == 0) {
+        int32_t orientation = QT_EXTENDED_SURFACE_ORIENTATION_PRIMARYORIENTATION;
+
+        if (newValue != NULL) {
+            if (strcmp(newValue, "portrait") == 0) {
+                orientation = QT_EXTENDED_SURFACE_ORIENTATION_PORTRAITORIENTATION;
+            } else if (strcmp(newValue, "landscape") == 0) {
+                orientation = QT_EXTENDED_SURFACE_ORIENTATION_LANDSCAPEORIENTATION;
+            } else if (strcmp(newValue, "inverted-portrait") == 0) {
+                orientation = QT_EXTENDED_SURFACE_ORIENTATION_INVERTEDPORTRAITORIENTATION;
+            } else if (strcmp(newValue, "inverted-landscape") == 0) {
+                orientation = QT_EXTENDED_SURFACE_ORIENTATION_INVERTEDLANDSCAPEORIENTATION;
+            }
+        }
+
+        qt_extended_surface_set_content_orientation(qt_extended_surface, orientation);
+    } else if (strcmp(name, SDL_HINT_QTWAYLAND_WINDOW_FLAGS) == 0) {
+        uint32_t flags = 0;
+
+        if (newValue != NULL) {
+            char *tmp = strdup(newValue);
+            char *saveptr = NULL;
+
+            char *flag = strtok_r(tmp, " ", &saveptr);
+            while (flag) {
+                if (strcmp(flag, "OverridesSystemGestures") == 0) {
+                    flags |= QT_EXTENDED_SURFACE_WINDOWFLAG_OVERRIDESSYSTEMGESTURES;
+                } else if (strcmp(flag, "StaysOnTop") == 0) {
+                    flags |= QT_EXTENDED_SURFACE_WINDOWFLAG_STAYSONTOP;
+                } else if (strcmp(flag, "BypassWindowManager") == 0) {
+                    // See https://github.com/qtproject/qtwayland/commit/fb4267103d
+                    flags |= 4 /* QT_EXTENDED_SURFACE_WINDOWFLAG_BYPASSWINDOWMANAGER */;
+                }
+
+                flag = strtok_r(NULL, " ", &saveptr);
+            }
+
+            free(tmp);
+        }
+
+        qt_extended_surface_set_window_flags(qt_extended_surface, flags);
+    }
+}
+
+static void QtExtendedSurface_Subscribe(struct qt_extended_surface *surface, const char *name)
+{
+    SDL_AddHintCallback(name, QtExtendedSurface_OnHintChanged, surface);
+}
+
+static void QtExtendedSurface_Unsubscribe(struct qt_extended_surface *surface, const char *name)
+{
+    SDL_DelHintCallback(name, QtExtendedSurface_OnHintChanged, surface);
+}
+#endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */
+
 void
 Wayland_SetWindowFullscreen(_THIS, SDL_Window * window,
                             SDL_VideoDisplay * _display, SDL_bool fullscreen)
@@ -227,10 +313,13 @@ int Wayland_CreateWindow(_THIS, SDL_Window *window)
     data->shell_surface = wl_shell_get_shell_surface(c->shell,
                                                      data->surface);
     wl_shell_surface_set_class (data->shell_surface, c->classname);
-#ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH    
+#ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH
     if (c->surface_extension) {
         data->extended_surface = qt_surface_extension_get_extended_surface(
                 c->surface_extension, data->surface);
+
+        QtExtendedSurface_Subscribe(data->extended_surface, SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION);
+        QtExtendedSurface_Subscribe(data->extended_surface, SDL_HINT_QTWAYLAND_WINDOW_FLAGS);
     }
 #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */
 
@@ -310,8 +399,11 @@ void Wayland_DestroyWindow(_THIS, SDL_Window *window)
             wl_shell_surface_destroy(wind->shell_surface);
 
 #ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH
-        if (wind->extended_surface)
+        if (wind->extended_surface) {
+            QtExtendedSurface_Unsubscribe(wind->extended_surface, SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION);
+            QtExtendedSurface_Unsubscribe(wind->extended_surface, SDL_HINT_QTWAYLAND_WINDOW_FLAGS);
             qt_extended_surface_destroy(wind->extended_surface);
+        }
 #endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */
         wl_surface_destroy(wind->surface);
 
diff --git a/src/video/wayland/SDL_waylandwindow.h b/src/video/wayland/SDL_waylandwindow.h
index 319a573..8898847 100644
--- a/src/video/wayland/SDL_waylandwindow.h
+++ b/src/video/wayland/SDL_waylandwindow.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_waylandwindow_h
-#define _SDL_waylandwindow_h
+#ifndef SDL_waylandwindow_h_
+#define SDL_waylandwindow_h_
 
 #include "../SDL_sysvideo.h"
 #include "SDL_syswm.h"
@@ -61,6 +61,6 @@ extern SDL_bool
 Wayland_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info);
 extern int Wayland_SetWindowHitTest(SDL_Window *window, SDL_bool enabled);
 
-#endif /* _SDL_waylandwindow_h */
+#endif /* SDL_waylandwindow_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_msctf.h b/src/video/windows/SDL_msctf.h
index 74e22f1..b98e75e 100644
--- a/src/video/windows/SDL_msctf.h
+++ b/src/video/windows/SDL_msctf.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -19,8 +19,8 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 
-#ifndef _SDL_msctf_h
-#define _SDL_msctf_h
+#ifndef SDL_msctf_h_
+#define SDL_msctf_h_
 
 #include <unknwn.h>
 
@@ -239,4 +239,4 @@ struct ITfSource
     const struct ITfSourceVtbl *lpVtbl;
 };
 
-#endif /* _SDL_msctf_h */
+#endif /* SDL_msctf_h_ */
diff --git a/src/video/windows/SDL_vkeys.h b/src/video/windows/SDL_vkeys.h
index fd65204..0158aa4 100644
--- a/src/video/windows/SDL_vkeys.h
+++ b/src/video/windows/SDL_vkeys.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/windows/SDL_windowsclipboard.c b/src/video/windows/SDL_windowsclipboard.c
index b57a66a..ab4c5dd 100644
--- a/src/video/windows/SDL_windowsclipboard.c
+++ b/src/video/windows/SDL_windowsclipboard.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/windows/SDL_windowsclipboard.h b/src/video/windows/SDL_windowsclipboard.h
index d86cd97..000e39b 100644
--- a/src/video/windows/SDL_windowsclipboard.h
+++ b/src/video/windows/SDL_windowsclipboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_windowsclipboard_h
-#define _SDL_windowsclipboard_h
+#ifndef SDL_windowsclipboard_h_
+#define SDL_windowsclipboard_h_
 
 /* Forward declaration */
 struct SDL_VideoData;
@@ -31,6 +31,6 @@ extern char *WIN_GetClipboardText(_THIS);
 extern SDL_bool WIN_HasClipboardText(_THIS);
 extern void WIN_CheckClipboardUpdate(struct SDL_VideoData * data);
 
-#endif /* _SDL_windowsclipboard_h */
+#endif /* SDL_windowsclipboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_windowsevents.c b/src/video/windows/SDL_windowsevents.c
index 02768fb..cc6ef7e 100644
--- a/src/video/windows/SDL_windowsevents.c
+++ b/src/video/windows/SDL_windowsevents.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -28,6 +28,7 @@
 #include "SDL_syswm.h"
 #include "SDL_timer.h"
 #include "SDL_vkeys.h"
+#include "SDL_hints.h"
 #include "../../events/SDL_events_c.h"
 #include "../../events/SDL_touch_c.h"
 #include "../../events/scancodes_windows.h"
@@ -82,119 +83,135 @@
 #endif
 
 static SDL_Scancode
+VKeytoScancode(WPARAM vkey)
+{
+    switch (vkey) {
+    case VK_CLEAR: return SDL_SCANCODE_CLEAR;
+    case VK_MODECHANGE: return SDL_SCANCODE_MODE;
+    case VK_SELECT: return SDL_SCANCODE_SELECT;
+    case VK_EXECUTE: return SDL_SCANCODE_EXECUTE;
+    case VK_HELP: return SDL_SCANCODE_HELP;
+    case VK_PAUSE: return SDL_SCANCODE_PAUSE;
+    case VK_NUMLOCK: return SDL_SCANCODE_NUMLOCKCLEAR;
+
+    case VK_F13: return SDL_SCANCODE_F13;
+    case VK_F14: return SDL_SCANCODE_F14;
+    case VK_F15: return SDL_SCANCODE_F15;
+    case VK_F16: return SDL_SCANCODE_F16;
+    case VK_F17: return SDL_SCANCODE_F17;
+    case VK_F18: return SDL_SCANCODE_F18;
+    case VK_F19: return SDL_SCANCODE_F19;
+    case VK_F20: return SDL_SCANCODE_F20;
+    case VK_F21: return SDL_SCANCODE_F21;
+    case VK_F22: return SDL_SCANCODE_F22;
+    case VK_F23: return SDL_SCANCODE_F23;
+    case VK_F24: return SDL_SCANCODE_F24;
+
+    case VK_OEM_NEC_EQUAL: return SDL_SCANCODE_KP_EQUALS;
+    case VK_BROWSER_BACK: return SDL_SCANCODE_AC_BACK;
+    case VK_BROWSER_FORWARD: return SDL_SCANCODE_AC_FORWARD;
+    case VK_BROWSER_REFRESH: return SDL_SCANCODE_AC_REFRESH;
+    case VK_BROWSER_STOP: return SDL_SCANCODE_AC_STOP;
+    case VK_BROWSER_SEARCH: return SDL_SCANCODE_AC_SEARCH;
+    case VK_BROWSER_FAVORITES: return SDL_SCANCODE_AC_BOOKMARKS;
+    case VK_BROWSER_HOME: return SDL_SCANCODE_AC_HOME;
+    case VK_VOLUME_MUTE: return SDL_SCANCODE_AUDIOMUTE;
+    case VK_VOLUME_DOWN: return SDL_SCANCODE_VOLUMEDOWN;
+    case VK_VOLUME_UP: return SDL_SCANCODE_VOLUMEUP;
+
+    case VK_MEDIA_NEXT_TRACK: return SDL_SCANCODE_AUDIONEXT;
+    case VK_MEDIA_PREV_TRACK: return SDL_SCANCODE_AUDIOPREV;
+    case VK_MEDIA_STOP: return SDL_SCANCODE_AUDIOSTOP;
+    case VK_MEDIA_PLAY_PAUSE: return SDL_SCANCODE_AUDIOPLAY;
+    case VK_LAUNCH_MAIL: return SDL_SCANCODE_MAIL;
+    case VK_LAUNCH_MEDIA_SELECT: return SDL_SCANCODE_MEDIASELECT;
+
+    case VK_OEM_102: return SDL_SCANCODE_NONUSBACKSLASH;
+
+    case VK_ATTN: return SDL_SCANCODE_SYSREQ;
+    case VK_CRSEL: return SDL_SCANCODE_CRSEL;
+    case VK_EXSEL: return SDL_SCANCODE_EXSEL;
+    case VK_OEM_CLEAR: return SDL_SCANCODE_CLEAR;
+
+    case VK_LAUNCH_APP1: return SDL_SCANCODE_APP1;
+    case VK_LAUNCH_APP2: return SDL_SCANCODE_APP2;
+
+    default: return SDL_SCANCODE_UNKNOWN;
+    }
+}
+
+static SDL_Scancode
 WindowsScanCodeToSDLScanCode(LPARAM lParam, WPARAM wParam)
 {
     SDL_Scancode code;
-    char bIsExtended;
     int nScanCode = (lParam >> 16) & 0xFF;
+    SDL_bool bIsExtended = (lParam & (1 << 24)) != 0;
 
-    /* 0x45 here to work around both pause and numlock sharing the same scancode, so use the VK key to tell them apart */
-    if (nScanCode == 0 || nScanCode == 0x45) {
-        switch(wParam) {
-        case VK_CLEAR: return SDL_SCANCODE_CLEAR;
-        case VK_MODECHANGE: return SDL_SCANCODE_MODE;
-        case VK_SELECT: return SDL_SCANCODE_SELECT;
-        case VK_EXECUTE: return SDL_SCANCODE_EXECUTE;
-        case VK_HELP: return SDL_SCANCODE_HELP;
-        case VK_PAUSE: return SDL_SCANCODE_PAUSE;
-        case VK_NUMLOCK: return SDL_SCANCODE_NUMLOCKCLEAR;
-
-        case VK_F13: return SDL_SCANCODE_F13;
-        case VK_F14: return SDL_SCANCODE_F14;
-        case VK_F15: return SDL_SCANCODE_F15;
-        case VK_F16: return SDL_SCANCODE_F16;
-        case VK_F17: return SDL_SCANCODE_F17;
-        case VK_F18: return SDL_SCANCODE_F18;
-        case VK_F19: return SDL_SCANCODE_F19;
-        case VK_F20: return SDL_SCANCODE_F20;
-        case VK_F21: return SDL_SCANCODE_F21;
-        case VK_F22: return SDL_SCANCODE_F22;
-        case VK_F23: return SDL_SCANCODE_F23;
-        case VK_F24: return SDL_SCANCODE_F24;
-
-        case VK_OEM_NEC_EQUAL: return SDL_SCANCODE_KP_EQUALS;
-        case VK_BROWSER_BACK: return SDL_SCANCODE_AC_BACK;
-        case VK_BROWSER_FORWARD: return SDL_SCANCODE_AC_FORWARD;
-        case VK_BROWSER_REFRESH: return SDL_SCANCODE_AC_REFRESH;
-        case VK_BROWSER_STOP: return SDL_SCANCODE_AC_STOP;
-        case VK_BROWSER_SEARCH: return SDL_SCANCODE_AC_SEARCH;
-        case VK_BROWSER_FAVORITES: return SDL_SCANCODE_AC_BOOKMARKS;
-        case VK_BROWSER_HOME: return SDL_SCANCODE_AC_HOME;
-        case VK_VOLUME_MUTE: return SDL_SCANCODE_AUDIOMUTE;
-        case VK_VOLUME_DOWN: return SDL_SCANCODE_VOLUMEDOWN;
-        case VK_VOLUME_UP: return SDL_SCANCODE_VOLUMEUP;
-
-        case VK_MEDIA_NEXT_TRACK: return SDL_SCANCODE_AUDIONEXT;
-        case VK_MEDIA_PREV_TRACK: return SDL_SCANCODE_AUDIOPREV;
-        case VK_MEDIA_STOP: return SDL_SCANCODE_AUDIOSTOP;
-        case VK_MEDIA_PLAY_PAUSE: return SDL_SCANCODE_AUDIOPLAY;
-        case VK_LAUNCH_MAIL: return SDL_SCANCODE_MAIL;
-        case VK_LAUNCH_MEDIA_SELECT: return SDL_SCANCODE_MEDIASELECT;
-
-        case VK_OEM_102: return SDL_SCANCODE_NONUSBACKSLASH;
-
-        case VK_ATTN: return SDL_SCANCODE_SYSREQ;
-        case VK_CRSEL: return SDL_SCANCODE_CRSEL;
-        case VK_EXSEL: return SDL_SCANCODE_EXSEL;
-        case VK_OEM_CLEAR: return SDL_SCANCODE_CLEAR;
-
-        case VK_LAUNCH_APP1: return SDL_SCANCODE_APP1;
-        case VK_LAUNCH_APP2: return SDL_SCANCODE_APP2;
-
-        default: return SDL_SCANCODE_UNKNOWN;
-        }
-    }
+    code = VKeytoScancode(wParam);
 
-    if (nScanCode > 127)
-        return SDL_SCANCODE_UNKNOWN;
-
-    code = windows_scancode_table[nScanCode];
-
-    bIsExtended = (lParam & (1 << 24)) != 0;
-    if (!bIsExtended) {
-        switch (code) {
-        case SDL_SCANCODE_HOME:
-            return SDL_SCANCODE_KP_7;
-        case SDL_SCANCODE_UP:
-            return SDL_SCANCODE_KP_8;
-        case SDL_SCANCODE_PAGEUP:
-            return SDL_SCANCODE_KP_9;
-        case SDL_SCANCODE_LEFT:
-            return SDL_SCANCODE_KP_4;
-        case SDL_SCANCODE_RIGHT:
-            return SDL_SCANCODE_KP_6;
-        case SDL_SCANCODE_END:
-            return SDL_SCANCODE_KP_1;
-        case SDL_SCANCODE_DOWN:
-            return SDL_SCANCODE_KP_2;
-        case SDL_SCANCODE_PAGEDOWN:
-            return SDL_SCANCODE_KP_3;
-        case SDL_SCANCODE_INSERT:
-            return SDL_SCANCODE_KP_0;
-        case SDL_SCANCODE_DELETE:
-            return SDL_SCANCODE_KP_PERIOD;
-        case SDL_SCANCODE_PRINTSCREEN:
-            return SDL_SCANCODE_KP_MULTIPLY;
-        default:
-            break;
-        }
-    } else {
-        switch (code) {
-        case SDL_SCANCODE_RETURN:
-            return SDL_SCANCODE_KP_ENTER;
-        case SDL_SCANCODE_LALT:
-            return SDL_SCANCODE_RALT;
-        case SDL_SCANCODE_LCTRL:
-            return SDL_SCANCODE_RCTRL;
-        case SDL_SCANCODE_SLASH:
-            return SDL_SCANCODE_KP_DIVIDE;
-        case SDL_SCANCODE_CAPSLOCK:
-            return SDL_SCANCODE_KP_PLUS;
-        default:
-            break;
+    if (code == SDL_SCANCODE_UNKNOWN && nScanCode <= 127) {
+        code = windows_scancode_table[nScanCode];
+
+        if (bIsExtended) {
+            switch (code) {
+            case SDL_SCANCODE_RETURN:
+                code = SDL_SCANCODE_KP_ENTER;
+                break;
+            case SDL_SCANCODE_LALT:
+                code = SDL_SCANCODE_RALT;
+                break;
+            case SDL_SCANCODE_LCTRL:
+                code = SDL_SCANCODE_RCTRL;
+                break;
+            case SDL_SCANCODE_SLASH:
+                code = SDL_SCANCODE_KP_DIVIDE;
+                break;
+            case SDL_SCANCODE_CAPSLOCK:
+                code = SDL_SCANCODE_KP_PLUS;
+                break;
+            default:
+                break;
+            }
+        } else {
+            switch (code) {
+            case SDL_SCANCODE_HOME:
+                code = SDL_SCANCODE_KP_7;
+                break;
+            case SDL_SCANCODE_UP:
+                code = SDL_SCANCODE_KP_8;
+                break;
+            case SDL_SCANCODE_PAGEUP:
+                code = SDL_SCANCODE_KP_9;
+                break;
+            case SDL_SCANCODE_LEFT:
+                code = SDL_SCANCODE_KP_4;
+                break;
+            case SDL_SCANCODE_RIGHT:
+                code = SDL_SCANCODE_KP_6;
+                break;
+            case SDL_SCANCODE_END:
+                code = SDL_SCANCODE_KP_1;
+                break;
+            case SDL_SCANCODE_DOWN:
+                code = SDL_SCANCODE_KP_2;
+                break;
+            case SDL_SCANCODE_PAGEDOWN:
+                code = SDL_SCANCODE_KP_3;
+                break;
+            case SDL_SCANCODE_INSERT:
+                code = SDL_SCANCODE_KP_0;
+                break;
+            case SDL_SCANCODE_DELETE:
+                code = SDL_SCANCODE_KP_PERIOD;
+                break;
+            case SDL_SCANCODE_PRINTSCREEN:
+                code = SDL_SCANCODE_KP_MULTIPLY;
+                break;
+            default:
+                break;
+            }
         }
     }
-
     return code;
 }
 
@@ -204,7 +221,7 @@ WIN_ShouldIgnoreFocusClick()
     return !SDL_GetHintBoolean(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, SDL_FALSE);
 }
 
-void
+static void
 WIN_CheckWParamMouseButton(SDL_bool bwParamMousePressed, SDL_bool bSDLMousePressed, SDL_WindowData *data, Uint8 button, SDL_MouseID mouseID)
 {
     if (data->focus_click_pending & SDL_BUTTON(button)) {
@@ -231,7 +248,7 @@ WIN_CheckWParamMouseButton(SDL_bool bwParamMousePressed, SDL_bool bSDLMousePress
 * Some windows systems fail to send a WM_LBUTTONDOWN sometimes, but each mouse move contains the current button state also
 *  so this funciton reconciles our view of the world with the current buttons reported by windows
 */
-void
+static void
 WIN_CheckWParamMouseButtons(WPARAM wParam, SDL_WindowData *data, SDL_MouseID mouseID)
 {
     if (wParam != data->mouse_button_flags) {
@@ -246,7 +263,7 @@ WIN_CheckWParamMouseButtons(WPARAM wParam, SDL_WindowData *data, SDL_MouseID mou
 }
 
 
-void
+static void
 WIN_CheckRawMouseButtons(ULONG rawButtons, SDL_WindowData *data)
 {
     if (rawButtons != data->mouse_button_flags) {
@@ -275,7 +292,7 @@ WIN_CheckRawMouseButtons(ULONG rawButtons, SDL_WindowData *data)
     }
 }
 
-void
+static void
 WIN_CheckAsyncMouseRelease(SDL_WindowData *data)
 {
     Uint32 mouseFlags;
@@ -309,7 +326,7 @@ WIN_CheckAsyncMouseRelease(SDL_WindowData *data)
     data->mouse_button_flags = 0;
 }
 
-BOOL 
+static BOOL
 WIN_ConvertUTF32toUTF8(UINT32 codepoint, char * text)
 {
     if (codepoint <= 0x7F) {
@@ -423,11 +440,11 @@ WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
                 if (SDL_GetKeyboardFocus() != data->window) {
                     SDL_SetKeyboardFocus(data->window);
                 }
-                
+
                 GetCursorPos(&cursorPos);
                 ScreenToClient(hwnd, &cursorPos);
                 SDL_SendMouseMotion(data->window, 0, 0, cursorPos.x, cursorPos.y);
-                
+
                 WIN_CheckAsyncMouseRelease(data);
 
                 /*
@@ -515,7 +532,7 @@ WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
                             initialMousePoint.y = rawmouse->lLastY;
                         }
 
-                        SDL_SendMouseMotion(data->window, 0, 1, (int)(rawmouse->lLastX-initialMousePoint.x), (int)(rawmouse->lLastY-initialMousePoint.y) );
+                        SDL_SendMouseMotion(data->window, 0, 1, (int)(rawmouse->lLastX-initialMousePoint.x), (int)(rawmouse->lLastY-initialMousePoint.y));
 
                         initialMousePoint.x = rawmouse->lLastX;
                         initialMousePoint.y = rawmouse->lLastY;
@@ -524,10 +541,17 @@ WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
                 } else if (isCapture) {
                     /* we check for where Windows thinks the system cursor lives in this case, so we don't really lose mouse accel, etc. */
                     POINT pt;
+                    RECT hwndRect;
+                    HWND currentHnd;
+
                     GetCursorPos(&pt);
-                    if (WindowFromPoint(pt) != hwnd) {  /* if in the window, WM_MOUSEMOVE, etc, will cover it. */
-                        ScreenToClient(hwnd, &pt);
-                        SDL_SendMouseMotion(data->window, 0, 0, (int) pt.x, (int) pt.y);
+                    currentHnd = WindowFromPoint(pt);
+                    ScreenToClient(hwnd, &pt);
+                    GetClientRect(hwnd, &hwndRect);
+
+                    /* if in the window, WM_MOUSEMOVE, etc, will cover it. */
+                    if(currentHnd != hwnd || pt.x < 0 || pt.y < 0 || pt.x > hwndRect.right || pt.y > hwndRect.right) {
+                        SDL_SendMouseMotion(data->window, 0, 0, (int)pt.x, (int)pt.y);
                         SDL_SendMouseButton(data->window, 0, GetAsyncKeyState(VK_LBUTTON) & 0x8000 ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_LEFT);
                         SDL_SendMouseButton(data->window, 0, GetAsyncKeyState(VK_RBUTTON) & 0x8000 ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_RIGHT);
                         SDL_SendMouseButton(data->window, 0, GetAsyncKeyState(VK_MBUTTON) & 0x8000 ? SDL_PRESSED : SDL_RELEASED, SDL_BUTTON_MIDDLE);
@@ -542,40 +566,14 @@ WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
         break;
 
     case WM_MOUSEWHEEL:
-        {
-            static short s_AccumulatedMotion;
-
-            s_AccumulatedMotion += GET_WHEEL_DELTA_WPARAM(wParam);
-            if (s_AccumulatedMotion > 0) {
-                while (s_AccumulatedMotion >= WHEEL_DELTA) {
-                    SDL_SendMouseWheel(data->window, 0, 0, 1, SDL_MOUSEWHEEL_NORMAL);
-                    s_AccumulatedMotion -= WHEEL_DELTA;
-                }
-            } else {
-                while (s_AccumulatedMotion <= -WHEEL_DELTA) {
-                    SDL_SendMouseWheel(data->window, 0, 0, -1, SDL_MOUSEWHEEL_NORMAL);
-                    s_AccumulatedMotion += WHEEL_DELTA;
-                }
-            }
-        }
-        break;
-
     case WM_MOUSEHWHEEL:
         {
-            static short s_AccumulatedMotion;
-
-            s_AccumulatedMotion += GET_WHEEL_DELTA_WPARAM(wParam);
-            if (s_AccumulatedMotion > 0) {
-                while (s_AccumulatedMotion >= WHEEL_DELTA) {
-                    SDL_SendMouseWheel(data->window, 0, 1, 0, SDL_MOUSEWHEEL_NORMAL);
-                    s_AccumulatedMotion -= WHEEL_DELTA;
-                }
-            } else {
-                while (s_AccumulatedMotion <= -WHEEL_DELTA) {
-                    SDL_SendMouseWheel(data->window, 0, -1, 0, SDL_MOUSEWHEEL_NORMAL);
-                    s_AccumulatedMotion += WHEEL_DELTA;
-                }
-            }
+            short amount = GET_WHEEL_DELTA_WPARAM(wParam);
+            float fAmount = (float) amount / WHEEL_DELTA;
+            if (msg == WM_MOUSEWHEEL)
+                SDL_SendMouseWheel(data->window, 0, 0.0f, fAmount, SDL_MOUSEWHEEL_NORMAL);
+            else
+                SDL_SendMouseWheel(data->window, 0, fAmount, 0.0f, SDL_MOUSEWHEEL_NORMAL);
         }
         break;
 
@@ -612,7 +610,7 @@ WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
                 SDL_SendKeyboardKey(SDL_PRESSED, code);
             }
         }
- 
+
         returnCode = 0;
         break;
 
@@ -769,7 +767,7 @@ WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
             RECT rect;
             int x, y;
             int w, h;
-            
+
             if (data->initializing || data->in_border_change) {
                 break;
             }
@@ -801,6 +799,8 @@ WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
             switch (wParam) {
             case SIZE_MAXIMIZED:
                 SDL_SendWindowEvent(data->window,
+                    SDL_WINDOWEVENT_RESTORED, 0, 0);
+                SDL_SendWindowEvent(data->window,
                     SDL_WINDOWEVENT_MAXIMIZED, 0, 0);
                 break;
             case SIZE_MINIMIZED:
@@ -875,7 +875,7 @@ WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
         break;
 
     case WM_TOUCH:
-        {
+        if (data->videodata->GetTouchInputInfo && data->videodata->CloseTouchInputHandle) {
             UINT i, num_inputs = LOWORD(wParam);
             PTOUCHINPUT inputs = SDL_stack_alloc(TOUCHINPUT, num_inputs);
             if (data->videodata->GetTouchInputInfo((HTOUCHINPUT)lParam, num_inputs, inputs, sizeof(TOUCHINPUT))) {
@@ -1045,6 +1045,7 @@ HINSTANCE SDL_Instance = NULL;
 int
 SDL_RegisterApp(char *name, Uint32 style, void *hInst)
 {
+    const char *hint;
     WNDCLASSEX wcex;
     TCHAR path[MAX_PATH];
 
@@ -1081,9 +1082,19 @@ SDL_RegisterApp(char *name, Uint32 style, void *hInst)
     wcex.cbClsExtra     = 0;
     wcex.cbWndExtra     = 0;
 
-    /* Use the first icon as a default icon, like in the Explorer */
-    GetModuleFileName(SDL_Instance, path, MAX_PATH);
-    ExtractIconEx(path, 0, &wcex.hIcon, &wcex.hIconSm, 1);
+    hint = SDL_GetHint(SDL_HINT_WINDOWS_INTRESOURCE_ICON);
+    if (hint && *hint) {
+        wcex.hIcon = LoadIcon(SDL_Instance, MAKEINTRESOURCE(SDL_atoi(hint)));
+
+        hint = SDL_GetHint(SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL);
+        if (hint && *hint) {
+            wcex.hIconSm = LoadIcon(SDL_Instance, MAKEINTRESOURCE(SDL_atoi(hint)));
+        }
+    } else {
+        /* Use the first icon as a default icon, like in the Explorer */
+        GetModuleFileName(SDL_Instance, path, MAX_PATH);
+        ExtractIconEx(path, 0, &wcex.hIcon, &wcex.hIconSm, 1);
+    }
 
     if (!RegisterClassEx(&wcex)) {
         return SDL_SetError("Couldn't register application class");
diff --git a/src/video/windows/SDL_windowsevents.h b/src/video/windows/SDL_windowsevents.h
index dcd3118..1f8c0cf 100644
--- a/src/video/windows/SDL_windowsevents.h
+++ b/src/video/windows/SDL_windowsevents.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_windowsevents_h
-#define _SDL_windowsevents_h
+#ifndef SDL_windowsevents_h_
+#define SDL_windowsevents_h_
 
 extern LPTSTR SDL_Appname;
 extern Uint32 SDL_Appstyle;
@@ -31,6 +31,6 @@ extern LRESULT CALLBACK WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam,
                                        LPARAM lParam);
 extern void WIN_PumpEvents(_THIS);
 
-#endif /* _SDL_windowsevents_h */
+#endif /* SDL_windowsevents_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_windowsframebuffer.c b/src/video/windows/SDL_windowsframebuffer.c
index 7bb07ed..7ee94c0 100644
--- a/src/video/windows/SDL_windowsframebuffer.c
+++ b/src/video/windows/SDL_windowsframebuffer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/windows/SDL_windowsframebuffer.h b/src/video/windows/SDL_windowsframebuffer.h
index 0c825f9..7c06c0e 100644
--- a/src/video/windows/SDL_windowsframebuffer.h
+++ b/src/video/windows/SDL_windowsframebuffer.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/windows/SDL_windowskeyboard.c b/src/video/windows/SDL_windowskeyboard.c
index 8271b04..6edb1b8 100644
--- a/src/video/windows/SDL_windowskeyboard.c
+++ b/src/video/windows/SDL_windowskeyboard.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -268,7 +268,7 @@ void IME_Present(SDL_VideoData *videodata)
 
 #else
 
-#ifdef _SDL_msctf_h
+#ifdef SDL_msctf_h_
 #define USE_INIT_GUID
 #elif defined(__GNUC__)
 #define USE_INIT_GUID
@@ -295,11 +295,11 @@ DEFINE_GUID(IID_ITfThreadMgrEx,                                0x3E90ADE3,0x7594
 #define IMEID_VER(id) ((id) & 0xffff0000)
 #define IMEID_LANG(id) ((id) & 0x0000ffff)
 
-#define CHT_HKL_DAYI            ((HKL)0xE0060404)
-#define CHT_HKL_NEW_PHONETIC    ((HKL)0xE0080404)
-#define CHT_HKL_NEW_CHANG_JIE   ((HKL)0xE0090404)
-#define CHT_HKL_NEW_QUICK       ((HKL)0xE00A0404)
-#define CHT_HKL_HK_CANTONESE    ((HKL)0xE00B0404)
+#define CHT_HKL_DAYI            ((HKL)(UINT_PTR)0xE0060404)
+#define CHT_HKL_NEW_PHONETIC    ((HKL)(UINT_PTR)0xE0080404)
+#define CHT_HKL_NEW_CHANG_JIE   ((HKL)(UINT_PTR)0xE0090404)
+#define CHT_HKL_NEW_QUICK       ((HKL)(UINT_PTR)0xE00A0404)
+#define CHT_HKL_HK_CANTONESE    ((HKL)(UINT_PTR)0xE00B0404)
 #define CHT_IMEFILENAME1        "TINTLGNT.IME"
 #define CHT_IMEFILENAME2        "CINTLGNT.IME"
 #define CHT_IMEFILENAME3        "MSTCIPHA.IME"
@@ -312,7 +312,7 @@ DEFINE_GUID(IID_ITfThreadMgrEx,                                0x3E90ADE3,0x7594
 #define IMEID_CHT_VER60         (LANG_CHT | MAKEIMEVERSION(6, 0))
 #define IMEID_CHT_VER_VISTA     (LANG_CHT | MAKEIMEVERSION(7, 0))
 
-#define CHS_HKL                 ((HKL)0xE00E0804)
+#define CHS_HKL                 ((HKL)(UINT_PTR)0xE00E0804)
 #define CHS_IMEFILENAME1        "PINTLGNT.IME"
 #define CHS_IMEFILENAME2        "MSSCIPYA.IME"
 #define IMEID_CHS_VER41         (LANG_CHS | MAKEIMEVERSION(4, 1))
@@ -331,9 +331,6 @@ static DWORD IME_GetId(SDL_VideoData *videodata, UINT uIndex);
 static void IME_SendEditingEvent(SDL_VideoData *videodata);
 static void IME_DestroyTextures(SDL_VideoData *videodata);
 
-#define SDL_IsEqualIID(riid1, riid2) SDL_IsEqualGUID(riid1, riid2)
-#define SDL_IsEqualGUID(rguid1, rguid2) (!SDL_memcmp(rguid1, rguid2, sizeof(GUID)))
-
 static SDL_bool UILess_SetupSinks(SDL_VideoData *videodata);
 static void UILess_ReleaseSinks(SDL_VideoData *videodata);
 static void UILess_EnableUIUpdates(SDL_VideoData *videodata);
@@ -354,6 +351,7 @@ IME_Init(SDL_VideoData *videodata, HWND hwnd)
     videodata->ime_himm32 = SDL_LoadObject("imm32.dll");
     if (!videodata->ime_himm32) {
         videodata->ime_available = SDL_FALSE;
+        SDL_ClearError();
         return;
     }
     videodata->ImmLockIMC = (LPINPUTCONTEXT2 (WINAPI *)(HIMC))SDL_LoadFunction(videodata->ime_himm32, "ImmLockIMC");
@@ -837,7 +835,11 @@ IME_GetCandidateList(HIMC himc, SDL_VideoData *videodata)
                     videodata->ime_candpgsize = i - page_start;
                 } else {
                     videodata->ime_candpgsize = SDL_min(cand_list->dwPageSize, MAX_CANDLIST);
-                    page_start = (cand_list->dwSelection / videodata->ime_candpgsize) * videodata->ime_candpgsize;
+                    if (videodata->ime_candpgsize > 0) {
+                        page_start = (cand_list->dwSelection / videodata->ime_candpgsize) * videodata->ime_candpgsize;
+                    } else {
+                        page_start = 0;
+                    }
                 }
                 SDL_memset(&videodata->ime_candidates, 0, sizeof(videodata->ime_candidates));
                 for (i = page_start, j = 0; (DWORD)i < cand_list->dwCount && j < (int)videodata->ime_candpgsize; i++, j++) {
@@ -1036,7 +1038,7 @@ STDMETHODIMP_(ULONG) TSFSink_AddRef(TSFSink *sink)
     return ++sink->refcount;
 }
 
-STDMETHODIMP_(ULONG)TSFSink_Release(TSFSink *sink)
+STDMETHODIMP_(ULONG) TSFSink_Release(TSFSink *sink)
 {
     --sink->refcount;
     if (sink->refcount == 0) {
@@ -1052,9 +1054,9 @@ STDMETHODIMP UIElementSink_QueryInterface(TSFSink *sink, REFIID riid, PVOID *ppv
         return E_INVALIDARG;
 
     *ppv = 0;
-    if (SDL_IsEqualIID(riid, &IID_IUnknown))
+    if (WIN_IsEqualIID(riid, &IID_IUnknown))
         *ppv = (IUnknown *)sink;
-    else if (SDL_IsEqualIID(riid, &IID_ITfUIElementSink))
+    else if (WIN_IsEqualIID(riid, &IID_ITfUIElementSink))
         *ppv = (ITfUIElementSink *)sink;
 
     if (*ppv) {
@@ -1158,9 +1160,9 @@ STDMETHODIMP IPPASink_QueryInterface(TSFSink *sink, REFIID riid, PVOID *ppv)
         return E_INVALIDARG;
 
     *ppv = 0;
-    if (SDL_IsEqualIID(riid, &IID_IUnknown))
+    if (WIN_IsEqualIID(riid, &IID_IUnknown))
         *ppv = (IUnknown *)sink;
-    else if (SDL_IsEqualIID(riid, &IID_ITfInputProcessorProfileActivationSink))
+    else if (WIN_IsEqualIID(riid, &IID_ITfInputProcessorProfileActivationSink))
         *ppv = (ITfInputProcessorProfileActivationSink *)sink;
 
     if (*ppv) {
@@ -1174,8 +1176,8 @@ STDMETHODIMP IPPASink_OnActivated(TSFSink *sink, DWORD dwProfileType, LANGID lan
 {
     static const GUID TF_PROFILE_DAYI = { 0x037B2C25, 0x480C, 0x4D7F, { 0xB0, 0x27, 0xD6, 0xCA, 0x6B, 0x69, 0x78, 0x8A } };
     SDL_VideoData *videodata = (SDL_VideoData *)sink->data;
-    videodata->ime_candlistindexbase = SDL_IsEqualGUID(&TF_PROFILE_DAYI, guidProfile) ? 0 : 1;
-    if (SDL_IsEqualIID(catid, &GUID_TFCAT_TIP_KEYBOARD) && (dwFlags & TF_IPSINK_FLAG_ACTIVE))
+    videodata->ime_candlistindexbase = WIN_IsEqualGUID(&TF_PROFILE_DAYI, guidProfile) ? 0 : 1;
+    if (WIN_IsEqualIID(catid, &GUID_TFCAT_TIP_KEYBOARD) && (dwFlags & TF_IPSINK_FLAG_ACTIVE))
         IME_InputLangChanged((SDL_VideoData *)sink->data);
 
     IME_HideCandidateList(videodata);
diff --git a/src/video/windows/SDL_windowskeyboard.h b/src/video/windows/SDL_windowskeyboard.h
index 84654d7..cc1955d 100644
--- a/src/video/windows/SDL_windowskeyboard.h
+++ b/src/video/windows/SDL_windowskeyboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_windowskeyboard_h
-#define _SDL_windowskeyboard_h
+#ifndef SDL_windowskeyboard_h_
+#define SDL_windowskeyboard_h_
 
 extern void WIN_InitKeyboard(_THIS);
 extern void WIN_UpdateKeymap(void);
@@ -35,6 +35,6 @@ extern void WIN_SetTextInputRect(_THIS, SDL_Rect *rect);
 
 extern SDL_bool IME_HandleMessage(HWND hwnd, UINT msg, WPARAM wParam, LPARAM *lParam, struct SDL_VideoData *videodata);
 
-#endif /* _SDL_windowskeyboard_h */
+#endif /* SDL_windowskeyboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_windowsmessagebox.c b/src/video/windows/SDL_windowsmessagebox.c
index 689e5bb..70c9520 100644
--- a/src/video/windows/SDL_windowsmessagebox.c
+++ b/src/video/windows/SDL_windowsmessagebox.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -346,7 +346,6 @@ WIN_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
 {
     WIN_DialogData *dialog;
     int i, x, y;
-    UINT_PTR which;
     const SDL_MessageBoxButtonData *buttons = messageboxdata->buttons;
     HFONT DialogFont;
     SIZE Size;
@@ -354,6 +353,7 @@ WIN_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
     wchar_t* wmessage;
     TEXTMETRIC TM;
 
+    HWND ParentWindow = NULL;
 
     const int ButtonWidth = 88;
     const int ButtonHeight = 26;
@@ -411,14 +411,24 @@ WIN_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
     {
         /* Get the metrics to try and figure our DLU conversion. */
         GetTextMetrics(FontDC, &TM);
-        s_BaseUnitsX = TM.tmAveCharWidth + 1;
+
+        /* Calculation from the following documentation:
+         * https://support.microsoft.com/en-gb/help/125681/how-to-calculate-dialog-base-units-with-non-system-based-font
+         * This fixes bug 2137, dialog box calculation with a fixed-width system font
+         */
+        {
+            SIZE extent;
+            GetTextExtentPoint32A(FontDC, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 52, &extent);
+            s_BaseUnitsX = (extent.cx / 26 + 1) / 2;
+        }
+        /*s_BaseUnitsX = TM.tmAveCharWidth + 1;*/
         s_BaseUnitsY = TM.tmHeight;
     }
 
     /* Measure the *pixel* size of the string. */
     wmessage = WIN_UTF8ToString(messageboxdata->message);
     SDL_zero(TextSize);
-    Size.cx = DrawText(FontDC, wmessage, -1, &TextSize, DT_CALCRECT);
+    DrawText(FontDC, wmessage, -1, &TextSize, DT_CALCRECT);
 
     /* Add some padding for hangs, etc. */
     TextSize.right += 2;
@@ -462,16 +472,20 @@ WIN_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
         } else {
             isDefault = SDL_FALSE;
         }
-        if (!AddDialogButton(dialog, x, y, ButtonWidth, ButtonHeight, buttons[i].text, i, isDefault)) {
+        if (!AddDialogButton(dialog, x, y, ButtonWidth, ButtonHeight, buttons[i].text, buttons[i].buttonid, isDefault)) {
             FreeDialogData(dialog);
             return -1;
         }
         x += ButtonWidth + ButtonMargin;
     }
 
-    /* FIXME: If we have a parent window, get the Instance and HWND for them */
-    which = DialogBoxIndirect(NULL, (DLGTEMPLATE*)dialog->lpDialog, NULL, (DLGPROC)MessageBoxDialogProc);
-    *buttonid = buttons[which].buttonid;
+    /* If we have a parent window, get the Instance and HWND for them
+     * so that our little dialog gets exclusive focus at all times. */
+    if (messageboxdata->window) {
+        ParentWindow = ((SDL_WindowData*)messageboxdata->window->driverdata)->hwnd;
+    }
+
+    *buttonid = (int)DialogBoxIndirect(NULL, (DLGTEMPLATE*)dialog->lpDialog, ParentWindow, (DLGPROC)MessageBoxDialogProc);
 
     FreeDialogData(dialog);
     return 0;
diff --git a/src/video/windows/SDL_windowsmessagebox.h b/src/video/windows/SDL_windowsmessagebox.h
index e9c6925..8dea07a 100644
--- a/src/video/windows/SDL_windowsmessagebox.h
+++ b/src/video/windows/SDL_windowsmessagebox.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/windows/SDL_windowsmodes.c b/src/video/windows/SDL_windowsmodes.c
index f172f9a..d40479e 100644
--- a/src/video/windows/SDL_windowsmodes.c
+++ b/src/video/windows/SDL_windowsmodes.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,56 +24,18 @@
 
 #include "SDL_windowsvideo.h"
 #include "../../../include/SDL_assert.h"
+#include "../../../include/SDL_log.h"
 
 /* Windows CE compatibility */
 #ifndef CDS_FULLSCREEN
 #define CDS_FULLSCREEN 0
 #endif
 
-typedef struct _WIN_GetMonitorDPIData {
-    SDL_VideoData *vid_data;
-    SDL_DisplayMode *mode;
-    SDL_DisplayModeData *mode_data;
-} WIN_GetMonitorDPIData;
-
-static BOOL CALLBACK
-WIN_GetMonitorDPI(HMONITOR hMonitor,
-                  HDC      hdcMonitor,
-                  LPRECT   lprcMonitor,
-                  LPARAM   dwData)
-{
-    WIN_GetMonitorDPIData *data = (WIN_GetMonitorDPIData*) dwData;
-    UINT hdpi, vdpi;
-
-    if (data->vid_data->GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, &hdpi, &vdpi) == S_OK &&
-        hdpi > 0 &&
-        vdpi > 0) {
-        float hsize, vsize;
-        
-        data->mode_data->HorzDPI = (float)hdpi;
-        data->mode_data->VertDPI = (float)vdpi;
-
-        // Figure out the monitor size and compute the diagonal DPI.
-        hsize = data->mode->w / data->mode_data->HorzDPI;
-        vsize = data->mode->h / data->mode_data->VertDPI;
-        
-        data->mode_data->DiagDPI = SDL_ComputeDiagonalDPI( data->mode->w,
-                                                           data->mode->h,
-                                                           hsize,
-                                                           vsize );
-
-        // We can only handle one DPI per display mode so end the enumeration.
-        return FALSE;
-    }
-
-    // We didn't get DPI information so keep going.
-    return TRUE;
-}
+/* #define DEBUG_MODES */
 
 static void
 WIN_UpdateDisplayMode(_THIS, LPCTSTR deviceName, DWORD index, SDL_DisplayMode * mode)
 {
-    SDL_VideoData *vid_data = (SDL_VideoData *) _this->driverdata;
     SDL_DisplayModeData *data = (SDL_DisplayModeData *) mode->driverdata;
     HDC hdc;
 
@@ -89,39 +51,8 @@ WIN_UpdateDisplayMode(_THIS, LPCTSTR deviceName, DWORD index, SDL_DisplayMode *
         int logical_width = GetDeviceCaps( hdc, HORZRES );
         int logical_height = GetDeviceCaps( hdc, VERTRES );
 
-        data->ScaleX = (float)logical_width / data->DeviceMode.dmPelsWidth;
-        data->ScaleY = (float)logical_height / data->DeviceMode.dmPelsHeight;
         mode->w = logical_width;
         mode->h = logical_height;
-
-        // WIN_GetMonitorDPI needs mode->w and mode->h
-        // so only call after those are set.
-        if (vid_data->GetDpiForMonitor) {
-            WIN_GetMonitorDPIData dpi_data;
-            RECT monitor_rect;
-
-            dpi_data.vid_data = vid_data;
-            dpi_data.mode = mode;
-            dpi_data.mode_data = data;
-            monitor_rect.left = data->DeviceMode.dmPosition.x;
-            monitor_rect.top = data->DeviceMode.dmPosition.y;
-            monitor_rect.right = monitor_rect.left + 1;
-            monitor_rect.bottom = monitor_rect.top + 1;
-            EnumDisplayMonitors(NULL, &monitor_rect, WIN_GetMonitorDPI, (LPARAM)&dpi_data);
-        } else {
-            // We don't have the Windows 8.1 routine so just
-            // get system DPI.
-            data->HorzDPI = (float)GetDeviceCaps( hdc, LOGPIXELSX );
-            data->VertDPI = (float)GetDeviceCaps( hdc, LOGPIXELSY );
-            if (data->HorzDPI == data->VertDPI) {
-                data->DiagDPI = data->HorzDPI;
-            } else {
-                data->DiagDPI = SDL_ComputeDiagonalDPI( mode->w,
-                                                        mode->h,
-                                                        (float)GetDeviceCaps( hdc, HORZSIZE ) / 25.4f,
-                                                        (float)GetDeviceCaps( hdc, VERTSIZE ) / 25.4f );
-            }
-        }
         
         SDL_zero(bmi_data);
         bmi = (LPBITMAPINFO) bmi_data;
@@ -199,13 +130,6 @@ WIN_GetDisplayMode(_THIS, LPCTSTR deviceName, DWORD index, SDL_DisplayMode * mod
     mode->driverdata = data;
     data->DeviceMode = devmode;
 
-    /* Default basic information */
-    data->ScaleX = 1.0f;
-    data->ScaleY = 1.0f;
-    data->DiagDPI = 0.0f;
-    data->HorzDPI = 0.0f;
-    data->VertDPI = 0.0f;
-
     mode->format = SDL_PIXELFORMAT_UNKNOWN;
     mode->w = data->DeviceMode.dmPelsWidth;
     mode->h = data->DeviceMode.dmPelsHeight;
@@ -217,7 +141,7 @@ WIN_GetDisplayMode(_THIS, LPCTSTR deviceName, DWORD index, SDL_DisplayMode * mod
 }
 
 static SDL_bool
-WIN_AddDisplay(_THIS, LPTSTR DeviceName)
+WIN_AddDisplay(_THIS, HMONITOR hMonitor, const MONITORINFOEX *info)
 {
     SDL_VideoDisplay display;
     SDL_DisplayData *displaydata;
@@ -225,9 +149,10 @@ WIN_AddDisplay(_THIS, LPTSTR DeviceName)
     DISPLAY_DEVICE device;
 
 #ifdef DEBUG_MODES
-    printf("Display: %s\n", WIN_StringToUTF8(DeviceName));
+    SDL_Log("Display: %s\n", WIN_StringToUTF8(info->szDevice));
 #endif
-    if (!WIN_GetDisplayMode(_this, DeviceName, ENUM_CURRENT_SETTINGS, &mode)) {
+
+    if (!WIN_GetDisplayMode(_this, info->szDevice, ENUM_CURRENT_SETTINGS, &mode)) {
         return SDL_FALSE;
     }
 
@@ -235,12 +160,13 @@ WIN_AddDisplay(_THIS, LPTSTR DeviceName)
     if (!displaydata) {
         return SDL_FALSE;
     }
-    SDL_memcpy(displaydata->DeviceName, DeviceName,
+    SDL_memcpy(displaydata->DeviceName, info->szDevice,
                sizeof(displaydata->DeviceName));
+    displaydata->MonitorHandle = hMonitor;
 
     SDL_zero(display);
     device.cb = sizeof(device);
-    if (EnumDisplayDevices(DeviceName, 0, &device, 0)) {
+    if (EnumDisplayDevices(info->szDevice, 0, &device, 0)) {
         display.name = WIN_StringToUTF8(device.DeviceString);
     }
     display.desktop_mode = mode;
@@ -251,63 +177,53 @@ WIN_AddDisplay(_THIS, LPTSTR DeviceName)
     return SDL_TRUE;
 }
 
-int
-WIN_InitModes(_THIS)
+typedef struct _WIN_AddDisplaysData {
+    SDL_VideoDevice *video_device;
+    SDL_bool want_primary;
+} WIN_AddDisplaysData;
+
+static BOOL CALLBACK
+WIN_AddDisplaysCallback(HMONITOR hMonitor,
+                        HDC      hdcMonitor,
+                        LPRECT   lprcMonitor,
+                        LPARAM   dwData)
 {
-    int pass;
-    DWORD i, j, count;
-    DISPLAY_DEVICE device;
+    WIN_AddDisplaysData *data = (WIN_AddDisplaysData*)dwData;
+    MONITORINFOEX info;
 
-    device.cb = sizeof(device);
+    SDL_zero(info);
+    info.cbSize = sizeof(info);
 
-    /* Get the primary display in the first pass */
-    for (pass = 0; pass < 2; ++pass) {
-        for (i = 0; ; ++i) {
-            TCHAR DeviceName[32];
+    if (GetMonitorInfo(hMonitor, (LPMONITORINFO)&info) != 0) {
+        const SDL_bool is_primary = ((info.dwFlags & MONITORINFOF_PRIMARY) == MONITORINFOF_PRIMARY);
 
-            if (!EnumDisplayDevices(NULL, i, &device, 0)) {
-                break;
-            }
-            if (!(device.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP)) {
-                continue;
-            }
-            if (pass == 0) {
-                if (!(device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE)) {
-                    continue;
-                }
-            } else {
-                if (device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) {
-                    continue;
-                }
-            }
-            SDL_memcpy(DeviceName, device.DeviceName, sizeof(DeviceName));
-#ifdef DEBUG_MODES
-            printf("Device: %s\n", WIN_StringToUTF8(DeviceName));
-#endif
-            count = 0;
-            for (j = 0; ; ++j) {
-                if (!EnumDisplayDevices(DeviceName, j, &device, 0)) {
-                    break;
-                }
-                if (!(device.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP)) {
-                    continue;
-                }
-                if (pass == 0) {
-                    if (!(device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE)) {
-                        continue;
-                    }
-                } else {
-                    if (device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) {
-                        continue;
-                    }
-                }
-                count += WIN_AddDisplay(_this, device.DeviceName);
-            }
-            if (count == 0) {
-                WIN_AddDisplay(_this, DeviceName);
-            }
+        if (is_primary == data->want_primary) {
+            WIN_AddDisplay(data->video_device, hMonitor, &info);
         }
     }
+
+    // continue enumeration
+    return TRUE;
+}
+
+static void
+WIN_AddDisplays(_THIS)
+{
+    WIN_AddDisplaysData callback_data;
+    callback_data.video_device = _this;
+
+    callback_data.want_primary = SDL_TRUE;
+    EnumDisplayMonitors(NULL, NULL, WIN_AddDisplaysCallback, (LPARAM)&callback_data);
+
+    callback_data.want_primary = SDL_FALSE;
+    EnumDisplayMonitors(NULL, NULL, WIN_AddDisplaysCallback, (LPARAM)&callback_data);
+}
+
+int
+WIN_InitModes(_THIS)
+{
+    WIN_AddDisplays(_this);
+
     if (_this->num_displays == 0) {
         return SDL_SetError("No displays available");
     }
@@ -317,67 +233,104 @@ WIN_InitModes(_THIS)
 int
 WIN_GetDisplayBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect)
 {
-    SDL_DisplayModeData *data = (SDL_DisplayModeData *) display->current_mode.driverdata;
+    const SDL_DisplayData *data = (const SDL_DisplayData *)display->driverdata;
+    MONITORINFO minfo;
+    BOOL rc;
 
-    rect->x = (int)SDL_ceil(data->DeviceMode.dmPosition.x * data->ScaleX);
-    rect->y = (int)SDL_ceil(data->DeviceMode.dmPosition.y * data->ScaleY);
-    rect->w = (int)SDL_ceil(data->DeviceMode.dmPelsWidth * data->ScaleX);
-    rect->h = (int)SDL_ceil(data->DeviceMode.dmPelsHeight * data->ScaleY);
+    SDL_zero(minfo);
+    minfo.cbSize = sizeof(MONITORINFO);
+    rc = GetMonitorInfo(data->MonitorHandle, &minfo);
+
+    if (!rc) {
+        return SDL_SetError("Couldn't find monitor data");
+    }
+
+    rect->x = minfo.rcMonitor.left;
+    rect->y = minfo.rcMonitor.top;
+    rect->w = minfo.rcMonitor.right - minfo.rcMonitor.left;
+    rect->h = minfo.rcMonitor.bottom - minfo.rcMonitor.top;
 
     return 0;
 }
 
 int
-WIN_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi, float * hdpi, float * vdpi)
+WIN_GetDisplayDPI(_THIS, SDL_VideoDisplay * display, float * ddpi_out, float * hdpi_out, float * vdpi_out)
 {
-    SDL_DisplayModeData *data = (SDL_DisplayModeData *) display->current_mode.driverdata;
+    const SDL_DisplayData *displaydata = (SDL_DisplayData *)display->driverdata;
+    const SDL_VideoData *videodata = (SDL_VideoData *)display->device->driverdata;
+    float hdpi = 0, vdpi = 0, ddpi = 0;
+    
+    if (videodata->GetDpiForMonitor) {
+        UINT hdpi_uint, vdpi_uint;
+        // Windows 8.1+ codepath
+        if (videodata->GetDpiForMonitor(displaydata->MonitorHandle, MDT_EFFECTIVE_DPI, &hdpi_uint, &vdpi_uint) == S_OK) {
+            // GetDpiForMonitor docs promise to return the same hdpi/vdpi
+            hdpi = (float)hdpi_uint;
+            vdpi = (float)hdpi_uint;
+            ddpi = (float)hdpi_uint;
+        } else {
+            return SDL_SetError("GetDpiForMonitor failed");
+        }
+    } else {
+        // Window 8.0 and below: same DPI for all monitors.
+        HDC hdc;
+        int hdpi_int, vdpi_int, hpoints, vpoints, hpix, vpix;
+        float hinches, vinches;
+
+        hdc = GetDC(NULL);
+        if (hdc == NULL) {
+            return SDL_SetError("GetDC failed");
+        }
+        hdpi_int = GetDeviceCaps(hdc, LOGPIXELSX);
+        vdpi_int = GetDeviceCaps(hdc, LOGPIXELSY);
+        ReleaseDC(NULL, hdc);
 
-    if (ddpi) {
-        *ddpi = data->DiagDPI;
+        hpoints = GetSystemMetrics(SM_CXVIRTUALSCREEN);
+        vpoints = GetSystemMetrics(SM_CYVIRTUALSCREEN);
+
+        hpix = MulDiv(hpoints, hdpi_int, 96);
+        vpix = MulDiv(vpoints, vdpi_int, 96);
+
+        hinches = (float)hpoints / 96.0f;
+        vinches = (float)vpoints / 96.0f;
+
+        hdpi = (float)hdpi_int;
+        vdpi = (float)vdpi_int;
+        ddpi = SDL_ComputeDiagonalDPI(hpix, vpix, hinches, vinches);
     }
-    if (hdpi) {
-        *hdpi = data->HorzDPI;
+
+    if (ddpi_out) {
+        *ddpi_out = ddpi;
     }
-    if (vdpi) {
-        *vdpi = data->VertDPI;
+    if (hdpi_out) {
+        *hdpi_out = hdpi;
+    }
+    if (vdpi_out) {
+        *vdpi_out = vdpi;
     }
 
-    return data->DiagDPI != 0.0f ? 0 : SDL_SetError("Couldn't get DPI");
+    return ddpi != 0.0f ? 0 : SDL_SetError("Couldn't get DPI");
 }
 
 int
 WIN_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * display, SDL_Rect * rect)
 {
-    const SDL_DisplayModeData *data = (const SDL_DisplayModeData *) display->current_mode.driverdata;
-    const DEVMODE *pDevMode = &data->DeviceMode;
-    POINT pt = {
-        /* !!! FIXME: no scale, right? */
-        (LONG) (pDevMode->dmPosition.x + (pDevMode->dmPelsWidth / 2)),
-        (LONG) (pDevMode->dmPosition.y + (pDevMode->dmPelsHeight / 2))
-    };
-    HMONITOR hmon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
+    const SDL_DisplayData *data = (const SDL_DisplayData *)display->driverdata;
     MONITORINFO minfo;
-    const RECT *work;
-    BOOL rc = FALSE;
-
-    SDL_assert(hmon != NULL);
+    BOOL rc;
 
-    if (hmon != NULL) {
-        SDL_zero(minfo);
-        minfo.cbSize = sizeof (MONITORINFO);
-        rc = GetMonitorInfo(hmon, &minfo);
-        SDL_assert(rc);
-    }
+    SDL_zero(minfo);
+    minfo.cbSize = sizeof(MONITORINFO);
+    rc = GetMonitorInfo(data->MonitorHandle, &minfo);
 
     if (!rc) {
         return SDL_SetError("Couldn't find monitor data");
     }
 
-    work = &minfo.rcWork;
-    rect->x = (int)SDL_ceil(work->left * data->ScaleX);
-    rect->y = (int)SDL_ceil(work->top * data->ScaleY);
-    rect->w = (int)SDL_ceil((work->right - work->left) * data->ScaleX);
-    rect->h = (int)SDL_ceil((work->bottom - work->top) * data->ScaleY);
+    rect->x = minfo.rcWork.left;
+    rect->y = minfo.rcWork.top;
+    rect->w = minfo.rcWork.right - minfo.rcWork.left;
+    rect->h = minfo.rcWork.bottom - minfo.rcWork.top;
 
     return 0;
 }
diff --git a/src/video/windows/SDL_windowsmodes.h b/src/video/windows/SDL_windowsmodes.h
index 6aa293d..b953504 100644
--- a/src/video/windows/SDL_windowsmodes.h
+++ b/src/video/windows/SDL_windowsmodes.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,22 +20,18 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_windowsmodes_h
-#define _SDL_windowsmodes_h
+#ifndef SDL_windowsmodes_h_
+#define SDL_windowsmodes_h_
 
 typedef struct
 {
     TCHAR DeviceName[32];
+    HMONITOR MonitorHandle;
 } SDL_DisplayData;
 
 typedef struct
 {
     DEVMODE DeviceMode;
-    float ScaleX;
-    float ScaleY;
-    float DiagDPI;
-    float HorzDPI;
-    float VertDPI;
 } SDL_DisplayModeData;
 
 extern int WIN_InitModes(_THIS);
@@ -46,6 +42,6 @@ extern void WIN_GetDisplayModes(_THIS, SDL_VideoDisplay * display);
 extern int WIN_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode);
 extern void WIN_QuitModes(_THIS);
 
-#endif /* _SDL_windowsmodes_h */
+#endif /* SDL_windowsmodes_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_windowsmouse.c b/src/video/windows/SDL_windowsmouse.c
index 72d7892..51da4be 100644
--- a/src/video/windows/SDL_windowsmouse.c
+++ b/src/video/windows/SDL_windowsmouse.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -311,13 +311,6 @@ WIN_InitMouse(_THIS)
 void
 WIN_QuitMouse(_THIS)
 {
-    SDL_Mouse *mouse = SDL_GetMouse();
-    if ( mouse->def_cursor ) {
-        SDL_free(mouse->def_cursor);
-        mouse->def_cursor = NULL;
-        mouse->cur_cursor = NULL;
-    }
-
     if (rawInputEnableCount) {  /* force RAWINPUT off here. */
         rawInputEnableCount = 1;
         ToggleRawInput(SDL_FALSE);
diff --git a/src/video/windows/SDL_windowsmouse.h b/src/video/windows/SDL_windowsmouse.h
index 60672e6..70ea2fc 100644
--- a/src/video/windows/SDL_windowsmouse.h
+++ b/src/video/windows/SDL_windowsmouse.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,14 +20,14 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_windowsmouse_h
-#define _SDL_windowsmouse_h
+#ifndef SDL_windowsmouse_h_
+#define SDL_windowsmouse_h_
 
 extern HCURSOR SDL_cursor;
 
 extern void WIN_InitMouse(_THIS);
 extern void WIN_QuitMouse(_THIS);
 
-#endif /* _SDL_windowsmouse_h */
+#endif /* SDL_windowsmouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_windowsopengl.c b/src/video/windows/SDL_windowsopengl.c
index d30d838..ae5e455 100644
--- a/src/video/windows/SDL_windowsopengl.c
+++ b/src/video/windows/SDL_windowsopengl.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -26,6 +26,7 @@
 #include "SDL_loadso.h"
 #include "SDL_windowsvideo.h"
 #include "SDL_windowsopengles.h"
+#include "SDL_hints.h"
 
 /* WGL implementation of SDL OpenGL support */
 
@@ -81,6 +82,11 @@
 #define WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB          0x2098
 #endif
 
+#ifndef WGL_ARB_create_context_no_error
+#define WGL_ARB_create_context_no_error
+#define WGL_CONTEXT_OPENGL_NO_ERROR_ARB                 0x31B3
+#endif
+
 typedef HGLRC(APIENTRYP PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC,
                                                             HGLRC
                                                             hShareContext,
@@ -131,6 +137,44 @@ WIN_GL_LoadLibrary(_THIS, const char *path)
         return SDL_SetError("Could not retrieve OpenGL functions");
     }
 
+    /* XXX Too sleazy? WIN_GL_InitExtensions looks for certain OpenGL
+       extensions via SDL_GL_DeduceMaxSupportedESProfile. This uses
+       SDL_GL_ExtensionSupported which in turn calls SDL_GL_GetProcAddress.
+       However SDL_GL_GetProcAddress will fail if the library is not
+       loaded; it checks for gl_config.driver_loaded > 0. To avoid this
+       test failing, increment driver_loaded around the call to
+       WIN_GLInitExtensions.
+
+       Successful loading of the library is normally indicated by
+       SDL_GL_LoadLibrary incrementing driver_loaded immediately after
+       this function returns 0 to it.
+
+       Alternatives to this are:
+       - moving SDL_GL_DeduceMaxSupportedESProfile to both the WIN and
+         X11 platforms while adding a function equivalent to
+         SDL_GL_ExtensionSupported but which directly calls
+         glGetProcAddress(). Having 3 copies of the
+         SDL_GL_ExtensionSupported makes this alternative unattractive.
+       - moving SDL_GL_DeduceMaxSupportedESProfile to a new file shared
+         by the WIN and X11 platforms while adding a function equivalent
+         to SDL_GL_ExtensionSupported. This is unattractive due to the
+         number of project files that will need updating, plus there
+         will be 2 copies of the SDL_GL_ExtensionSupported code.
+       - Add a private equivalent of SDL_GL_ExtensionSupported to
+         SDL_video.c.
+       - Move the call to WIN_GL_InitExtensions back to WIN_CreateWindow
+         and add a flag to gl_data to avoid multiple calls to this
+         expensive function. This is probably the least objectionable
+         alternative if this increment/decrement trick is unacceptable.
+
+       Note that the driver_loaded > 0 check needs to remain in
+       SDL_GL_ExtensionSupported and SDL_GL_GetProcAddress as they are
+       public API functions.
+    */
+    ++_this->gl_config.driver_loaded;
+    WIN_GL_InitExtensions(_this);
+    --_this->gl_config.driver_loaded;
+
     return 0;
 }
 
@@ -407,16 +451,28 @@ WIN_GL_InitExtensions(_THIS)
     }
 
     /* Check for WGL_EXT_create_context_es2_profile */
-    _this->gl_data->HAS_WGL_EXT_create_context_es2_profile = SDL_FALSE;
     if (HasExtension("WGL_EXT_create_context_es2_profile", extensions)) {
-        _this->gl_data->HAS_WGL_EXT_create_context_es2_profile = SDL_TRUE;
+        SDL_GL_DeduceMaxSupportedESProfile(
+            &_this->gl_data->es_profile_max_supported_version.major,
+            &_this->gl_data->es_profile_max_supported_version.minor
+        );
     }
 
-    /* Check for GLX_ARB_context_flush_control */
+    /* Check for WGL_ARB_context_flush_control */
     if (HasExtension("WGL_ARB_context_flush_control", extensions)) {
         _this->gl_data->HAS_WGL_ARB_context_flush_control = SDL_TRUE;
     }
 
+    /* Check for WGL_ARB_create_context_robustness */
+    if (HasExtension("WGL_ARB_create_context_robustness", extensions)) {
+        _this->gl_data->HAS_WGL_ARB_create_context_robustness = SDL_TRUE;
+    }
+
+    /* Check for WGL_ARB_create_context_no_error */
+    if (HasExtension("WGL_ARB_create_context_no_error", extensions)) {
+        _this->gl_data->HAS_WGL_ARB_create_context_no_error = SDL_TRUE;
+    }
+
     _this->gl_data->wglMakeCurrent(hdc, NULL);
     _this->gl_data->wglDeleteContext(hglrc);
     ReleaseDC(hwnd, hdc);
@@ -593,14 +649,26 @@ WIN_GL_SetupWindow(_THIS, SDL_Window * window)
     return retval;
 }
 
+SDL_bool
+WIN_GL_UseEGL(_THIS)
+{
+    SDL_assert(_this->gl_data != NULL);
+    SDL_assert(_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES);
+
+    return (SDL_GetHintBoolean(SDL_HINT_OPENGL_ES_DRIVER, SDL_FALSE)
+            || _this->gl_config.major_version == 1 /* No WGL extension for OpenGL ES 1.x profiles. */
+            || _this->gl_config.major_version > _this->gl_data->es_profile_max_supported_version.major
+            || (_this->gl_config.major_version == _this->gl_data->es_profile_max_supported_version.major
+                && _this->gl_config.minor_version > _this->gl_data->es_profile_max_supported_version.minor));
+}
+
 SDL_GLContext
 WIN_GL_CreateContext(_THIS, SDL_Window * window)
 {
     HDC hdc = ((SDL_WindowData *) window->driverdata)->hdc;
     HGLRC context, share_context;
 
-    if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES &&
-        !_this->gl_data->HAS_WGL_EXT_create_context_es2_profile) {
+    if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES && WIN_GL_UseEGL(_this)) {
 #if SDL_VIDEO_OPENGL_EGL        
         /* Switch to EGL based functions */
         WIN_GL_UnloadLibrary(_this);
@@ -660,13 +728,13 @@ WIN_GL_CreateContext(_THIS, SDL_Window * window)
             SDL_SetError("GL 3.x is not supported");
             context = temp_context;
         } else {
-        /* max 10 attributes plus terminator */
-            int attribs[11] = {
-                WGL_CONTEXT_MAJOR_VERSION_ARB, _this->gl_config.major_version,
-                WGL_CONTEXT_MINOR_VERSION_ARB, _this->gl_config.minor_version,
-                0
-            };
-            int iattr = 4;
+            int attribs[15];  /* max 14 attributes plus terminator */
+            int iattr = 0;
+
+            attribs[iattr++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
+            attribs[iattr++] = _this->gl_config.major_version;
+            attribs[iattr++] = WGL_CONTEXT_MINOR_VERSION_ARB;
+            attribs[iattr++] = _this->gl_config.minor_version;
 
             /* SDL profile bits match WGL profile bits */
             if (_this->gl_config.profile_mask != 0) {
@@ -688,6 +756,20 @@ WIN_GL_CreateContext(_THIS, SDL_Window * window)
                                     WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB;
             }
 
+            /* only set if wgl extension is available */
+            if (_this->gl_data->HAS_WGL_ARB_create_context_robustness) {
+                attribs[iattr++] = WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB;
+                attribs[iattr++] = _this->gl_config.reset_notification ?
+                                    WGL_LOSE_CONTEXT_ON_RESET_ARB :
+                                    WGL_NO_RESET_NOTIFICATION_ARB;
+            }
+
+            /* only set if wgl extension is available */
+            if (_this->gl_data->HAS_WGL_ARB_create_context_no_error) {
+                attribs[iattr++] = WGL_CONTEXT_OPENGL_NO_ERROR_ARB;
+                attribs[iattr++] = _this->gl_config.no_error;
+            }
+
             attribs[iattr++] = 0;
 
             /* Create the GL 3.x context */
@@ -766,12 +848,15 @@ WIN_GL_GetSwapInterval(_THIS)
     return retval;
 }
 
-void
+int
 WIN_GL_SwapWindow(_THIS, SDL_Window * window)
 {
     HDC hdc = ((SDL_WindowData *) window->driverdata)->hdc;
 
-    SwapBuffers(hdc);
+    if (!SwapBuffers(hdc)) {
+        return WIN_SetError("SwapBuffers()");
+    }
+    return 0;
 }
 
 void
diff --git a/src/video/windows/SDL_windowsopengl.h b/src/video/windows/SDL_windowsopengl.h
index 7b95cc8..4dc4d8f 100644
--- a/src/video/windows/SDL_windowsopengl.h
+++ b/src/video/windows/SDL_windowsopengl.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_windowsopengl_h
-#define _SDL_windowsopengl_h
+#ifndef SDL_windowsopengl_h_
+#define SDL_windowsopengl_h_
 
 #if SDL_VIDEO_OPENGL_WGL
 
@@ -29,10 +29,20 @@ struct SDL_GLDriverData
 {
     SDL_bool HAS_WGL_ARB_pixel_format;
     SDL_bool HAS_WGL_EXT_swap_control_tear;
-    SDL_bool HAS_WGL_EXT_create_context_es2_profile;
     SDL_bool HAS_WGL_ARB_context_flush_control;
+    SDL_bool HAS_WGL_ARB_create_context_robustness;
+    SDL_bool HAS_WGL_ARB_create_context_no_error;
 
-    void *(WINAPI * wglGetProcAddress) (const char *proc);
+	/* Max version of OpenGL ES context that can be created if the
+	   implementation supports WGL_EXT_create_context_es2_profile.
+	   major = minor = 0 when unsupported.
+	 */
+	struct {
+		int major;
+		int minor;
+	} es_profile_max_supported_version;
+
+	void *(WINAPI * wglGetProcAddress) (const char *proc);
       HGLRC(WINAPI * wglCreateContext) (HDC hdc);
       BOOL(WINAPI * wglDeleteContext) (HGLRC hglrc);
       BOOL(WINAPI * wglMakeCurrent) (HDC hdc, HGLRC hglrc);
@@ -56,13 +66,14 @@ struct SDL_GLDriverData
 extern int WIN_GL_LoadLibrary(_THIS, const char *path);
 extern void *WIN_GL_GetProcAddress(_THIS, const char *proc);
 extern void WIN_GL_UnloadLibrary(_THIS);
+extern SDL_bool WIN_GL_UseEGL(_THIS);
 extern int WIN_GL_SetupWindow(_THIS, SDL_Window * window);
 extern SDL_GLContext WIN_GL_CreateContext(_THIS, SDL_Window * window);
 extern int WIN_GL_MakeCurrent(_THIS, SDL_Window * window,
                               SDL_GLContext context);
 extern int WIN_GL_SetSwapInterval(_THIS, int interval);
 extern int WIN_GL_GetSwapInterval(_THIS);
-extern void WIN_GL_SwapWindow(_THIS, SDL_Window * window);
+extern int WIN_GL_SwapWindow(_THIS, SDL_Window * window);
 extern void WIN_GL_DeleteContext(_THIS, SDL_GLContext context);
 extern void WIN_GL_InitExtensions(_THIS);
 extern SDL_bool WIN_GL_SetPixelFormatFrom(_THIS, SDL_Window * fromWindow, SDL_Window * toWindow);
@@ -126,6 +137,6 @@ extern SDL_bool WIN_GL_SetPixelFormatFrom(_THIS, SDL_Window * fromWindow, SDL_Wi
 
 #endif /* SDL_VIDEO_OPENGL_WGL */
 
-#endif /* _SDL_windowsopengl_h */
+#endif /* SDL_windowsopengl_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_windowsopengles.c b/src/video/windows/SDL_windowsopengles.c
index f66cc08..e2ef5f8 100644
--- a/src/video/windows/SDL_windowsopengles.c
+++ b/src/video/windows/SDL_windowsopengles.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -52,7 +52,7 @@ WIN_GLES_LoadLibrary(_THIS, const char *path) {
     }
     
     if (_this->egl_data == NULL) {
-        return SDL_EGL_LoadLibrary(_this, NULL, EGL_DEFAULT_DISPLAY);
+        return SDL_EGL_LoadLibrary(_this, NULL, EGL_DEFAULT_DISPLAY, 0);
     }
 
     return 0;
@@ -110,7 +110,7 @@ WIN_GLES_SetupWindow(_THIS, SDL_Window * window)
 
 
     if (_this->egl_data == NULL) {
-        if (SDL_EGL_LoadLibrary(_this, NULL, EGL_DEFAULT_DISPLAY) < 0) {
+        if (SDL_EGL_LoadLibrary(_this, NULL, EGL_DEFAULT_DISPLAY, 0) < 0) {
             SDL_EGL_UnloadLibrary(_this);
             return -1;
         }
@@ -126,17 +126,6 @@ WIN_GLES_SetupWindow(_THIS, SDL_Window * window)
     return WIN_GLES_MakeCurrent(_this, current_win, current_ctx);    
 }
 
-int
-WIN_GLES_SetSwapInterval(_THIS, int interval)
-{
-    /* FIXME: This should call SDL_EGL_SetSwapInterval, but ANGLE has a bug that prevents this
-     * from working if we do (the window contents freeze and don't swap properly). So, we ignore
-     * the request for now.
-     */
-    SDL_Log("WARNING: Ignoring SDL_GL_SetSwapInterval call due to ANGLE bug");
-    return 0;
-}
-
 #endif /* SDL_VIDEO_DRIVER_WINDOWS && SDL_VIDEO_OPENGL_EGL */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_windowsopengles.h b/src/video/windows/SDL_windowsopengles.h
index dbdf5f6..9b55a9b 100644
--- a/src/video/windows/SDL_windowsopengles.h
+++ b/src/video/windows/SDL_windowsopengles.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_winopengles_h
-#define _SDL_winopengles_h
+#ifndef SDL_winopengles_h_
+#define SDL_winopengles_h_
 
 #if SDL_VIDEO_OPENGL_EGL
 
@@ -33,19 +33,17 @@
 #define WIN_GLES_GetProcAddress SDL_EGL_GetProcAddress
 #define WIN_GLES_UnloadLibrary SDL_EGL_UnloadLibrary
 #define WIN_GLES_GetSwapInterval SDL_EGL_GetSwapInterval
-/* See the WIN_GLES_GetSwapInterval implementation to see why this is commented out */
-/*#define WIN_GLES_SetSwapInterval SDL_EGL_SetSwapInterval*/
-extern int WIN_GLES_SetSwapInterval(_THIS, int interval);
+#define WIN_GLES_SetSwapInterval SDL_EGL_SetSwapInterval
 
 extern int WIN_GLES_LoadLibrary(_THIS, const char *path);
 extern SDL_GLContext WIN_GLES_CreateContext(_THIS, SDL_Window * window);
-extern void WIN_GLES_SwapWindow(_THIS, SDL_Window * window);
+extern int WIN_GLES_SwapWindow(_THIS, SDL_Window * window);
 extern int WIN_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 extern void WIN_GLES_DeleteContext(_THIS, SDL_GLContext context);
 extern int WIN_GLES_SetupWindow(_THIS, SDL_Window * window);
 
 #endif /* SDL_VIDEO_OPENGL_EGL */
 
-#endif /* _SDL_winopengles_h */
+#endif /* SDL_winopengles_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_windowsshape.c b/src/video/windows/SDL_windowsshape.c
index 0a50985..2d601c1 100644
--- a/src/video/windows/SDL_windowsshape.c
+++ b/src/video/windows/SDL_windowsshape.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -45,7 +45,7 @@ Win32_CreateShaper(SDL_Window * window) {
     return result;
 }
 
-void
+static void
 CombineRectRegions(SDL_ShapeTree* node,void* closure) {
     HRGN mask_region = *((HRGN*)closure),temp_region = NULL;
     if(node->kind == OpaqueShape) {
diff --git a/src/video/windows/SDL_windowsshape.h b/src/video/windows/SDL_windowsshape.h
index ddd8f49..09d356f 100644
--- a/src/video/windows/SDL_windowsshape.h
+++ b/src/video/windows/SDL_windowsshape.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -21,8 +21,8 @@
 
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_windowsshape_h
-#define _SDL_windowsshape_h
+#ifndef SDL_windowsshape_h_
+#define SDL_windowsshape_h_
 
 #include "SDL_video.h"
 #include "SDL_shape.h"
@@ -37,4 +37,4 @@ extern SDL_WindowShaper* Win32_CreateShaper(SDL_Window * window);
 extern int Win32_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode);
 extern int Win32_ResizeWindowShape(SDL_Window *window);
 
-#endif /* _SDL_windowsshape_h */
+#endif /* SDL_windowsshape_h_ */
diff --git a/src/video/windows/SDL_windowsvideo.c b/src/video/windows/SDL_windowsvideo.c
index 21f63a0..f4ab2a0 100644
--- a/src/video/windows/SDL_windowsvideo.c
+++ b/src/video/windows/SDL_windowsvideo.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,6 +33,7 @@
 #include "SDL_windowsvideo.h"
 #include "SDL_windowsframebuffer.h"
 #include "SDL_windowsshape.h"
+#include "SDL_windowsvulkan.h"
 
 /* Initialization/Query functions */
 static int WIN_VideoInit(_THIS);
@@ -42,7 +43,8 @@ static void WIN_VideoQuit(_THIS);
 SDL_bool g_WindowsEnableMessageLoop = SDL_TRUE;
 SDL_bool g_WindowFrameUsableWhileCursorHidden = SDL_TRUE;
 
-static void UpdateWindowsEnableMessageLoop(void *userdata, const char *name, const char *oldValue, const char *newValue)
+static void SDLCALL
+UpdateWindowsEnableMessageLoop(void *userdata, const char *name, const char *oldValue, const char *newValue)
 {
     if (newValue && *newValue == '0') {
         g_WindowsEnableMessageLoop = SDL_FALSE;
@@ -51,7 +53,8 @@ static void UpdateWindowsEnableMessageLoop(void *userdata, const char *name, con
     }
 }
 
-static void UpdateWindowFrameUsableWhileCursorHidden(void *userdata, const char *name, const char *oldValue, const char *newValue)
+static void SDLCALL
+UpdateWindowFrameUsableWhileCursorHidden(void *userdata, const char *name, const char *oldValue, const char *newValue)
 {
     if (newValue && *newValue == '0') {
         g_WindowFrameUsableWhileCursorHidden = SDL_FALSE;
@@ -113,11 +116,15 @@ WIN_CreateDevice(int devindex)
         data->CloseTouchInputHandle = (BOOL (WINAPI *)(HTOUCHINPUT)) SDL_LoadFunction(data->userDLL, "CloseTouchInputHandle");
         data->GetTouchInputInfo = (BOOL (WINAPI *)(HTOUCHINPUT, UINT, PTOUCHINPUT, int)) SDL_LoadFunction(data->userDLL, "GetTouchInputInfo");
         data->RegisterTouchWindow = (BOOL (WINAPI *)(HWND, ULONG)) SDL_LoadFunction(data->userDLL, "RegisterTouchWindow");
+    } else {
+        SDL_ClearError();
     }
 
     data->shcoreDLL = SDL_LoadObject("SHCORE.DLL");
     if (data->shcoreDLL) {
         data->GetDpiForMonitor = (HRESULT (WINAPI *)(HMONITOR, MONITOR_DPI_TYPE, UINT *, UINT *)) SDL_LoadFunction(data->shcoreDLL, "GetDpiForMonitor");
+    } else {
+        SDL_ClearError();
     }
 
     /* Set the function pointers */
@@ -130,9 +137,8 @@ WIN_CreateDevice(int devindex)
     device->SetDisplayMode = WIN_SetDisplayMode;
     device->PumpEvents = WIN_PumpEvents;
 
-#undef CreateWindow
-    device->CreateWindow = WIN_CreateWindow;
-    device->CreateWindowFrom = WIN_CreateWindowFrom;
+    device->CreateSDLWindow = WIN_CreateWindow;
+    device->CreateSDLWindowFrom = WIN_CreateWindowFrom;
     device->SetWindowTitle = WIN_SetWindowTitle;
     device->SetWindowIcon = WIN_SetWindowIcon;
     device->SetWindowPosition = WIN_SetWindowPosition;
@@ -184,6 +190,13 @@ WIN_CreateDevice(int devindex)
     device->GL_SwapWindow = WIN_GLES_SwapWindow;
     device->GL_DeleteContext = WIN_GLES_DeleteContext;
 #endif
+#if SDL_VIDEO_VULKAN
+    device->Vulkan_LoadLibrary = WIN_Vulkan_LoadLibrary;
+    device->Vulkan_UnloadLibrary = WIN_Vulkan_UnloadLibrary;
+    device->Vulkan_GetInstanceExtensions = WIN_Vulkan_GetInstanceExtensions;
+    device->Vulkan_CreateSurface = WIN_Vulkan_CreateSurface;
+#endif
+
     device->StartTextInput = WIN_StartTextInput;
     device->StopTextInput = WIN_StopTextInput;
     device->SetTextInputRect = WIN_SetTextInputRect;
diff --git a/src/video/windows/SDL_windowsvideo.h b/src/video/windows/SDL_windowsvideo.h
index 912d876..ed94abd 100644
--- a/src/video/windows/SDL_windowsvideo.h
+++ b/src/video/windows/SDL_windowsvideo.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_windowsvideo_h
-#define _SDL_windowsvideo_h
+#ifndef SDL_windowsvideo_h_
+#define SDL_windowsvideo_h_
 
 #include "../../core/windows/SDL_windows.h"
 
@@ -194,6 +194,6 @@ extern SDL_bool g_WindowFrameUsableWhileCursorHidden;
 typedef struct IDirect3D9 IDirect3D9;
 extern SDL_bool D3D_LoadDLL( void **pD3DDLL, IDirect3D9 **pDirect3D9Interface );
 
-#endif /* _SDL_windowsvideo_h */
+#endif /* SDL_windowsvideo_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_windowsvulkan.c b/src/video/windows/SDL_windowsvulkan.c
new file mode 100644
index 0000000..ec3ef28
--- /dev/null
+++ b/src/video/windows/SDL_windowsvulkan.c
@@ -0,0 +1,176 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.c.
+ */
+
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_WINDOWS
+
+#include "SDL_windowsvideo.h"
+#include "SDL_windowswindow.h"
+#include "SDL_assert.h"
+
+#include "SDL_loadso.h"
+#include "SDL_windowsvulkan.h"
+#include "SDL_syswm.h"
+
+int WIN_Vulkan_LoadLibrary(_THIS, const char *path)
+{
+    VkExtensionProperties *extensions = NULL;
+    Uint32 extensionCount = 0;
+	Uint32 i;
+    SDL_bool hasSurfaceExtension = SDL_FALSE;
+    SDL_bool hasWin32SurfaceExtension = SDL_FALSE;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
+    if(_this->vulkan_config.loader_handle)
+        return SDL_SetError("Vulkan already loaded");
+
+    /* Load the Vulkan loader library */
+    if(!path)
+        path = SDL_getenv("SDL_VULKAN_LIBRARY");
+    if(!path)
+        path = "vulkan-1.dll";
+    _this->vulkan_config.loader_handle = SDL_LoadObject(path);
+    if(!_this->vulkan_config.loader_handle)
+        return -1;
+    SDL_strlcpy(_this->vulkan_config.loader_path, path,
+                SDL_arraysize(_this->vulkan_config.loader_path));
+    vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction(
+        _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr");
+    if(!vkGetInstanceProcAddr)
+        goto fail;
+    _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr;
+    _this->vulkan_config.vkEnumerateInstanceExtensionProperties =
+        (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)(
+            VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties");
+    if(!_this->vulkan_config.vkEnumerateInstanceExtensionProperties)
+        goto fail;
+    extensions = SDL_Vulkan_CreateInstanceExtensionsList(
+        (PFN_vkEnumerateInstanceExtensionProperties)
+            _this->vulkan_config.vkEnumerateInstanceExtensionProperties,
+        &extensionCount);
+    if(!extensions)
+        goto fail;
+    for(i = 0; i < extensionCount; i++)
+    {
+        if(SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasSurfaceExtension = SDL_TRUE;
+        else if(SDL_strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasWin32SurfaceExtension = SDL_TRUE;
+    }
+    SDL_free(extensions);
+    if(!hasSurfaceExtension)
+    {
+        SDL_SetError("Installed Vulkan doesn't implement the "
+                     VK_KHR_SURFACE_EXTENSION_NAME " extension");
+        goto fail;
+    }
+    else if(!hasWin32SurfaceExtension)
+    {
+        SDL_SetError("Installed Vulkan doesn't implement the "
+                     VK_KHR_WIN32_SURFACE_EXTENSION_NAME "extension");
+        goto fail;
+    }
+    return 0;
+
+fail:
+    SDL_UnloadObject(_this->vulkan_config.loader_handle);
+    _this->vulkan_config.loader_handle = NULL;
+    return -1;
+}
+
+void WIN_Vulkan_UnloadLibrary(_THIS)
+{
+    if(_this->vulkan_config.loader_handle)
+    {
+        SDL_UnloadObject(_this->vulkan_config.loader_handle);
+        _this->vulkan_config.loader_handle = NULL;
+    }
+}
+
+SDL_bool WIN_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names)
+{
+    static const char *const extensionsForWin32[] = {
+        VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME
+    };
+    if(!_this->vulkan_config.loader_handle)
+    {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+    return SDL_Vulkan_GetInstanceExtensions_Helper(
+            count, names, SDL_arraysize(extensionsForWin32),
+            extensionsForWin32);
+}
+
+SDL_bool WIN_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface)
+{
+    SDL_WindowData *windowData = (SDL_WindowData *)window->driverdata;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr =
+        (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr;
+    PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR =
+        (PFN_vkCreateWin32SurfaceKHR)vkGetInstanceProcAddr(
+                                            (VkInstance)instance,
+                                            "vkCreateWin32SurfaceKHR");
+    VkWin32SurfaceCreateInfoKHR createInfo;
+    VkResult result;
+
+    if(!_this->vulkan_config.loader_handle)
+    {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+
+    if(!vkCreateWin32SurfaceKHR)
+    {
+        SDL_SetError(VK_KHR_WIN32_SURFACE_EXTENSION_NAME
+                     " extension is not enabled in the Vulkan instance.");
+        return SDL_FALSE;
+    }
+    createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
+    createInfo.pNext = NULL;
+    createInfo.flags = 0;
+    createInfo.hinstance = windowData->hinstance;
+    createInfo.hwnd = windowData->hwnd;
+    result = vkCreateWin32SurfaceKHR(instance, &createInfo,
+                                       NULL, surface);
+    if(result != VK_SUCCESS)
+    {
+        SDL_SetError("vkCreateWin32SurfaceKHR failed: %s",
+                     SDL_Vulkan_GetResultString(result));
+        return SDL_FALSE;
+    }
+    return SDL_TRUE;
+}
+
+#endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/emscripten/SDL_emscriptenvideo.h b/src/video/windows/SDL_windowsvulkan.h
similarity index 56%
copy from src/video/emscripten/SDL_emscriptenvideo.h
copy to src/video/windows/SDL_windowsvulkan.h
index 7618ab6..adda6bc 100644
--- a/src/video/emscripten/SDL_emscriptenvideo.h
+++ b/src/video/windows/SDL_windowsvulkan.h
@@ -18,37 +18,35 @@
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */
-#include "../../SDL_internal.h"
-
-#ifndef _SDL_emscriptenvideo_h
-#define _SDL_emscriptenvideo_h
 
-#include "../SDL_sysvideo.h"
-#include "../../events/SDL_touch_c.h"
-#include <emscripten/emscripten.h>
-#include <emscripten/html5.h>
+/*
+ * @author Mark Callow, www.edgewise-consulting.com. Based on Jacob Lifshay's
+ * SDL_x11vulkan.h.
+ */
 
-#include <EGL/egl.h>
+#include "../../SDL_internal.h"
 
-typedef struct SDL_WindowData
-{
-#if SDL_VIDEO_OPENGL_EGL
-    EGLSurface egl_surface;
-#endif
-    SDL_Window *window;
-    SDL_Surface *surface;
+#ifndef SDL_windowsvulkan_h_
+#define SDL_windowsvulkan_h_
 
-    float pixel_ratio;
+#include "../SDL_vulkan_internal.h"
+#include "../SDL_sysvideo.h"
 
-    SDL_bool external_size;
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_WINDOWS
 
-    int requested_fullscreen_mode;
-    SDL_bool fullscreen_resize;
+int WIN_Vulkan_LoadLibrary(_THIS, const char *path);
+void WIN_Vulkan_UnloadLibrary(_THIS);
+SDL_bool WIN_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names);
+SDL_bool WIN_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface);
 
-    SDL_bool finger_touching;  /* for mapping touch events to mice */
-    SDL_FingerID first_finger;
-} SDL_WindowData;
+#endif
 
-#endif /* _SDL_emscriptenvideo_h */
+#endif /* SDL_windowsvulkan_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/SDL_windowswindow.c b/src/video/windows/SDL_windowswindow.c
index 5ce40e6..3bde266 100644
--- a/src/video/windows/SDL_windowswindow.c
+++ b/src/video/windows/SDL_windowswindow.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -71,6 +71,8 @@ GetWindowStyle(SDL_Window * window)
         } else {
             style |= STYLE_NORMAL;
         }
+
+        /* You can have a borderless resizable window */
         if (window->flags & SDL_WINDOW_RESIZABLE) {
             style |= STYLE_RESIZABLE;
         }
@@ -79,34 +81,52 @@ GetWindowStyle(SDL_Window * window)
 }
 
 static void
-WIN_SetWindowPositionInternal(_THIS, SDL_Window * window, UINT flags)
+WIN_AdjustWindowRectWithStyle(SDL_Window *window, DWORD style, BOOL menu, int *x, int *y, int *width, int *height, SDL_bool use_current)
+{
+    RECT rect;
+
+    rect.left = 0;
+    rect.top = 0;
+    rect.right = (use_current ? window->w : window->windowed.w);
+    rect.bottom = (use_current ? window->h : window->windowed.h);
+    AdjustWindowRectEx(&rect, style, menu, 0);
+
+    *x = (use_current ? window->x : window->windowed.x) + rect.left;
+    *y = (use_current ? window->y : window->windowed.y) + rect.top;
+    *width = (rect.right - rect.left);
+    *height = (rect.bottom - rect.top);
+}
+
+static void
+WIN_AdjustWindowRect(SDL_Window *window, int *x, int *y, int *width, int *height, SDL_bool use_current)
 {
     SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
     HWND hwnd = data->hwnd;
-    RECT rect;
     DWORD style;
-    HWND top;
     BOOL menu;
+
+    style = GetWindowLong(hwnd, GWL_STYLE);
+    menu = (style & WS_CHILDWINDOW) ? FALSE : (GetMenu(hwnd) != NULL);
+    WIN_AdjustWindowRectWithStyle(window, style, menu, x, y, width, height, use_current);
+}
+
+static void
+WIN_SetWindowPositionInternal(_THIS, SDL_Window * window, UINT flags)
+{
+    SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
+    HWND hwnd = data->hwnd;
+    HWND top;
     int x, y;
     int w, h;
 
     /* Figure out what the window area will be */
-    if (SDL_ShouldAllowTopmost() && (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS)) == (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS)) {
+    if (SDL_ShouldAllowTopmost() && ((window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS)) == (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS) || (window->flags & SDL_WINDOW_ALWAYS_ON_TOP))) {
         top = HWND_TOPMOST;
     } else {
         top = HWND_NOTOPMOST;
     }
-    style = GetWindowLong(hwnd, GWL_STYLE);
-    rect.left = 0;
-    rect.top = 0;
-    rect.right = window->w;
-    rect.bottom = window->h;
-    menu = (style & WS_CHILDWINDOW) ? FALSE : (GetMenu(hwnd) != NULL);
-    AdjustWindowRectEx(&rect, style, menu, 0);
-    w = (rect.right - rect.left);
-    h = (rect.bottom - rect.top);
-    x = window->x + rect.left;
-    y = window->y + rect.top;
+
+    WIN_AdjustWindowRect(window, &x, &y, &w, &h, SDL_TRUE);    
 
     data->expected_resize = SDL_TRUE;
     SetWindowPos(hwnd, top, x, y, w, h, flags);
@@ -114,7 +134,7 @@ WIN_SetWindowPositionInternal(_THIS, SDL_Window * window, UINT flags)
 }
 
 static int
-SetupWindowData(_THIS, SDL_Window * window, HWND hwnd, SDL_bool created)
+SetupWindowData(_THIS, SDL_Window * window, HWND hwnd, HWND parent, SDL_bool created)
 {
     SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
     SDL_WindowData *data;
@@ -126,7 +146,9 @@ SetupWindowData(_THIS, SDL_Window * window, HWND hwnd, SDL_bool created)
     }
     data->window = window;
     data->hwnd = hwnd;
+    data->parent = parent;
     data->hdc = GetDC(hwnd);
+    data->hinstance = (HINSTANCE) GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
     data->created = created;
     data->mouse_button_flags = 0;
     data->videodata = videodata;
@@ -166,25 +188,11 @@ SetupWindowData(_THIS, SDL_Window * window, HWND hwnd, SDL_bool created)
             int h = rect.bottom;
             if ((window->w && window->w != w) || (window->h && window->h != h)) {
                 /* We tried to create a window larger than the desktop and Windows didn't allow it.  Override! */
-                RECT rect;
-                DWORD style;
-                BOOL menu;
                 int x, y;
                 int w, h;
 
                 /* Figure out what the window area will be */
-                style = GetWindowLong(hwnd, GWL_STYLE);
-                rect.left = 0;
-                rect.top = 0;
-                rect.right = window->w;
-                rect.bottom = window->h;
-                menu = (style & WS_CHILDWINDOW) ? FALSE : (GetMenu(hwnd) != NULL);
-                AdjustWindowRectEx(&rect, style, menu, 0);
-                w = (rect.right - rect.left);
-                h = (rect.bottom - rect.top);
-                x = window->x + rect.left;
-                y = window->y + rect.top;
-
+                WIN_AdjustWindowRect(window, &x, &y, &w, &h, SDL_TRUE);
                 SetWindowPos(hwnd, HWND_NOTOPMOST, x, y, w, h, SWP_NOCOPYBITS | SWP_NOZORDER | SWP_NOACTIVATE);
             } else {
                 window->w = w;
@@ -262,30 +270,27 @@ SetupWindowData(_THIS, SDL_Window * window, HWND hwnd, SDL_bool created)
     return 0;
 }
 
+
+
 int
 WIN_CreateWindow(_THIS, SDL_Window * window)
 {
-    HWND hwnd;
-    RECT rect;
+    HWND hwnd, parent = NULL;
     DWORD style = STYLE_BASIC;
     int x, y;
     int w, h;
 
+    if (window->flags & SDL_WINDOW_SKIP_TASKBAR) {
+        parent = CreateWindow(SDL_Appname, TEXT(""), STYLE_BASIC, 0, 0, 32, 32, NULL, NULL, SDL_Instance, NULL);
+    }
+
     style |= GetWindowStyle(window);
 
     /* Figure out what the window area will be */
-    rect.left = window->x;
-    rect.top = window->y;
-    rect.right = window->x + window->w;
-    rect.bottom = window->y + window->h;
-    AdjustWindowRectEx(&rect, style, FALSE, 0);
-    x = rect.left;
-    y = rect.top;
-    w = (rect.right - rect.left);
-    h = (rect.bottom - rect.top);
+    WIN_AdjustWindowRectWithStyle(window, style, FALSE, &x, &y, &w, &h, SDL_TRUE);
 
     hwnd =
-        CreateWindow(SDL_Appname, TEXT(""), style, x, y, w, h, NULL, NULL,
+        CreateWindow(SDL_Appname, TEXT(""), style, x, y, w, h, parent, NULL,
                      SDL_Instance, NULL);
     if (!hwnd) {
         return WIN_SetError("Couldn't create window");
@@ -293,43 +298,44 @@ WIN_CreateWindow(_THIS, SDL_Window * window)
 
     WIN_PumpEvents(_this);
 
-    if (SetupWindowData(_this, window, hwnd, SDL_TRUE) < 0) {
+    if (SetupWindowData(_this, window, hwnd, parent, SDL_TRUE) < 0) {
         DestroyWindow(hwnd);
+        if (parent) {
+            DestroyWindow(parent);
+        }
         return -1;
     }
 
-#if SDL_VIDEO_OPENGL_WGL
-    /* We need to initialize the extensions before deciding how to create ES profiles */
-    if (window->flags & SDL_WINDOW_OPENGL) {
-        WIN_GL_InitExtensions(_this);
+    if (!(window->flags & SDL_WINDOW_OPENGL)) {
+        return 0;
     }
-#endif
 
+    /* The rest of this macro mess is for OpenGL or OpenGL ES windows */
 #if SDL_VIDEO_OPENGL_ES2
-    if ((window->flags & SDL_WINDOW_OPENGL) &&
-        _this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES
-#if SDL_VIDEO_OPENGL_WGL           
-        && (!_this->gl_data || !_this->gl_data->HAS_WGL_EXT_create_context_es2_profile)
-#endif  
-        ) {
-#if SDL_VIDEO_OPENGL_EGL  
+    if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES
+#if SDL_VIDEO_OPENGL_WGL
+        && (!_this->gl_data || WIN_GL_UseEGL(_this))
+#endif /* SDL_VIDEO_OPENGL_WGL */
+    ) {
+#if SDL_VIDEO_OPENGL_EGL
         if (WIN_GLES_SetupWindow(_this, window) < 0) {
             WIN_DestroyWindow(_this, window);
             return -1;
         }
+        return 0;
 #else
-        return SDL_SetError("Could not create GLES window surface (no EGL support available)");
-#endif /* SDL_VIDEO_OPENGL_EGL */
-    } else 
+        return SDL_SetError("Could not create GLES window surface (EGL support not configured)");
+#endif /* SDL_VIDEO_OPENGL_EGL */ 
+    }
 #endif /* SDL_VIDEO_OPENGL_ES2 */
 
 #if SDL_VIDEO_OPENGL_WGL
-    if (window->flags & SDL_WINDOW_OPENGL) {
-        if (WIN_GL_SetupWindow(_this, window) < 0) {
-            WIN_DestroyWindow(_this, window);
-            return -1;
-        }
+    if (WIN_GL_SetupWindow(_this, window) < 0) {
+        WIN_DestroyWindow(_this, window);
+        return -1;
     }
+#else
+    return SDL_SetError("Could not create GL window (WGL support not configured)");
 #endif
 
     return 0;
@@ -357,7 +363,7 @@ WIN_CreateWindowFrom(_THIS, SDL_Window * window, const void *data)
         SDL_stack_free(title);
     }
 
-    if (SetupWindowData(_this, window, hwnd, SDL_FALSE) < 0) {
+    if (SetupWindowData(_this, window, hwnd, GetParent(hwnd), SDL_FALSE) < 0) {
         return -1;
     }
 
@@ -408,7 +414,7 @@ WIN_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon)
     SDL_RWops *dst;
 
     /* Create temporary bitmap buffer */
-    icon_len = 40 + icon->h * icon->w * 4;
+    icon_len = 40 + icon->h * icon->w * sizeof(Uint32);
     icon_bmp = SDL_stack_alloc(BYTE, icon_len);
     dst = SDL_RWFromMem(icon_bmp, icon_len);
     if (!dst) {
@@ -423,7 +429,7 @@ WIN_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon)
     SDL_WriteLE16(dst, 1);
     SDL_WriteLE16(dst, 32);
     SDL_WriteLE32(dst, BI_RGB);
-    SDL_WriteLE32(dst, icon->h * icon->w * 4);
+    SDL_WriteLE32(dst, icon->h * icon->w * sizeof(Uint32));
     SDL_WriteLE32(dst, 0);
     SDL_WriteLE32(dst, 0);
     SDL_WriteLE32(dst, 0);
@@ -434,7 +440,7 @@ WIN_SetWindowIcon(_THIS, SDL_Window * window, SDL_Surface * icon)
     y = icon->h;
     while (y--) {
         Uint8 *src = (Uint8 *) icon->pixels + y * icon->pitch;
-        SDL_RWwrite(dst, src, icon->pitch, 1);
+        SDL_RWwrite(dst, src, icon->w * sizeof(Uint32), 1);
     }
 
     hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
@@ -504,15 +510,11 @@ WIN_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered)
 {
     SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
     HWND hwnd = data->hwnd;
-    DWORD style = GetWindowLong(hwnd, GWL_STYLE);
+    DWORD style;
 
-    if (bordered) {
-        style &= ~STYLE_BORDERLESS;
-        style |= STYLE_NORMAL;
-    } else {
-        style &= ~STYLE_NORMAL;
-        style |= STYLE_BORDERLESS;
-    }
+    style = GetWindowLong(hwnd, GWL_STYLE);
+    style &= ~STYLE_MASK;
+    style |= GetWindowStyle(window);
 
     data->in_border_change = SDL_TRUE;
     SetWindowLong(hwnd, GWL_STYLE, style);
@@ -525,13 +527,11 @@ WIN_SetWindowResizable(_THIS, SDL_Window * window, SDL_bool resizable)
 {
     SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
     HWND hwnd = data->hwnd;
-    DWORD style = GetWindowLong(hwnd, GWL_STYLE);
+    DWORD style;
 
-    if (resizable) {
-        style |= STYLE_RESIZABLE;
-    } else {
-        style &= ~STYLE_RESIZABLE;
-    }
+    style = GetWindowLong(hwnd, GWL_STYLE);
+    style &= ~STYLE_MASK;
+    style |= GetWindowStyle(window);
 
     SetWindowLong(hwnd, GWL_STYLE, style);
 }
@@ -551,15 +551,13 @@ WIN_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display,
 {
     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
     HWND hwnd = data->hwnd;
-    RECT rect;
     SDL_Rect bounds;
     DWORD style;
     HWND top;
-    BOOL menu;
     int x, y;
     int w, h;
 
-    if (SDL_ShouldAllowTopmost() && (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS)) == (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS)) {
+    if (SDL_ShouldAllowTopmost() && ((window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS)) == (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_INPUT_FOCUS) || window->flags & SDL_WINDOW_ALWAYS_ON_TOP)) {
         top = HWND_TOPMOST;
     } else {
         top = HWND_NOTOPMOST;
@@ -595,16 +593,8 @@ WIN_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display,
             style |= WS_MAXIMIZE;
             data->windowed_mode_was_maximized = SDL_FALSE;
         }
-        rect.left = 0;
-        rect.top = 0;
-        rect.right = window->windowed.w;
-        rect.bottom = window->windowed.h;
-        menu = (style & WS_CHILDWINDOW) ? FALSE : (GetMenu(hwnd) != NULL);
-        AdjustWindowRectEx(&rect, style, menu, 0);
-        w = (rect.right - rect.left);
-        h = (rect.bottom - rect.top);
-        x = window->windowed.x + rect.left;
-        y = window->windowed.y + rect.top;
+
+        WIN_AdjustWindowRect(window, &x, &y, &w, &h, SDL_FALSE);
     }
     SetWindowLong(hwnd, GWL_STYLE, style);
     data->expected_resize = SDL_TRUE;
@@ -675,6 +665,9 @@ WIN_DestroyWindow(_THIS, SDL_Window * window)
         RemoveProp(data->hwnd, TEXT("SDL_WindowData"));
         if (data->created) {
             DestroyWindow(data->hwnd);
+            if (data->parent) {
+                DestroyWindow(data->parent);
+            }
         } else {
             /* Restore any original event handler... */
             if (data->wndproc != NULL) {
@@ -697,12 +690,22 @@ WIN_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
 {
     const SDL_WindowData *data = (const SDL_WindowData *) window->driverdata;
     if (info->version.major <= SDL_MAJOR_VERSION) {
+        int versionnum = SDL_VERSIONNUM(info->version.major, info->version.minor, info->version.patch);
+
         info->subsystem = SDL_SYSWM_WINDOWS;
         info->info.win.window = data->hwnd;
-        info->info.win.hdc = data->hdc;
+
+        if (versionnum >= SDL_VERSIONNUM(2, 0, 4)) {
+            info->info.win.hdc = data->hdc;
+        }
+
+        if (versionnum >= SDL_VERSIONNUM(2, 0, 5)) {
+            info->info.win.hinstance = data->hinstance;
+        }
+
         return SDL_TRUE;
     } else {
-        SDL_SetError("Application not compiled with SDL %d.%d\n",
+        SDL_SetError("Application not compiled with SDL %d.%d",
                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
@@ -780,20 +783,27 @@ SDL_HelperWindowDestroy(void)
 
 void WIN_OnWindowEnter(_THIS, SDL_Window * window)
 {
-#ifdef WM_MOUSELEAVE
     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
-    TRACKMOUSEEVENT trackMouseEvent;
 
     if (!data || !data->hwnd) {
         /* The window wasn't fully initialized */
         return;
     }
 
-    trackMouseEvent.cbSize = sizeof(TRACKMOUSEEVENT);
-    trackMouseEvent.dwFlags = TME_LEAVE;
-    trackMouseEvent.hwndTrack = data->hwnd;
+    if (window->flags & SDL_WINDOW_ALWAYS_ON_TOP) {
+        WIN_SetWindowPositionInternal(_this, window, SWP_NOCOPYBITS | SWP_NOSIZE | SWP_NOACTIVATE);
+    }
 
-    TrackMouseEvent(&trackMouseEvent);
+#ifdef WM_MOUSELEAVE
+    {
+        TRACKMOUSEEVENT trackMouseEvent;
+
+        trackMouseEvent.cbSize = sizeof(TRACKMOUSEEVENT);
+        trackMouseEvent.dwFlags = TME_LEAVE;
+        trackMouseEvent.hwndTrack = data->hwnd;
+
+        TrackMouseEvent(&trackMouseEvent);
+    }
 #endif /* WM_MOUSELEAVE */
 }
 
diff --git a/src/video/windows/SDL_windowswindow.h b/src/video/windows/SDL_windowswindow.h
index 7d50ba6..421469b 100644
--- a/src/video/windows/SDL_windowswindow.h
+++ b/src/video/windows/SDL_windowswindow.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_windowswindow_h
-#define _SDL_windowswindow_h
+#ifndef SDL_windowswindow_h_
+#define SDL_windowswindow_h_
 
 #if SDL_VIDEO_OPENGL_EGL   
 #include "../SDL_egl_c.h"
@@ -31,8 +31,10 @@ typedef struct
 {
     SDL_Window *window;
     HWND hwnd;
+    HWND parent;
     HDC hdc;
     HDC mdc;
+    HINSTANCE hinstance;
     HBITMAP hbm;
     WNDPROC wndproc;
     SDL_bool created;
@@ -76,6 +78,6 @@ extern void WIN_OnWindowEnter(_THIS, SDL_Window * window);
 extern void WIN_UpdateClipCursor(SDL_Window *window);
 extern int WIN_SetWindowHitTest(SDL_Window *window, SDL_bool enabled);
 
-#endif /* _SDL_windowswindow_h */
+#endif /* SDL_windowswindow_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/windows/wmmsg.h b/src/video/windows/wmmsg.h
index 8c1351f..5b9d499 100644
--- a/src/video/windows/wmmsg.h
+++ b/src/video/windows/wmmsg.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/winrt/SDL_winrtevents.cpp b/src/video/winrt/SDL_winrtevents.cpp
index 30cf016..00cd415 100644
--- a/src/video/winrt/SDL_winrtevents.cpp
+++ b/src/video/winrt/SDL_winrtevents.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -105,7 +105,7 @@ WINRT_XAMLThreadMain(void * userdata)
 }
 
 void
-WINRT_CycleXAMLThread()
+WINRT_CycleXAMLThread(void)
 {
     switch (_threadState) {
         case ThreadState_NotLaunched:
diff --git a/src/video/winrt/SDL_winrtevents_c.h b/src/video/winrt/SDL_winrtevents_c.h
index 05a90a3..1e54285 100644
--- a/src/video/winrt/SDL_winrtevents_c.h
+++ b/src/video/winrt/SDL_winrtevents_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -75,7 +75,7 @@ extern SDL_bool WINRT_IsScreenKeyboardShown(_THIS, SDL_Window *window);
 #endif  // NTDDI_VERSION >= ...
 
 /* XAML Thread Management */
-extern void WINRT_CycleXAMLThread();
+extern void WINRT_CycleXAMLThread(void);
 
 #endif // ifdef __cplusplus_winrt
 
diff --git a/src/video/winrt/SDL_winrtgamebar.cpp b/src/video/winrt/SDL_winrtgamebar.cpp
index 215dfcc..8eae1ad 100644
--- a/src/video/winrt/SDL_winrtgamebar.cpp
+++ b/src/video/winrt/SDL_winrtgamebar.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/winrt/SDL_winrtgamebar_cpp.h b/src/video/winrt/SDL_winrtgamebar_cpp.h
index afcef37..26ffd09 100644
--- a/src/video/winrt/SDL_winrtgamebar_cpp.h
+++ b/src/video/winrt/SDL_winrtgamebar_cpp.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "SDL_config.h"
 
-#ifndef _SDL_winrtgamebar_h
-#define _SDL_winrtgamebar_h
+#ifndef SDL_winrtgamebar_h_
+#define SDL_winrtgamebar_h_
 
 #ifdef __cplusplus
 /* These are exported as C++ functions, rather than C, to fix a compilation
@@ -30,6 +30,6 @@ extern void WINRT_InitGameBar(_THIS);
 extern void WINRT_QuitGameBar(_THIS);
 #endif
 
-#endif /* _SDL_winrtmouse_h */
+#endif /* SDL_winrtgamebar_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/winrt/SDL_winrtkeyboard.cpp b/src/video/winrt/SDL_winrtkeyboard.cpp
index affcae6..0396276 100644
--- a/src/video/winrt/SDL_winrtkeyboard.cpp
+++ b/src/video/winrt/SDL_winrtkeyboard.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -28,7 +28,7 @@
 
 
 /* SDL-specific includes */
-#include <SDL.h>
+#include "SDL.h"
 #include "SDL_winrtevents_c.h"
 
 extern "C" {
diff --git a/src/video/winrt/SDL_winrtmessagebox.cpp b/src/video/winrt/SDL_winrtmessagebox.cpp
index ca95810..824f856 100644
--- a/src/video/winrt/SDL_winrtmessagebox.cpp
+++ b/src/video/winrt/SDL_winrtmessagebox.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/winrt/SDL_winrtmessagebox.h b/src/video/winrt/SDL_winrtmessagebox.h
index 4184aa5..84c0aa3 100644
--- a/src/video/winrt/SDL_winrtmessagebox.h
+++ b/src/video/winrt/SDL_winrtmessagebox.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/winrt/SDL_winrtmouse.cpp b/src/video/winrt/SDL_winrtmouse.cpp
index 9997d6e..348656a 100644
--- a/src/video/winrt/SDL_winrtmouse.cpp
+++ b/src/video/winrt/SDL_winrtmouse.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/winrt/SDL_winrtmouse_c.h b/src/video/winrt/SDL_winrtmouse_c.h
index 464ba4d..3c74c67 100644
--- a/src/video/winrt/SDL_winrtmouse_c.h
+++ b/src/video/winrt/SDL_winrtmouse_c.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "SDL_config.h"
 
-#ifndef _SDL_winrtmouse_h
-#define _SDL_winrtmouse_h
+#ifndef SDL_winrtmouse_h_
+#define SDL_winrtmouse_h_
 
 #ifdef __cplusplus
 extern "C" {
@@ -35,6 +35,6 @@ extern SDL_bool WINRT_UsingRelativeMouseMode;
 }
 #endif
 
-#endif /* _SDL_winrtmouse_h */
+#endif /* SDL_winrtmouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/winrt/SDL_winrtopengles.cpp b/src/video/winrt/SDL_winrtopengles.cpp
index cca07fa..4edb566 100644
--- a/src/video/winrt/SDL_winrtopengles.cpp
+++ b/src/video/winrt/SDL_winrtopengles.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -28,6 +28,7 @@
 extern "C" {
 #include "SDL_winrtopengles.h"
 #include "SDL_loadso.h"
+#include "../SDL_egl_c.h"
 }
 
 /* Windows includes */
@@ -57,7 +58,7 @@ WINRT_GLES_LoadLibrary(_THIS, const char *path)
 {
     SDL_VideoData *video_data = (SDL_VideoData *)_this->driverdata;
 
-    if (SDL_EGL_LoadLibrary(_this, path, EGL_DEFAULT_DISPLAY) != 0) {
+    if (SDL_EGL_LoadLibrary(_this, path, EGL_DEFAULT_DISPLAY, 0) != 0) {
         return -1;
     }
 
@@ -87,11 +88,11 @@ WINRT_GLES_LoadLibrary(_THIS, const char *path)
         Microsoft::WRL::ComPtr<IUnknown> cpp_display = video_data->winrtEglWindow;
         _this->egl_data->egl_display = ((eglGetDisplay_Old_Function)_this->egl_data->eglGetDisplay)(cpp_display);
         if (!_this->egl_data->egl_display) {
-            return SDL_SetError("Could not get Windows 8.0 EGL display");
+            return SDL_EGL_SetError("Could not get Windows 8.0 EGL display", "eglGetDisplay");
         }
 
         if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE) {
-            return SDL_SetError("Could not initialize Windows 8.0 EGL");
+            return SDL_EGL_SetError("Could not initialize Windows 8.0 EGL", "eglInitialize");
         }
     } else {
         /* Declare some ANGLE/EGL initialization property-sets, as suggested by
@@ -132,7 +133,7 @@ WINRT_GLES_LoadLibrary(_THIS, const char *path)
          */
         eglGetPlatformDisplayEXT_Function eglGetPlatformDisplayEXT = (eglGetPlatformDisplayEXT_Function)_this->egl_data->eglGetProcAddress("eglGetPlatformDisplayEXT");
         if (!eglGetPlatformDisplayEXT) {
-            return SDL_SetError("Could not retrieve ANGLE/WinRT display function(s)");
+            return SDL_EGL_SetError("Could not retrieve ANGLE/WinRT display function(s)", "eglGetProcAddress");
         }
 
 #if (WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP)
@@ -141,7 +142,7 @@ WINRT_GLES_LoadLibrary(_THIS, const char *path)
          */
         _this->egl_data->egl_display = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, defaultDisplayAttributes);
         if (!_this->egl_data->egl_display) {
-            return SDL_SetError("Could not get 10_0+ EGL display");
+            return SDL_EGL_SetError("Could not get EGL display for Direct3D 10_0+", "eglGetPlatformDisplayEXT");
         }
 
         if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE)
@@ -153,7 +154,7 @@ WINRT_GLES_LoadLibrary(_THIS, const char *path)
              */
             _this->egl_data->egl_display = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, fl9_3DisplayAttributes);
             if (!_this->egl_data->egl_display) {
-                return SDL_SetError("Could not get 9_3 EGL display");
+                return SDL_EGL_SetError("Could not get EGL display for Direct3D 9_3", "eglGetPlatformDisplayEXT");
             }
 
             if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE) {
@@ -162,11 +163,11 @@ WINRT_GLES_LoadLibrary(_THIS, const char *path)
                  */
                 _this->egl_data->egl_display = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, warpDisplayAttributes);
                 if (!_this->egl_data->egl_display) {
-                    return SDL_SetError("Could not get WARP EGL display");
+                    return SDL_EGL_SetError("Could not get EGL display for Direct3D WARP", "eglGetPlatformDisplayEXT");
                 }
 
                 if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE) {
-                    return SDL_SetError("Could not initialize WinRT 8.x+ EGL");
+                    return SDL_EGL_SetError("Could not initialize WinRT 8.x+ EGL", "eglInitialize");
                 }
             }
         }
diff --git a/src/video/winrt/SDL_winrtopengles.h b/src/video/winrt/SDL_winrtopengles.h
index 1da757b..f1cdc49 100644
--- a/src/video/winrt/SDL_winrtopengles.h
+++ b/src/video/winrt/SDL_winrtopengles.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "SDL_config.h"
 
-#ifndef _SDL_winrtopengles_h
-#define _SDL_winrtopengles_h
+#ifndef SDL_winrtopengles_h_
+#define SDL_winrtopengles_h_
 
 #if SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL
 
@@ -38,7 +38,7 @@
 extern int WINRT_GLES_LoadLibrary(_THIS, const char *path);
 extern void WINRT_GLES_UnloadLibrary(_THIS);
 extern SDL_GLContext WINRT_GLES_CreateContext(_THIS, SDL_Window * window);
-extern void WINRT_GLES_SwapWindow(_THIS, SDL_Window * window);
+extern int WINRT_GLES_SwapWindow(_THIS, SDL_Window * window);
 extern int WINRT_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 
 
@@ -65,6 +65,6 @@ typedef EGLDisplay (EGLAPIENTRY *eglGetPlatformDisplayEXT_Function)(EGLenum, voi
 
 #endif /* SDL_VIDEO_DRIVER_WINRT && SDL_VIDEO_OPENGL_EGL */
 
-#endif /* _SDL_winrtopengles_h */
+#endif /* SDL_winrtopengles_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/winrt/SDL_winrtpointerinput.cpp b/src/video/winrt/SDL_winrtpointerinput.cpp
index 1d648f9..934f2a4 100644
--- a/src/video/winrt/SDL_winrtpointerinput.cpp
+++ b/src/video/winrt/SDL_winrtpointerinput.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -295,7 +295,7 @@ void WINRT_ProcessPointerReleasedEvent(SDL_Window *window, Windows::UI::Input::P
             }
             WINRT_LeftFingerDown = 0;
         }
-    
+
         SDL_SendTouch(
             WINRT_TouchID,
             (SDL_FingerID) pointerPoint->PointerId,
@@ -335,9 +335,8 @@ WINRT_ProcessPointerWheelChangedEvent(SDL_Window *window, Windows::UI::Input::Po
         return;
     }
 
-    // FIXME: This may need to accumulate deltas up to WHEEL_DELTA
-    short motion = pointerPoint->Properties->MouseWheelDelta / WHEEL_DELTA;
-    SDL_SendMouseWheel(window, 0, 0, motion, SDL_MOUSEWHEEL_NORMAL);
+    float motion = (float) pointerPoint->Properties->MouseWheelDelta / WHEEL_DELTA;
+    SDL_SendMouseWheel(window, 0, 0, (float) motion, SDL_MOUSEWHEEL_NORMAL);
 }
 
 void
@@ -369,7 +368,7 @@ WINRT_ProcessMouseMovedEvent(SDL_Window * window, Windows::Devices::Input::Mouse
     // http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.input.mouseeventargs.mousedelta ),
     // does not seem to indicate (to me) that its values should be so large.  It
     // says that its values should be a "change in screen location".  I could
-    // be misinterpreting this, however a post on MSDN from a Microsoft engineer (see: 
+    // be misinterpreting this, however a post on MSDN from a Microsoft engineer (see:
     // http://social.msdn.microsoft.com/Forums/en-US/winappswithnativecode/thread/09a9868e-95bb-4858-ba1a-cb4d2c298d62 ),
     // indicates that these values are in DIPs, which is the same unit used
     // by CoreWindow's PointerMoved events (via the Position field in its CurrentPoint
diff --git a/src/video/winrt/SDL_winrtvideo.cpp b/src/video/winrt/SDL_winrtvideo.cpp
index 9a26705..ad087e2 100644
--- a/src/video/winrt/SDL_winrtvideo.cpp
+++ b/src/video/winrt/SDL_winrtvideo.cpp
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -140,7 +140,7 @@ WINRT_CreateDevice(int devindex)
     /* Set the function pointers */
     device->VideoInit = WINRT_VideoInit;
     device->VideoQuit = WINRT_VideoQuit;
-    device->CreateWindow = WINRT_CreateWindow;
+    device->CreateSDLWindow = WINRT_CreateWindow;
     device->SetWindowSize = WINRT_SetWindowSize;
     device->SetWindowFullscreen = WINRT_SetWindowFullscreen;
     device->DestroyWindow = WINRT_DestroyWindow;
@@ -621,7 +621,7 @@ WINRT_CreateWindow(_THIS, SDL_Window * window)
                 _this->egl_data->egl_config,
                 cpp_winrtEglWindow, NULL);
             if (data->egl_surface == NULL) {
-                return SDL_SetError("eglCreateWindowSurface failed");
+                return SDL_EGL_SetError("unable to create EGL native-window surface", "eglCreateWindowSurface");
             }
         } else if (data->coreWindow.Get() != nullptr) {
             /* Attempt to create a window surface using newer versions of
@@ -634,7 +634,7 @@ WINRT_CreateWindow(_THIS, SDL_Window * window)
                 coreWindowAsIInspectable,
                 NULL);
             if (data->egl_surface == NULL) {
-                return SDL_SetError("eglCreateWindowSurface failed");
+                return SDL_EGL_SetError("unable to create EGL native-window surface", "eglCreateWindowSurface");
             }
         } else {
             return SDL_SetError("No supported means to create an EGL window surface are available");
@@ -771,7 +771,7 @@ WINRT_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
         info->info.winrt.window = reinterpret_cast<IInspectable *>(data->coreWindow.Get());
         return SDL_TRUE;
     } else {
-        SDL_SetError("Application not compiled with SDL %d.%d\n",
+        SDL_SetError("Application not compiled with SDL %d.%d",
                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
diff --git a/src/video/winrt/SDL_winrtvideo_cpp.h b/src/video/winrt/SDL_winrtvideo_cpp.h
index 7d5ce13..7ec1e40 100644
--- a/src/video/winrt/SDL_winrtvideo_cpp.h
+++ b/src/video/winrt/SDL_winrtvideo_cpp.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/x11/SDL_x11clipboard.c b/src/video/x11/SDL_x11clipboard.c
index 34c0a71..f471fdf 100644
--- a/src/video/x11/SDL_x11clipboard.c
+++ b/src/video/x11/SDL_x11clipboard.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -40,13 +40,23 @@
 static Window
 GetWindow(_THIS)
 {
-    SDL_Window *window;
-
-    window = _this->windows;
-    if (window) {
-        return ((SDL_WindowData *) window->driverdata)->xwindow;
+    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
+
+    /* We create an unmapped window that exists just to manage the clipboard,
+       since X11 selection data is tied to a specific window and dies with it.
+       We create the window on demand, so apps that don't use the clipboard
+       don't have to keep an unnecessary resource around. */
+    if (data->clipboard_window == None) {
+        Display *dpy = data->display;
+        Window parent = RootWindow(dpy, DefaultScreen(dpy));
+        XSetWindowAttributes xattr;
+        data->clipboard_window = X11_XCreateWindow(dpy, parent, -10, -10, 1, 1, 0,
+                                                   CopyFromParent, InputOnly,
+                                                   CopyFromParent, 0, &xattr);
+        X11_XFlush(data->display);
     }
-    return None;
+
+    return data->clipboard_window;
 }
 
 /* We use our own cut-buffer for intermediate storage instead of  
diff --git a/src/video/x11/SDL_x11clipboard.h b/src/video/x11/SDL_x11clipboard.h
index 15dae7d..aa846fa 100644
--- a/src/video/x11/SDL_x11clipboard.h
+++ b/src/video/x11/SDL_x11clipboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,14 +20,14 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11clipboard_h
-#define _SDL_x11clipboard_h
+#ifndef SDL_x11clipboard_h_
+#define SDL_x11clipboard_h_
 
 extern int X11_SetClipboardText(_THIS, const char *text);
 extern char *X11_GetClipboardText(_THIS);
 extern SDL_bool X11_HasClipboardText(_THIS);
 extern Atom X11_GetSDLCutBufferClipboardType(Display *display);
 
-#endif /* _SDL_x11clipboard_h */
+#endif /* SDL_x11clipboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11dyn.c b/src/video/x11/SDL_x11dyn.c
index d07fda7..d7caad9 100644
--- a/src/video/x11/SDL_x11dyn.c
+++ b/src/video/x11/SDL_x11dyn.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/x11/SDL_x11dyn.h b/src/video/x11/SDL_x11dyn.h
index be1ddaa..85e525f 100644
--- a/src/video/x11/SDL_x11dyn.h
+++ b/src/video/x11/SDL_x11dyn.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11dyn_h
-#define _SDL_x11dyn_h
+#ifndef SDL_x11dyn_h_
+#define SDL_x11dyn_h_
 
 #include <X11/Xlib.h>
 #include <X11/Xutil.h>
@@ -107,5 +107,5 @@ extern SDL_DYNX11FN_XGetICValues X11_XGetICValues;
 }
 #endif
 
-#endif                          /* !defined _SDL_x11dyn_h */
+#endif                          /* !defined SDL_x11dyn_h_ */
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11events.c b/src/video/x11/SDL_x11events.c
index 56d2368..4173cbb 100644
--- a/src/video/x11/SDL_x11events.c
+++ b/src/video/x11/SDL_x11events.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -31,6 +31,7 @@
 #include "SDL_x11video.h"
 #include "SDL_x11touch.h"
 #include "SDL_x11xinput2.h"
+#include "../../core/unix/SDL_poll.h"
 #include "../../events/SDL_events_c.h"
 #include "../../events/SDL_mouse_c.h"
 #include "../../events/SDL_touch_c.h"
@@ -38,6 +39,7 @@
 #include "SDL_hints.h"
 #include "SDL_timer.h"
 #include "SDL_syswm.h"
+#include "SDL_assert.h"
 
 #include <stdio.h>
 
@@ -201,7 +203,7 @@ X11_IsWheelEvent(Display * display,XEvent * event,int * xticks,int * yticks)
 
    On error, -1 is returned.
  */
-int X11_URIDecode(char *buf, int len) {
+static int X11_URIDecode(char *buf, int len) {
     int ri, wi, di;
     char decode = '\0';
     if (buf == NULL || len < 0) {
@@ -301,10 +303,10 @@ static char* X11_URIToLocal(char* uri) {
 }
 
 #if SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS
-static void X11_HandleGenericEvent(SDL_VideoData *videodata,XEvent event)
+static void X11_HandleGenericEvent(SDL_VideoData *videodata, XEvent *xev)
 {
     /* event is a union, so cookie == &event, but this is type safe. */
-    XGenericEventCookie *cookie = &event.xcookie;
+    XGenericEventCookie *cookie = &xev->xcookie;
     if (X11_XGetEventData(videodata->display, cookie)) {
         X11_HandleXinput2Event(videodata, cookie);
         X11_XFreeEventData(videodata->display, cookie);
@@ -348,6 +350,7 @@ X11_ReconcileKeyboardState(_THIS)
     Window junk_window;
     int x, y;
     unsigned int mask;
+    const Uint8 *keyboardState;
 
     X11_XQueryKeymap(display, keys);
 
@@ -357,11 +360,16 @@ X11_ReconcileKeyboardState(_THIS)
         SDL_ToggleModState(KMOD_NUM, (mask & X11_GetNumLockModifierMask(_this)) != 0);
     }
 
+    keyboardState = SDL_GetKeyboardState(0);
     for (keycode = 0; keycode < 256; ++keycode) {
-        if (keys[keycode / 8] & (1 << (keycode % 8))) {
-            SDL_SendKeyboardKey(SDL_PRESSED, viddata->key_layout[keycode]);
-        } else {
-            SDL_SendKeyboardKey(SDL_RELEASED, viddata->key_layout[keycode]);
+        SDL_Scancode scancode = viddata->key_layout[keycode];
+        SDL_bool x11KeyPressed = (keys[keycode / 8] & (1 << (keycode % 8))) != 0;
+        SDL_bool sdlKeyPressed = keyboardState[scancode] == SDL_PRESSED;
+
+        if (x11KeyPressed && !sdlKeyPressed) {
+            SDL_SendKeyboardKey(SDL_PRESSED, scancode);
+        } else if (!x11KeyPressed && sdlKeyPressed) {
+            SDL_SendKeyboardKey(SDL_RELEASED, scancode);
         }
     }
 }
@@ -531,6 +539,95 @@ X11_UpdateUserTime(SDL_WindowData *data, const unsigned long latest)
     }
 }
 
+static void
+X11_HandleClipboardEvent(_THIS, const XEvent *xevent)
+{
+    SDL_VideoData *videodata = (SDL_VideoData *) _this->driverdata;
+    Display *display = videodata->display;
+
+    SDL_assert(videodata->clipboard_window != None);
+    SDL_assert(xevent->xany.window == videodata->clipboard_window);
+
+    switch (xevent->type) {
+    /* Copy the selection from our own CUTBUFFER to the requested property */
+        case SelectionRequest: {
+            const XSelectionRequestEvent *req = &xevent->xselectionrequest;
+            XEvent sevent;
+            int seln_format;
+            unsigned long nbytes;
+            unsigned long overflow;
+            unsigned char *seln_data;
+
+#ifdef DEBUG_XEVENTS
+            printf("window CLIPBOARD: SelectionRequest (requestor = %ld, target = %ld)\n",
+                req->requestor, req->target);
+#endif
+
+            SDL_zero(sevent);
+            sevent.xany.type = SelectionNotify;
+            sevent.xselection.selection = req->selection;
+            sevent.xselection.target = None;
+            sevent.xselection.property = None;  /* tell them no by default */
+            sevent.xselection.requestor = req->requestor;
+            sevent.xselection.time = req->time;
+
+            /* !!! FIXME: We were probably storing this on the root window
+               because an SDL window might go away...? but we don't have to do
+               this now (or ever, really). */
+            if (X11_XGetWindowProperty(display, DefaultRootWindow(display),
+                    X11_GetSDLCutBufferClipboardType(display), 0, INT_MAX/4, False, req->target,
+                    &sevent.xselection.target, &seln_format, &nbytes,
+                    &overflow, &seln_data) == Success) {
+                /* !!! FIXME: cache atoms */
+                Atom XA_TARGETS = X11_XInternAtom(display, "TARGETS", 0);
+                if (sevent.xselection.target == req->target) {
+                    X11_XChangeProperty(display, req->requestor, req->property,
+                        sevent.xselection.target, seln_format, PropModeReplace,
+                        seln_data, nbytes);
+                    sevent.xselection.property = req->property;
+                } else if (XA_TARGETS == req->target) {
+                    Atom SupportedFormats[] = { XA_TARGETS, sevent.xselection.target };
+                    X11_XChangeProperty(display, req->requestor, req->property,
+                        XA_ATOM, 32, PropModeReplace,
+                        (unsigned char*)SupportedFormats,
+                        SDL_arraysize(SupportedFormats));
+                    sevent.xselection.property = req->property;
+                    sevent.xselection.target = XA_TARGETS;
+                }
+                X11_XFree(seln_data);
+            }
+            X11_XSendEvent(display, req->requestor, False, 0, &sevent);
+            X11_XSync(display, False);
+        }
+        break;
+
+        case SelectionNotify: {
+#ifdef DEBUG_XEVENTS
+            printf("window CLIPBOARD: SelectionNotify (requestor = %ld, target = %ld)\n",
+                xevent->xselection.requestor, xevent->xselection.target);
+#endif
+            videodata->selection_waiting = SDL_FALSE;
+        }
+        break;
+
+        case SelectionClear: {
+            /* !!! FIXME: cache atoms */
+            Atom XA_CLIPBOARD = X11_XInternAtom(display, "CLIPBOARD", 0);
+
+#ifdef DEBUG_XEVENTS
+            printf("window CLIPBOARD: SelectionClear (requestor = %ld, target = %ld)\n",
+                xevent->xselection.requestor, xevent->xselection.target);
+#endif
+
+            if (xevent->xselectionclear.selection == XA_PRIMARY ||
+                (XA_CLIPBOARD != None && xevent->xselectionclear.selection == XA_CLIPBOARD)) {
+                SDL_SendClipboardUpdate();
+            }
+        }
+        break;
+    }
+}
+
 
 static void
 X11_DispatchEvent(_THIS)
@@ -568,14 +665,21 @@ X11_DispatchEvent(_THIS)
         printf("Filtered event type = %d display = %d window = %d\n",
                xevent.type, xevent.xany.display, xevent.xany.window);
 #endif
+        /* Make sure dead key press/release events are sent */
+        /* But only if we're using one of the DBus IMEs, otherwise
+           some XIM IMEs will generate duplicate events */
         if (orig_keycode) {
-            /* Make sure dead key press/release events are sent */
+#if defined(HAVE_IBUS_IBUS_H) || defined(HAVE_FCITX_FRONTEND_H)
             SDL_Scancode scancode = videodata->key_layout[orig_keycode];
+            videodata->filter_code = orig_keycode;
+            videodata->filter_time = xevent.xkey.time;
+
             if (orig_event_type == KeyPress) {
                 SDL_SendKeyboardKey(SDL_PRESSED, scancode);
             } else {
                 SDL_SendKeyboardKey(SDL_RELEASED, scancode);
             }
+#endif
         }
         return;
     }
@@ -592,7 +696,7 @@ X11_DispatchEvent(_THIS)
 
 #if SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS
     if(xevent.type == GenericEvent) {
-        X11_HandleGenericEvent(videodata,xevent);
+        X11_HandleGenericEvent(videodata, &xevent);
         return;
     }
 #endif
@@ -602,6 +706,12 @@ X11_DispatchEvent(_THIS)
            xevent.type, xevent.xany.display, xevent.xany.window);
 #endif
 
+    if ((videodata->clipboard_window != None) &&
+        (videodata->clipboard_window == xevent.xany.window)) {
+        X11_HandleClipboardEvent(_this, &xevent);
+        return;
+    }
+
     data = NULL;
     if (videodata && videodata->windowlist) {
         for (i = 0; i < videodata->numwindows; ++i) {
@@ -768,7 +878,7 @@ X11_DispatchEvent(_THIS)
                 X11_XDisplayKeycodes(display, &min_keycode, &max_keycode);
                 keysym = X11_KeyCodeToSym(_this, keycode, xevent.xkey.state >> 13);
                 fprintf(stderr,
-                        "The key you just pressed is not recognized by SDL. To help get this fixed, please report this to the SDL mailing list <sdl at libsdl.org> X11 KeyCode %d (%d), X11 KeySym 0x%lX (%s).\n",
+                        "The key you just pressed is not recognized by SDL. To help get this fixed, please report this to the SDL forums/mailing list <https://discourse.libsdl.org/> X11 KeyCode %d (%d), X11 KeySym 0x%lX (%s).\n",
                         keycode, keycode - min_keycode, keysym,
                         X11_XKeysymToString(keysym));
             }
@@ -792,7 +902,10 @@ X11_DispatchEvent(_THIS)
             }
 #endif
             if (!handled_by_ime) {
-                SDL_SendKeyboardKey(SDL_PRESSED, videodata->key_layout[keycode]);
+                /* Don't send the key if it looks like a duplicate of a filtered key sent by an IME */
+                if (xevent.xkey.keycode != videodata->filter_code || xevent.xkey.time != videodata->filter_time) {
+                    SDL_SendKeyboardKey(SDL_PRESSED, videodata->key_layout[keycode]);
+                }
                 if(*text) {
                     SDL_SendKeyboardText(text);
                 }
@@ -892,7 +1005,7 @@ X11_DispatchEvent(_THIS)
                 printf("Protocol version to use : %d\n", xdnd_version);
                 printf("More then 3 data types : %d\n", (int) use_list);
 #endif
- 
+
                 if (use_list) {
                     /* fetch conversion targets */
                     SDL_x11Prop p;
@@ -906,7 +1019,7 @@ X11_DispatchEvent(_THIS)
                 }
             }
             else if (xevent.xclient.message_type == videodata->XdndPosition) {
-            
+
 #ifdef DEBUG_XEVENTS
                 Atom act= videodata->XdndActionCopy;
                 if(xdnd_version >= 2) {
@@ -914,7 +1027,7 @@ X11_DispatchEvent(_THIS)
                 }
                 printf("Action requested by user is : %s\n", X11_XGetAtomName(display , act));
 #endif
-                
+
 
                 /* reply with status */
                 memset(&m, 0, sizeof(XClientMessageEvent));
@@ -1017,7 +1130,7 @@ X11_DispatchEvent(_THIS)
             printf("window %p: ButtonPress (X11 button = %d)\n", data, xevent.xbutton.button);
 #endif
             if (X11_IsWheelEvent(display,&xevent,&xticks, &yticks)) {
-                SDL_SendMouseWheel(data->window, 0, xticks, yticks, SDL_MOUSEWHEEL_NORMAL);
+                SDL_SendMouseWheel(data->window, 0, (float) xticks, (float) yticks, SDL_MOUSEWHEEL_NORMAL);
             } else {
                 SDL_bool ignore_click = SDL_FALSE;
                 int button = xevent.xbutton.button;
@@ -1207,55 +1320,6 @@ X11_DispatchEvent(_THIS)
         }
         break;
 
-    /* Copy the selection from our own CUTBUFFER to the requested property */
-    case SelectionRequest: {
-            XSelectionRequestEvent *req;
-            XEvent sevent;
-            int seln_format;
-            unsigned long nbytes;
-            unsigned long overflow;
-            unsigned char *seln_data;
-
-            req = &xevent.xselectionrequest;
-#ifdef DEBUG_XEVENTS
-            printf("window %p: SelectionRequest (requestor = %ld, target = %ld)\n", data,
-                req->requestor, req->target);
-#endif
-
-            SDL_zero(sevent);
-            sevent.xany.type = SelectionNotify;
-            sevent.xselection.selection = req->selection;
-            sevent.xselection.target = None;
-            sevent.xselection.property = None;
-            sevent.xselection.requestor = req->requestor;
-            sevent.xselection.time = req->time;
-
-            if (X11_XGetWindowProperty(display, DefaultRootWindow(display),
-                    X11_GetSDLCutBufferClipboardType(display), 0, INT_MAX/4, False, req->target,
-                    &sevent.xselection.target, &seln_format, &nbytes,
-                    &overflow, &seln_data) == Success) {
-                Atom XA_TARGETS = X11_XInternAtom(display, "TARGETS", 0);
-                if (sevent.xselection.target == req->target) {
-                    X11_XChangeProperty(display, req->requestor, req->property,
-                        sevent.xselection.target, seln_format, PropModeReplace,
-                        seln_data, nbytes);
-                    sevent.xselection.property = req->property;
-                } else if (XA_TARGETS == req->target) {
-                    Atom SupportedFormats[] = { XA_TARGETS, sevent.xselection.target };
-                    X11_XChangeProperty(display, req->requestor, req->property,
-                        XA_ATOM, 32, PropModeReplace,
-                        (unsigned char*)SupportedFormats,
-                        SDL_arraysize(SupportedFormats));
-                    sevent.xselection.property = req->property;
-                    sevent.xselection.target = XA_TARGETS;
-                }
-                X11_XFree(seln_data);
-            }
-            X11_XSendEvent(display, req->requestor, False, 0, &sevent);
-            X11_XSync(display, False);
-        }
-        break;
-
     case SelectionNotify: {
             Atom target = xevent.xselection.target;
 #ifdef DEBUG_XEVENTS
@@ -1299,19 +1363,6 @@ X11_DispatchEvent(_THIS)
                 X11_XSendEvent(display, data->xdnd_source, False, NoEventMask, (XEvent*)&m);
 
                 X11_XSync(display, False);
-
-            } else {
-                videodata->selection_waiting = SDL_FALSE;
-            }
-        }
-        break;
-
-    case SelectionClear: {
-            Atom XA_CLIPBOARD = X11_XInternAtom(display, "CLIPBOARD", 0);
-
-            if (xevent.xselectionclear.selection == XA_PRIMARY ||
-                (XA_CLIPBOARD != None && xevent.xselectionclear.selection == XA_CLIPBOARD)) {
-                SDL_SendClipboardUpdate();
             }
         }
         break;
@@ -1359,17 +1410,8 @@ X11_Pending(Display * display)
     }
 
     /* More drastic measures are required -- see if X is ready to talk */
-    {
-        static struct timeval zero_time;        /* static == 0 */
-        int x11_fd;
-        fd_set fdset;
-
-        x11_fd = ConnectionNumber(display);
-        FD_ZERO(&fdset);
-        FD_SET(x11_fd, &fdset);
-        if (select(x11_fd + 1, &fdset, NULL, NULL, &zero_time) == 1) {
-            return (X11_XPending(display));
-        }
+    if (SDL_IOReady(ConnectionNumber(display), SDL_FALSE, 0)) {
+        return (X11_XPending(display));
     }
 
     /* Oh well, nothing is ready .. */
diff --git a/src/video/x11/SDL_x11events.h b/src/video/x11/SDL_x11events.h
index 024fca3..257ad70 100644
--- a/src/video/x11/SDL_x11events.h
+++ b/src/video/x11/SDL_x11events.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,12 +20,12 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11events_h
-#define _SDL_x11events_h
+#ifndef SDL_x11events_h_
+#define SDL_x11events_h_
 
 extern void X11_PumpEvents(_THIS);
 extern void X11_SuspendScreenSaver(_THIS);
 
-#endif /* _SDL_x11events_h */
+#endif /* SDL_x11events_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11framebuffer.c b/src/video/x11/SDL_x11framebuffer.c
index a488616..afd1d51 100644
--- a/src/video/x11/SDL_x11framebuffer.c
+++ b/src/video/x11/SDL_x11framebuffer.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -97,7 +97,7 @@ X11_CreateWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format,
                 shm_error = False;
                 X_handler = X11_XSetErrorHandler(shm_errhandler);
                 X11_XShmAttach(display, shminfo);
-                X11_XSync(display, True);
+                X11_XSync(display, False);
                 X11_XSetErrorHandler(X_handler);
                 if ( shm_error )
                     shmdt(shminfo->shmaddr);
diff --git a/src/video/x11/SDL_x11framebuffer.h b/src/video/x11/SDL_x11framebuffer.h
index 7326e7d..cd78653 100644
--- a/src/video/x11/SDL_x11framebuffer.h
+++ b/src/video/x11/SDL_x11framebuffer.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/x11/SDL_x11keyboard.c b/src/video/x11/SDL_x11keyboard.c
index b888bff..fee710d 100644
--- a/src/video/x11/SDL_x11keyboard.c
+++ b/src/video/x11/SDL_x11keyboard.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,6 +33,10 @@
 
 #include "imKStoUCS.h"
 
+#ifdef X_HAVE_UTF8_STRING
+#include <locale.h>
+#endif
+
 /* *INDENT-OFF* */
 static const struct {
     KeySym keysym;
@@ -262,19 +266,82 @@ X11_InitKeyboard(_THIS)
     int best_distance;
     int best_index;
     int distance;
-
+    BOOL xkb_repeat = 0;
+    
     X11_XAutoRepeatOn(data->display);
 
 #if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
     {
-	    int xkb_major = XkbMajorVersion;
-	    int xkb_minor = XkbMinorVersion;
-	    if (X11_XkbQueryExtension(data->display, NULL, NULL, NULL, &xkb_major, &xkb_minor)) {
-	        data->xkb = X11_XkbGetMap(data->display, XkbAllClientInfoMask, XkbUseCoreKbd);
-	    }
-	}
+        int xkb_major = XkbMajorVersion;
+        int xkb_minor = XkbMinorVersion;
+
+        if (X11_XkbQueryExtension(data->display, NULL, NULL, NULL, &xkb_major, &xkb_minor)) {
+            data->xkb = X11_XkbGetMap(data->display, XkbAllClientInfoMask, XkbUseCoreKbd);
+        }
+
+        /* This will remove KeyRelease events for held keys */
+        X11_XkbSetDetectableAutoRepeat(data->display, True, &xkb_repeat);
+    }
+#endif
+    
+    /* Open a connection to the X input manager */
+#ifdef X_HAVE_UTF8_STRING
+    if (SDL_X11_HAVE_UTF8) {
+        /* Set the locale, and call XSetLocaleModifiers before XOpenIM so that 
+           Compose keys will work correctly. */
+        char *prev_locale = setlocale(LC_ALL, NULL);
+        char *prev_xmods  = X11_XSetLocaleModifiers(NULL);
+        const char *new_xmods = "";
+#if defined(HAVE_IBUS_IBUS_H) || defined(HAVE_FCITX_FRONTEND_H)
+        const char *env_xmods = SDL_getenv("XMODIFIERS");
+#endif
+        SDL_bool has_dbus_ime_support = SDL_FALSE;
+
+        if (prev_locale) {
+            prev_locale = SDL_strdup(prev_locale);
+        }
+
+        if (prev_xmods) {
+            prev_xmods = SDL_strdup(prev_xmods);
+        }
+
+        /* IBus resends some key events that were filtered by XFilterEvents
+           when it is used via XIM which causes issues. Prevent this by forcing
+           @im=none if XMODIFIERS contains @im=ibus. IBus can still be used via 
+           the DBus implementation, which also has support for pre-editing. */
+#ifdef HAVE_IBUS_IBUS_H
+        if (env_xmods && SDL_strstr(env_xmods, "@im=ibus") != NULL) {
+            has_dbus_ime_support = SDL_TRUE;
+        }
 #endif
+#ifdef HAVE_FCITX_FRONTEND_H
+        if (env_xmods && SDL_strstr(env_xmods, "@im=fcitx") != NULL) {
+            has_dbus_ime_support = SDL_TRUE;
+        }
+#endif
+        if (has_dbus_ime_support || !xkb_repeat) {
+            new_xmods = "@im=none";
+        }
+
+        setlocale(LC_ALL, "");
+        X11_XSetLocaleModifiers(new_xmods);
 
+        data->im = X11_XOpenIM(data->display, NULL, data->classname, data->classname);
+
+        /* Reset the locale + X locale modifiers back to how they were,
+           locale first because the X locale modifiers depend on it. */
+        setlocale(LC_ALL, prev_locale);
+        X11_XSetLocaleModifiers(prev_xmods);
+
+        if (prev_locale) {
+            SDL_free(prev_locale);
+        }
+
+        if (prev_xmods) {
+            SDL_free(prev_xmods);
+        }
+    }
+#endif
     /* Try to determine which scancodes are being used based on fingerprint */
     best_distance = SDL_arraysize(fingerprint) + 1;
     best_index = -1;
@@ -313,7 +380,7 @@ X11_InitKeyboard(_THIS)
         SDL_Keycode keymap[SDL_NUM_SCANCODES];
 
         printf
-            ("Keyboard layout unknown, please send the following to the SDL mailing list (sdl at libsdl.org):\n");
+            ("Keyboard layout unknown, please report the following to the SDL forums/mailing list (https://discourse.libsdl.org/):\n");
 
         /* Determine key_layout - only works on US QWERTY layout */
         SDL_GetDefaultKeymap(keymap);
@@ -417,7 +484,7 @@ X11_QuitKeyboard(_THIS)
 
 #if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
     if (data->xkb) {
-        X11_XkbFreeClientMap(data->xkb, 0, True);
+        X11_XkbFreeKeyboard(data->xkb, 0, True);
         data->xkb = NULL;
     }
 #endif
diff --git a/src/video/x11/SDL_x11keyboard.h b/src/video/x11/SDL_x11keyboard.h
index 6ce3c9c..30281f6 100644
--- a/src/video/x11/SDL_x11keyboard.h
+++ b/src/video/x11/SDL_x11keyboard.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11keyboard_h
-#define _SDL_x11keyboard_h
+#ifndef SDL_x11keyboard_h_
+#define SDL_x11keyboard_h_
 
 extern int X11_InitKeyboard(_THIS);
 extern void X11_UpdateKeymap(_THIS);
@@ -31,6 +31,6 @@ extern void X11_StopTextInput(_THIS);
 extern void X11_SetTextInputRect(_THIS, SDL_Rect *rect);
 extern KeySym X11_KeyCodeToSym(_THIS, KeyCode, unsigned char group);
 
-#endif /* _SDL_x11keyboard_h */
+#endif /* SDL_x11keyboard_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11messagebox.c b/src/video/x11/SDL_x11messagebox.c
index fc8b1b2..789fa51 100644
--- a/src/video/x11/SDL_x11messagebox.c
+++ b/src/video/x11/SDL_x11messagebox.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -27,6 +27,7 @@
 #include "SDL_x11video.h"
 #include "SDL_x11dyn.h"
 #include "SDL_assert.h"
+#include "SDL_x11messagebox.h"
 
 #include <X11/keysym.h>
 #include <locale.h>
@@ -49,7 +50,7 @@
 #define MIN_DIALOG_HEIGHT       100     /* Minimum dialog height */
 
 static const char g_MessageBoxFontLatin1[] = "-*-*-medium-r-normal--0-120-*-*-p-0-iso8859-1";
-static const char g_MessageBoxFont[] = "-*-*-*-*-*-*-*-120-*-*-*-*-*-*";
+static const char g_MessageBoxFont[] = "-*-*-medium-r-normal--*-120-*-*-*-*-*-*";
 
 static const SDL_MessageBoxColor g_default_colors[ SDL_MESSAGEBOX_COLOR_MAX ] = {
     { 56,  54,  53  }, /* SDL_MESSAGEBOX_COLOR_BACKGROUND, */
@@ -377,10 +378,11 @@ X11_MessageBoxCreateWindow( SDL_MessageBoxDataX11 *data )
     int x, y;
     XSizeHints *sizehints;
     XSetWindowAttributes wnd_attr;
-    Atom _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_DIALOG, _NET_WM_NAME, UTF8_STRING;
+    Atom _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_DIALOG, _NET_WM_NAME;
     Display *display = data->display;
     SDL_WindowData *windowdata = NULL;
     const SDL_MessageBoxData *messageboxdata = data->messageboxdata;
+    char *title_locale = NULL;
 
     if ( messageboxdata->window ) {
         SDL_DisplayData *displaydata =
@@ -413,10 +415,30 @@ X11_MessageBoxCreateWindow( SDL_MessageBoxDataX11 *data )
 
     X11_XStoreName( display, data->window, messageboxdata->title );
     _NET_WM_NAME = X11_XInternAtom(display, "_NET_WM_NAME", False);
-    UTF8_STRING = X11_XInternAtom(display, "UTF8_STRING", False);
-    X11_XChangeProperty(display, data->window, _NET_WM_NAME, UTF8_STRING, 8,
-                    PropModeReplace, (unsigned char *) messageboxdata->title,
-                    strlen(messageboxdata->title) + 1 );
+
+    title_locale = SDL_iconv_utf8_locale(messageboxdata->title);
+    if (title_locale) {
+        XTextProperty titleprop;
+        Status status = X11_XStringListToTextProperty(&title_locale, 1, &titleprop);
+        SDL_free(title_locale);
+        if (status) {
+            X11_XSetTextProperty(display, data->window, &titleprop, XA_WM_NAME);
+            X11_XFree(titleprop.value);
+        }
+    }
+
+#ifdef X_HAVE_UTF8_STRING
+    if (SDL_X11_HAVE_UTF8) {
+        XTextProperty titleprop;
+        Status status = X11_Xutf8TextListToTextProperty(display, (char **) &messageboxdata->title, 1,
+                                            XUTF8StringStyle, &titleprop);
+        if (status == Success) {
+            X11_XSetTextProperty(display, data->window, &titleprop,
+                                 _NET_WM_NAME);
+            X11_XFree(titleprop.value);
+        }
+    }
+#endif
 
     /* Let the window manager know this is a dialog box */
     _NET_WM_WINDOW_TYPE = X11_XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
diff --git a/src/video/x11/SDL_x11messagebox.h b/src/video/x11/SDL_x11messagebox.h
index c77c57f..7519919 100644
--- a/src/video/x11/SDL_x11messagebox.h
+++ b/src/video/x11/SDL_x11messagebox.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/x11/SDL_x11modes.c b/src/video/x11/SDL_x11modes.c
index 29307b3..d7c032d 100644
--- a/src/video/x11/SDL_x11modes.c
+++ b/src/video/x11/SDL_x11modes.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -134,14 +134,14 @@ X11_GetPixelFormatFromVisualInfo(Display * display, XVisualInfo * vinfo)
             } else {
                 return SDL_PIXELFORMAT_INDEX4MSB;
             }
-            break;
+            /* break; -Wunreachable-code-break */
         case 1:
             if (BitmapBitOrder(display) == LSBFirst) {
                 return SDL_PIXELFORMAT_INDEX1LSB;
             } else {
                 return SDL_PIXELFORMAT_INDEX1MSB;
             }
-            break;
+            /* break; -Wunreachable-code-break */
         }
     }
 
@@ -149,7 +149,7 @@ X11_GetPixelFormatFromVisualInfo(Display * display, XVisualInfo * vinfo)
 }
 
 /* Global for the error handler */
-int vm_event, vm_error = -1;
+static int vm_event, vm_error = -1;
 
 #if SDL_VIDEO_DRIVER_X11_XINERAMA
 static SDL_bool
@@ -349,7 +349,7 @@ SetXRandRDisplayName(Display *dpy, Atom EDID, char *name, const size_t namelen,
 }
 
 
-int
+static int
 X11_InitModes_XRandR(_THIS)
 {
     SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
@@ -396,9 +396,16 @@ X11_InitModes_XRandR(_THIS)
                 X11_XFree(pixmapformats);
             }
 
-            res = X11_XRRGetScreenResources(dpy, RootWindow(dpy, screen));
-            if (!res) {
-                continue;
+            res = X11_XRRGetScreenResourcesCurrent(dpy, RootWindow(dpy, screen));
+            if (!res || res->noutput == 0) {
+                if (res) {
+                    X11_XRRFreeScreenResources(res);
+                }
+
+                res = X11_XRRGetScreenResources(dpy, RootWindow(dpy, screen));
+                if (!res) {
+                    continue;
+                }
             }
 
             for (output = 0; output < res->noutput; output++) {
@@ -464,8 +471,8 @@ X11_InitModes_XRandR(_THIS)
                 displaydata->screen = screen;
                 displaydata->visual = vinfo.visual;
                 displaydata->depth = vinfo.depth;
-                displaydata->hdpi = ((float) mode.w) * 25.4f / display_mm_width;
-                displaydata->vdpi = ((float) mode.h) * 25.4f / display_mm_height;
+                displaydata->hdpi = display_mm_width ? (((float) mode.w) * 25.4f / display_mm_width) : 0.0f;
+                displaydata->vdpi = display_mm_height ? (((float) mode.h) * 25.4f / display_mm_height) : 0.0f;
                 displaydata->ddpi = SDL_ComputeDiagonalDPI(mode.w, mode.h, ((float) display_mm_width) / 25.4f,((float) display_mm_height) / 25.4f);
                 displaydata->scanline_pad = scanline_pad;
                 displaydata->x = display_x;
@@ -569,7 +576,7 @@ CalculateXVidModeRefreshRate(const XF86VidModeModeInfo * info)
                                                          info->vtotal)) : 0;
 }
 
-SDL_bool
+static SDL_bool
 SetXVidModeModeInfo(const XF86VidModeModeInfo *info, SDL_DisplayMode *mode)
 {
     mode->w = info->hdisplay;
@@ -584,7 +591,7 @@ int
 X11_InitModes(_THIS)
 {
     SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
-    int snum, screen, screencount;
+    int snum, screen, screencount = 0;
 #if SDL_VIDEO_DRIVER_X11_XINERAMA
     int xinerama_major, xinerama_minor;
     int use_xinerama = 0;
@@ -604,7 +611,8 @@ X11_InitModes(_THIS)
     /* require at least XRandR v1.3 */
     if (CheckXRandR(data->display, &xrandr_major, &xrandr_minor) &&
         (xrandr_major >= 2 || (xrandr_major == 1 && xrandr_minor >= 3))) {
-        return X11_InitModes_XRandR(_this);
+        if (X11_InitModes_XRandR(_this) == 0)
+            return 0;
     }
 #endif /* SDL_VIDEO_DRIVER_X11_XRANDR */
 
@@ -741,9 +749,9 @@ X11_InitModes(_THIS)
         displaydata->visual = vinfo.visual;
         displaydata->depth = vinfo.depth;
 
-        // We use the displaydata screen index here so that this works
-        // for both the Xinerama case, where we get the overall DPI,
-        // and the regular X11 screen info case.
+        /* We use the displaydata screen index here so that this works
+           for both the Xinerama case, where we get the overall DPI,
+           and the regular X11 screen info case. */
         displaydata->hdpi = (float)DisplayWidth(data->display, displaydata->screen) * 25.4f /
             DisplayWidthMM(data->display, displaydata->screen);
         displaydata->vdpi = (float)DisplayHeight(data->display, displaydata->screen) * 25.4f /
@@ -824,8 +832,6 @@ X11_GetDisplayModes(_THIS, SDL_VideoDisplay * sdl_display)
     int nmodes;
     XF86VidModeModeInfo ** modes;
 #endif
-    int screen_w;
-    int screen_h;
     SDL_DisplayMode mode;
 
     /* Unfortunately X11 requires the window to be created with the correct
@@ -837,11 +843,14 @@ X11_GetDisplayModes(_THIS, SDL_VideoDisplay * sdl_display)
     mode.format = sdl_display->current_mode.format;
     mode.driverdata = NULL;
 
-    screen_w = DisplayWidth(display, data->screen);
-    screen_h = DisplayHeight(display, data->screen);
-
 #if SDL_VIDEO_DRIVER_X11_XINERAMA
     if (data->use_xinerama) {
+        int screen_w;
+        int screen_h;
+
+        screen_w = DisplayWidth(display, data->screen);
+        screen_h = DisplayHeight(display, data->screen);
+
         if (data->use_vidmode && !data->xinerama_info.x_org && !data->xinerama_info.y_org &&
            (screen_w > data->xinerama_info.width || screen_h > data->xinerama_info.height)) {
             SDL_DisplayModeData *modedata;
diff --git a/src/video/x11/SDL_x11modes.h b/src/video/x11/SDL_x11modes.h
index 4f47f3b..e837085 100644
--- a/src/video/x11/SDL_x11modes.h
+++ b/src/video/x11/SDL_x11modes.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11modes_h
-#define _SDL_x11modes_h
+#ifndef SDL_x11modes_h_
+#define SDL_x11modes_h_
 
 typedef struct
 {
@@ -80,6 +80,6 @@ extern int X11_GetDisplayBounds(_THIS, SDL_VideoDisplay * sdl_display, SDL_Rect
 extern int X11_GetDisplayUsableBounds(_THIS, SDL_VideoDisplay * sdl_display, SDL_Rect * rect);
 extern int X11_GetDisplayDPI(_THIS, SDL_VideoDisplay * sdl_display, float * ddpi, float * hdpi, float * vdpi);
 
-#endif /* _SDL_x11modes_h */
+#endif /* SDL_x11modes_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11mouse.c b/src/video/x11/SDL_x11mouse.c
index e1a16c2..60b052b 100644
--- a/src/video/x11/SDL_x11mouse.c
+++ b/src/video/x11/SDL_x11mouse.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -309,22 +309,26 @@ X11_ShowCursor(SDL_Cursor * cursor)
 }
 
 static void
+WarpMouseInternal(Window xwindow, const int x, const int y)
+{
+    SDL_VideoData *videodata = (SDL_VideoData *) SDL_GetVideoDevice()->driverdata;
+    Display *display = videodata->display;
+    X11_XWarpPointer(display, None, xwindow, 0, 0, 0, 0, x, y);
+    X11_XSync(display, False);
+    videodata->global_mouse_changed = SDL_TRUE;
+}
+
+static void
 X11_WarpMouse(SDL_Window * window, int x, int y)
 {
     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
-    Display *display = data->videodata->display;
-
-    X11_XWarpPointer(display, None, data->xwindow, 0, 0, 0, 0, x, y);
-    X11_XSync(display, False);
+    WarpMouseInternal(data->xwindow, x, y);
 }
 
 static int
 X11_WarpMouseGlobal(int x, int y)
 {
-    Display *display = GetDisplay();
-
-    X11_XWarpPointer(display, None, DefaultRootWindow(display), 0, 0, 0, 0, x, y);
-    X11_XSync(display, False);
+    WarpMouseInternal(DefaultRootWindow(GetDisplay()), x, y);
     return 0;
 }
 
diff --git a/src/video/x11/SDL_x11mouse.h b/src/video/x11/SDL_x11mouse.h
index d31d6b7..853f80c 100644
--- a/src/video/x11/SDL_x11mouse.h
+++ b/src/video/x11/SDL_x11mouse.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,12 +20,12 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11mouse_h
-#define _SDL_x11mouse_h
+#ifndef SDL_x11mouse_h_
+#define SDL_x11mouse_h_
 
 extern void X11_InitMouse(_THIS);
 extern void X11_QuitMouse(_THIS);
 
-#endif /* _SDL_x11mouse_h */
+#endif /* SDL_x11mouse_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11opengl.c b/src/video/x11/SDL_x11opengl.c
index abc699d..ab1bf58 100644
--- a/src/video/x11/SDL_x11opengl.c
+++ b/src/video/x11/SDL_x11opengl.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -24,6 +24,7 @@
 
 #include "SDL_x11video.h"
 #include "SDL_assert.h"
+#include "SDL_hints.h"
 
 /* GLX implementation of SDL OpenGL support */
 
@@ -113,6 +114,13 @@ typedef GLXContext(*PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display * dpy,
 #endif
 #endif
 
+#ifndef GLX_ARB_create_context_no_error
+#define GLX_ARB_create_context_no_error
+#ifndef GLX_CONTEXT_OPENGL_NO_ERROR_ARB
+#define GLX_CONTEXT_OPENGL_NO_ERROR_ARB                 0x31B3
+#endif
+#endif
+
 #ifndef GLX_EXT_swap_control
 #define GLX_SWAP_INTERVAL_EXT              0x20F1
 #define GLX_MAX_SWAP_INTERVAL_EXT          0x20F2
@@ -143,7 +151,6 @@ typedef GLXContext(*PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display * dpy,
 
 static void X11_GL_InitExtensions(_THIS);
 
-
 int
 X11_GL_LoadLibrary(_THIS, const char *path)
 {
@@ -222,13 +229,17 @@ X11_GL_LoadLibrary(_THIS, const char *path)
     }
 
     /* Initialize extensions */
+    /* See lengthy comment about the inc/dec in 
+       ../windows/SDL_windowsopengl.c. */
+    ++_this->gl_config.driver_loaded;
     X11_GL_InitExtensions(_this);
+    --_this->gl_config.driver_loaded;
     
     /* If we need a GL ES context and there's no  
      * GLX_EXT_create_context_es2_profile extension, switch over to X11_GLES functions  
      */
     if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES && 
-        ! _this->gl_data->HAS_GLX_EXT_create_context_es2_profile ) {
+        X11_GL_UseEGL(_this) ) {
 #if SDL_VIDEO_OPENGL_EGL
         X11_GL_UnloadLibrary(_this);
         /* Better avoid conflicts! */
@@ -320,9 +331,48 @@ X11_GL_InitExtensions(_THIS)
 {
     Display *display = ((SDL_VideoData *) _this->driverdata)->display;
     const int screen = DefaultScreen(display);
+    XVisualInfo *vinfo = NULL;
+    Window w = 0;
+    GLXContext prev_ctx = 0;
+    GLXDrawable prev_drawable = 0;
+    GLXContext context = 0;
     const char *(*glXQueryExtensionsStringFunc) (Display *, int);
     const char *extensions;
 
+    vinfo = X11_GL_GetVisual(_this, display, screen);
+    if (vinfo) {
+        GLXContext (*glXGetCurrentContextFunc) (void) =
+            (GLXContext(*)(void))
+                X11_GL_GetProcAddress(_this, "glXGetCurrentContext");
+
+        GLXDrawable (*glXGetCurrentDrawableFunc) (void) =
+            (GLXDrawable(*)(void))
+                X11_GL_GetProcAddress(_this, "glXGetCurrentDrawable");
+
+        if (glXGetCurrentContextFunc && glXGetCurrentDrawableFunc) {
+            XSetWindowAttributes xattr;
+            prev_ctx = glXGetCurrentContextFunc();
+            prev_drawable = glXGetCurrentDrawableFunc();
+
+            xattr.background_pixel = 0;
+            xattr.border_pixel = 0;
+            xattr.colormap =
+                X11_XCreateColormap(display, RootWindow(display, screen),
+                                    vinfo->visual, AllocNone);
+            w = X11_XCreateWindow(display, RootWindow(display, screen), 0, 0,
+                        32, 32, 0, vinfo->depth, InputOutput, vinfo->visual,
+                        (CWBackPixel | CWBorderPixel | CWColormap), &xattr);
+
+            context = _this->gl_data->glXCreateContext(display, vinfo,
+                                                        NULL, True);
+            if (context) {
+                _this->gl_data->glXMakeCurrent(display, w, context);
+            }
+        }
+
+        X11_XFree(vinfo);
+    }
+
     glXQueryExtensionsStringFunc =
         (const char *(*)(Display *, int)) X11_GL_GetProcAddress(_this,
                                                                 "glXQueryExtensionsString");
@@ -380,23 +430,56 @@ X11_GL_InitExtensions(_THIS)
     
     /* Check for GLX_EXT_create_context_es2_profile */
     if (HasExtension("GLX_EXT_create_context_es2_profile", extensions)) {
-        _this->gl_data->HAS_GLX_EXT_create_context_es2_profile = SDL_TRUE;
+        /* this wants to call glGetString(), so it needs a context. */
+        /* !!! FIXME: it would be nice not to make a context here though! */
+        if (context) {
+            SDL_GL_DeduceMaxSupportedESProfile(
+                &_this->gl_data->es_profile_max_supported_version.major,
+                &_this->gl_data->es_profile_max_supported_version.minor
+            );
+        }
     }
 
     /* Check for GLX_ARB_context_flush_control */
     if (HasExtension("GLX_ARB_context_flush_control", extensions)) {
         _this->gl_data->HAS_GLX_ARB_context_flush_control = SDL_TRUE;
     }
+
+    /* Check for GLX_ARB_create_context_robustness */
+    if (HasExtension("GLX_ARB_create_context_robustness", extensions)) {
+        _this->gl_data->HAS_GLX_ARB_create_context_robustness = SDL_TRUE;
+    }
+
+    /* Check for GLX_ARB_create_context_no_error */
+    if (HasExtension("GLX_ARB_create_context_no_error", extensions)) {
+        _this->gl_data->HAS_GLX_ARB_create_context_no_error = SDL_TRUE;
+    }
+
+    if (context) {
+        _this->gl_data->glXMakeCurrent(display, None, NULL);
+        _this->gl_data->glXDestroyContext(display, context);
+        if (prev_ctx && prev_drawable) {
+            _this->gl_data->glXMakeCurrent(display, prev_drawable, prev_ctx);
+        }
+    }
+
+    X11_XDestroyWindow(display, w);
+    X11_PumpEvents(_this);
 }
 
 /* glXChooseVisual and glXChooseFBConfig have some small differences in
  * the attribute encoding, it can be chosen with the for_FBConfig parameter.
+ * Some targets fail if you use GLX_X_VISUAL_TYPE_EXT/GLX_DIRECT_COLOR_EXT,
+ *  so it gets specified last if used and is pointed to by *_pvistypeattr.
+ *  In case of failure, if that pointer is not NULL, set that pointer to None
+ *  and try again.
  */
 static int
-X11_GL_GetAttributes(_THIS, Display * display, int screen, int * attribs, int size, Bool for_FBConfig)
+X11_GL_GetAttributes(_THIS, Display * display, int screen, int * attribs, int size, Bool for_FBConfig, int **_pvistypeattr)
 {
     int i = 0;
     const int MAX_ATTRIBUTES = 64;
+    int *pvistypeattr = NULL;
 
     /* assert buffer is large enough to hold all SDL attributes. */
     SDL_assert(size >= MAX_ATTRIBUTES);
@@ -488,6 +571,7 @@ X11_GL_GetAttributes(_THIS, Display * display, int screen, int * attribs, int si
        EXT_visual_info extension, then add GLX_X_VISUAL_TYPE_EXT. */
     if (X11_UseDirectColorVisuals() &&
         _this->gl_data->HAS_GLX_EXT_visual_info) {
+        pvistypeattr = &attribs[i];
         attribs[i++] = GLX_X_VISUAL_TYPE_EXT;
         attribs[i++] = GLX_DIRECT_COLOR_EXT;
     }
@@ -496,6 +580,10 @@ X11_GL_GetAttributes(_THIS, Display * display, int screen, int * attribs, int si
 
     SDL_assert(i <= MAX_ATTRIBUTES);
 
+    if (_pvistypeattr) {
+        *_pvistypeattr = pvistypeattr;
+    }
+
     return i;
 }
 
@@ -505,29 +593,27 @@ X11_GL_GetVisual(_THIS, Display * display, int screen)
     /* 64 seems nice. */
     int attribs[64];
     XVisualInfo *vinfo;
+    int *pvistypeattr = NULL;
 
     if (!_this->gl_data) {
         /* The OpenGL library wasn't loaded, SDL_GetError() should have info */
         return NULL;
     }
 
-    X11_GL_GetAttributes(_this, display, screen, attribs, 64, SDL_FALSE);
+    X11_GL_GetAttributes(_this, display, screen, attribs, 64, SDL_FALSE, &pvistypeattr);
     vinfo = _this->gl_data->glXChooseVisual(display, screen, attribs);
+
+    if (!vinfo && (pvistypeattr != NULL)) {
+        *pvistypeattr = None;
+        vinfo = _this->gl_data->glXChooseVisual(display, screen, attribs);
+    }
+
     if (!vinfo) {
         SDL_SetError("Couldn't find matching GLX visual");
     }
     return vinfo;
 }
 
-#ifndef GLXBadContext
-#define GLXBadContext 0
-#endif
-#ifndef GLXBadFBConfig
-#define GLXBadFBConfig 9
-#endif
-#ifndef GLXBadProfileARB
-#define GLXBadProfileARB 13
-#endif
 static int (*handler) (Display *, XErrorEvent *) = NULL;
 static const char *errorHandlerOperation = NULL;
 static int errorBase = 0;
@@ -551,12 +637,25 @@ X11_GL_ErrorHandler(Display * d, XErrorEvent * e)
     }
     else
     {
-        SDL_SetError("Could not %s: %i (Base %i)\n", errorHandlerOperation, errorCode, errorBase);
+        SDL_SetError("Could not %s: %i (Base %i)", errorHandlerOperation, errorCode, errorBase);
     }
 
     return (0);
 }
 
+SDL_bool
+X11_GL_UseEGL(_THIS)
+{
+    SDL_assert(_this->gl_data != NULL);
+    SDL_assert(_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES);
+
+    return (SDL_GetHintBoolean(SDL_HINT_OPENGL_ES_DRIVER, SDL_FALSE)
+            || _this->gl_config.major_version == 1 /* No GLX extension for OpenGL ES 1.x profiles. */
+            || _this->gl_config.major_version > _this->gl_data->es_profile_max_supported_version.major
+            || (_this->gl_config.major_version == _this->gl_data->es_profile_max_supported_version.major
+                && _this->gl_config.minor_version > _this->gl_data->es_profile_max_supported_version.minor));
+}
+
 SDL_GLContext
 X11_GL_CreateContext(_THIS, SDL_Window * window)
 {
@@ -593,8 +692,8 @@ X11_GL_CreateContext(_THIS, SDL_Window * window)
             context =
                 _this->gl_data->glXCreateContext(display, vinfo, share_context, True);
         } else {
-            /* max 10 attributes plus terminator */
-            int attribs[11] = {
+            /* max 14 attributes plus terminator */
+            int attribs[15] = {
                 GLX_CONTEXT_MAJOR_VERSION_ARB,
                 _this->gl_config.major_version,
                 GLX_CONTEXT_MINOR_VERSION_ARB,
@@ -624,6 +723,21 @@ X11_GL_CreateContext(_THIS, SDL_Window * window)
                     GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB;
             }
 
+            /* only set if glx extension is available */
+            if( _this->gl_data->HAS_GLX_ARB_create_context_robustness ) {
+                attribs[iattr++] = GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB;
+                attribs[iattr++] =
+                    _this->gl_config.reset_notification ?
+                    GLX_LOSE_CONTEXT_ON_RESET_ARB :
+                    GLX_NO_RESET_NOTIFICATION_ARB;
+            }
+
+            /* only set if glx extension is available */
+            if( _this->gl_data->HAS_GLX_ARB_create_context_no_error ) {
+                attribs[iattr++] = GLX_CONTEXT_OPENGL_NO_ERROR_ARB;
+                attribs[iattr++] = _this->gl_config.no_error;
+            }
+
             attribs[iattr++] = 0;
 
             /* Get a pointer to the context creation function for GL 3.0 */
@@ -635,19 +749,28 @@ X11_GL_CreateContext(_THIS, SDL_Window * window)
                 /* Create a GL 3.x context */
                 GLXFBConfig *framebuffer_config = NULL;
                 int fbcount = 0;
+                int *pvistypeattr = NULL;
 
-                X11_GL_GetAttributes(_this,display,screen,glxAttribs,64,SDL_TRUE);
+                X11_GL_GetAttributes(_this,display,screen,glxAttribs,64,SDL_TRUE,&pvistypeattr);
 
-                if (!_this->gl_data->glXChooseFBConfig
-                    || !(framebuffer_config =
-                        _this->gl_data->glXChooseFBConfig(display,
+                if (_this->gl_data->glXChooseFBConfig) {
+                    framebuffer_config = _this->gl_data->glXChooseFBConfig(display,
                                           DefaultScreen(display), glxAttribs,
-                                          &fbcount))) {
-                    SDL_SetError("No good framebuffers found. OpenGL 3.0 and later unavailable");
-                } else {
-                    context = _this->gl_data->glXCreateContextAttribsARB(display,
-                                                    framebuffer_config[0],
-                                                    share_context, True, attribs);
+                                          &fbcount);
+
+                    if (!framebuffer_config && (pvistypeattr != NULL)) {
+                        *pvistypeattr = None;
+                        framebuffer_config = _this->gl_data->glXChooseFBConfig(display,
+                                          DefaultScreen(display), glxAttribs,
+                                          &fbcount);
+                    }
+            
+                    if (framebuffer_config) {
+                        context = _this->gl_data->glXCreateContextAttribsARB(display,
+                                                        framebuffer_config[0],
+                                                        share_context, True, attribs);
+                        X11_XFree(framebuffer_config);
+                    }
                 }
             }
         }
@@ -791,13 +914,14 @@ X11_GL_GetSwapInterval(_THIS)
     }
 }
 
-void
+int
 X11_GL_SwapWindow(_THIS, SDL_Window * window)
 {
     SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
     Display *display = data->videodata->display;
 
     _this->gl_data->glXSwapBuffers(display, data->xwindow);
+    return 0;
 }
 
 void
diff --git a/src/video/x11/SDL_x11opengl.h b/src/video/x11/SDL_x11opengl.h
index 86e77d7..8e0b0f3 100644
--- a/src/video/x11/SDL_x11opengl.h
+++ b/src/video/x11/SDL_x11opengl.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11opengl_h
-#define _SDL_x11opengl_h
+#ifndef SDL_x11opengl_h_
+#define SDL_x11opengl_h_
 
 #if SDL_VIDEO_OPENGL_GLX
 #include "SDL_opengl.h"
@@ -34,8 +34,18 @@ struct SDL_GLDriverData
     SDL_bool HAS_GLX_EXT_visual_rating;
     SDL_bool HAS_GLX_EXT_visual_info;
     SDL_bool HAS_GLX_EXT_swap_control_tear;
-    SDL_bool HAS_GLX_EXT_create_context_es2_profile;
     SDL_bool HAS_GLX_ARB_context_flush_control;
+    SDL_bool HAS_GLX_ARB_create_context_robustness;
+    SDL_bool HAS_GLX_ARB_create_context_no_error;
+
+	/* Max version of OpenGL ES context that can be created if the
+	   implementation supports GLX_EXT_create_context_es2_profile.
+	   major = minor = 0 when unsupported.
+	 */
+	struct {
+		int major;
+		int minor;
+	} es_profile_max_supported_version;
 
     Bool (*glXQueryExtension) (Display*,int*,int*);
     void *(*glXGetProcAddress) (const GLubyte*);
@@ -57,17 +67,18 @@ struct SDL_GLDriverData
 extern int X11_GL_LoadLibrary(_THIS, const char *path);
 extern void *X11_GL_GetProcAddress(_THIS, const char *proc);
 extern void X11_GL_UnloadLibrary(_THIS);
+extern SDL_bool X11_GL_UseEGL(_THIS);
 extern XVisualInfo *X11_GL_GetVisual(_THIS, Display * display, int screen);
 extern SDL_GLContext X11_GL_CreateContext(_THIS, SDL_Window * window);
 extern int X11_GL_MakeCurrent(_THIS, SDL_Window * window,
                               SDL_GLContext context);
 extern int X11_GL_SetSwapInterval(_THIS, int interval);
 extern int X11_GL_GetSwapInterval(_THIS);
-extern void X11_GL_SwapWindow(_THIS, SDL_Window * window);
+extern int X11_GL_SwapWindow(_THIS, SDL_Window * window);
 extern void X11_GL_DeleteContext(_THIS, SDL_GLContext context);
 
 #endif /* SDL_VIDEO_OPENGL_GLX */
 
-#endif /* _SDL_x11opengl_h */
+#endif /* SDL_x11opengl_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11opengles.c b/src/video/x11/SDL_x11opengles.c
index 5311722..8f62abf 100644
--- a/src/video/x11/SDL_x11opengles.c
+++ b/src/video/x11/SDL_x11opengles.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -52,7 +52,7 @@ X11_GLES_LoadLibrary(_THIS, const char *path)
         #endif
     }
     
-    return SDL_EGL_LoadLibrary(_this, path, (NativeDisplayType) data->display);
+    return SDL_EGL_LoadLibrary(_this, path, (NativeDisplayType) data->display, 0);
 }
 
 XVisualInfo *
diff --git a/src/video/x11/SDL_x11opengles.h b/src/video/x11/SDL_x11opengles.h
index 716e6e6..fec022d 100644
--- a/src/video/x11/SDL_x11opengles.h
+++ b/src/video/x11/SDL_x11opengles.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11opengles_h
-#define _SDL_x11opengles_h
+#ifndef SDL_x11opengles_h_
+#define SDL_x11opengles_h_
 
 #if SDL_VIDEO_OPENGL_EGL
 
@@ -30,6 +30,9 @@
 
 typedef struct SDL_PrivateGLESData
 {
+  /* 1401 If the struct-declaration-list contains no named members, the behavior is undefined. */
+  /* warning: empty struct has size 0 in C, size 1 in C++ [-Wc++-compat] */
+  int dummy; 
 } SDL_PrivateGLESData;
 
 /* OpenGLES functions */
@@ -43,11 +46,11 @@ typedef struct SDL_PrivateGLESData
 extern int X11_GLES_LoadLibrary(_THIS, const char *path);
 extern XVisualInfo *X11_GLES_GetVisual(_THIS, Display * display, int screen);
 extern SDL_GLContext X11_GLES_CreateContext(_THIS, SDL_Window * window);
-extern void X11_GLES_SwapWindow(_THIS, SDL_Window * window);
+extern int X11_GLES_SwapWindow(_THIS, SDL_Window * window);
 extern int X11_GLES_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context);
 
 #endif /* SDL_VIDEO_OPENGL_EGL */
 
-#endif /* _SDL_x11opengles_h */
+#endif /* SDL_x11opengles_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11shape.c b/src/video/x11/SDL_x11shape.c
index 4f78ae8..5627ea6 100644
--- a/src/video/x11/SDL_x11shape.c
+++ b/src/video/x11/SDL_x11shape.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -28,11 +28,6 @@
 #include "SDL_x11window.h"
 #include "../SDL_shape_internals.h"
 
-SDL_Window*
-X11_CreateShapedWindow(const char *title,unsigned int x,unsigned int y,unsigned int w,unsigned int h,Uint32 flags) {
-    return SDL_CreateWindow(title,x,y,w,h,flags);
-}
-
 SDL_WindowShaper*
 X11_CreateShaper(SDL_Window* window) {
     SDL_WindowShaper* result = NULL;
@@ -118,4 +113,3 @@ X11_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMo
 }
 
 #endif /* SDL_VIDEO_DRIVER_X11 */
-
diff --git a/src/video/x11/SDL_x11shape.h b/src/video/x11/SDL_x11shape.h
index cd88ab7..ad1deff 100644
--- a/src/video/x11/SDL_x11shape.h
+++ b/src/video/x11/SDL_x11shape.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11shape_h
-#define _SDL_x11shape_h
+#ifndef SDL_x11shape_h_
+#define SDL_x11shape_h_
 
 #include "SDL_video.h"
 #include "SDL_shape.h"
@@ -32,9 +32,8 @@ typedef struct {
     Uint32 bitmapsize;
 } SDL_ShapeData;
 
-extern SDL_Window* X11_CreateShapedWindow(const char *title,unsigned int x,unsigned int y,unsigned int w,unsigned int h,Uint32 flags);
 extern SDL_WindowShaper* X11_CreateShaper(SDL_Window* window);
 extern int X11_ResizeWindowShape(SDL_Window* window);
 extern int X11_SetWindowShape(SDL_WindowShaper *shaper,SDL_Surface *shape,SDL_WindowShapeMode *shapeMode);
 
-#endif /* _SDL_x11shape_h */
+#endif /* SDL_x11shape_h_ */
diff --git a/src/video/x11/SDL_x11sym.h b/src/video/x11/SDL_x11sym.h
index 7290412..c9af216 100644
--- a/src/video/x11/SDL_x11sym.h
+++ b/src/video/x11/SDL_x11sym.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -179,6 +179,8 @@ SDL_X11_SYM(Status,XkbGetState,(Display* a,unsigned int b,XkbStatePtr c),(a,b,c)
 SDL_X11_SYM(Status,XkbGetUpdatedMap,(Display* a,unsigned int b,XkbDescPtr c),(a,b,c),return)
 SDL_X11_SYM(XkbDescPtr,XkbGetMap,(Display* a,unsigned int b,unsigned int c),(a,b,c),return)
 SDL_X11_SYM(void,XkbFreeClientMap,(XkbDescPtr a,unsigned int b, Bool c),(a,b,c),)
+SDL_X11_SYM(void,XkbFreeKeyboard,(XkbDescPtr a,unsigned int b, Bool c),(a,b,c),)
+SDL_X11_SYM(BOOL,XkbSetDetectableAutoRepeat,(Display* a, BOOL b, BOOL* c),(a,b,c),return)
 #endif
 
 #if NeedWidePrototypes
@@ -290,6 +292,7 @@ SDL_X11_SYM(void,XRRFreeScreenConfigInfo,(XRRScreenConfiguration *config),(confi
 SDL_X11_SYM(void,XRRSetScreenSize,(Display *dpy, Window window,int width, int height,int mmWidth, int mmHeight),(dpy,window,width,height,mmWidth,mmHeight),)
 SDL_X11_SYM(Status,XRRGetScreenSizeRange,(Display *dpy, Window window,int *minWidth, int *minHeight, int *maxWidth, int *maxHeight),(dpy,window,minWidth,minHeight,maxWidth,maxHeight),return)
 SDL_X11_SYM(XRRScreenResources *,XRRGetScreenResources,(Display *dpy, Window window),(dpy, window),return)
+SDL_X11_SYM(XRRScreenResources *,XRRGetScreenResourcesCurrent,(Display *dpy, Window window),(dpy, window),return)
 SDL_X11_SYM(void,XRRFreeScreenResources,(XRRScreenResources *resources),(resources),)
 SDL_X11_SYM(XRROutputInfo *,XRRGetOutputInfo,(Display *dpy, XRRScreenResources *resources, RROutput output),(dpy,resources,output),return)
 SDL_X11_SYM(void,XRRFreeOutputInfo,(XRROutputInfo *outputInfo),(outputInfo),)
diff --git a/src/video/x11/SDL_x11touch.c b/src/video/x11/SDL_x11touch.c
index c19e80a..12d2ef8 100644
--- a/src/video/x11/SDL_x11touch.c
+++ b/src/video/x11/SDL_x11touch.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -42,6 +42,13 @@ X11_QuitTouch(_THIS)
     SDL_TouchQuit();
 }
 
+void
+X11_ResetTouch(_THIS)
+{
+    X11_QuitTouch(_this);
+    X11_InitTouch(_this);
+}
+
 #endif /* SDL_VIDEO_DRIVER_X11 */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11touch.h b/src/video/x11/SDL_x11touch.h
index 7f8d18e..d077f74 100644
--- a/src/video/x11/SDL_x11touch.h
+++ b/src/video/x11/SDL_x11touch.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,12 +20,13 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11touch_h
-#define _SDL_x11touch_h
+#ifndef SDL_x11touch_h_
+#define SDL_x11touch_h_
 
 extern void X11_InitTouch(_THIS);
 extern void X11_QuitTouch(_THIS);
+extern void X11_ResetTouch(_THIS);
 
-#endif /* _SDL_x11touch_h */
+#endif /* SDL_x11touch_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11video.c b/src/video/x11/SDL_x11video.c
index 38b34de..1f9c2b3 100644
--- a/src/video/x11/SDL_x11video.c
+++ b/src/video/x11/SDL_x11video.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -26,6 +26,7 @@
 
 #include "SDL_video.h"
 #include "SDL_mouse.h"
+#include "SDL_timer.h"
 #include "../SDL_sysvideo.h"
 #include "../SDL_pixels_c.h"
 
@@ -39,9 +40,7 @@
 #include "SDL_x11opengles.h"
 #endif
 
-#ifdef X_HAVE_UTF8_STRING
-#include <locale.h>
-#endif
+#include "SDL_x11vulkan.h"
 
 /* Initialization/Query functions */
 static int X11_VideoInit(_THIS);
@@ -110,6 +109,9 @@ static void
 X11_DeleteDevice(SDL_VideoDevice * device)
 {
     SDL_VideoData *data = (SDL_VideoData *) device->driverdata;
+    if (device->vulkan_config.loader_handle) {
+        device->Vulkan_UnloadLibrary(device);
+    }
     if (data->display) {
         X11_XCloseDisplay(data->display);
     }
@@ -190,8 +192,8 @@ X11_CreateDevice(int devindex)
        }
      */
     data->display = X11_XOpenDisplay(display);
-#if defined(__osf__) && defined(SDL_VIDEO_DRIVER_X11_DYNAMIC)
-    /* On Tru64 if linking without -lX11, it fails and you get following message.
+#ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC
+    /* On some systems if linking without -lX11, it fails and you get following message.
      * Xlib: connection to ":0.0" refused by server
      * Xlib: XDM authorization key matches an existing client!
      *
@@ -220,6 +222,7 @@ X11_CreateDevice(int devindex)
     /* Set the function pointers */
     device->VideoInit = X11_VideoInit;
     device->VideoQuit = X11_VideoQuit;
+    device->ResetTouch = X11_ResetTouch;
     device->GetDisplayModes = X11_GetDisplayModes;
     device->GetDisplayBounds = X11_GetDisplayBounds;
     device->GetDisplayUsableBounds = X11_GetDisplayUsableBounds;
@@ -228,8 +231,8 @@ X11_CreateDevice(int devindex)
     device->SuspendScreenSaver = X11_SuspendScreenSaver;
     device->PumpEvents = X11_PumpEvents;
 
-    device->CreateWindow = X11_CreateWindow;
-    device->CreateWindowFrom = X11_CreateWindowFrom;
+    device->CreateSDLWindow = X11_CreateWindow;
+    device->CreateSDLWindowFrom = X11_CreateWindowFrom;
     device->SetWindowTitle = X11_SetWindowTitle;
     device->SetWindowIcon = X11_SetWindowIcon;
     device->SetWindowPosition = X11_SetWindowPosition;
@@ -293,6 +296,13 @@ X11_CreateDevice(int devindex)
 
     device->free = X11_DeleteDevice;
 
+#if SDL_VIDEO_VULKAN
+    device->Vulkan_LoadLibrary = X11_Vulkan_LoadLibrary;
+    device->Vulkan_UnloadLibrary = X11_Vulkan_UnloadLibrary;
+    device->Vulkan_GetInstanceExtensions = X11_Vulkan_GetInstanceExtensions;
+    device->Vulkan_CreateSurface = X11_Vulkan_CreateSurface;
+#endif
+
     return device;
 }
 
@@ -388,65 +398,6 @@ X11_VideoInit(_THIS)
     /* I have no idea how random this actually is, or has to be. */
     data->window_group = (XID) (((size_t) data->pid) ^ ((size_t) _this));
 
-    /* Open a connection to the X input manager */
-#ifdef X_HAVE_UTF8_STRING
-    if (SDL_X11_HAVE_UTF8) {
-        /* Set the locale, and call XSetLocaleModifiers before XOpenIM so that 
-           Compose keys will work correctly. */
-        char *prev_locale = setlocale(LC_ALL, NULL);
-        char *prev_xmods  = X11_XSetLocaleModifiers(NULL);
-        const char *new_xmods = "";
-#if defined(HAVE_IBUS_IBUS_H) || defined(HAVE_FCITX_FRONTEND_H)
-        const char *env_xmods = SDL_getenv("XMODIFIERS");
-#endif
-        SDL_bool has_dbus_ime_support = SDL_FALSE;
-
-        if (prev_locale) {
-            prev_locale = SDL_strdup(prev_locale);
-        }
-
-        if (prev_xmods) {
-            prev_xmods = SDL_strdup(prev_xmods);
-        }
-
-        /* IBus resends some key events that were filtered by XFilterEvents
-           when it is used via XIM which causes issues. Prevent this by forcing
-           @im=none if XMODIFIERS contains @im=ibus. IBus can still be used via 
-           the DBus implementation, which also has support for pre-editing. */
-#ifdef HAVE_IBUS_IBUS_H
-        if (env_xmods && SDL_strstr(env_xmods, "@im=ibus") != NULL) {
-            has_dbus_ime_support = SDL_TRUE;
-        }
-#endif
-#ifdef HAVE_FCITX_FRONTEND_H
-        if (env_xmods && SDL_strstr(env_xmods, "@im=fcitx") != NULL) {
-            has_dbus_ime_support = SDL_TRUE;
-        }
-#endif
-        if (has_dbus_ime_support) {
-            new_xmods = "@im=none";
-        }
-
-        setlocale(LC_ALL, "");
-        X11_XSetLocaleModifiers(new_xmods);
-
-        data->im = X11_XOpenIM(data->display, NULL, data->classname, data->classname);
-
-        /* Reset the locale + X locale modifiers back to how they were,
-           locale first because the X locale modifiers depend on it. */
-        setlocale(LC_ALL, prev_locale);
-        X11_XSetLocaleModifiers(prev_xmods);
-
-        if (prev_locale) {
-            SDL_free(prev_locale);
-        }
-
-        if (prev_xmods) {
-            SDL_free(prev_xmods);
-        }
-    }
-#endif
-
     /* Look up some useful Atoms */
 #define GET_ATOM(X) data->X = X11_XInternAtom(data->display, #X, False)
     GET_ATOM(WM_PROTOCOLS);
@@ -511,6 +462,10 @@ X11_VideoQuit(_THIS)
 {
     SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
 
+    if (data->clipboard_window) {
+        X11_XDestroyWindow(data->display, data->clipboard_window);
+    }
+
     SDL_free(data->classname);
 #ifdef X_HAVE_UTF8_STRING
     if (data->im) {
@@ -523,6 +478,8 @@ X11_VideoQuit(_THIS)
     X11_QuitMouse(_this);
     X11_QuitTouch(_this);
 
+/* !!! FIXME: other subsystems use D-Bus, so we shouldn't quit it here;
+       have SDL.c do this at a higher level, or add refcounting. */
 #if SDL_USE_LIBDBUS
     SDL_DBus_Quit();
 #endif
diff --git a/src/video/x11/SDL_x11video.h b/src/video/x11/SDL_x11video.h
index a3324ff..b58f468 100644
--- a/src/video/x11/SDL_x11video.h
+++ b/src/video/x11/SDL_x11video.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11video_h
-#define _SDL_x11video_h
+#ifndef SDL_x11video_h_
+#define SDL_x11video_h_
 
 #include "SDL_keycode.h"
 
@@ -68,6 +68,7 @@
 #include "SDL_x11mouse.h"
 #include "SDL_x11opengl.h"
 #include "SDL_x11window.h"
+#include "SDL_x11vulkan.h"
 
 /* Private display data */
 
@@ -82,6 +83,7 @@ typedef struct SDL_VideoData
     SDL_WindowData **windowlist;
     int windowlistlength;
     XID window_group;
+    Window clipboard_window;
 
     /* This is true for ICCCM2.0-compliant window managers */
     SDL_bool net_wm;
@@ -124,6 +126,8 @@ typedef struct SDL_VideoData
     SDL_Scancode key_layout[256];
     SDL_bool selection_waiting;
 
+    SDL_bool broken_pointer_grab;  /* true if XGrabPointer seems unreliable. */
+
     Uint32 last_mode_change_deadline;
 
     SDL_bool global_mouse_changed;
@@ -133,10 +137,20 @@ typedef struct SDL_VideoData
 #if SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM
     XkbDescPtr xkb;
 #endif
+
+    KeyCode filter_code;
+    Time    filter_time;
+
+#if SDL_VIDEO_VULKAN
+    /* Vulkan variables only valid if _this->vulkan_config.loader_handle is not NULL */
+    void *vulkan_xlib_xcb_library;
+    PFN_XGetXCBConnection vulkan_XGetXCBConnection;
+#endif
+
 } SDL_VideoData;
 
 extern SDL_bool X11_UseDirectColorVisuals(void);
 
-#endif /* _SDL_x11video_h */
+#endif /* SDL_x11video_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11vulkan.c b/src/video/x11/SDL_x11vulkan.c
new file mode 100644
index 0000000..d4eb125
--- /dev/null
+++ b/src/video/x11/SDL_x11vulkan.c
@@ -0,0 +1,241 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "../../SDL_internal.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_X11
+
+#include "SDL_x11video.h"
+#include "SDL_assert.h"
+
+#include "SDL_loadso.h"
+#include "SDL_x11vulkan.h"
+
+#include <X11/Xlib.h>
+/*#include <xcb/xcb.h>*/
+/*
+typedef uint32_t xcb_window_t;
+typedef uint32_t xcb_visualid_t;
+*/
+
+int X11_Vulkan_LoadLibrary(_THIS, const char *path)
+{
+    SDL_VideoData *videoData = (SDL_VideoData *)_this->driverdata;
+    VkExtensionProperties *extensions = NULL;
+    Uint32 extensionCount = 0;
+    SDL_bool hasSurfaceExtension = SDL_FALSE;
+    SDL_bool hasXlibSurfaceExtension = SDL_FALSE;
+    SDL_bool hasXCBSurfaceExtension = SDL_FALSE;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
+    Uint32 i;
+    if(_this->vulkan_config.loader_handle)
+        return SDL_SetError("Vulkan already loaded");
+
+    /* Load the Vulkan loader library */
+    if(!path)
+        path = SDL_getenv("SDL_VULKAN_LIBRARY");
+    if(!path)
+        path = "libvulkan.so.1";
+    _this->vulkan_config.loader_handle = SDL_LoadObject(path);
+    if(!_this->vulkan_config.loader_handle)
+        return -1;
+    SDL_strlcpy(_this->vulkan_config.loader_path, path, SDL_arraysize(_this->vulkan_config.loader_path));
+    vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_LoadFunction(
+        _this->vulkan_config.loader_handle, "vkGetInstanceProcAddr");
+    if(!vkGetInstanceProcAddr)
+        goto fail;
+    _this->vulkan_config.vkGetInstanceProcAddr = (void *)vkGetInstanceProcAddr;
+    _this->vulkan_config.vkEnumerateInstanceExtensionProperties =
+        (void *)((PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr)(
+            VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties");
+    if(!_this->vulkan_config.vkEnumerateInstanceExtensionProperties)
+        goto fail;
+    extensions = SDL_Vulkan_CreateInstanceExtensionsList(
+        (PFN_vkEnumerateInstanceExtensionProperties)
+            _this->vulkan_config.vkEnumerateInstanceExtensionProperties,
+        &extensionCount);
+    if(!extensions)
+        goto fail;
+    for(i = 0; i < extensionCount; i++)
+    {
+        if(SDL_strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasSurfaceExtension = SDL_TRUE;
+        else if(SDL_strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasXCBSurfaceExtension = SDL_TRUE;
+        else if(SDL_strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, extensions[i].extensionName) == 0)
+            hasXlibSurfaceExtension = SDL_TRUE;
+    }
+    SDL_free(extensions);
+    if(!hasSurfaceExtension)
+    {
+        SDL_SetError("Installed Vulkan doesn't implement the "
+                     VK_KHR_SURFACE_EXTENSION_NAME " extension");
+        goto fail;
+    }
+    if(hasXlibSurfaceExtension)
+    {
+        videoData->vulkan_xlib_xcb_library = NULL;
+    }
+    else if(!hasXCBSurfaceExtension)
+    {
+        SDL_SetError("Installed Vulkan doesn't implement either the "
+                     VK_KHR_XCB_SURFACE_EXTENSION_NAME "extension or the "
+                     VK_KHR_XLIB_SURFACE_EXTENSION_NAME " extension");
+        goto fail;
+    }
+    else
+    {
+        const char *libX11XCBLibraryName = SDL_getenv("SDL_X11_XCB_LIBRARY");
+        if(!libX11XCBLibraryName)
+            libX11XCBLibraryName = "libX11-xcb.so";
+        videoData->vulkan_xlib_xcb_library = SDL_LoadObject(libX11XCBLibraryName);
+        if(!videoData->vulkan_xlib_xcb_library)
+            goto fail;
+        videoData->vulkan_XGetXCBConnection =
+            SDL_LoadFunction(videoData->vulkan_xlib_xcb_library, "XGetXCBConnection");
+        if(!videoData->vulkan_XGetXCBConnection)
+        {
+            SDL_UnloadObject(videoData->vulkan_xlib_xcb_library);
+            goto fail;
+        }
+    }
+    return 0;
+
+fail:
+    SDL_UnloadObject(_this->vulkan_config.loader_handle);
+    _this->vulkan_config.loader_handle = NULL;
+    return -1;
+}
+
+void X11_Vulkan_UnloadLibrary(_THIS)
+{
+    SDL_VideoData *videoData = (SDL_VideoData *)_this->driverdata;
+    if(_this->vulkan_config.loader_handle)
+    {
+        if(videoData->vulkan_xlib_xcb_library)
+            SDL_UnloadObject(videoData->vulkan_xlib_xcb_library);
+        SDL_UnloadObject(_this->vulkan_config.loader_handle);
+        _this->vulkan_config.loader_handle = NULL;
+    }
+}
+
+SDL_bool X11_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names)
+{
+    SDL_VideoData *videoData = (SDL_VideoData *)_this->driverdata;
+    if(!_this->vulkan_config.loader_handle)
+    {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+    if(videoData->vulkan_xlib_xcb_library)
+    {
+        static const char *const extensionsForXCB[] = {
+            VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_XCB_SURFACE_EXTENSION_NAME,
+        };
+        return SDL_Vulkan_GetInstanceExtensions_Helper(
+            count, names, SDL_arraysize(extensionsForXCB), extensionsForXCB);
+    }
+    else
+    {
+        static const char *const extensionsForXlib[] = {
+            VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_XLIB_SURFACE_EXTENSION_NAME,
+        };
+        return SDL_Vulkan_GetInstanceExtensions_Helper(
+            count, names, SDL_arraysize(extensionsForXlib), extensionsForXlib);
+    }
+}
+
+SDL_bool X11_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface)
+{
+    SDL_VideoData *videoData = (SDL_VideoData *)_this->driverdata;
+    SDL_WindowData *windowData = (SDL_WindowData *)window->driverdata;
+    PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr;
+    if(!_this->vulkan_config.loader_handle)
+    {
+        SDL_SetError("Vulkan is not loaded");
+        return SDL_FALSE;
+    }
+    vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)_this->vulkan_config.vkGetInstanceProcAddr;
+    if(videoData->vulkan_xlib_xcb_library)
+    {
+        PFN_vkCreateXcbSurfaceKHR vkCreateXcbSurfaceKHR =
+            (PFN_vkCreateXcbSurfaceKHR)vkGetInstanceProcAddr((VkInstance)instance,
+                                                             "vkCreateXcbSurfaceKHR");
+        VkXcbSurfaceCreateInfoKHR createInfo = {};
+        VkResult result;
+        if(!vkCreateXcbSurfaceKHR)
+        {
+            SDL_SetError(VK_KHR_XCB_SURFACE_EXTENSION_NAME
+                         " extension is not enabled in the Vulkan instance.");
+            return SDL_FALSE;
+        }
+        createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
+        createInfo.connection = videoData->vulkan_XGetXCBConnection(videoData->display);
+        if(!createInfo.connection)
+        {
+            SDL_SetError("XGetXCBConnection failed");
+            return SDL_FALSE;
+        }
+        createInfo.window = (xcb_window_t)windowData->xwindow;
+        result = vkCreateXcbSurfaceKHR(instance, &createInfo,
+                                       NULL, surface);
+        if(result != VK_SUCCESS)
+        {
+            SDL_SetError("vkCreateXcbSurfaceKHR failed: %s", SDL_Vulkan_GetResultString(result));
+            return SDL_FALSE;
+        }
+        return SDL_TRUE;
+    }
+    else
+    {
+        PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR =
+            (PFN_vkCreateXlibSurfaceKHR)vkGetInstanceProcAddr((VkInstance)instance,
+                                                              "vkCreateXlibSurfaceKHR");
+        VkXlibSurfaceCreateInfoKHR createInfo = {};
+        VkResult result;
+        if(!vkCreateXlibSurfaceKHR)
+        {
+            SDL_SetError(VK_KHR_XLIB_SURFACE_EXTENSION_NAME
+                         " extension is not enabled in the Vulkan instance.");
+            return SDL_FALSE;
+        }
+        createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
+        createInfo.dpy = videoData->display;
+        createInfo.window = (xcb_window_t)windowData->xwindow;
+        result = vkCreateXlibSurfaceKHR(instance, &createInfo,
+                                        NULL, surface);
+        if(result != VK_SUCCESS)
+        {
+            SDL_SetError("vkCreateXlibSurfaceKHR failed: %s", SDL_Vulkan_GetResultString(result));
+            return SDL_FALSE;
+        }
+        return SDL_TRUE;
+    }
+}
+
+#endif
+
+/* vim: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/nas/SDL_nasaudio.h b/src/video/x11/SDL_x11vulkan.h
similarity index 55%
copy from src/audio/nas/SDL_nasaudio.h
copy to src/video/x11/SDL_x11vulkan.h
index 2f46b0b..f6cd1ee 100644
--- a/src/audio/nas/SDL_nasaudio.h
+++ b/src/video/x11/SDL_x11vulkan.h
@@ -20,37 +20,29 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_nasaudio_h
-#define _SDL_nasaudio_h
+#ifndef SDL_x11vulkan_h_
+#define SDL_x11vulkan_h_
+
+#include "../SDL_vulkan_internal.h"
+
+#if SDL_VIDEO_VULKAN && SDL_VIDEO_DRIVER_X11
+
+/*typedef struct xcb_connection_t xcb_connection_t;*/
+typedef xcb_connection_t *(*PFN_XGetXCBConnection)(Display *dpy);
+
+int X11_Vulkan_LoadLibrary(_THIS, const char *path);
+void X11_Vulkan_UnloadLibrary(_THIS);
+SDL_bool X11_Vulkan_GetInstanceExtensions(_THIS,
+                                          SDL_Window *window,
+                                          unsigned *count,
+                                          const char **names);
+SDL_bool X11_Vulkan_CreateSurface(_THIS,
+                                  SDL_Window *window,
+                                  VkInstance instance,
+                                  VkSurfaceKHR *surface);
 
-#ifdef __sgi
-#include <nas/audiolib.h>
-#else
-#include <audio/audiolib.h>
 #endif
-#include <sys/time.h>
-
-#include "../SDL_sysaudio.h"
-
-/* Hidden "this" pointer for the audio functions */
-#define _THIS   SDL_AudioDevice *this
-
-struct SDL_PrivateAudioData
-{
-    AuServer *aud;
-    AuFlowID flow;
-    AuDeviceID dev;
-
-    /* Raw mixing buffer */
-    Uint8 *mixbuf;
-    int mixlen;
-
-    int written;
-    int really;
-    int bps;
-    struct timeval last_tv;
-    int buf_free;
-};
-#endif /* _SDL_nasaudio_h */
+
+#endif /* SDL_x11vulkan_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11window.c b/src/video/x11/SDL_x11window.c
index 668bce2..d532d2b 100644
--- a/src/video/x11/SDL_x11window.c
+++ b/src/video/x11/SDL_x11window.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -40,11 +40,10 @@
 
 #include "SDL_timer.h"
 #include "SDL_syswm.h"
-#include "SDL_assert.h"
+#include "SDL_log.h"
 
 #define _NET_WM_STATE_REMOVE    0l
 #define _NET_WM_STATE_ADD       1l
-#define _NET_WM_STATE_TOGGLE    2l
 
 static Bool isMapNotify(Display *dpy, XEvent *ev, XPointer win)
 {
@@ -226,6 +225,19 @@ X11_GetNetWMState(_THIS, Window xwindow)
         if (fullscreen == 1) {
             flags |= SDL_WINDOW_FULLSCREEN;
         }
+
+        /* If the window is unmapped, numItems will be zero and _NET_WM_STATE_HIDDEN
+         * will not be set. Do an additional check to see if the window is unmapped
+         * and mark it as SDL_WINDOW_HIDDEN if it is.
+         */
+        {
+            XWindowAttributes attr;
+            SDL_memset(&attr,0,sizeof(attr));
+            X11_XGetWindowAttributes(videodata->display, xwindow, &attr);
+            if (attr.map_state == IsUnmapped) {
+                flags |= SDL_WINDOW_HIDDEN;
+            }
+        }
         X11_XFree(propertyValue);
     }
 
@@ -376,7 +388,7 @@ X11_CreateWindow(_THIS, SDL_Window * window)
     Atom _NET_WM_WINDOW_TYPE;
     Atom wintype;
     const char *wintype_name = NULL;
-    int compositor = 1;
+    long compositor = 1;
     Atom _NET_WM_PID;
     Atom XdndAware, xdnd_version = 5;
     long fevent = 0;
@@ -389,7 +401,7 @@ X11_CreateWindow(_THIS, SDL_Window * window)
 #if SDL_VIDEO_OPENGL_EGL
         if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES 
 #if SDL_VIDEO_OPENGL_GLX            
-            && ( !_this->gl_data || ! _this->gl_data->HAS_GLX_EXT_create_context_es2_profile )
+            && ( !_this->gl_data || X11_GL_UseEGL(_this) )
 #endif
         ) {
             vinfo = X11_GLES_GetVisual(_this, display, screen);
@@ -600,7 +612,7 @@ X11_CreateWindow(_THIS, SDL_Window * window)
     if ((window->flags & SDL_WINDOW_OPENGL) && 
         _this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES
 #if SDL_VIDEO_OPENGL_GLX            
-        && ( !_this->gl_data || ! _this->gl_data->HAS_GLX_EXT_create_context_es2_profile )
+        && ( !_this->gl_data || X11_GL_UseEGL(_this) )
 #endif  
     ) {
 #if SDL_VIDEO_OPENGL_EGL  
@@ -617,7 +629,7 @@ X11_CreateWindow(_THIS, SDL_Window * window)
             return SDL_SetError("Could not create GLES window surface");
         }
 #else
-        return SDL_SetError("Could not create GLES window surface (no EGL support available)");
+        return SDL_SetError("Could not create GLES window surface (EGL support not configured)");
 #endif /* SDL_VIDEO_OPENGL_EGL */
     }
 #endif
@@ -1029,7 +1041,8 @@ X11_ShowWindow(_THIS, SDL_Window * window)
         /* Blocking wait for "MapNotify" event.
          * We use X11_XIfEvent because pXWindowEvent takes a mask rather than a type,
          * and XCheckTypedWindowEvent doesn't block */
-        X11_XIfEvent(display, &event, &isMapNotify, (XPointer)&data->xwindow);
+        if(!(window->flags & SDL_WINDOW_FOREIGN))
+            X11_XIfEvent(display, &event, &isMapNotify, (XPointer)&data->xwindow);
         X11_XFlush(display);
     }
 
@@ -1051,7 +1064,8 @@ X11_HideWindow(_THIS, SDL_Window * window)
     if (X11_IsWindowMapped(_this, window)) {
         X11_XWithdrawWindow(display, data->xwindow, displaydata->screen);
         /* Blocking wait for "UnmapNotify" event */
-        X11_XIfEvent(display, &event, &isUnmapNotify, (XPointer)&data->xwindow);
+        if(!(window->flags & SDL_WINDOW_FOREIGN))
+            X11_XIfEvent(display, &event, &isUnmapNotify, (XPointer)&data->xwindow);
         X11_XFlush(display);
     }
 }
@@ -1484,14 +1498,25 @@ X11_SetWindowGrab(_THIS, SDL_Window * window, SDL_bool grabbed)
 
     if (oldstyle_fullscreen || grabbed) {
         /* Try to grab the mouse */
-        for (;;) {
-            int result =
-                X11_XGrabPointer(display, data->xwindow, True, 0, GrabModeAsync,
-                             GrabModeAsync, data->xwindow, None, CurrentTime);
-            if (result == GrabSuccess) {
-                break;
+        if (!data->videodata->broken_pointer_grab) {
+            const unsigned int mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask;
+            int attempts;
+            int result;
+
+            /* Try for up to 5000ms (5s) to grab. If it still fails, stop trying. */
+            for (attempts = 0; attempts < 100; attempts++) {
+                result = X11_XGrabPointer(display, data->xwindow, True, mask, GrabModeAsync,
+                                 GrabModeAsync, data->xwindow, None, CurrentTime);
+                if (result == GrabSuccess) {
+                    break;
+                }
+                SDL_Delay(50);
+            }
+
+            if (result != GrabSuccess) {
+                SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "The X server refused to let us grab the mouse. You might experience input bugs.");
+                data->videodata->broken_pointer_grab = SDL_TRUE;  /* don't try again. */
             }
-            SDL_Delay(50);
         }
 
         /* Raise the window if we grab the mouse */
@@ -1566,7 +1591,7 @@ X11_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
         info->info.x11.window = data->xwindow;
         return SDL_TRUE;
     } else {
-        SDL_SetError("Application not compiled with SDL %d.%d\n",
+        SDL_SetError("Application not compiled with SDL %d.%d",
                      SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
         return SDL_FALSE;
     }
diff --git a/src/video/x11/SDL_x11window.h b/src/video/x11/SDL_x11window.h
index 50a739d..f0b8fa5 100644
--- a/src/video/x11/SDL_x11window.h
+++ b/src/video/x11/SDL_x11window.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11window_h
-#define _SDL_x11window_h
+#ifndef SDL_x11window_h_
+#define SDL_x11window_h_
 
 /* We need to queue the focus in/out changes because they may occur during
    video mode changes and we can respond to them by triggering more mode
@@ -105,6 +105,6 @@ extern SDL_bool X11_GetWindowWMInfo(_THIS, SDL_Window * window,
                                     struct SDL_SysWMinfo *info);
 extern int X11_SetWindowHitTest(SDL_Window *window, SDL_bool enabled);
 
-#endif /* _SDL_x11window_h */
+#endif /* SDL_x11window_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/SDL_x11xinput2.c b/src/video/x11/SDL_x11xinput2.c
index bed4234..654fb84 100644
--- a/src/video/x11/SDL_x11xinput2.c
+++ b/src/video/x11/SDL_x11xinput2.c
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/src/video/x11/SDL_x11xinput2.h b/src/video/x11/SDL_x11xinput2.h
index ed8dd1a..145b1bc 100644
--- a/src/video/x11/SDL_x11xinput2.h
+++ b/src/video/x11/SDL_x11xinput2.h
@@ -1,6 +1,6 @@
 /*
   Simple DirectMedia Layer
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,8 +20,8 @@
 */
 #include "../../SDL_internal.h"
 
-#ifndef _SDL_x11xinput2_h
-#define _SDL_x11xinput2_h
+#ifndef SDL_x11xinput2_h_
+#define SDL_x11xinput2_h_
 
 #ifndef SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS
 /* Define XGenericEventCookie as forward declaration when
@@ -37,6 +37,6 @@ extern int X11_Xinput2IsInitialized(void);
 extern int X11_Xinput2IsMultitouchSupported(void);
 extern void X11_Xinput2SelectTouch(_THIS, SDL_Window *window);
 
-#endif /* _SDL_x11xinput2_h */
+#endif /* SDL_x11xinput2_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/x11/edid-parse.c b/src/video/x11/edid-parse.c
index 57f225b..e22324f 100644
--- a/src/video/x11/edid-parse.c
+++ b/src/video/x11/edid-parse.c
@@ -140,14 +140,14 @@ decode_display_parameters (const uchar *edid, MonitorInfo *info)
 	};
 
 	bits = get_bits (edid[0x14], 4, 6);
-	info->digital.bits_per_primary = bit_depth[bits];
+	info->ad.digital.bits_per_primary = bit_depth[bits];
 
 	bits = get_bits (edid[0x14], 0, 3);
 	
 	if (bits <= 5)
-	    info->digital.interface = interfaces[bits];
+	    info->ad.digital.interface = interfaces[bits];
 	else
-	    info->digital.interface = UNDEFINED;
+	    info->ad.digital.interface = UNDEFINED;
     }
     else
     {
@@ -161,17 +161,17 @@ decode_display_parameters (const uchar *edid, MonitorInfo *info)
 	    { 0.7,   0.0,    0.7 },
 	};
 
-	info->analog.video_signal_level = levels[bits][0];
-	info->analog.sync_signal_level = levels[bits][1];
-	info->analog.total_signal_level = levels[bits][2];
+	info->ad.analog.video_signal_level = levels[bits][0];
+	info->ad.analog.sync_signal_level = levels[bits][1];
+	info->ad.analog.total_signal_level = levels[bits][2];
 
-	info->analog.blank_to_black = get_bit (edid[0x14], 4);
+	info->ad.analog.blank_to_black = get_bit (edid[0x14], 4);
 
-	info->analog.separate_hv_sync = get_bit (edid[0x14], 3);
-	info->analog.composite_sync_on_h = get_bit (edid[0x14], 2);
-	info->analog.composite_sync_on_green = get_bit (edid[0x14], 1);
+	info->ad.analog.separate_hv_sync = get_bit (edid[0x14], 3);
+	info->ad.analog.composite_sync_on_h = get_bit (edid[0x14], 2);
+	info->ad.analog.composite_sync_on_green = get_bit (edid[0x14], 1);
 
-	info->analog.serration_on_vsync = get_bit (edid[0x14], 0);
+	info->ad.analog.serration_on_vsync = get_bit (edid[0x14], 0);
     }
 
     /* Screen Size / Aspect Ratio */
@@ -213,11 +213,11 @@ decode_display_parameters (const uchar *edid, MonitorInfo *info)
 
     if (info->is_digital)
     {
-	info->digital.rgb444 = TRUE;
+	info->ad.digital.rgb444 = TRUE;
 	if (get_bit (edid[0x18], 3))
-	    info->digital.ycrcb444 = 1;
+	    info->ad.digital.ycrcb444 = 1;
 	if (get_bit (edid[0x18], 4))
-	    info->digital.ycrcb422 = 1;
+	    info->ad.digital.ycrcb422 = 1;
     }
     else
     {
@@ -227,7 +227,7 @@ decode_display_parameters (const uchar *edid, MonitorInfo *info)
 	    MONOCHROME, RGB, OTHER_COLOR, UNDEFINED_COLOR
 	};
 
-	info->analog.color_type = color_type[bits];
+	info->ad.analog.color_type = color_type[bits];
     }
 
     info->srgb_is_standard = get_bit (edid[0x18], 2);
@@ -455,26 +455,26 @@ decode_detailed_timing (const uchar *timing,
     detailed->digital_sync = get_bit (bits, 4);
     if (detailed->digital_sync)
     {
-	detailed->digital.composite = !get_bit (bits, 3);
+	detailed->ad.digital.composite = !get_bit (bits, 3);
 
-	if (detailed->digital.composite)
+	if (detailed->ad.digital.composite)
 	{
-	    detailed->digital.serrations = get_bit (bits, 2);
-	    detailed->digital.negative_vsync = FALSE;
+	    detailed->ad.digital.serrations = get_bit (bits, 2);
+	    detailed->ad.digital.negative_vsync = FALSE;
 	}
 	else
 	{
-	    detailed->digital.serrations = FALSE;
-	    detailed->digital.negative_vsync = !get_bit (bits, 2);
+	    detailed->ad.digital.serrations = FALSE;
+	    detailed->ad.digital.negative_vsync = !get_bit (bits, 2);
 	}
 
-	detailed->digital.negative_hsync = !get_bit (bits, 0);
+	detailed->ad.digital.negative_hsync = !get_bit (bits, 0);
     }
     else
     {
-	detailed->analog.bipolar = get_bit (bits, 3);
-	detailed->analog.serrations = get_bit (bits, 2);
-	detailed->analog.sync_on_green = !get_bit (bits, 1);
+	detailed->ad.analog.bipolar = get_bit (bits, 3);
+	detailed->ad.analog.serrations = get_bit (bits, 2);
+	detailed->ad.analog.sync_on_green = !get_bit (bits, 1);
     }
 }
 
@@ -579,12 +579,12 @@ dump_monitor_info (MonitorInfo *info)
     if (info->is_digital)
     {
 	const char *interface;
-	if (info->digital.bits_per_primary != -1)
-	    printf ("Bits Per Primary: %d\n", info->digital.bits_per_primary);
+	if (info->ad.digital.bits_per_primary != -1)
+	    printf ("Bits Per Primary: %d\n", info->ad.digital.bits_per_primary);
 	else
 	    printf ("Bits Per Primary: undefined\n");
 	
-	switch (info->digital.interface)
+	switch (info->ad.digital.interface)
 	{
 	case DVI: interface = "DVI"; break;
 	case HDMI_A: interface = "HDMI-a"; break;
@@ -596,27 +596,27 @@ dump_monitor_info (MonitorInfo *info)
 	}
 	printf ("Interface: %s\n", interface);
 	
-	printf ("RGB 4:4:4: %s\n", yesno (info->digital.rgb444));
-	printf ("YCrCb 4:4:4: %s\n", yesno (info->digital.ycrcb444));
-	printf ("YCrCb 4:2:2: %s\n", yesno (info->digital.ycrcb422));
+	printf ("RGB 4:4:4: %s\n", yesno (info->ad.digital.rgb444));
+	printf ("YCrCb 4:4:4: %s\n", yesno (info->ad.digital.ycrcb444));
+	printf ("YCrCb 4:2:2: %s\n", yesno (info->ad.digital.ycrcb422));
     }
     else
     {
        const char *s;
-	printf ("Video Signal Level: %f\n", info->analog.video_signal_level);
-	printf ("Sync Signal Level: %f\n", info->analog.sync_signal_level);
-	printf ("Total Signal Level: %f\n", info->analog.total_signal_level);
+	printf ("Video Signal Level: %f\n", info->ad.analog.video_signal_level);
+	printf ("Sync Signal Level: %f\n", info->ad.analog.sync_signal_level);
+	printf ("Total Signal Level: %f\n", info->ad.analog.total_signal_level);
 	
 	printf ("Blank to Black: %s\n",
-		yesno (info->analog.blank_to_black));
+		yesno (info->ad.analog.blank_to_black));
 	printf ("Separate HV Sync: %s\n",
-		yesno (info->analog.separate_hv_sync));
+		yesno (info->ad.analog.separate_hv_sync));
 	printf ("Composite Sync on H: %s\n",
-		yesno (info->analog.composite_sync_on_h));
+		yesno (info->ad.analog.composite_sync_on_h));
 	printf ("Serration on VSync: %s\n",
-		yesno (info->analog.serration_on_vsync));
+		yesno (info->ad.analog.serration_on_vsync));
 	
-	switch (info->analog.color_type)
+	switch (info->ad.analog.color_type)
 	{
 	case UNDEFINED_COLOR: s = "undefined"; break;
 	case MONOCHROME: s = "monochrome"; break;
@@ -729,20 +729,20 @@ dump_monitor_info (MonitorInfo *info)
 	if (timing->digital_sync)
 	{
 	    printf ("  Digital Sync:\n");
-	    printf ("    composite: %s\n", yesno (timing->digital.composite));
-	    printf ("    serrations: %s\n", yesno (timing->digital.serrations));
+	    printf ("    composite: %s\n", yesno (timing->ad.digital.composite));
+	    printf ("    serrations: %s\n", yesno (timing->ad.digital.serrations));
 	    printf ("    negative vsync: %s\n",
-		    yesno (timing->digital.negative_vsync));
+		    yesno (timing->ad.digital.negative_vsync));
 	    printf ("    negative hsync: %s\n",
-		    yesno (timing->digital.negative_hsync));
+		    yesno (timing->ad.digital.negative_hsync));
 	}
 	else
 	{
 	    printf ("  Analog Sync:\n");
-	    printf ("    bipolar: %s\n", yesno (timing->analog.bipolar));
-	    printf ("    serrations: %s\n", yesno (timing->analog.serrations));
+	    printf ("    bipolar: %s\n", yesno (timing->ad.analog.bipolar));
+	    printf ("    serrations: %s\n", yesno (timing->ad.analog.serrations));
 	    printf ("    sync on green: %s\n", yesno (
-			timing->analog.sync_on_green));
+			timing->ad.analog.sync_on_green));
 	}
     }
     
diff --git a/src/video/x11/edid.h b/src/video/x11/edid.h
index 8c217eb..cb9f0e8 100644
--- a/src/video/x11/edid.h
+++ b/src/video/x11/edid.h
@@ -74,7 +74,7 @@ struct DetailedTiming
 	    int negative_vsync;
 	    int negative_hsync;
 	} digital;
-    };
+    } ad;
 };
 
 struct MonitorInfo
@@ -118,7 +118,7 @@ struct MonitorInfo
 	    int		serration_on_vsync;
 	    ColorType	color_type;
 	} analog;
-    };
+    } ad;
 
     int			width_mm;		/* -1 if not specified */
     int			height_mm;		/* -1 if not specified */
diff --git a/test/Makefile.in b/test/Makefile.in
index 68f0d3d..0ac70e9 100644
--- a/test/Makefile.in
+++ b/test/Makefile.in
@@ -66,8 +66,9 @@ TARGETS = \
 	testdisplayinfo$(EXE) \
 	testqsort$(EXE) \
 	controllermap$(EXE) \
+	testvulkan$(EXE) \
 	
-all: Makefile $(TARGETS)
+all: Makefile $(TARGETS) copydatafiles
 
 Makefile: $(srcdir)/Makefile.in
 	$(SHELL) config.status $@
@@ -289,6 +290,9 @@ testcustomcursor$(EXE): $(srcdir)/testcustomcursor.c
 controllermap$(EXE): $(srcdir)/controllermap.c
 	$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
 
+testvulkan$(EXE): $(srcdir)/testvulkan.c
+	$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
+
 
 clean:
 	rm -f $(TARGETS)
@@ -297,3 +301,20 @@ distclean: clean
 	rm -f Makefile
 	rm -f config.status config.cache config.log
 	rm -rf $(srcdir)/autom4te*
+
+
+%.bmp: $(srcdir)/%.bmp
+	cp $< $@
+
+%.wav: $(srcdir)/%.wav
+	cp $< $@
+
+copydatafiles: copybmpfiles copywavfiles
+.PHONY : copydatafiles
+
+copybmpfiles: $(foreach bmp,$(wildcard $(srcdir)/*.bmp),$(notdir $(bmp)))
+.PHONY : copybmpfiles
+
+copywavfiles: $(foreach wav,$(wildcard $(srcdir)/*.wav),$(notdir $(wav)))
+.PHONY : copywavfiles
+
diff --git a/test/axis.bmp b/test/axis.bmp
index c7addd3..2b3a7c8 100644
Binary files a/test/axis.bmp and b/test/axis.bmp differ
diff --git a/test/checkkeys.c b/test/checkkeys.c
index 771369f..066c786 100644
--- a/test/checkkeys.c
+++ b/test/checkkeys.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -168,7 +168,19 @@ loop()
             PrintText("INPUT", event.text.text);
             break;
         case SDL_MOUSEBUTTONDOWN:
-            /* Any button press quits the app... */
+            /* Left button quits the app, other buttons toggles text input */
+            if (event.button.button == SDL_BUTTON_LEFT) {
+                done = 1;
+            } else {
+                if (SDL_IsTextInputActive()) {
+                    SDL_Log("Stopping text input\n");
+                    SDL_StopTextInput();
+                } else {
+                    SDL_Log("Starting text input\n");
+                    SDL_StartTextInput();
+                }
+            }
+            break;
         case SDL_QUIT:
             done = 1;
             break;
diff --git a/test/controllermap.c b/test/controllermap.c
index d626f9f..c4fe592 100644
--- a/test/controllermap.c
+++ b/test/controllermap.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -32,16 +32,124 @@
 #define MARKER_BUTTON 1
 #define MARKER_AXIS 2
 
-typedef struct MappingStep
+enum
+{
+    SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE,
+    SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE,
+    SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE,
+    SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE,
+    SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE,
+    SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE,
+    SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE,
+    SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE,
+    SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT,
+    SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT,
+    SDL_CONTROLLER_BINDING_AXIS_MAX,
+};
+
+#define BINDING_COUNT (SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_MAX)
+
+static struct 
 {
     int x, y;
     double angle;
     int marker;
-    char *field;
-    int axis, button, hat, hat_value;
-    char mapping[4096];
-}MappingStep;
 
+} s_arrBindingDisplay[BINDING_COUNT] = {
+    { 387, 167, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_A */
+    { 431, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_B */
+    { 342, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_X */
+    { 389, 101, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_Y */
+    { 174, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_BACK */
+    { 233, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_GUIDE */
+    { 289, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_START */
+    {  75, 154, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_LEFTSTICK */
+    { 305, 230, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_RIGHTSTICK */
+    {  77,  40, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_LEFTSHOULDER */
+    { 396,  36, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_RIGHTSHOULDER */
+    { 154, 188, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_UP */
+    { 154, 249, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_DOWN */
+    { 116, 217, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_LEFT */
+    { 186, 217, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_RIGHT */
+    {  74, 153, 270.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE */
+    {  74, 153, 90.0,  MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE */
+    {  74, 153, 0.0,   MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE */
+    {  74, 153, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE */
+    { 306, 231, 270.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE */
+    { 306, 231, 90.0,  MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE */
+    { 306, 231, 0.0,   MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE */
+    { 306, 231, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE */
+    {  91, -20, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT */
+    { 375, -20, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT */
+};
+
+static int s_arrBindingOrder[BINDING_COUNT] = {
+    SDL_CONTROLLER_BUTTON_A,
+    SDL_CONTROLLER_BUTTON_B,
+    SDL_CONTROLLER_BUTTON_Y,
+    SDL_CONTROLLER_BUTTON_X,
+    SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE,
+    SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE,
+    SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE,
+    SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE,
+    SDL_CONTROLLER_BUTTON_LEFTSTICK,
+    SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE,
+    SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE,
+    SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE,
+    SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE,
+    SDL_CONTROLLER_BUTTON_RIGHTSTICK,
+    SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
+    SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT,
+    SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
+    SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT,
+    SDL_CONTROLLER_BUTTON_DPAD_UP,
+    SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
+    SDL_CONTROLLER_BUTTON_DPAD_DOWN,
+    SDL_CONTROLLER_BUTTON_DPAD_LEFT,
+    SDL_CONTROLLER_BUTTON_BACK,
+    SDL_CONTROLLER_BUTTON_GUIDE,
+    SDL_CONTROLLER_BUTTON_START,
+};
+
+typedef struct
+{
+    SDL_GameControllerBindType bindType;
+    union
+    {
+        int button;
+
+        struct {
+            int axis;
+            int axis_min;
+            int axis_max;
+        } axis;
+
+        struct {
+            int hat;
+            int hat_mask;
+        } hat;
+
+    } value;
+
+    SDL_bool committed;
+
+} SDL_GameControllerExtendedBind;
+
+static SDL_GameControllerExtendedBind s_arrBindings[BINDING_COUNT];
+
+typedef struct
+{
+    SDL_bool m_bMoving;
+    int m_nStartingValue;
+    int m_nFarthestValue;
+} AxisState;
+
+static int s_nNumAxes;
+static AxisState *s_arrAxisState;
+    
+static int s_iCurrentBinding;
+static Uint32 s_unPendingAdvanceTime;
+static SDL_bool s_bBindingComplete;
 
 SDL_Texture *
 LoadTexture(SDL_Renderer *renderer, const char *file, SDL_bool transparent)
@@ -60,23 +168,6 @@ LoadTexture(SDL_Renderer *renderer, const char *file, SDL_bool transparent)
     if (transparent) {
         if (temp->format->palette) {
             SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *) temp->pixels);
-        } else {
-            switch (temp->format->BitsPerPixel) {
-            case 15:
-                SDL_SetColorKey(temp, SDL_TRUE,
-                                (*(Uint16 *) temp->pixels) & 0x00007FFF);
-                break;
-            case 16:
-                SDL_SetColorKey(temp, SDL_TRUE, *(Uint16 *) temp->pixels);
-                break;
-            case 24:
-                SDL_SetColorKey(temp, SDL_TRUE,
-                                (*(Uint32 *) temp->pixels) & 0x00FFFFFF);
-                break;
-            case 32:
-                SDL_SetColorKey(temp, SDL_TRUE, *(Uint32 *) temp->pixels);
-                break;
-            }
         }
     }
 
@@ -93,45 +184,186 @@ LoadTexture(SDL_Renderer *renderer, const char *file, SDL_bool transparent)
     return texture;
 }
 
+static int
+StandardizeAxisValue(int nValue)
+{
+    if (nValue > SDL_JOYSTICK_AXIS_MAX/2) {
+        return SDL_JOYSTICK_AXIS_MAX;
+    } else if (nValue < SDL_JOYSTICK_AXIS_MIN/2) {
+        return SDL_JOYSTICK_AXIS_MIN;
+    } else {
+        return 0;
+    }
+}
+
+static void
+SetCurrentBinding(int iBinding)
+{
+    int iIndex;
+    SDL_GameControllerExtendedBind *pBinding;
+
+    if (iBinding < 0) {
+        return;
+    }
+
+    if (iBinding == BINDING_COUNT) {
+        s_bBindingComplete = SDL_TRUE;
+        return;
+    }
+
+    s_iCurrentBinding = iBinding;
+
+    pBinding = &s_arrBindings[s_arrBindingOrder[s_iCurrentBinding]];
+    SDL_zerop(pBinding);
+
+    for (iIndex = 0; iIndex < s_nNumAxes; ++iIndex) {
+        s_arrAxisState[iIndex].m_nFarthestValue = s_arrAxisState[iIndex].m_nStartingValue;
+    }
+
+    s_unPendingAdvanceTime = 0;
+}
+
+static SDL_bool
+BBindingContainsBinding(const SDL_GameControllerExtendedBind *pBindingA, const SDL_GameControllerExtendedBind *pBindingB)
+{
+    if (pBindingA->bindType != pBindingB->bindType)
+    {
+        return SDL_FALSE;
+    }
+    switch (pBindingA->bindType)
+    {
+    case SDL_CONTROLLER_BINDTYPE_AXIS:
+        if (pBindingA->value.axis.axis != pBindingB->value.axis.axis) {
+            return SDL_FALSE;
+        }
+        if (!pBindingA->committed) {
+            return SDL_FALSE;
+        }
+        {
+            int minA = SDL_min(pBindingA->value.axis.axis_min, pBindingA->value.axis.axis_max);
+            int maxA = SDL_max(pBindingA->value.axis.axis_min, pBindingA->value.axis.axis_max);
+            int minB = SDL_min(pBindingB->value.axis.axis_min, pBindingB->value.axis.axis_max);
+            int maxB = SDL_max(pBindingB->value.axis.axis_min, pBindingB->value.axis.axis_max);
+            return (minA <= minB && maxA >= maxB);
+        }
+        /* Not reached */
+    default:
+        return SDL_memcmp(pBindingA, pBindingB, sizeof(*pBindingA)) == 0;
+    }
+}
+
+static void
+ConfigureBinding(const SDL_GameControllerExtendedBind *pBinding)
+{
+    SDL_GameControllerExtendedBind *pCurrent;
+    int iIndex;
+    int iCurrentElement = s_arrBindingOrder[s_iCurrentBinding];
+
+    /* Do we already have this binding? */
+    for (iIndex = 0; iIndex < SDL_arraysize(s_arrBindings); ++iIndex) {
+        pCurrent = &s_arrBindings[iIndex];
+        if (BBindingContainsBinding(pCurrent, pBinding)) {
+            if (iIndex == SDL_CONTROLLER_BUTTON_A && iCurrentElement != SDL_CONTROLLER_BUTTON_B) {
+                /* Skip to the next binding */
+                SetCurrentBinding(s_iCurrentBinding + 1);
+                return;
+            }
+
+            if (iIndex == SDL_CONTROLLER_BUTTON_B) {
+                /* Go back to the previous binding */
+                SetCurrentBinding(s_iCurrentBinding - 1);
+                return;
+            }
+
+            /* Already have this binding, ignore it */
+            return;
+        }
+    }
+
+#ifdef DEBUG_CONTROLLERMAP
+    switch ( pBinding->bindType )
+    {
+    case SDL_CONTROLLER_BINDTYPE_NONE:
+            break;
+    case SDL_CONTROLLER_BINDTYPE_BUTTON:
+            SDL_Log("Configuring button binding for button %d\n", pBinding->value.button);
+            break;
+    case SDL_CONTROLLER_BINDTYPE_AXIS:
+            SDL_Log("Configuring axis binding for axis %d %d/%d committed = %s\n", pBinding->value.axis.axis, pBinding->value.axis.axis_min, pBinding->value.axis.axis_max, pBinding->committed ? "true" : "false");
+            break;
+    case SDL_CONTROLLER_BINDTYPE_HAT:
+            SDL_Log("Configuring hat binding for hat %d %d\n", pBinding->value.hat.hat, pBinding->value.hat.hat_mask);
+            break;
+    }
+#endif /* DEBUG_CONTROLLERMAP */
+
+    /* Should the new binding override the existing one? */
+    pCurrent = &s_arrBindings[iCurrentElement];
+    if (pCurrent->bindType != SDL_CONTROLLER_BINDTYPE_NONE) {
+        SDL_bool bNativeDPad, bCurrentDPad;
+        SDL_bool bNativeAxis, bCurrentAxis;
+        
+        bNativeDPad = (iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_UP ||
+                       iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_DOWN ||
+                       iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_LEFT ||
+                       iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
+        bCurrentDPad = (pCurrent->bindType == SDL_CONTROLLER_BINDTYPE_HAT);
+        if (bNativeDPad && bCurrentDPad) {
+            /* We already have a binding of the type we want, ignore the new one */
+            return;
+        }
+
+        bNativeAxis = (iCurrentElement >= SDL_CONTROLLER_BUTTON_MAX);
+        bCurrentAxis = (pCurrent->bindType == SDL_CONTROLLER_BINDTYPE_AXIS);
+        if (bNativeAxis == bCurrentAxis &&
+            (pBinding->bindType != SDL_CONTROLLER_BINDTYPE_AXIS ||
+             pBinding->value.axis.axis != pCurrent->value.axis.axis)) {
+            /* We already have a binding of the type we want, ignore the new one */
+            return;
+        }
+    }
+
+    *pCurrent = *pBinding;
+
+    if (pBinding->committed) {
+        s_unPendingAdvanceTime = SDL_GetTicks();
+    } else {
+        s_unPendingAdvanceTime = 0;
+    }
+}
+
 static SDL_bool
+BMergeAxisBindings(int iIndex)
+{
+    SDL_GameControllerExtendedBind *pBindingA = &s_arrBindings[iIndex];
+    SDL_GameControllerExtendedBind *pBindingB = &s_arrBindings[iIndex+1];
+    if (pBindingA->bindType == SDL_CONTROLLER_BINDTYPE_AXIS &&
+        pBindingB->bindType == SDL_CONTROLLER_BINDTYPE_AXIS &&
+        pBindingA->value.axis.axis == pBindingB->value.axis.axis) {
+        if (pBindingA->value.axis.axis_min == pBindingB->value.axis.axis_min) {
+            pBindingA->value.axis.axis_min = pBindingA->value.axis.axis_max;
+            pBindingA->value.axis.axis_max = pBindingB->value.axis.axis_max;
+            pBindingB->bindType = SDL_CONTROLLER_BINDTYPE_NONE;
+            return SDL_TRUE;
+        }
+    }
+    return SDL_FALSE;
+}
+
+static void
 WatchJoystick(SDL_Joystick * joystick)
 {
     SDL_Window *window = NULL;
     SDL_Renderer *screen = NULL;
     SDL_Texture *background, *button, *axis, *marker;
     const char *name = NULL;
-    SDL_bool retval = SDL_FALSE;
-    SDL_bool done = SDL_FALSE, next=SDL_FALSE;
+    SDL_bool done = SDL_FALSE;
     SDL_Event event;
     SDL_Rect dst;
-    int s, _s;
     Uint8 alpha=200, alpha_step = -1;
     Uint32 alpha_ticks = 0;
-    char mapping[4096], temp[4096];
-    MappingStep *step, *prev_step;
-    MappingStep steps[] = {
-        {342, 132,  0.0,  MARKER_BUTTON, "x", -1, -1, -1, -1, ""},
-        {387, 167,  0.0,  MARKER_BUTTON, "a", -1, -1, -1, -1, ""},
-        {431, 132,  0.0,  MARKER_BUTTON, "b", -1, -1, -1, -1, ""},
-        {389, 101,  0.0,  MARKER_BUTTON, "y", -1, -1, -1, -1, ""},
-        {174, 132,  0.0,  MARKER_BUTTON, "back", -1, -1, -1, -1, ""},
-        {233, 132,  0.0,  MARKER_BUTTON, "guide", -1, -1, -1, -1, ""},
-        {289, 132,  0.0,  MARKER_BUTTON, "start", -1, -1, -1, -1, ""},        
-        {116, 217,  0.0,  MARKER_BUTTON, "dpleft", -1, -1, -1, -1, ""},
-        {154, 249,  0.0,  MARKER_BUTTON, "dpdown", -1, -1, -1, -1, ""},
-        {186, 217,  0.0,  MARKER_BUTTON, "dpright", -1, -1, -1, -1, ""},
-        {154, 188,  0.0,  MARKER_BUTTON, "dpup", -1, -1, -1, -1, ""},
-        {77,  40,   0.0,  MARKER_BUTTON, "leftshoulder", -1, -1, -1, -1, ""},
-        {91, 0,    0.0,  MARKER_BUTTON, "lefttrigger", -1, -1, -1, -1, ""},
-        {396, 36,   0.0,  MARKER_BUTTON, "rightshoulder", -1, -1, -1, -1, ""},
-        {375, 0,    0.0,  MARKER_BUTTON, "righttrigger", -1, -1, -1, -1, ""},
-        {75,  154,  0.0,  MARKER_BUTTON, "leftstick", -1, -1, -1, -1, ""},
-        {305, 230,  0.0,  MARKER_BUTTON, "rightstick", -1, -1, -1, -1, ""},
-        {75,  154,  0.0,  MARKER_AXIS,   "leftx", -1, -1, -1, -1, ""},
-        {75,  154,  90.0, MARKER_AXIS,   "lefty", -1, -1, -1, -1, ""},        
-        {305, 230,  0.0,  MARKER_AXIS,   "rightx", -1, -1, -1, -1, ""},
-        {305, 230,  90.0, MARKER_AXIS,   "righty", -1, -1, -1, -1, ""},
-    };
+    SDL_JoystickID nJoystickID;
+    int iIndex;
 
     /* Create a window to display joystick axis position */
     window = SDL_CreateWindow("Game Controller Map", SDL_WINDOWPOS_CENTERED,
@@ -139,14 +371,14 @@ WatchJoystick(SDL_Joystick * joystick)
                               SCREEN_HEIGHT, 0);
     if (window == NULL) {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
-        return SDL_FALSE;
+        return;
     }
 
     screen = SDL_CreateRenderer(window, -1, 0);
     if (screen == NULL) {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
         SDL_DestroyWindow(window);
-        return SDL_FALSE;
+        return;
     }
     
     background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE);
@@ -173,23 +405,24 @@ WatchJoystick(SDL_Joystick * joystick)
     To skip a button, press SPACE or click/touch the screen\n\
     To exit, press ESC\n\
     ====================================================================================\n");
-    
-    /* Initialize mapping with GUID and name */
-    SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, SDL_arraysize(temp));
-    SDL_snprintf(mapping, SDL_arraysize(mapping), "%s,%s,platform:%s,",
-        temp, name ? name : "Unknown Joystick", SDL_GetPlatform());
+
+    nJoystickID = SDL_JoystickInstanceID(joystick);
+
+    s_nNumAxes = SDL_JoystickNumAxes(joystick);
+    s_arrAxisState = (AxisState *)SDL_calloc(s_nNumAxes, sizeof(*s_arrAxisState));
+    for (iIndex = 0; iIndex < s_nNumAxes; ++iIndex) {
+        AxisState *pAxisState = &s_arrAxisState[iIndex];
+        Sint16 nInitialValue;
+        pAxisState->m_bMoving = SDL_JoystickGetAxisInitialState(joystick, iIndex, &nInitialValue);
+        pAxisState->m_nStartingValue = nInitialValue;
+        pAxisState->m_nFarthestValue = nInitialValue;
+    }
 
     /* Loop, getting joystick events! */
-    for(s=0; s<SDL_arraysize(steps) && !done;) {
-        /* blank screen, set up for drawing this frame. */
-        step = &steps[s];
-        SDL_strlcpy(step->mapping, mapping, SDL_arraysize(step->mapping));
-        step->axis = -1;
-        step->button = -1;
-        step->hat = -1;
-        step->hat_value = -1;
-        
-        switch(step->marker) {
+    while (!done && !s_bBindingComplete) {
+        int iElement = s_arrBindingOrder[s_iCurrentBinding];
+
+        switch (s_arrBindingDisplay[iElement].marker) {
             case MARKER_AXIS:
                 marker = axis;
                 break;
@@ -200,137 +433,271 @@ WatchJoystick(SDL_Joystick * joystick)
                 break;
         }
         
-        dst.x = step->x;
-        dst.y = step->y;
+        dst.x = s_arrBindingDisplay[iElement].x;
+        dst.y = s_arrBindingDisplay[iElement].y;
         SDL_QueryTexture(marker, NULL, NULL, &dst.w, &dst.h);
-        next=SDL_FALSE;
 
-        SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);
+        if (SDL_GetTicks() - alpha_ticks > 5) {
+            alpha_ticks = SDL_GetTicks();
+            alpha += alpha_step;
+            if (alpha == 255) {
+                alpha_step = -1;
+            }
+            if (alpha < 128) {
+                alpha_step = 1;
+            }
+        }
 
-        while (!done && !next) {
-            if (SDL_GetTicks() - alpha_ticks > 5) {
-                alpha_ticks = SDL_GetTicks();
-                alpha += alpha_step;
-                if (alpha == 255) {
-                    alpha_step = -1;
+        SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);
+        SDL_RenderClear(screen);
+        SDL_RenderCopy(screen, background, NULL, NULL);
+        SDL_SetTextureAlphaMod(marker, alpha);
+        SDL_SetTextureColorMod(marker, 10, 255, 21);
+        SDL_RenderCopyEx(screen, marker, NULL, &dst, s_arrBindingDisplay[iElement].angle, NULL, SDL_FLIP_NONE);
+        SDL_RenderPresent(screen);
+            
+        while (SDL_PollEvent(&event) > 0) {
+            switch (event.type) {
+            case SDL_JOYDEVICEREMOVED:
+                if (event.jaxis.which == nJoystickID) {
+                    done = SDL_TRUE;
                 }
-                if (alpha < 128) {
-                    alpha_step = 1;
+                break;
+            case SDL_JOYAXISMOTION:
+                if (event.jaxis.which == nJoystickID) {
+                    AxisState *pAxisState = &s_arrAxisState[event.jaxis.axis];
+                    int nValue = event.jaxis.value;
+                    int nCurrentDistance, nFarthestDistance;
+                    if (!pAxisState->m_bMoving) {
+                        pAxisState->m_bMoving = SDL_TRUE;
+                        pAxisState->m_nStartingValue = nValue;
+                        pAxisState->m_nFarthestValue = nValue;
+                    }
+                    nCurrentDistance = SDL_abs(nValue - pAxisState->m_nStartingValue);
+                    nFarthestDistance = SDL_abs(pAxisState->m_nFarthestValue - pAxisState->m_nStartingValue);
+                    if (nCurrentDistance > nFarthestDistance) {
+                        pAxisState->m_nFarthestValue = nValue;
+                        nFarthestDistance = SDL_abs(pAxisState->m_nFarthestValue - pAxisState->m_nStartingValue);
+                    }
+
+#ifdef DEBUG_CONTROLLERMAP
+                    SDL_Log("AXIS %d nValue %d nCurrentDistance %d nFarthestDistance %d\n", event.jaxis.axis, nValue, nCurrentDistance, nFarthestDistance);
+#endif
+                    if (nFarthestDistance >= 16000) {
+                        /* If we've gone out far enough and started to come back, let's bind this axis */
+                        SDL_bool bCommitBinding = (nCurrentDistance <= 10000) ? SDL_TRUE : SDL_FALSE;
+                        SDL_GameControllerExtendedBind binding;
+                        SDL_zero(binding);
+                        binding.bindType = SDL_CONTROLLER_BINDTYPE_AXIS;
+                        binding.value.axis.axis = event.jaxis.axis;
+                        binding.value.axis.axis_min = StandardizeAxisValue(pAxisState->m_nStartingValue);
+                        binding.value.axis.axis_max = StandardizeAxisValue(pAxisState->m_nFarthestValue);
+                        binding.committed = bCommitBinding;
+                        ConfigureBinding(&binding);
+                    }
                 }
-            }
-            
-            SDL_RenderClear(screen);
-            SDL_RenderCopy(screen, background, NULL, NULL);
-            SDL_SetTextureAlphaMod(marker, alpha);
-            SDL_SetTextureColorMod(marker, 10, 255, 21);
-            SDL_RenderCopyEx(screen, marker, NULL, &dst, step->angle, NULL, SDL_FLIP_NONE);
-            SDL_RenderPresent(screen);
-            
-            if (SDL_PollEvent(&event)) {
-                switch (event.type) {
-                case SDL_JOYAXISMOTION:
-                    if ((event.jaxis.value > 20000 || event.jaxis.value < -20000) && event.jaxis.value != -32768) {
-                        for (_s = 0; _s < s; _s++) {
-                            if (steps[_s].axis == event.jaxis.axis) {
-                                break;
-                            }
-                        }
-                        if (_s == s) {
-                            step->axis = event.jaxis.axis;
-                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
-                            SDL_snprintf(temp, SDL_arraysize(temp), ":a%u,", event.jaxis.axis);
-                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
-                            s++;
-                            next=SDL_TRUE;
-                        }
+                break;
+            case SDL_JOYHATMOTION:
+                if (event.jhat.which == nJoystickID) {
+                    if (event.jhat.value != SDL_HAT_CENTERED) {
+                        SDL_GameControllerExtendedBind binding;
+
+#ifdef DEBUG_CONTROLLERMAP
+                        SDL_Log("HAT %d %d\n", event.jhat.hat, event.jhat.value);
+#endif
+                        SDL_zero(binding);
+                        binding.bindType = SDL_CONTROLLER_BINDTYPE_HAT;
+                        binding.value.hat.hat = event.jhat.hat;
+                        binding.value.hat.hat_mask = event.jhat.value;
+                        binding.committed = SDL_TRUE;
+                        ConfigureBinding(&binding);
                     }
-                    
+                }
+                break;
+            case SDL_JOYBALLMOTION:
+                break;
+            case SDL_JOYBUTTONDOWN:
+                if (event.jbutton.which == nJoystickID) {
+                    SDL_GameControllerExtendedBind binding;
+
+#ifdef DEBUG_CONTROLLERMAP
+                    SDL_Log("BUTTON %d\n", event.jbutton.button);
+#endif
+                    SDL_zero(binding);
+                    binding.bindType = SDL_CONTROLLER_BINDTYPE_BUTTON;
+                    binding.value.button = event.jbutton.button;
+                    binding.committed = SDL_TRUE;
+                    ConfigureBinding(&binding);
+                }
+                break;
+            case SDL_FINGERDOWN:
+            case SDL_MOUSEBUTTONDOWN:
+                /* Skip this step */
+                SetCurrentBinding(s_iCurrentBinding + 1);
+                break;
+            case SDL_KEYDOWN:
+                if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) {
+                    SetCurrentBinding(s_iCurrentBinding - 1);
                     break;
-                case SDL_JOYHATMOTION:
-                        if (event.jhat.value == SDL_HAT_CENTERED) {
-                            break;  /* ignore centering, we're probably just coming back to the center from the previous item we set. */
-                        }
-                        for (_s = 0; _s < s; _s++) {
-                            if (steps[_s].hat == event.jhat.hat && steps[_s].hat_value == event.jhat.value) {
-                                break;
-                            }
-                        }
-                        if (_s == s) {
-                            step->hat = event.jhat.hat;
-                            step->hat_value = event.jhat.value;
-                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
-                            SDL_snprintf(temp, SDL_arraysize(temp), ":h%u.%u,", event.jhat.hat, event.jhat.value );
-                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
-                            s++;
-                            next=SDL_TRUE;
-                        }
+                }
+                if (event.key.keysym.sym == SDLK_SPACE) {
+                    SetCurrentBinding(s_iCurrentBinding + 1);
                     break;
-                case SDL_JOYBALLMOTION:
+                }
+
+                if ((event.key.keysym.sym != SDLK_ESCAPE)) {
                     break;
-                case SDL_JOYBUTTONUP:
-                    for (_s = 0; _s < s; _s++) {
-                        if (steps[_s].button == event.jbutton.button) {
-                            break;
-                        }
-                    }
-                    if (_s == s) {
-                        step->button = event.jbutton.button;
-                        SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
-                        SDL_snprintf(temp, SDL_arraysize(temp), ":b%u,", event.jbutton.button);
-                        SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
-                        s++;
-                        next=SDL_TRUE;
+                }
+                /* Fall through to signal quit */
+            case SDL_QUIT:
+                done = SDL_TRUE;
+                break;
+            default:
+                break;
+            }
+        }
+
+        SDL_Delay(15);
+
+        /* Wait 100 ms for joystick events to stop coming in,
+           in case a controller sends multiple events for a single control (e.g. axis and button for trigger)
+        */
+        if (s_unPendingAdvanceTime && SDL_GetTicks() - s_unPendingAdvanceTime >= 100) {
+            SetCurrentBinding(s_iCurrentBinding + 1);
+        }
+    }
+
+    if (s_bBindingComplete) {
+        char mapping[1024];
+        char trimmed_name[128];
+        char *spot;
+        int iIndex;
+        char pszElement[12];
+
+        SDL_strlcpy(trimmed_name, name, SDL_arraysize(trimmed_name));
+        while (SDL_isspace(trimmed_name[0])) {
+            SDL_memmove(&trimmed_name[0], &trimmed_name[1], SDL_strlen(trimmed_name));
+        }
+        while (trimmed_name[0] && SDL_isspace(trimmed_name[SDL_strlen(trimmed_name) - 1])) {
+            trimmed_name[SDL_strlen(trimmed_name) - 1] = '\0';
+        }
+        while ((spot = SDL_strchr(trimmed_name, ',')) != NULL) {
+            SDL_memmove(spot, spot + 1, SDL_strlen(spot));
+        }
+
+        /* Initialize mapping with GUID and name */
+        SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), mapping, SDL_arraysize(mapping));
+        SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
+        SDL_strlcat(mapping, trimmed_name, SDL_arraysize(mapping));
+        SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
+        SDL_strlcat(mapping, "platform:", SDL_arraysize(mapping));
+        SDL_strlcat(mapping, SDL_GetPlatform(), SDL_arraysize(mapping));
+        SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
+
+        for (iIndex = 0; iIndex < SDL_arraysize(s_arrBindings); ++iIndex) {
+            SDL_GameControllerExtendedBind *pBinding = &s_arrBindings[iIndex];
+            if (pBinding->bindType == SDL_CONTROLLER_BINDTYPE_NONE) {
+                continue;
+            }
+
+            if (iIndex < SDL_CONTROLLER_BUTTON_MAX) {
+                SDL_GameControllerButton eButton = (SDL_GameControllerButton)iIndex;
+                SDL_strlcat(mapping, SDL_GameControllerGetStringForButton(eButton), SDL_arraysize(mapping));
+            } else {
+                const char *pszAxisName;
+                switch (iIndex - SDL_CONTROLLER_BUTTON_MAX) {
+                case SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE:
+                    if (!BMergeAxisBindings(iIndex)) {
+                        SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
                     }
+                    pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTX);
                     break;
-                case SDL_FINGERDOWN:
-                case SDL_MOUSEBUTTONDOWN:
-                    /* Skip this step */
-                    s++;
-                    next=SDL_TRUE;
+                case SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE:
+                    SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
+                    pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTX);
                     break;
-                case SDL_KEYDOWN:
-                    if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) {
-                        /* Undo! */
-                        if (s > 0) {
-                            prev_step = &steps[--s];
-                            SDL_strlcpy(mapping, prev_step->mapping, SDL_arraysize(prev_step->mapping));
-                            next = SDL_TRUE;
-                        }
-                        break;
+                case SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE:
+                    if (!BMergeAxisBindings(iIndex)) {
+                        SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
                     }
-                    if (event.key.keysym.sym == SDLK_SPACE) {
-                        /* Skip this step */
-                        s++;
-                        next=SDL_TRUE;
-                        break;
+                    pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTY);
+                    break;
+                case SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE:
+                    SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
+                    pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTY);
+                    break;
+                case SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE:
+                    if (!BMergeAxisBindings(iIndex)) {
+                        SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
                     }
-                    
-                    if ((event.key.keysym.sym != SDLK_ESCAPE)) {
-                        break;
+                    pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTX);
+                    break;
+                case SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE:
+                    SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
+                    pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTX);
+                    break;
+                case SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE:
+                    if (!BMergeAxisBindings(iIndex)) {
+                        SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
                     }
-                    /* Fall through to signal quit */
-                case SDL_QUIT:
-                    done = SDL_TRUE;
+                    pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTY);
+                    break;
+                case SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE:
+                    SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
+                    pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTY);
                     break;
-                default:
+                case SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT:
+                    pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_TRIGGERLEFT);
+                    break;
+                case SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT:
+                    pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_TRIGGERRIGHT);
                     break;
                 }
+                SDL_strlcat(mapping, pszAxisName, SDL_arraysize(mapping));
             }
-        }
+            SDL_strlcat(mapping, ":", SDL_arraysize(mapping));
 
-    }
+            pszElement[0] = '\0';
+            switch (pBinding->bindType) {
+            case SDL_CONTROLLER_BINDTYPE_BUTTON:
+                SDL_snprintf(pszElement, sizeof(pszElement), "b%d", pBinding->value.button);
+                break;
+            case SDL_CONTROLLER_BINDTYPE_AXIS:
+                if (pBinding->value.axis.axis_min == 0 && pBinding->value.axis.axis_max == SDL_JOYSTICK_AXIS_MIN) {
+                    /* The negative half axis */
+                    SDL_snprintf(pszElement, sizeof(pszElement), "-a%d", pBinding->value.axis.axis);
+                } else if (pBinding->value.axis.axis_min == 0 && pBinding->value.axis.axis_max == SDL_JOYSTICK_AXIS_MAX) {
+                    /* The positive half axis */
+                    SDL_snprintf(pszElement, sizeof(pszElement), "+a%d", pBinding->value.axis.axis);
+                } else {
+                    SDL_snprintf(pszElement, sizeof(pszElement), "a%d", pBinding->value.axis.axis);
+                    if (pBinding->value.axis.axis_min > pBinding->value.axis.axis_max) {
+                        /* Invert the axis */
+                        SDL_strlcat(pszElement, "~", SDL_arraysize(pszElement));
+                    }
+                }
+                break;
+            case SDL_CONTROLLER_BINDTYPE_HAT:
+                SDL_snprintf(pszElement, sizeof(pszElement), "h%d.%d", pBinding->value.hat.hat, pBinding->value.hat.hat_mask);
+                break;
+            default:
+                SDL_assert(!"Unknown bind type");
+                break;
+            }
+            SDL_strlcat(mapping, pszElement, SDL_arraysize(mapping));
+            SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
+        }
 
-    if (s == SDL_arraysize(steps) ) {
         SDL_Log("Mapping:\n\n%s\n\n", mapping);
         /* Print to stdout as well so the user can cat the output somewhere */
         printf("%s\n", mapping);
     }
-    
-    while(SDL_PollEvent(&event)) {};
+
+    SDL_free(s_arrAxisState);
+    s_arrAxisState = NULL;
     
     SDL_DestroyRenderer(screen);
     SDL_DestroyWindow(window);
-    return retval;
 }
 
 int
@@ -368,6 +735,7 @@ main(int argc, char *argv[])
             SDL_Log("    buttons: %d\n", SDL_JoystickNumButtons(joystick));
             SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick));
             SDL_Log("       guid: %s\n", guid);
+            SDL_Log("    VID/PID: 0x%.4x/0x%.4x\n", SDL_JoystickGetVendor(joystick), SDL_JoystickGetProduct(joystick));
             SDL_JoystickClose(joystick);
         }
     }
@@ -377,9 +745,6 @@ main(int argc, char *argv[])
 #else
     if (argv[1]) {
 #endif
-        SDL_bool reportederror = SDL_FALSE;
-        SDL_bool keepGoing = SDL_TRUE;
-        SDL_Event event;
         int device;
 #ifdef __ANDROID__
         device = 0;
@@ -387,34 +752,11 @@ main(int argc, char *argv[])
         device = atoi(argv[1]);
 #endif
         joystick = SDL_JoystickOpen(device);
-
-        while ( keepGoing ) {
-            if (joystick == NULL) {
-                if ( !reportederror ) {
-                    SDL_Log("Couldn't open joystick %d: %s\n", device, SDL_GetError());
-                    keepGoing = SDL_FALSE;
-                    reportederror = SDL_TRUE;
-                }
-            } else {
-                reportederror = SDL_FALSE;
-                keepGoing = WatchJoystick(joystick);
-                SDL_JoystickClose(joystick);
-            }
-
-            joystick = NULL;
-            if (keepGoing) {
-                SDL_Log("Waiting for attach\n");
-            }
-            while (keepGoing) {
-                SDL_WaitEvent(&event);
-                if ((event.type == SDL_QUIT) || (event.type == SDL_FINGERDOWN)
-                    || (event.type == SDL_MOUSEBUTTONDOWN)) {
-                    keepGoing = SDL_FALSE;
-                } else if (event.type == SDL_JOYDEVICEADDED) {
-                    joystick = SDL_JoystickOpen(device);
-                    break;
-                }
-            }
+        if (joystick == NULL) {
+            SDL_Log("Couldn't open joystick %d: %s\n", device, SDL_GetError());
+        } else {
+            WatchJoystick(joystick);
+            SDL_JoystickClose(joystick);
         }
     }
     else {
@@ -435,3 +777,5 @@ main(int argc, char *argv[])
 }
 
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/test/loopwave.c b/test/loopwave.c
index ec9f528..63e1996 100644
--- a/test/loopwave.c
+++ b/test/loopwave.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,17 +20,13 @@
 #include <stdio.h>
 #include <stdlib.h>
 
-#if HAVE_SIGNAL_H
-#include <signal.h>
-#endif
-
 #ifdef __EMSCRIPTEN__
 #include <emscripten/emscripten.h>
 #endif
 
 #include "SDL.h"
 
-struct
+static struct
 {
     SDL_AudioSpec spec;
     Uint8 *sound;               /* Pointer to wave data */
@@ -38,6 +34,7 @@ struct
     int soundpos;               /* Current play position */
 } wave;
 
+static SDL_AudioDeviceID device;
 
 /* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
 static void
@@ -47,6 +44,37 @@ quit(int rc)
     exit(rc);
 }
 
+static void
+close_audio()
+{
+    if (device != 0) {
+        SDL_CloseAudioDevice(device);
+        device = 0;
+    }
+}
+
+static void
+open_audio()
+{
+    /* Initialize fillerup() variables */
+    device = SDL_OpenAudioDevice(NULL, SDL_FALSE, &wave.spec, NULL, 0);
+    if (!device) {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open audio: %s\n", SDL_GetError());
+        SDL_FreeWAV(wave.sound);
+        quit(2);
+    }
+
+
+    /* Let the audio run */
+    SDL_PauseAudioDevice(device, SDL_FALSE);
+}
+
+static void reopen_audio()
+{
+    close_audio();
+    open_audio();
+}
+
 
 void SDLCALL
 fillerup(void *unused, Uint8 * stream, int len)
@@ -72,17 +100,12 @@ fillerup(void *unused, Uint8 * stream, int len)
 }
 
 static int done = 0;
-void
-poked(int sig)
-{
-    done = 1;
-}
 
 #ifdef __EMSCRIPTEN__
 void
 loop()
 {
-    if(done || (SDL_GetAudioStatus() != SDL_AUDIO_PLAYING))
+    if(done || (SDL_GetAudioDeviceStatus(device) != SDL_AUDIO_PLAYING))
         emscripten_cancel_main_loop();
 }
 #endif
@@ -97,7 +120,7 @@ main(int argc, char *argv[])
     SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
 
     /* Load the SDL library */
-    if (SDL_Init(SDL_INIT_AUDIO) < 0) {
+    if (SDL_Init(SDL_INIT_AUDIO|SDL_INIT_EVENTS) < 0) {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
         return (1);
     }
@@ -114,17 +137,6 @@ main(int argc, char *argv[])
     }
 
     wave.spec.callback = fillerup;
-#if HAVE_SIGNAL_H
-    /* Set the signals */
-#ifdef SIGHUP
-    signal(SIGHUP, poked);
-#endif
-    signal(SIGINT, poked);
-#ifdef SIGQUIT
-    signal(SIGQUIT, poked);
-#endif
-    signal(SIGTERM, poked);
-#endif /* HAVE_SIGNAL_H */
 
     /* Show the list of available drivers */
     SDL_Log("Available audio drivers:");
@@ -132,27 +144,33 @@ main(int argc, char *argv[])
         SDL_Log("%i: %s", i, SDL_GetAudioDriver(i));
     }
 
-    /* Initialize fillerup() variables */
-    if (SDL_OpenAudio(&wave.spec, NULL) < 0) {
-        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open audio: %s\n", SDL_GetError());
-        SDL_FreeWAV(wave.sound);
-        quit(2);
-    }
-
     SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());
 
-    /* Let the audio run */
-    SDL_PauseAudio(0);
+    open_audio();
+
+    SDL_FlushEvents(SDL_AUDIODEVICEADDED, SDL_AUDIODEVICEREMOVED);
 
 #ifdef __EMSCRIPTEN__
     emscripten_set_main_loop(loop, 0, 1);
 #else
-    while (!done && (SDL_GetAudioStatus() == SDL_AUDIO_PLAYING))
-        SDL_Delay(1000);
+    while (!done) {
+        SDL_Event event;
+
+        while (SDL_PollEvent(&event) > 0) {
+            if (event.type == SDL_QUIT) {
+                done = 1;
+            }
+            if ((event.type == SDL_AUDIODEVICEADDED && !event.adevice.iscapture) ||
+                (event.type == SDL_AUDIODEVICEREMOVED && !event.adevice.iscapture && event.adevice.which == device)) {
+                reopen_audio();
+            }
+        }
+        SDL_Delay(100);
+    }
 #endif
 
     /* Clean up on signal */
-    SDL_CloseAudio();
+    close_audio();
     SDL_FreeWAV(wave.sound);
     SDL_Quit();
     return (0);
diff --git a/test/loopwavequeue.c b/test/loopwavequeue.c
index 85f5bd5..3dc7792 100644
--- a/test/loopwavequeue.c
+++ b/test/loopwavequeue.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,12 +25,11 @@
 #include <signal.h>
 #endif
 
-struct
+static struct
 {
     SDL_AudioSpec spec;
     Uint8 *sound;               /* Pointer to wave data */
     Uint32 soundlen;            /* Length of wave data */
-    int soundpos;               /* Current play position */
 } wave;
 
 
diff --git a/test/nacl/common.js b/test/nacl/common.js
index a108fad..a700015 100644
--- a/test/nacl/common.js
+++ b/test/nacl/common.js
@@ -39,7 +39,7 @@ var common = (function() {
         mimetype = 'application/x-ppapi-release';
       else
         mimetype = 'application/x-ppapi-debug';
-    } else if (tool == 'pnacl' && isRelease) {
+    } else if (tool == 'pnacl') {
       mimetype = 'application/x-pnacl';
     }
     return mimetype;
@@ -147,6 +147,11 @@ var common = (function() {
     var listenerDiv = document.getElementById('listener');
     listenerDiv.appendChild(moduleEl);
 
+    // Request the offsetTop property to force a relayout. As of Apr 10, 2014
+    // this is needed if the module is being loaded on a Chrome App's
+    // background page (see crbug.com/350445).
+    moduleEl.offsetTop;
+
     // Host plugins don't send a moduleDidLoad message. We'll fake it here.
     var isHost = isHostToolchain(tool);
     if (isHost) {
diff --git a/test/testatomic.c b/test/testatomic.c
index d371ef3..f8dca91 100644
--- a/test/testatomic.c
+++ b/test/testatomic.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -103,7 +103,10 @@ void RunBasicTest()
 #define NInter (CountTo/CountInc/NThreads)
 #define Expect (CountTo-NInter*CountInc*NThreads)
 
-SDL_COMPILE_TIME_ASSERT(size, CountTo>0); /* check for rollover */
+enum {
+   CountTo_GreaterThanZero = CountTo > 0,
+};
+SDL_COMPILE_TIME_ASSERT(size, CountTo_GreaterThanZero); /* check for rollover */
 
 static SDL_atomic_t good = { 42 };
 
@@ -114,7 +117,7 @@ static SDL_atomic_t threadsRunning;
 static SDL_sem *threadDone;
 
 static
-int adder(void* junk)
+int SDLCALL adder(void* junk)
 {
     unsigned long N=NInter;
     SDL_Log("Thread subtracting %d %lu times\n",CountInc,N);
@@ -492,7 +495,7 @@ typedef struct
     char padding[SDL_CACHELINE_SIZE-(sizeof(SDL_EventQueue*)+sizeof(int)*NUM_WRITERS+sizeof(int)+sizeof(SDL_bool))%SDL_CACHELINE_SIZE];
 } ReaderData;
 
-static int FIFO_Writer(void* _data)
+static int SDLCALL FIFO_Writer(void* _data)
 {
     WriterData *data = (WriterData *)_data;
     SDL_EventQueue *queue = data->queue;
@@ -527,7 +530,7 @@ static int FIFO_Writer(void* _data)
     return 0;
 }
 
-static int FIFO_Reader(void* _data)
+static int SDLCALL FIFO_Reader(void* _data)
 {
     ReaderData *data = (ReaderData *)_data;
     SDL_EventQueue *queue = data->queue;
@@ -567,7 +570,7 @@ static int FIFO_Reader(void* _data)
 
 #ifdef TEST_SPINLOCK_FIFO
 /* This thread periodically locks the queue for no particular reason */
-static int FIFO_Watcher(void* _data)
+static int SDLCALL FIFO_Watcher(void* _data)
 {
     SDL_EventQueue *queue = (SDL_EventQueue *)_data;
 
@@ -597,7 +600,7 @@ static void RunFIFOTest(SDL_bool lock_free)
     int i, j;
     int grand_total;
     char textBuffer[1024];
-    int len;
+    size_t len;
 
     SDL_Log("\nFIFO test---------------------------------------\n\n");
     SDL_Log("Mode: %s\n", lock_free ? "LockFree" : "Mutex");
diff --git a/test/testaudiocapture.c b/test/testaudiocapture.c
index 26321a7..3b7ea0b 100644
--- a/test/testaudiocapture.c
+++ b/test/testaudiocapture.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testaudiohotplug.c b/test/testaudiohotplug.c
index 73d4805..a72f917 100644
--- a/test/testaudiohotplug.c
+++ b/test/testaudiohotplug.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testaudioinfo.c b/test/testaudioinfo.c
index 485fd0a..c70b86b 100644
--- a/test/testaudioinfo.c
+++ b/test/testaudioinfo.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testautomation.c b/test/testautomation.c
index eea74b3..9fd22be 100644
--- a/test/testautomation.c
+++ b/test/testautomation.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testautomation_audio.c b/test/testautomation_audio.c
index bef838d..be0f15e 100644
--- a/test/testautomation_audio.c
+++ b/test/testautomation_audio.c
@@ -46,7 +46,7 @@ int _audio_testCallbackLength;
 
 
 /* Test callback function */
-void _audio_testCallback(void *userdata, Uint8 *stream, int len)
+void SDLCALL _audio_testCallback(void *userdata, Uint8 *stream, int len)
 {
    /* track that callback was called */
    _audio_testCallbackCounter++;
diff --git a/test/testautomation_clipboard.c b/test/testautomation_clipboard.c
index f943ffe..417d957 100644
--- a/test/testautomation_clipboard.c
+++ b/test/testautomation_clipboard.c
@@ -121,7 +121,7 @@ clipboard_testClipboardTextFunctions(void *arg)
     SDLTest_AssertCheck(
         charResult[0] == '\0',
         "Verify SDL_GetClipboardText returned string with length 0, got length %i",
-        SDL_strlen(charResult));
+        (int) SDL_strlen(charResult));
     intResult = SDL_SetClipboardText((const char *)text);
     SDLTest_AssertPass("Call to SDL_SetClipboardText succeeded");
     SDLTest_AssertCheck(
diff --git a/test/testautomation_events.c b/test/testautomation_events.c
index a0119bd..09004da 100644
--- a/test/testautomation_events.c
+++ b/test/testautomation_events.c
@@ -25,7 +25,7 @@ int _userdataValue1 = 1;
 int _userdataValue2 = 2;
 
 /* Event filter that sets some flags and optionally checks userdata */
-int _events_sampleNullEventFilter(void *userdata, SDL_Event *event)
+int SDLCALL _events_sampleNullEventFilter(void *userdata, SDL_Event *event)
 {
    _eventFilterCalled = 1;
 
diff --git a/test/testautomation_keyboard.c b/test/testautomation_keyboard.c
index b2c3b9a..6f25bb7 100644
--- a/test/testautomation_keyboard.c
+++ b/test/testautomation_keyboard.c
@@ -312,7 +312,7 @@ keyboard_getSetModState(void *arg)
    /* Get state, cache for later reset */
    result = SDL_GetModState();
    SDLTest_AssertPass("Call to SDL_GetModState()");
-   SDLTest_AssertCheck(result >=0 && result <= allStates, "Verify result from call is valid, expected: 0 <= result <= %i, got: %i", allStates, result);
+   SDLTest_AssertCheck(/*result >= 0 &&*/ result <= allStates, "Verify result from call is valid, expected: 0 <= result <= %i, got: %i", allStates, result);
    currentState = result;
 
    /* Set random state */
diff --git a/test/testautomation_mouse.c b/test/testautomation_mouse.c
index 57cadee..ed30f26 100644
--- a/test/testautomation_mouse.c
+++ b/test/testautomation_mouse.c
@@ -447,11 +447,23 @@ mouse_warpMouseInWindow(void *arg)
 {
     const int w = MOUSE_TESTWINDOW_WIDTH, h = MOUSE_TESTWINDOW_HEIGHT;
     int numPositions = 6;
-    int xPositions[] = {-1, 0, 1, w-1, w, w+1 };
-    int yPositions[] = {-1, 0, 1, h-1, h, h+1 };
+    int xPositions[6];
+    int yPositions[6];
     int x, y, i, j;
     SDL_Window *window;
 
+    xPositions[0] = -1;
+    xPositions[1] = 0;
+    xPositions[2] = 1;
+    xPositions[3] = w-1;
+    xPositions[4] = w;
+    xPositions[5] = w+1;
+    yPositions[0] = -1;
+    yPositions[1] = 0;
+    yPositions[2] = 1;
+    yPositions[3] = h-1;
+    yPositions[4] = h;
+    yPositions[5] = h+1;
     /* Create test window */
     window = _createMouseSuiteTestWindow();
     if (window == NULL) return TEST_ABORTED;
diff --git a/test/testautomation_platform.c b/test/testautomation_platform.c
index 5211a4a..7cc732a 100644
--- a/test/testautomation_platform.c
+++ b/test/testautomation_platform.c
@@ -112,7 +112,7 @@ int platform_testGetFunctions (void *arg)
    char *platform;
    char *revision;
    int ret;
-   int len;
+   size_t len;
 
    platform = (char *)SDL_GetPlatform();
    SDLTest_AssertPass("SDL_GetPlatform()");
@@ -122,7 +122,7 @@ int platform_testGetFunctions (void *arg)
      SDLTest_AssertCheck(len > 0,
              "SDL_GetPlatform(): expected non-empty platform, was platform: '%s', len: %i",
              platform,
-             len);
+             (int) len);
    }
 
    ret = SDL_GetCPUCount();
@@ -282,7 +282,7 @@ int platform_testGetSetClearError(void *arg)
    int result;
    const char *testError = "Testing";
    char *lastError;
-   int len;
+   size_t len;
 
    SDL_ClearError();
    SDLTest_AssertPass("SDL_ClearError()");
@@ -295,7 +295,7 @@ int platform_testGetSetClearError(void *arg)
    {
      len = SDL_strlen(lastError);
      SDLTest_AssertCheck(len == 0,
-             "SDL_GetError(): no message expected, len: %i", len);
+             "SDL_GetError(): no message expected, len: %i", (int) len);
    }
 
    result = SDL_SetError("%s", testError);
@@ -309,8 +309,8 @@ int platform_testGetSetClearError(void *arg)
      len = SDL_strlen(lastError);
      SDLTest_AssertCheck(len == SDL_strlen(testError),
              "SDL_GetError(): expected message len %i, was len: %i",
-             SDL_strlen(testError),
-             len);
+             (int) SDL_strlen(testError),
+             (int) len);
      SDLTest_AssertCheck(SDL_strcmp(lastError, testError) == 0,
              "SDL_GetError(): expected message %s, was message: %s",
              testError,
@@ -334,7 +334,7 @@ int platform_testSetErrorEmptyInput(void *arg)
    int result;
    const char *testError = "";
    char *lastError;
-   int len;
+   size_t len;
 
    result = SDL_SetError("%s", testError);
    SDLTest_AssertPass("SDL_SetError()");
@@ -347,8 +347,8 @@ int platform_testSetErrorEmptyInput(void *arg)
      len = SDL_strlen(lastError);
      SDLTest_AssertCheck(len == SDL_strlen(testError),
              "SDL_GetError(): expected message len %i, was len: %i",
-             SDL_strlen(testError),
-             len);
+             (int) SDL_strlen(testError),
+             (int) len);
      SDLTest_AssertCheck(SDL_strcmp(lastError, testError) == 0,
              "SDL_GetError(): expected message '%s', was message: '%s'",
              testError,
@@ -373,14 +373,14 @@ int platform_testSetErrorInvalidInput(void *arg)
    const char *invalidError = NULL;
    const char *probeError = "Testing";
    char *lastError;
-   int len;
+   size_t len;
 
    /* Reset */
    SDL_ClearError();
    SDLTest_AssertPass("SDL_ClearError()");
 
    /* Check for no-op */
-   result = SDL_SetError(invalidError);
+   result = SDL_SetError("%s", invalidError);
    SDLTest_AssertPass("SDL_SetError()");
    SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
    lastError = (char *)SDL_GetError();
@@ -391,16 +391,16 @@ int platform_testSetErrorInvalidInput(void *arg)
      len = SDL_strlen(lastError);
      SDLTest_AssertCheck(len == 0,
              "SDL_GetError(): expected message len 0, was len: %i",
-             len);
+             (int) len);
    }
 
    /* Set */
-   result = SDL_SetError(probeError);
+   result = SDL_SetError("%s", probeError);
    SDLTest_AssertPass("SDL_SetError('%s')", probeError);
    SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
 
    /* Check for no-op */
-   result = SDL_SetError(invalidError);
+   result = SDL_SetError("%s", invalidError);
    SDLTest_AssertPass("SDL_SetError(NULL)");
    SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
    lastError = (char *)SDL_GetError();
@@ -411,7 +411,7 @@ int platform_testSetErrorInvalidInput(void *arg)
      len = SDL_strlen(lastError);
      SDLTest_AssertCheck(len == 0,
              "SDL_GetError(): expected message len 0, was len: %i",
-             len);
+             (int) len);
    }
 
    /* Reset */
@@ -419,7 +419,7 @@ int platform_testSetErrorInvalidInput(void *arg)
    SDLTest_AssertPass("SDL_ClearError()");
 
    /* Set and check */
-   result = SDL_SetError(probeError);
+   result = SDL_SetError("%s", probeError);
    SDLTest_AssertPass("SDL_SetError()");
    SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
    lastError = (char *)SDL_GetError();
@@ -430,8 +430,8 @@ int platform_testSetErrorInvalidInput(void *arg)
      len = SDL_strlen(lastError);
      SDLTest_AssertCheck(len == SDL_strlen(probeError),
              "SDL_GetError(): expected message len %i, was len: %i",
-             SDL_strlen(probeError),
-             len);
+             (int) SDL_strlen(probeError),
+             (int) len);
      SDLTest_AssertCheck(SDL_strcmp(lastError, probeError) == 0,
              "SDL_GetError(): expected message '%s', was message: '%s'",
              probeError,
diff --git a/test/testautomation_rwops.c b/test/testautomation_rwops.c
index 16f2161..9a1a29a 100644
--- a/test/testautomation_rwops.c
+++ b/test/testautomation_rwops.c
@@ -32,9 +32,9 @@ static const char RWopsAlphabetString[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 void
 RWopsSetUp(void *arg)
 {
-    int fileLen;
+    size_t fileLen;
     FILE *handle;
-    int writtenLen;
+    size_t writtenLen;
     int result;
 
     /* Clean up from previous runs (if any); ignore errors */
@@ -49,8 +49,8 @@ RWopsSetUp(void *arg)
 
     /* Write some known text into it */
     fileLen = SDL_strlen(RWopsHelloWorldTestString);
-    writtenLen = (int)fwrite(RWopsHelloWorldTestString, 1, fileLen, handle);
-    SDLTest_AssertCheck(fileLen == writtenLen, "Verify number of written bytes, expected %i, got %i", fileLen, writtenLen);
+    writtenLen = fwrite(RWopsHelloWorldTestString, 1, fileLen, handle);
+    SDLTest_AssertCheck(fileLen == writtenLen, "Verify number of written bytes, expected %i, got %i", (int) fileLen, (int) writtenLen);
     result = fclose(handle);
     SDLTest_AssertCheck(result == 0, "Verify result from fclose, expected 0, got %i", result);
 
@@ -61,8 +61,8 @@ RWopsSetUp(void *arg)
 
     /* Write alphabet text into it */
     fileLen = SDL_strlen(RWopsAlphabetString);
-    writtenLen = (int)fwrite(RWopsAlphabetString, 1, fileLen, handle);
-    SDLTest_AssertCheck(fileLen == writtenLen, "Verify number of written bytes, expected %i, got %i", fileLen, writtenLen);
+    writtenLen = fwrite(RWopsAlphabetString, 1, fileLen, handle);
+    SDLTest_AssertCheck(fileLen == writtenLen, "Verify number of written bytes, expected %i, got %i", (int) fileLen, (int) writtenLen);
     result = fclose(handle);
     SDLTest_AssertCheck(result == 0, "Verify result from fclose, expected 0, got %i", result);
 
@@ -111,10 +111,10 @@ _testGenericRWopsValidations(SDL_RWops *rw, int write)
    s = SDL_RWwrite(rw, RWopsHelloWorldTestString, sizeof(RWopsHelloWorldTestString)-1, 1);
    SDLTest_AssertPass("Call to SDL_RWwrite succeeded");
    if (write) {
-        SDLTest_AssertCheck(s == (size_t)1, "Verify result of writing one byte with SDL_RWwrite, expected 1, got %i", s);
+        SDLTest_AssertCheck(s == (size_t)1, "Verify result of writing one byte with SDL_RWwrite, expected 1, got %i", (int) s);
    }
    else {
-        SDLTest_AssertCheck(s == (size_t)0, "Verify result of writing with SDL_RWwrite, expected: 0, got %i", s);
+        SDLTest_AssertCheck(s == (size_t)0, "Verify result of writing with SDL_RWwrite, expected: 0, got %i", (int) s);
    }
 
    /* Test seek to random position */
@@ -133,8 +133,8 @@ _testGenericRWopsValidations(SDL_RWops *rw, int write)
    SDLTest_AssertCheck(
        s == (size_t)(sizeof(RWopsHelloWorldTestString)-1),
        "Verify result from SDL_RWread, expected %i, got %i",
-       sizeof(RWopsHelloWorldTestString)-1,
-       s);
+       (int) (sizeof(RWopsHelloWorldTestString)-1),
+       (int) s);
    SDLTest_AssertCheck(
        SDL_memcmp(buf, RWopsHelloWorldTestString, sizeof(RWopsHelloWorldTestString)-1 ) == 0,
        "Verify read bytes match expected string, expected '%s', got '%s'", RWopsHelloWorldTestString, buf);
@@ -144,25 +144,25 @@ _testGenericRWopsValidations(SDL_RWops *rw, int write)
    SDLTest_AssertPass("Call to SDL_RWseek(...,-4,RW_SEEK_CUR) succeeded");
    SDLTest_AssertCheck(
        i == (Sint64)(sizeof(RWopsHelloWorldTestString)-5),
-       "Verify seek to -4 with SDL_RWseek (RW_SEEK_CUR), expected %i, got %"SDL_PRIs64,
-       sizeof(RWopsHelloWorldTestString)-5,
-       i);
+       "Verify seek to -4 with SDL_RWseek (RW_SEEK_CUR), expected %i, got %i",
+       (int) (sizeof(RWopsHelloWorldTestString)-5),
+       (int) i);
 
    i = SDL_RWseek( rw, -1, RW_SEEK_END );
    SDLTest_AssertPass("Call to SDL_RWseek(...,-1,RW_SEEK_END) succeeded");
    SDLTest_AssertCheck(
        i == (Sint64)(sizeof(RWopsHelloWorldTestString)-2),
-       "Verify seek to -1 with SDL_RWseek (RW_SEEK_END), expected %i, got %"SDL_PRIs64,
-       sizeof(RWopsHelloWorldTestString)-2,
-       i);
+       "Verify seek to -1 with SDL_RWseek (RW_SEEK_END), expected %i, got %i",
+       (int) (sizeof(RWopsHelloWorldTestString)-2),
+       (int) i);
 
    /* Invalid whence seek */
    i = SDL_RWseek( rw, 0, 999 );
    SDLTest_AssertPass("Call to SDL_RWseek(...,0,invalid_whence) succeeded");
    SDLTest_AssertCheck(
        i == (Sint64)(-1),
-       "Verify seek with SDL_RWseek (invalid_whence); expected: -1, got %"SDL_PRIs64,
-       i);
+       "Verify seek with SDL_RWseek (invalid_whence); expected: -1, got %i",
+       (int) i);
 }
 
 /* !
@@ -559,8 +559,8 @@ rwops_testCompareRWFromMemWithRWFromFile(void)
      SDLTest_AssertCheck(result == 0, "Verify result value is 0; got: %d", result);
 
      /* Compare */
-     SDLTest_AssertCheck(rv_mem == rv_file, "Verify returned read blocks matches for mem and file reads; got: rv_mem=%d rv_file=%d", rv_mem, rv_file);
-     SDLTest_AssertCheck(sv_mem == sv_file, "Verify SEEK_END position matches for mem and file seeks; got: sv_mem=%"SDL_PRIu64" sv_file=%"SDL_PRIu64, sv_mem, sv_file);
+     SDLTest_AssertCheck(rv_mem == rv_file, "Verify returned read blocks matches for mem and file reads; got: rv_mem=%d rv_file=%d", (int) rv_mem, (int) rv_file);
+     SDLTest_AssertCheck(sv_mem == sv_file, "Verify SEEK_END position matches for mem and file seeks; got: sv_mem=%d sv_file=%d", (int) sv_mem, (int) sv_file);
      SDLTest_AssertCheck(buffer_mem[slen] == 0, "Verify mem buffer termination; expected: 0, got: %d", buffer_mem[slen]);
      SDLTest_AssertCheck(buffer_file[slen] == 0, "Verify file buffer termination; expected: 0, got: %d", buffer_file[slen]);
      SDLTest_AssertCheck(
@@ -648,27 +648,27 @@ rwops_testFileWriteReadEndian(void)
      /* Write test data */
      objectsWritten = SDL_WriteBE16(rw, BE16value);
      SDLTest_AssertPass("Call to SDL_WriteBE16()");
-     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
+     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
      objectsWritten = SDL_WriteBE32(rw, BE32value);
      SDLTest_AssertPass("Call to SDL_WriteBE32()");
-     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
+     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
      objectsWritten = SDL_WriteBE64(rw, BE64value);
      SDLTest_AssertPass("Call to SDL_WriteBE64()");
-     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
+     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
      objectsWritten = SDL_WriteLE16(rw, LE16value);
      SDLTest_AssertPass("Call to SDL_WriteLE16()");
-     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
+     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
      objectsWritten = SDL_WriteLE32(rw, LE32value);
      SDLTest_AssertPass("Call to SDL_WriteLE32()");
-     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
+     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
      objectsWritten = SDL_WriteLE64(rw, LE64value);
      SDLTest_AssertPass("Call to SDL_WriteLE64()");
-     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", objectsWritten);
+     SDLTest_AssertCheck(objectsWritten == 1, "Validate number of objects written, expected: 1, got: %i", (int) objectsWritten);
 
      /* Test seek to start */
      result = SDL_RWseek( rw, 0, RW_SEEK_SET );
      SDLTest_AssertPass("Call to SDL_RWseek succeeded");
-     SDLTest_AssertCheck(result == 0, "Verify result from position 0 with SDL_RWseek, expected 0, got %"SDL_PRIs64, result);
+     SDLTest_AssertCheck(result == 0, "Verify result from position 0 with SDL_RWseek, expected 0, got %i", (int) result);
 
      /* Read test data */
      BE16test = SDL_ReadBE16(rw);
diff --git a/test/testautomation_sdltest.c b/test/testautomation_sdltest.c
index 54cd6e2..979756a 100644
--- a/test/testautomation_sdltest.c
+++ b/test/testautomation_sdltest.c
@@ -2,17 +2,20 @@
  * SDL_test test suite
  */
 
+#include <limits.h>
 /* Visual Studio 2008 doesn't have stdint.h */
 #if defined(_MSC_VER) && _MSC_VER <= 1500
-#define UINT8_MAX   ~(Uint8)0
-#define UINT16_MAX  ~(Uint16)0
-#define UINT32_MAX  ~(Uint32)0
-#define UINT64_MAX  ~(Uint64)0
+#define UINT8_MAX   _UI8_MAX
+#define UINT16_MAX  _UI16_MAX
+#define UINT32_MAX  _UI32_MAX
+#define INT64_MIN    _I64_MIN
+#define INT64_MAX    _I64_MAX
+#define UINT64_MAX  _UI64_MAX
 #else
 #include <stdint.h>
 #endif
+
 #include <stdio.h>
-#include <limits.h>
 #include <float.h>
 #include <ctype.h>
 
@@ -31,7 +34,8 @@ int
 sdltest_generateRunSeed(void *arg)
 {
   char* result;
-  int i, l;
+  size_t i, l;
+  int j;
   
   for (i = 1; i <= 10; i += 3) {   
      result = SDLTest_GenerateRunSeed((const int)i);
@@ -39,14 +43,14 @@ sdltest_generateRunSeed(void *arg)
      SDLTest_AssertCheck(result != NULL, "Verify returned value is not NULL");
      if (result != NULL) {
        l = SDL_strlen(result);
-       SDLTest_AssertCheck(l == i, "Verify length of returned value is %d, got: %d", i, l);
+       SDLTest_AssertCheck(l == i, "Verify length of returned value is %d, got: %d", (int) i, (int) l);
        SDL_free(result);
      }
   }
 
   /* Negative cases */
-  for (i = -2; i <= 0; i++) {   
-     result = SDLTest_GenerateRunSeed((const int)i);
+  for (j = -2; j <= 0; j++) {
+     result = SDLTest_GenerateRunSeed((const int)j);
      SDLTest_AssertPass("Call to SDLTest_GenerateRunSeed()");
      SDLTest_AssertCheck(result == NULL, "Verify returned value is not NULL");
   }
@@ -988,38 +992,38 @@ sdltest_randomBoundaryNumberSint64(void *arg)
     "Validate result value for parameters (1,20,SDL_FALSE); expected: 0|21, got: %"SDL_PRIs64, sresult);
 
   /* RandomSintXBoundaryValue(LLONG_MIN, 99, SDL_FALSE) returns 100 */
-  sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(LLONG_MIN, 99, SDL_FALSE);
+  sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(INT64_MIN, 99, SDL_FALSE);
   SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
   SDLTest_AssertCheck(
     sresult == 100,
     "Validate result value for parameters (LLONG_MIN,99,SDL_FALSE); expected: 100, got: %"SDL_PRIs64, sresult);
 
   /* RandomSintXBoundaryValue(LLONG_MIN + 1, LLONG_MAX, SDL_FALSE) returns LLONG_MIN (no error) */
-  sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(LLONG_MIN + 1, LLONG_MAX, SDL_FALSE);
+  sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(INT64_MIN + 1, INT64_MAX, SDL_FALSE);
   SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
   SDLTest_AssertCheck(
-    sresult == LLONG_MIN,
-    "Validate result value for parameters (LLONG_MIN+1,LLONG_MAX,SDL_FALSE); expected: %"SDL_PRIs64", got: %"SDL_PRIs64, LLONG_MIN, sresult);
+    sresult == INT64_MIN,
+    "Validate result value for parameters (LLONG_MIN+1,LLONG_MAX,SDL_FALSE); expected: %"SDL_PRIs64", got: %"SDL_PRIs64, INT64_MIN, sresult);
   lastError = (char *)SDL_GetError();
   SDLTest_AssertPass("SDL_GetError()");
   SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
 
   /* RandomSintXBoundaryValue(LLONG_MIN, LLONG_MAX - 1, SDL_FALSE) returns LLONG_MAX (no error) */
-  sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(LLONG_MIN, LLONG_MAX - 1, SDL_FALSE);
+  sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(INT64_MIN, INT64_MAX - 1, SDL_FALSE);
   SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
   SDLTest_AssertCheck(
-    sresult == LLONG_MAX,
-    "Validate result value for parameters (LLONG_MIN,LLONG_MAX - 1,SDL_FALSE); expected: %"SDL_PRIs64", got: %"SDL_PRIs64, LLONG_MAX, sresult);
+    sresult == INT64_MAX,
+    "Validate result value for parameters (LLONG_MIN,LLONG_MAX - 1,SDL_FALSE); expected: %"SDL_PRIs64", got: %"SDL_PRIs64, INT64_MAX, sresult);
   lastError = (char *)SDL_GetError();
   SDLTest_AssertPass("SDL_GetError()");
   SDLTest_AssertCheck(lastError == NULL || lastError[0] == '\0', "Validate no error message was set");
 
   /* RandomSintXBoundaryValue(LLONG_MIN, LLONG_MAX, SDL_FALSE) returns 0 (sets error) */
-  sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(LLONG_MIN, LLONG_MAX, SDL_FALSE);
+  sresult = (Sint64)SDLTest_RandomSint64BoundaryValue(INT64_MIN, INT64_MAX, SDL_FALSE);
   SDLTest_AssertPass("Call to SDLTest_RandomSint64BoundaryValue");
   SDLTest_AssertCheck(
-    sresult == LLONG_MIN,
-    "Validate result value for parameters(LLONG_MIN,LLONG_MAX,SDL_FALSE); expected: %"SDL_PRIs64", got: %"SDL_PRIs64, LLONG_MIN, sresult);
+    sresult == INT64_MIN,
+    "Validate result value for parameters(LLONG_MIN,LLONG_MAX,SDL_FALSE); expected: %"SDL_PRIs64", got: %"SDL_PRIs64, INT64_MIN, sresult);
   lastError = (char *)SDL_GetError();
   SDLTest_AssertPass("SDL_GetError()");
   SDLTest_AssertCheck(lastError != NULL && SDL_strcmp(lastError, expectedError) == 0,
@@ -1116,16 +1120,16 @@ int
 sdltest_randomAsciiString(void *arg)
 {
   char* result;
-  int len;
+  size_t len;
   int nonAsciiCharacters;
-  int i;
+  size_t i;
 
   result = SDLTest_RandomAsciiString();
   SDLTest_AssertPass("Call to SDLTest_RandomAsciiString()");
   SDLTest_AssertCheck(result != NULL, "Validate that result is not NULL");
   if (result != NULL) {
      len = SDL_strlen(result);
-     SDLTest_AssertCheck(len >= 0 && len <= 255, "Validate that result length; expected: len=[1,255], got: %d", len);
+     SDLTest_AssertCheck(len >= 1 && len <= 255, "Validate that result length; expected: len=[1,255], got: %d", (int) len);
      nonAsciiCharacters = 0;
      for (i=0; i<len; i++) {
        if (iscntrl(result[i])) {
@@ -1152,18 +1156,18 @@ sdltest_randomAsciiStringWithMaximumLength(void *arg)
   const char* expectedError = "Parameter 'maxLength' is invalid";
   char* lastError;
   char* result;
-  int targetLen;
-  int len;
+  size_t targetLen;
+  size_t len;
   int nonAsciiCharacters;
-  int i;
+  size_t i;
 
   targetLen = 16 + SDLTest_RandomUint8();
-  result = SDLTest_RandomAsciiStringWithMaximumLength(targetLen);
+  result = SDLTest_RandomAsciiStringWithMaximumLength((int) targetLen);
   SDLTest_AssertPass("Call to SDLTest_RandomAsciiStringWithMaximumLength(%d)", targetLen);
   SDLTest_AssertCheck(result != NULL, "Validate that result is not NULL");
   if (result != NULL) {
      len = SDL_strlen(result);
-     SDLTest_AssertCheck(len >= 0 && len <= targetLen, "Validate that result length; expected: len=[1,%d], got: %d", targetLen, len);
+     SDLTest_AssertCheck(len >= 1 && len <= targetLen, "Validate that result length; expected: len=[1,%d], got: %d", (int) targetLen, (int) len);
      nonAsciiCharacters = 0;
      for (i=0; i<len; i++) {
        if (iscntrl(result[i])) {
@@ -1179,7 +1183,7 @@ sdltest_randomAsciiStringWithMaximumLength(void *arg)
 
   /* Negative test */
   targetLen = 0;
-  result = SDLTest_RandomAsciiStringWithMaximumLength(targetLen);
+  result = SDLTest_RandomAsciiStringWithMaximumLength((int) targetLen);
   SDLTest_AssertPass("Call to SDLTest_RandomAsciiStringWithMaximumLength(%d)", targetLen);
   SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
   lastError = (char *)SDL_GetError();
@@ -1205,19 +1209,19 @@ sdltest_randomAsciiStringOfSize(void *arg)
   const char* expectedError = "Parameter 'size' is invalid";
   char* lastError;
   char* result;
-  int targetLen;
-  int len;
+  size_t targetLen;
+  size_t len;
   int nonAsciiCharacters;
-  int i;
+  size_t i;
 
   /* Positive test */
   targetLen = 16 + SDLTest_RandomUint8();
-  result = SDLTest_RandomAsciiStringOfSize(targetLen);
+  result = SDLTest_RandomAsciiStringOfSize((int) targetLen);
   SDLTest_AssertPass("Call to SDLTest_RandomAsciiStringOfSize(%d)", targetLen);
   SDLTest_AssertCheck(result != NULL, "Validate that result is not NULL");
   if (result != NULL) {
      len = SDL_strlen(result);
-     SDLTest_AssertCheck(len == targetLen, "Validate that result length; expected: len=%d, got: %d", targetLen, len);
+     SDLTest_AssertCheck(len == targetLen, "Validate that result length; expected: len=%d, got: %d", (int) targetLen, (int) len);
      nonAsciiCharacters = 0;
      for (i=0; i<len; i++) {
        if (iscntrl(result[i])) {
@@ -1233,7 +1237,7 @@ sdltest_randomAsciiStringOfSize(void *arg)
 
   /* Negative test */
   targetLen = 0;
-  result = SDLTest_RandomAsciiStringOfSize(targetLen);
+  result = SDLTest_RandomAsciiStringOfSize((int) targetLen);
   SDLTest_AssertPass("Call to SDLTest_RandomAsciiStringOfSize(%d)", targetLen);
   SDLTest_AssertCheck(result == NULL, "Validate that result is NULL");
   lastError = (char *)SDL_GetError();
diff --git a/test/testautomation_stdlib.c b/test/testautomation_stdlib.c
index b541995..e741d54 100644
--- a/test/testautomation_stdlib.c
+++ b/test/testautomation_stdlib.c
@@ -25,13 +25,13 @@ stdlib_strlcpy(void *arg)
   expected = "foo";
   SDLTest_AssertPass("Call to SDL_strlcpy(\"foo\")");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
-  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", SDL_strlen(text), result);
+  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), (int) result);
 
   result = SDL_strlcpy(text, "foo", 2);
   expected = "f";
   SDLTest_AssertPass("Call to SDL_strlcpy(\"foo\") with buffer size 2");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
-  SDLTest_AssertCheck(result == 3, "Check result value, expected: 3, got: %d", result);
+  SDLTest_AssertCheck(result == 3, "Check result value, expected: 3, got: %d", (int) result);
 
   return TEST_COMPLETED;
 }
@@ -51,7 +51,7 @@ stdlib_snprintf(void *arg)
   expected = "foo";
   SDLTest_AssertPass("Call to SDL_snprintf(\"%%s\", \"foo\")");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
-  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", SDL_strlen(text), result);
+  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
 
   result = SDL_snprintf(text, 2, "%s", "foo");
   expected = "f";
@@ -66,49 +66,49 @@ stdlib_snprintf(void *arg)
   expected = "1.000000";
   SDLTest_AssertPass("Call to SDL_snprintf(\"%%f\", 1.0)");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
-  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", SDL_strlen(text), result);
+  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
 
   result = SDL_snprintf(text, sizeof(text), "%.f", 1.0);
   expected = "1";
   SDLTest_AssertPass("Call to SDL_snprintf(\"%%.f\", 1.0)");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
-  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", SDL_strlen(text), result);
+  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
 
   result = SDL_snprintf(text, sizeof(text), "%#.f", 1.0);
   expected = "1.";
   SDLTest_AssertPass("Call to SDL_snprintf(\"%%#.f\", 1.0)");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
-  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", SDL_strlen(text), result);
+  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
 
   result = SDL_snprintf(text, sizeof(text), "%f", 1.0 + 1.0 / 3.0);
   expected = "1.333333";
   SDLTest_AssertPass("Call to SDL_snprintf(\"%%f\", 1.0 + 1.0 / 3.0)");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
-  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", SDL_strlen(text), result);
+  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
 
   result = SDL_snprintf(text, sizeof(text), "%+f", 1.0 + 1.0 / 3.0);
   expected = "+1.333333";
   SDLTest_AssertPass("Call to SDL_snprintf(\"%%+f\", 1.0 + 1.0 / 3.0)");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
-  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", SDL_strlen(text), result);
+  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
 
   result = SDL_snprintf(text, sizeof(text), "%.2f", 1.0 + 1.0 / 3.0);
   expected = "1.33";
   SDLTest_AssertPass("Call to SDL_snprintf(\"%%.2f\", 1.0 + 1.0 / 3.0)");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
-  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", SDL_strlen(text), result);
+  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
 
   result = SDL_snprintf(text, sizeof(text), "%6.2f", 1.0 + 1.0 / 3.0);
   expected = "  1.33";
   SDLTest_AssertPass("Call to SDL_snprintf(\"%%6.2f\", 1.0 + 1.0 / 3.0)");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: '%s', got: '%s'", expected, text);
-  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", SDL_strlen(text), result);
+  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
 
   result = SDL_snprintf(text, sizeof(text), "%06.2f", 1.0 + 1.0 / 3.0);
   expected = "001.33";
   SDLTest_AssertPass("Call to SDL_snprintf(\"%%06.2f\", 1.0 + 1.0 / 3.0)");
   SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: '%s', got: '%s'", expected, text);
-  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", SDL_strlen(text), result);
+  SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int) SDL_strlen(text), result);
 
   result = SDL_snprintf(text, 5, "%06.2f", 1.0 + 1.0 / 3.0);
   expected = "001.";
@@ -146,7 +146,7 @@ stdlib_getsetenv(void *arg)
     text = SDL_getenv(name);
     SDLTest_AssertPass("Call to SDL_getenv('%s')", name);
     if (text != NULL) {
-      SDLTest_Log("Expected: NULL, Got: '%s' (%i)", text, SDL_strlen(text));
+      SDLTest_Log("Expected: NULL, Got: '%s' (%i)", text, (int) SDL_strlen(text));
     }
   } while (text != NULL);
    
diff --git a/test/testautomation_timer.c b/test/testautomation_timer.c
index 6d73856..a42eb37 100644
--- a/test/testautomation_timer.c
+++ b/test/testautomation_timer.c
@@ -104,7 +104,7 @@ timer_delayAndGetTicks(void *arg)
 }
 
 /* Test callback */
-Uint32 _timerTestCallback(Uint32 interval, void *param)
+Uint32 SDLCALL _timerTestCallback(Uint32 interval, void *param)
 {
    _timerCallbackCalled = 1;
 
diff --git a/test/testbounds.c b/test/testbounds.c
index b410be9..bc46cb8 100644
--- a/test/testbounds.c
+++ b/test/testbounds.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2014 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testcustomcursor.c b/test/testcustomcursor.c
index 88b5c32..59c6409 100644
--- a/test/testcustomcursor.c
+++ b/test/testcustomcursor.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testdisplayinfo.c b/test/testdisplayinfo.c
index f06722e..51c19b0 100644
--- a/test/testdisplayinfo.c
+++ b/test/testdisplayinfo.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testdraw2.c b/test/testdraw2.c
index 77bd8c1..1472a38 100644
--- a/test/testdraw2.c
+++ b/test/testdraw2.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testdrawchessboard.c b/test/testdrawchessboard.c
index af929e9..cef8621 100644
--- a/test/testdrawchessboard.c
+++ b/test/testdrawchessboard.c
@@ -1,5 +1,5 @@
 /*
-   Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+   Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
    This software is provided 'as-is', without any express or implied
    warranty.  In no event will the authors be held liable for any damages
@@ -25,6 +25,7 @@
 
 SDL_Window *window;
 SDL_Renderer *renderer;
+SDL_Surface *surface;
 int done;
 
 void
@@ -59,7 +60,20 @@ loop()
 {
     SDL_Event e;
     while (SDL_PollEvent(&e)) {
-        if (e.type == SDL_QUIT) {
+       
+       /* Re-create when window has been resized */
+       if ((e.type == SDL_WINDOWEVENT) && (e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)) {
+
+          SDL_DestroyRenderer(renderer);
+
+          surface = SDL_GetWindowSurface(window);
+          renderer = SDL_CreateSoftwareRenderer(surface);
+          /* Clear the rendering surface with the specified color */
+          SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
+          SDL_RenderClear(renderer);
+       }
+
+       if (e.type == SDL_QUIT) {
             done = 1;
 #ifdef __EMSCRIPTEN__
             emscripten_cancel_main_loop();
@@ -86,8 +100,6 @@ loop()
 int
 main(int argc, char *argv[])
 {
-    SDL_Surface *surface;
-
     /* Enable standard application logging */
     SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
 
@@ -100,7 +112,7 @@ main(int argc, char *argv[])
 
 
     /* Create window and renderer for given surface */
-    window = SDL_CreateWindow("Chess Board", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
+    window = SDL_CreateWindow("Chess Board", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_RESIZABLE);
     if(!window)
     {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Window creation fail : %s\n",SDL_GetError());
diff --git a/test/testdropfile.c b/test/testdropfile.c
index b729b2f..b3cb17d 100644
--- a/test/testdropfile.c
+++ b/test/testdropfile.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testerror.c b/test/testerror.c
index b5fa3fb..468f8a7 100644
--- a/test/testerror.c
+++ b/test/testerror.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -14,7 +14,6 @@
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <signal.h>
 
 #include "SDL.h"
 
diff --git a/test/testfile.c b/test/testfile.c
index b45795f..23215ea 100644
--- a/test/testfile.c
+++ b/test/testfile.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testfilesystem.c b/test/testfilesystem.c
index 61a6d5a..e8a3b3c 100644
--- a/test/testfilesystem.c
+++ b/test/testfilesystem.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -46,6 +46,15 @@ main(int argc, char *argv[])
     SDL_Log("pref path: '%s'\n", pref_path); 
     SDL_free(pref_path);
 
+    pref_path = SDL_GetPrefPath(NULL, "testfilesystem");
+    if(pref_path == NULL){
+      SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't find pref path without organization: %s\n",
+                   SDL_GetError());
+      return 1;
+    }
+    SDL_Log("pref path: '%s'\n", pref_path); 
+    SDL_free(pref_path);
+
     SDL_Quit();
     return 0;
 }
diff --git a/test/testgamecontroller.c b/test/testgamecontroller.c
index 38d2f77..f586bfe 100644
--- a/test/testgamecontroller.c
+++ b/test/testgamecontroller.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -53,12 +53,12 @@ static const struct { int x; int y; } button_positions[] = {
 
 /* This is indexed by SDL_GameControllerAxis. */
 static const struct { int x; int y; double angle; } axis_positions[] = {
-    {75,  154, 0.0},  /* LEFTX */
-    {75,  154, 90.0},  /* LEFTY */
-    {305, 230, 0.0},  /* RIGHTX */
-    {305, 230, 90.0},  /* RIGHTY */
-    {91, 0, 90.0},     /* TRIGGERLEFT */
-    {375, 0, 90.0},    /* TRIGGERRIGHT */
+    {74,  153, 270.0},  /* LEFTX */
+    {74,  153, 0.0},  /* LEFTY */
+    {306, 231, 270.0},  /* RIGHTX */
+    {306, 231, 0.0},  /* RIGHTY */
+    {91, -20, 0.0},     /* TRIGGERLEFT */
+    {375, -20, 0.0},    /* TRIGGERRIGHT */
 };
 
 SDL_Renderer *screen = NULL;
@@ -80,10 +80,6 @@ LoadTexture(SDL_Renderer *renderer, const char *file, SDL_bool transparent)
         if (transparent) {
             if (temp->format->BytesPerPixel == 1) {
                 SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *)temp->pixels);
-            } else {
-                SDL_assert(!temp->format->palette);
-                SDL_assert(temp->format->BitsPerPixel == 24);
-                SDL_SetColorKey(temp, SDL_TRUE, (*(Uint32 *)temp->pixels) & 0x00FFFFFF);
             }
         }
 
@@ -112,6 +108,13 @@ loop(void *arg)
 
     while (SDL_PollEvent(&event)) {
         switch (event.type) {
+        case SDL_CONTROLLERAXISMOTION:
+            SDL_Log("Controller axis %s changed to %d\n", SDL_GameControllerGetStringForAxis((SDL_GameControllerAxis)event.caxis.axis), event.caxis.value);
+            break;
+        case SDL_CONTROLLERBUTTONDOWN:
+        case SDL_CONTROLLERBUTTONUP:
+            SDL_Log("Controller button %s %s\n", SDL_GameControllerGetStringForButton((SDL_GameControllerButton)event.cbutton.button), event.cbutton.state ? "pressed" : "released");
+            break;
         case SDL_KEYDOWN:
             if (event.key.keysym.sym != SDLK_ESCAPE) {
                 break;
@@ -259,6 +262,19 @@ main(int argc, char *argv[])
     
     SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt");
 
+    /* Print information about the mappings */
+    if (!argv[1]) {
+        SDL_Log("Supported mappings:\n");
+        for (i = 0; i < SDL_GameControllerNumMappings(); ++i) {
+            char *mapping = SDL_GameControllerMappingForIndex(i);
+            if (mapping) {
+                SDL_Log("\t%s\n", mapping);
+                SDL_free(mapping);
+            }
+        }
+        SDL_Log("\n");
+    }
+
     /* Print information about the controller */
     for (i = 0; i < SDL_NumJoysticks(); ++i) {
         const char *name;
@@ -276,7 +292,9 @@ main(int argc, char *argv[])
             name = SDL_JoystickNameForIndex(i);
             description = "Joystick";
         }
-        SDL_Log("%s %d: %s (guid %s)\n", description, i, name ? name : "Unknown", guid);
+        SDL_Log("%s %d: %s (guid %s, VID 0x%.4x, PID 0x%.4x)\n",
+            description, i, name ? name : "Unknown", guid,
+            SDL_JoystickGetDeviceVendor(i), SDL_JoystickGetDeviceProduct(i));
     }
     SDL_Log("There are %d game controller(s) attached (%d joystick(s))\n", nController, SDL_NumJoysticks());
 
@@ -348,3 +366,5 @@ main(int argc, char *argv[])
 }
 
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/test/testgesture.c b/test/testgesture.c
index a289ce1..f7db94f 100644
--- a/test/testgesture.c
+++ b/test/testgesture.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -25,7 +25,6 @@
 #define WIDTH 640
 #define HEIGHT 480
 #define BPP 4
-#define DEPTH 32
 
 /* MUST BE A POWER OF 2! */
 #define EVENT_BUF_SIZE 256
diff --git a/test/testgl2.c b/test/testgl2.c
index 74147f9..114c141 100644
--- a/test/testgl2.c
+++ b/test/testgl2.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -56,7 +56,7 @@ static int LoadContext(GL_Context * data)
     do { \
         data->func = SDL_GL_GetProcAddress(#func); \
         if ( ! data->func ) { \
-            return SDL_SetError("Couldn't load GL function %s: %s\n", #func, SDL_GetError()); \
+            return SDL_SetError("Couldn't load GL function %s: %s", #func, SDL_GetError()); \
         } \
     } while ( 0 );
 #endif /* __SDL_NOGETPROCADDR__ */
diff --git a/test/testgles.c b/test/testgles.c
index 5be48ac..cb1da14 100644
--- a/test/testgles.c
+++ b/test/testgles.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testgles2.c b/test/testgles2.c
index 45b3d79..282e0b6 100644
--- a/test/testgles2.c
+++ b/test/testgles2.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (r) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,7 +20,8 @@
 
 #include "SDL_test_common.h"
 
-#if defined(__IPHONEOS__) || defined(__ANDROID__) || defined(__EMSCRIPTEN__) || defined(__NACL__)
+#if defined(__IPHONEOS__) || defined(__ANDROID__) || defined(__EMSCRIPTEN__) || defined(__NACL__) \
+    || defined(__WINDOWS__) || defined(__LINUX__)
 #define HAVE_OPENGLES2
 #endif
 
@@ -58,7 +59,7 @@ static int LoadContext(GLES2_Context * data)
     do { \
         data->func = SDL_GL_GetProcAddress(#func); \
         if ( ! data->func ) { \
-            return SDL_SetError("Couldn't load GLES2 function %s: %s\n", #func, SDL_GetError()); \
+            return SDL_SetError("Couldn't load GLES2 function %s: %s", #func, SDL_GetError()); \
         } \
     } while ( 0 );
 #endif /* __SDL_NOGETPROCADDR__ */
diff --git a/test/testhittesting.c b/test/testhittesting.c
index 5e32be4..c5223a9 100644
--- a/test/testhittesting.c
+++ b/test/testhittesting.c
@@ -14,7 +14,7 @@ const SDL_Rect drag_areas[] = {
 static const SDL_Rect *areas = drag_areas;
 static int numareas = SDL_arraysize(drag_areas);
 
-static SDL_HitTestResult
+static SDL_HitTestResult SDLCALL
 hitTest(SDL_Window *window, const SDL_Point *pt, void *data)
 {
     int i;
diff --git a/test/testhotplug.c b/test/testhotplug.c
index 1fa9637..765ce26 100644
--- a/test/testhotplug.c
+++ b/test/testhotplug.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testiconv.c b/test/testiconv.c
index 79efec8..ff3b28c 100644
--- a/test/testiconv.c
+++ b/test/testiconv.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testime.c b/test/testime.c
index 39a40f8..32f80cd 100644
--- a/test/testime.c
+++ b/test/testime.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -99,7 +99,7 @@ static Uint8 validate_hex(const char *cp, size_t len, Uint32 *np)
     return 1;
 }
 
-static void unifont_init(const char *fontname)
+static int unifont_init(const char *fontname)
 {
     Uint8 hexBuffer[65];
     Uint32 numGlyphs = 0;
@@ -114,7 +114,7 @@ static void unifont_init(const char *fontname)
     if (unifontGlyph == NULL)
     {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to allocate %d KiB for glyph data.\n", (int)(unifontGlyphSize + 1023) / 1024);
-        exit(-1);
+        return -1;
     }
     SDL_memset(unifontGlyph, 0, unifontGlyphSize);
 
@@ -123,7 +123,7 @@ static void unifont_init(const char *fontname)
     if (unifontTexture == NULL)
     {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to allocate %d KiB for texture pointer data.\n", (int)(unifontTextureSize + 1023) / 1024);
-        exit(-1);
+        return -1;
     }
     SDL_memset(unifontTexture, 0, unifontTextureSize);
 
@@ -131,7 +131,7 @@ static void unifont_init(const char *fontname)
     if (hexFile == NULL)
     {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to open font file: %s\n", fontname);
-        exit(-1);
+        return -1;
     }
 
     /* Read all the glyph data into memory to make it accessible later when textures are created. */
@@ -146,8 +146,8 @@ static void unifont_init(const char *fontname)
             break; /* EOF */
         if ((numGlyphs == 0 && bytesRead == 0) || (numGlyphs > 0 && bytesRead < 9))
         {
-            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unfiont: Unexpected end of hex file.\n");
-            exit(-1);
+            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Unexpected end of hex file.\n");
+            return -1;
         }
 
         /* Looking for the colon that separates the codepoint and glyph data at position 2, 4, 6 and 8. */
@@ -162,13 +162,13 @@ static void unifont_init(const char *fontname)
         else
         {
             SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Could not find codepoint and glyph data separator symbol in hex file on line %d.\n", lineNumber);
-            exit(-1);
+            return -1;
         }
 
         if (!validate_hex((const char *)hexBuffer, codepointHexSize, &codepoint))
         {
             SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Malformed hexadecimal number in hex file on line %d.\n", lineNumber);
-            exit(-1);
+            return -1;
         }
         if (codepoint > UNIFONT_MAX_CODEPOINT)
             SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "unifont: Codepoint on line %d exceeded limit of 0x%x.\n", lineNumber, UNIFONT_MAX_CODEPOINT);
@@ -181,7 +181,7 @@ static void unifont_init(const char *fontname)
         if (bytesRead < (33 - bytesOverread))
         {
             SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Unexpected end of hex file.\n");
-            exit(-1);
+            return -1;
         }
         if (hexBuffer[32] == '\n')
             glyphWidth = 8;
@@ -192,14 +192,14 @@ static void unifont_init(const char *fontname)
             if (bytesRead < 32)
             {
                 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Unexpected end of hex file.\n");
-                exit(-1);
+                return -1;
             }
         }
 
         if (!validate_hex((const char *)hexBuffer, glyphWidth * 4, NULL))
         {
             SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Malformed hexadecimal glyph data in hex file on line %d.\n", lineNumber);
-            exit(-1);
+            return -1;
         }
 
         if (codepoint <= UNIFONT_MAX_CODEPOINT)
@@ -221,6 +221,7 @@ static void unifont_init(const char *fontname)
 
     SDL_RWclose(hexFile);
     SDL_Log("unifont: Loaded %u glyphs.\n", numGlyphs);
+    return 0;
 }
 
 static void unifont_make_rgba(Uint8 *src, Uint8 *dst, Uint8 width)
@@ -259,7 +260,7 @@ static void unifont_make_rgba(Uint8 *src, Uint8 *dst, Uint8 width)
     }
 }
 
-static void unifont_load_texture(Uint32 textureID)
+static int unifont_load_texture(Uint32 textureID)
 {
     int i;
     Uint8 * textureRGBA;
@@ -267,14 +268,14 @@ static void unifont_load_texture(Uint32 textureID)
     if (textureID >= UNIFONT_NUM_TEXTURES)
     {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Tried to load out of range texture %u.\n", textureID);
-        exit(-1);
+        return -1;
     }
 
     textureRGBA = (Uint8 *)SDL_malloc(UNIFONT_TEXTURE_SIZE);
     if (textureRGBA == NULL)
     {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to allocate %d MiB for a texture.\n", UNIFONT_TEXTURE_SIZE / 1024 / 1024);
-        exit(-1);
+        return -1;
     }
     SDL_memset(textureRGBA, 0, UNIFONT_TEXTURE_SIZE);
 
@@ -301,7 +302,7 @@ static void unifont_load_texture(Uint32 textureID)
         if (tex == NULL)
         {
             SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to create texture %u for renderer %d.\n", textureID, i);
-            exit(-1);
+            return -1;
         }
         unifontTexture[UNIFONT_NUM_TEXTURES * i + textureID] = tex;
         SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
@@ -313,6 +314,7 @@ static void unifont_load_texture(Uint32 textureID)
 
     SDL_free(textureRGBA);
     unifontTextureLoaded[textureID] = 1;
+    return 0;
 }
 
 static Sint32 unifont_draw_glyph(Uint32 codepoint, int rendererID, SDL_Rect *dstrect)
@@ -321,10 +323,14 @@ static Sint32 unifont_draw_glyph(Uint32 codepoint, int rendererID, SDL_Rect *dst
     const Uint32 textureID = codepoint / UNIFONT_GLYPHS_IN_TEXTURE;
     SDL_Rect srcrect;
     srcrect.w = srcrect.h = 16;
-    if (codepoint > UNIFONT_MAX_CODEPOINT)
+    if (codepoint > UNIFONT_MAX_CODEPOINT) {
         return 0;
-    if (!unifontTextureLoaded[textureID])
-        unifont_load_texture(textureID);
+    }
+    if (!unifontTextureLoaded[textureID]) {
+        if (unifont_load_texture(textureID) < 0) {
+            return 0;
+        }
+    }
     texture = unifontTexture[UNIFONT_NUM_TEXTURES * rendererID + textureID];
     if (texture != NULL)
     {
@@ -430,12 +436,10 @@ Uint32 utf8_decode(char *p, size_t len)
 void usage()
 {
     SDL_Log("usage: testime [--font fontfile]\n");
-    exit(0);
 }
 
 void InitInput()
 {
-
     /* Prepare a rect for text input */
     textRect.x = textRect.y = 100;
     textRect.w = DEFAULT_WINDOW_WIDTH - 2 * textRect.x;
@@ -459,7 +463,8 @@ void CleanupVideo()
 #endif
 }
 
-void _Redraw(int rendererID) {
+void _Redraw(int rendererID)
+{
     SDL_Renderer * renderer = state->renderers[rendererID];
     SDL_Rect drawnTextRect, cursorRect, underlineRect;
     drawnTextRect = textRect;
@@ -607,7 +612,8 @@ void _Redraw(int rendererID) {
     SDL_SetTextInputRect(&markedRect);
 }
 
-void Redraw() {
+void Redraw()
+{
     int i;
     for (i = 0; i < state->num_windows; ++i) {
         SDL_Renderer *renderer = state->renderers[i];
@@ -623,7 +629,8 @@ void Redraw() {
     }
 }
 
-int main(int argc, char *argv[]) {
+int main(int argc, char *argv[])
+{
     int i, done;
     SDL_Event event;
     const char *fontname = DEFAULT_FONT;
@@ -673,14 +680,15 @@ int main(int argc, char *argv[]) {
     if (! font)
     {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to find font: %s\n", TTF_GetError());
-        exit(-1);
+        return -1;
     }
 #else
-    unifont_init(fontname);
+    if (unifont_init(fontname) < 0) {
+        return -1;
+    }
 #endif
 
     SDL_Log("Using font: %s\n", fontname);
-    atexit(SDL_Quit);
 
     InitInput();
     /* Create the windows and initialize the renderers */
diff --git a/test/testintersections.c b/test/testintersections.c
index 82aae63..dcf1bc1 100644
--- a/test/testintersections.c
+++ b/test/testintersections.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testjoystick.c b/test/testjoystick.c
index bed2721..50e5cc9 100644
--- a/test/testjoystick.c
+++ b/test/testjoystick.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -239,7 +239,7 @@ WatchJoystick(SDL_Joystick * joystick)
 int
 main(int argc, char *argv[])
 {
-    const char *name;
+    const char *name, *type;
     int i;
     SDL_Joystick *joystick;
 
@@ -268,12 +268,46 @@ main(int argc, char *argv[])
             SDL_assert(SDL_JoystickFromInstanceID(SDL_JoystickInstanceID(joystick)) == joystick);
             SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick),
                                       guid, sizeof (guid));
+            switch (SDL_JoystickGetType(joystick)) {
+            case SDL_JOYSTICK_TYPE_GAMECONTROLLER:
+                type = "Game Controller";
+                break;
+            case SDL_JOYSTICK_TYPE_WHEEL:
+                type = "Wheel";
+                break;
+            case SDL_JOYSTICK_TYPE_ARCADE_STICK:
+                type = "Arcade Stick";
+                break;
+            case SDL_JOYSTICK_TYPE_FLIGHT_STICK:
+                type = "Flight Stick";
+                break;
+            case SDL_JOYSTICK_TYPE_DANCE_PAD:
+                type = "Dance Pad";
+                break;
+            case SDL_JOYSTICK_TYPE_GUITAR:
+                type = "Guitar";
+                break;
+            case SDL_JOYSTICK_TYPE_DRUM_KIT:
+                type = "Drum Kit";
+                break;
+            case SDL_JOYSTICK_TYPE_ARCADE_PAD:
+                type = "Arcade Pad";
+                break;
+            case SDL_JOYSTICK_TYPE_THROTTLE:
+                type = "Throttle";
+                break;
+            default:
+                type = "Unknown";
+                break;
+            }
+            SDL_Log("       type: %s\n", type);
             SDL_Log("       axes: %d\n", SDL_JoystickNumAxes(joystick));
             SDL_Log("      balls: %d\n", SDL_JoystickNumBalls(joystick));
             SDL_Log("       hats: %d\n", SDL_JoystickNumHats(joystick));
             SDL_Log("    buttons: %d\n", SDL_JoystickNumButtons(joystick));
             SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick));
             SDL_Log("       guid: %s\n", guid);
+            SDL_Log("    VID/PID: 0x%.4x/0x%.4x\n", SDL_JoystickGetVendor(joystick), SDL_JoystickGetProduct(joystick));
             SDL_JoystickClose(joystick);
         }
     }
@@ -320,6 +354,7 @@ main(int argc, char *argv[])
                     || (event.type == SDL_MOUSEBUTTONDOWN)) {
                     keepGoing = SDL_FALSE;
                 } else if (event.type == SDL_JOYDEVICEADDED) {
+                    device = event.jdevice.which;
                     joystick = SDL_JoystickOpen(device);
                     if (joystick != NULL) {
                         SDL_assert(SDL_JoystickFromInstanceID(SDL_JoystickInstanceID(joystick)) == joystick);
@@ -344,3 +379,5 @@ main(int argc, char *argv[])
 }
 
 #endif
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/test/testkeys.c b/test/testkeys.c
index aea496c..33649d2 100644
--- a/test/testkeys.c
+++ b/test/testkeys.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testloadso.c b/test/testloadso.c
index fb87fbe..2dce11d 100644
--- a/test/testloadso.c
+++ b/test/testloadso.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testlock.c b/test/testlock.c
index 113ba0d..e79fcda 100644
--- a/test/testlock.c
+++ b/test/testlock.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testmessage.c b/test/testmessage.c
index 91968c3..07d0b03 100644
--- a/test/testmessage.c
+++ b/test/testmessage.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -14,7 +14,6 @@
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <signal.h>
 
 #include "SDL.h"
 
@@ -26,7 +25,7 @@ quit(int rc)
     exit(rc);
 }
 
-static int
+static int SDLCALL
 button_messagebox(void *eventNumber)
 {
     const SDL_MessageBoxButtonData buttons[] = {
@@ -47,12 +46,13 @@ button_messagebox(void *eventNumber)
         "Custom MessageBox",
         "This is a custom messagebox",
         2,
-        buttons,
+        NULL,/* buttons */
         NULL /* Default color scheme */
     };
 
     int button = -1;
     int success = 0;
+    data.buttons = buttons;
     if (eventNumber) {
         data.message = "This is a custom messagebox from a background thread.";
     }
diff --git a/test/testmultiaudio.c b/test/testmultiaudio.c
index 1b07ba9..4bae385 100644
--- a/test/testmultiaudio.c
+++ b/test/testmultiaudio.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testnative.c b/test/testnative.c
index 049c4c8..83bc495 100644
--- a/test/testnative.c
+++ b/test/testnative.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testnative.h b/test/testnative.h
index ed2bf7e..b2ee5fa 100644
--- a/test/testnative.h
+++ b/test/testnative.h
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testnativew32.c b/test/testnativew32.c
index aaea267..7a27b12 100644
--- a/test/testnativew32.c
+++ b/test/testnativew32.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testnativex11.c b/test/testnativex11.c
index 69fa37b..8908d22 100644
--- a/test/testnativex11.c
+++ b/test/testnativex11.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testoverlay2.c b/test/testoverlay2.c
index 453f0f4..2145c4d 100644
--- a/test/testoverlay2.c
+++ b/test/testoverlay2.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -33,110 +33,110 @@
 #define MOOSEFRAMES_COUNT 10
 
 SDL_Color MooseColors[84] = {
-    {49, 49, 49}
-    , {66, 24, 0}
-    , {66, 33, 0}
-    , {66, 66, 66}
+    {49, 49, 49, SDL_ALPHA_OPAQUE}
+    , {66, 24, 0, SDL_ALPHA_OPAQUE}
+    , {66, 33, 0, SDL_ALPHA_OPAQUE}
+    , {66, 66, 66, SDL_ALPHA_OPAQUE}
     ,
-    {66, 115, 49}
-    , {74, 33, 0}
-    , {74, 41, 16}
-    , {82, 33, 8}
+    {66, 115, 49, SDL_ALPHA_OPAQUE}
+    , {74, 33, 0, SDL_ALPHA_OPAQUE}
+    , {74, 41, 16, SDL_ALPHA_OPAQUE}
+    , {82, 33, 8, SDL_ALPHA_OPAQUE}
     ,
-    {82, 41, 8}
-    , {82, 49, 16}
-    , {82, 82, 82}
-    , {90, 41, 8}
+    {82, 41, 8, SDL_ALPHA_OPAQUE}
+    , {82, 49, 16, SDL_ALPHA_OPAQUE}
+    , {82, 82, 82, SDL_ALPHA_OPAQUE}
+    , {90, 41, 8, SDL_ALPHA_OPAQUE}
     ,
-    {90, 41, 16}
-    , {90, 57, 24}
-    , {99, 49, 16}
-    , {99, 66, 24}
+    {90, 41, 16, SDL_ALPHA_OPAQUE}
+    , {90, 57, 24, SDL_ALPHA_OPAQUE}
+    , {99, 49, 16, SDL_ALPHA_OPAQUE}
+    , {99, 66, 24, SDL_ALPHA_OPAQUE}
     ,
-    {99, 66, 33}
-    , {99, 74, 33}
-    , {107, 57, 24}
-    , {107, 82, 41}
+    {99, 66, 33, SDL_ALPHA_OPAQUE}
+    , {99, 74, 33, SDL_ALPHA_OPAQUE}
+    , {107, 57, 24, SDL_ALPHA_OPAQUE}
+    , {107, 82, 41, SDL_ALPHA_OPAQUE}
     ,
-    {115, 57, 33}
-    , {115, 66, 33}
-    , {115, 66, 41}
-    , {115, 74, 0}
+    {115, 57, 33, SDL_ALPHA_OPAQUE}
+    , {115, 66, 33, SDL_ALPHA_OPAQUE}
+    , {115, 66, 41, SDL_ALPHA_OPAQUE}
+    , {115, 74, 0, SDL_ALPHA_OPAQUE}
     ,
-    {115, 90, 49}
-    , {115, 115, 115}
-    , {123, 82, 0}
-    , {123, 99, 57}
+    {115, 90, 49, SDL_ALPHA_OPAQUE}
+    , {115, 115, 115, SDL_ALPHA_OPAQUE}
+    , {123, 82, 0, SDL_ALPHA_OPAQUE}
+    , {123, 99, 57, SDL_ALPHA_OPAQUE}
     ,
-    {132, 66, 41}
-    , {132, 74, 41}
-    , {132, 90, 8}
-    , {132, 99, 33}
+    {132, 66, 41, SDL_ALPHA_OPAQUE}
+    , {132, 74, 41, SDL_ALPHA_OPAQUE}
+    , {132, 90, 8, SDL_ALPHA_OPAQUE}
+    , {132, 99, 33, SDL_ALPHA_OPAQUE}
     ,
-    {132, 99, 66}
-    , {132, 107, 66}
-    , {140, 74, 49}
-    , {140, 99, 16}
+    {132, 99, 66, SDL_ALPHA_OPAQUE}
+    , {132, 107, 66, SDL_ALPHA_OPAQUE}
+    , {140, 74, 49, SDL_ALPHA_OPAQUE}
+    , {140, 99, 16, SDL_ALPHA_OPAQUE}
     ,
-    {140, 107, 74}
-    , {140, 115, 74}
-    , {148, 107, 24}
-    , {148, 115, 82}
+    {140, 107, 74, SDL_ALPHA_OPAQUE}
+    , {140, 115, 74, SDL_ALPHA_OPAQUE}
+    , {148, 107, 24, SDL_ALPHA_OPAQUE}
+    , {148, 115, 82, SDL_ALPHA_OPAQUE}
     ,
-    {148, 123, 74}
-    , {148, 123, 90}
-    , {156, 115, 33}
-    , {156, 115, 90}
+    {148, 123, 74, SDL_ALPHA_OPAQUE}
+    , {148, 123, 90, SDL_ALPHA_OPAQUE}
+    , {156, 115, 33, SDL_ALPHA_OPAQUE}
+    , {156, 115, 90, SDL_ALPHA_OPAQUE}
     ,
-    {156, 123, 82}
-    , {156, 132, 82}
-    , {156, 132, 99}
-    , {156, 156, 156}
+    {156, 123, 82, SDL_ALPHA_OPAQUE}
+    , {156, 132, 82, SDL_ALPHA_OPAQUE}
+    , {156, 132, 99, SDL_ALPHA_OPAQUE}
+    , {156, 156, 156, SDL_ALPHA_OPAQUE}
     ,
-    {165, 123, 49}
-    , {165, 123, 90}
-    , {165, 132, 82}
-    , {165, 132, 90}
+    {165, 123, 49, SDL_ALPHA_OPAQUE}
+    , {165, 123, 90, SDL_ALPHA_OPAQUE}
+    , {165, 132, 82, SDL_ALPHA_OPAQUE}
+    , {165, 132, 90, SDL_ALPHA_OPAQUE}
     ,
-    {165, 132, 99}
-    , {165, 140, 90}
-    , {173, 132, 57}
-    , {173, 132, 99}
+    {165, 132, 99, SDL_ALPHA_OPAQUE}
+    , {165, 140, 90, SDL_ALPHA_OPAQUE}
+    , {173, 132, 57, SDL_ALPHA_OPAQUE}
+    , {173, 132, 99, SDL_ALPHA_OPAQUE}
     ,
-    {173, 140, 107}
-    , {173, 140, 115}
-    , {173, 148, 99}
-    , {173, 173, 173}
+    {173, 140, 107, SDL_ALPHA_OPAQUE}
+    , {173, 140, 115, SDL_ALPHA_OPAQUE}
+    , {173, 148, 99, SDL_ALPHA_OPAQUE}
+    , {173, 173, 173, SDL_ALPHA_OPAQUE}
     ,
-    {181, 140, 74}
-    , {181, 148, 115}
-    , {181, 148, 123}
-    , {181, 156, 107}
+    {181, 140, 74, SDL_ALPHA_OPAQUE}
+    , {181, 148, 115, SDL_ALPHA_OPAQUE}
+    , {181, 148, 123, SDL_ALPHA_OPAQUE}
+    , {181, 156, 107, SDL_ALPHA_OPAQUE}
     ,
-    {189, 148, 123}
-    , {189, 156, 82}
-    , {189, 156, 123}
-    , {189, 156, 132}
+    {189, 148, 123, SDL_ALPHA_OPAQUE}
+    , {189, 156, 82, SDL_ALPHA_OPAQUE}
+    , {189, 156, 123, SDL_ALPHA_OPAQUE}
+    , {189, 156, 132, SDL_ALPHA_OPAQUE}
     ,
-    {189, 189, 189}
-    , {198, 156, 123}
-    , {198, 165, 132}
-    , {206, 165, 99}
+    {189, 189, 189, SDL_ALPHA_OPAQUE}
+    , {198, 156, 123, SDL_ALPHA_OPAQUE}
+    , {198, 165, 132, SDL_ALPHA_OPAQUE}
+    , {206, 165, 99, SDL_ALPHA_OPAQUE}
     ,
-    {206, 165, 132}
-    , {206, 173, 140}
-    , {206, 206, 206}
-    , {214, 173, 115}
+    {206, 165, 132, SDL_ALPHA_OPAQUE}
+    , {206, 173, 140, SDL_ALPHA_OPAQUE}
+    , {206, 206, 206, SDL_ALPHA_OPAQUE}
+    , {214, 173, 115, SDL_ALPHA_OPAQUE}
     ,
-    {214, 173, 140}
-    , {222, 181, 148}
-    , {222, 189, 132}
-    , {222, 189, 156}
+    {214, 173, 140, SDL_ALPHA_OPAQUE}
+    , {222, 181, 148, SDL_ALPHA_OPAQUE}
+    , {222, 189, 132, SDL_ALPHA_OPAQUE}
+    , {222, 189, 156, SDL_ALPHA_OPAQUE}
     ,
-    {222, 222, 222}
-    , {231, 198, 165}
-    , {231, 231, 231}
-    , {239, 206, 173}
+    {222, 222, 222, SDL_ALPHA_OPAQUE}
+    , {231, 198, 165, SDL_ALPHA_OPAQUE}
+    , {231, 231, 231, SDL_ALPHA_OPAQUE}
+    , {239, 206, 173, SDL_ALPHA_OPAQUE}
 };
 
 Uint8 MooseFrame[MOOSEFRAMES_COUNT][MOOSEFRAME_SIZE*2];
@@ -150,7 +150,7 @@ int paused = 0;
 int i;
 SDL_bool done = SDL_FALSE;
 Uint32 pixel_format = SDL_PIXELFORMAT_YV12;
-int fpsdelay;
+static int fpsdelay;
 
 /* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
 static void
@@ -328,7 +328,6 @@ main(int argc, char **argv)
     SDL_Window *window;
     int j;
     int fps = 12;
-    int fpsdelay;
     int nodelay = 0;
 #ifdef TEST_NV12
     Uint32 pixel_format = SDL_PIXELFORMAT_NV12;
@@ -404,7 +403,6 @@ main(int argc, char **argv)
     RawMooseData = (Uint8 *) malloc(MOOSEFRAME_SIZE * MOOSEFRAMES_COUNT);
     if (RawMooseData == NULL) {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Can't allocate memory for movie !\n");
-        free(RawMooseData);
         quit(1);
     }
 
diff --git a/test/testplatform.c b/test/testplatform.c
index 14acac4..001123b 100644
--- a/test/testplatform.c
+++ b/test/testplatform.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -128,6 +128,220 @@ TestEndian(SDL_bool verbose)
     return (error ? 1 : 0);
 }
 
+static int TST_allmul (void *a, void *b, int arg, void *result, void *expected)
+{
+    (*(long long *)result) = ((*(long long *)a) * (*(long long *)b));
+    return (*(long long *)result) == (*(long long *)expected);
+}
+
+static int TST_alldiv (void *a, void *b, int arg, void *result, void *expected)
+{
+    (*(long long *)result) = ((*(long long *)a) / (*(long long *)b));
+    return (*(long long *)result) == (*(long long *)expected);
+}
+
+static int TST_allrem (void *a, void *b, int arg, void *result, void *expected)
+{
+    (*(long long *)result) = ((*(long long *)a) % (*(long long *)b));
+    return (*(long long *)result) == (*(long long *)expected);
+}
+
+static int TST_ualldiv (void *a, void *b, int arg, void *result, void *expected)
+{
+    (*(unsigned long long *)result) = ((*(unsigned long long *)a) / (*(unsigned long long *)b));
+    return (*(unsigned long long *)result) == (*(unsigned long long *)expected);
+}
+
+static int TST_uallrem (void *a, void *b, int arg, void *result, void *expected)
+{
+    (*(unsigned long long *)result) = ((*(unsigned long long *)a) % (*(unsigned long long *)b));
+    return (*(unsigned long long *)result) == (*(unsigned long long *)expected);
+}
+
+static int TST_allshl (void *a, void *b, int arg, void *result, void *expected)
+{
+    (*(long long *)result) = (*(long long *)a) << arg;
+    return (*(long long *)result) == (*(long long *)expected);
+}
+
+static int TST_aullshl (void *a, void *b, int arg, void *result, void *expected)
+{
+    (*(unsigned long long *)result) = (*(unsigned long long *)a) << arg;
+    return (*(unsigned long long *)result) == (*(unsigned long long *)expected);
+}
+
+static int TST_allshr (void *a, void *b, int arg, void *result, void *expected)
+{
+    (*(long long *)result) = (*(long long *)a) >> arg;
+    return (*(long long *)result) == (*(long long *)expected);
+}
+
+static int TST_aullshr (void *a, void *b, int arg, void *result, void *expected)
+{
+    (*(unsigned long long *)result) = (*(unsigned long long *)a) >> arg;
+    return (*(unsigned long long *)result) == (*(unsigned long long *)expected);
+}
+
+
+typedef int (*LL_Intrinsic)(void *a, void *b, int arg, void *result, void *expected);
+
+typedef struct {
+    const char *operation;
+    LL_Intrinsic routine;
+    unsigned long long a, b;
+    int arg;
+    unsigned long long expected_result;
+} LL_Test;
+
+static LL_Test LL_Tests[] = 
+{
+    /* UNDEFINED {"_allshl",   &TST_allshl,   0xFFFFFFFFFFFFFFFFll,                  0ll, 65, 0x0000000000000000ll}, */
+    {"_allshl",   &TST_allshl,   0xFFFFFFFFFFFFFFFFll,                  0ll,  1, 0xFFFFFFFFFFFFFFFEll},
+    {"_allshl",   &TST_allshl,   0xFFFFFFFFFFFFFFFFll,                  0ll, 32, 0xFFFFFFFF00000000ll},
+    {"_allshl",   &TST_allshl,   0xFFFFFFFFFFFFFFFFll,                  0ll, 33, 0xFFFFFFFE00000000ll},
+    {"_allshl",   &TST_allshl,   0xFFFFFFFFFFFFFFFFll,                  0ll,  0, 0xFFFFFFFFFFFFFFFFll},
+
+    {"_allshr",   &TST_allshr,   0xAAAAAAAA55555555ll,                  0ll, 63, 0xFFFFFFFFFFFFFFFFll},
+    /* UNDEFINED {"_allshr",   &TST_allshr,   0xFFFFFFFFFFFFFFFFll,                  0ll, 65, 0xFFFFFFFFFFFFFFFFll}, */
+    {"_allshr",   &TST_allshr,   0xFFFFFFFFFFFFFFFFll,                  0ll,  1, 0xFFFFFFFFFFFFFFFFll},
+    {"_allshr",   &TST_allshr,   0xFFFFFFFFFFFFFFFFll,                  0ll, 32, 0xFFFFFFFFFFFFFFFFll},
+    {"_allshr",   &TST_allshr,   0xFFFFFFFFFFFFFFFFll,                  0ll, 33, 0xFFFFFFFFFFFFFFFFll},
+    {"_allshr",   &TST_allshr,   0xFFFFFFFFFFFFFFFFll,                  0ll,  0, 0xFFFFFFFFFFFFFFFFll},
+    /* UNDEFINED {"_allshr",   &TST_allshr,   0x5F5F5F5F5F5F5F5Fll,                  0ll, 65, 0x0000000000000000ll}, */
+    {"_allshr",   &TST_allshr,   0x5F5F5F5F5F5F5F5Fll,                  0ll,  1, 0x2FAFAFAFAFAFAFAFll},
+    {"_allshr",   &TST_allshr,   0x5F5F5F5F5F5F5F5Fll,                  0ll, 32, 0x000000005F5F5F5Fll},
+    {"_allshr",   &TST_allshr,   0x5F5F5F5F5F5F5F5Fll,                  0ll, 33, 0x000000002FAFAFAFll},
+
+    /* UNDEFINED {"_aullshl",  &TST_aullshl,  0xFFFFFFFFFFFFFFFFll,                  0ll, 65, 0x0000000000000000ll}, */
+    {"_aullshl",  &TST_aullshl,  0xFFFFFFFFFFFFFFFFll,                  0ll,  1, 0xFFFFFFFFFFFFFFFEll},
+    {"_aullshl",  &TST_aullshl,  0xFFFFFFFFFFFFFFFFll,                  0ll, 32, 0xFFFFFFFF00000000ll},
+    {"_aullshl",  &TST_aullshl,  0xFFFFFFFFFFFFFFFFll,                  0ll, 33, 0xFFFFFFFE00000000ll},
+    {"_aullshl",  &TST_aullshl,  0xFFFFFFFFFFFFFFFFll,                  0ll,  0, 0xFFFFFFFFFFFFFFFFll},
+
+    /* UNDEFINED {"_aullshr",  &TST_aullshr,  0xFFFFFFFFFFFFFFFFll,                  0ll, 65, 0x0000000000000000ll}, */
+    {"_aullshr",  &TST_aullshr,  0xFFFFFFFFFFFFFFFFll,                  0ll,  1, 0x7FFFFFFFFFFFFFFFll},
+    {"_aullshr",  &TST_aullshr,  0xFFFFFFFFFFFFFFFFll,                  0ll, 32, 0x00000000FFFFFFFFll},
+    {"_aullshr",  &TST_aullshr,  0xFFFFFFFFFFFFFFFFll,                  0ll, 33, 0x000000007FFFFFFFll},
+    {"_aullshr",  &TST_aullshr,  0xFFFFFFFFFFFFFFFFll,                  0ll,  0, 0xFFFFFFFFFFFFFFFFll},
+
+    {"_allmul",   &TST_allmul,   0xFFFFFFFFFFFFFFFFll, 0x0000000000000000ll,  0, 0x0000000000000000ll},
+    {"_allmul",   &TST_allmul,   0x0000000000000000ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_allmul",   &TST_allmul,   0x000000000FFFFFFFll, 0x0000000000000001ll,  0, 0x000000000FFFFFFFll},
+    {"_allmul",   &TST_allmul,   0x0000000000000001ll, 0x000000000FFFFFFFll,  0, 0x000000000FFFFFFFll},
+    {"_allmul",   &TST_allmul,   0x000000000FFFFFFFll, 0x0000000000000010ll,  0, 0x00000000FFFFFFF0ll},
+    {"_allmul",   &TST_allmul,   0x0000000000000010ll, 0x000000000FFFFFFFll,  0, 0x00000000FFFFFFF0ll},
+    {"_allmul",   &TST_allmul,   0x000000000FFFFFFFll, 0x0000000000000100ll,  0, 0x0000000FFFFFFF00ll},
+    {"_allmul",   &TST_allmul,   0x0000000000000100ll, 0x000000000FFFFFFFll,  0, 0x0000000FFFFFFF00ll},
+    {"_allmul",   &TST_allmul,   0x000000000FFFFFFFll, 0x0000000010000000ll,  0, 0x00FFFFFFF0000000ll},
+    {"_allmul",   &TST_allmul,   0x0000000010000000ll, 0x000000000FFFFFFFll,  0, 0x00FFFFFFF0000000ll},
+    {"_allmul",   &TST_allmul,   0x000000000FFFFFFFll, 0x0000000080000000ll,  0, 0x07FFFFFF80000000ll},
+    {"_allmul",   &TST_allmul,   0x0000000080000000ll, 0x000000000FFFFFFFll,  0, 0x07FFFFFF80000000ll},
+    {"_allmul",   &TST_allmul,   0xFFFFFFFFFFFFFFFEll, 0x0000000080000000ll,  0, 0xFFFFFFFF00000000ll},
+    {"_allmul",   &TST_allmul,   0x0000000080000000ll, 0xFFFFFFFFFFFFFFFEll,  0, 0xFFFFFFFF00000000ll},
+    {"_allmul",   &TST_allmul,   0xFFFFFFFFFFFFFFFEll, 0x0000000080000008ll,  0, 0xFFFFFFFEFFFFFFF0ll},
+    {"_allmul",   &TST_allmul,   0x0000000080000008ll, 0xFFFFFFFFFFFFFFFEll,  0, 0xFFFFFFFEFFFFFFF0ll},
+    {"_allmul",   &TST_allmul,   0x00000000FFFFFFFFll, 0x00000000FFFFFFFFll,  0, 0xFFFFFFFE00000001ll},
+
+    {"_alldiv",   &TST_alldiv,   0x0000000000000000ll, 0x0000000000000001ll,  0, 0x0000000000000000ll},
+    {"_alldiv",   &TST_alldiv,   0x0000000000000000ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_alldiv",   &TST_alldiv,   0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll,  0, 0xFFFFFFFFFFFFFFFFll},
+    {"_alldiv",   &TST_alldiv,   0xFFFFFFFFFFFFFFFFll, 0x0000000000000001ll,  0, 0xFFFFFFFFFFFFFFFFll},
+    {"_alldiv",   &TST_alldiv,   0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll,  0, 0xFFFFFFFFFFFFFFFFll},
+    {"_alldiv",   &TST_alldiv,   0x0000000000000001ll, 0x0000000000000001ll,  0, 0x0000000000000001ll},
+    {"_alldiv",   &TST_alldiv,   0xFFFFFFFFFFFFFFFFll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000001ll},
+    {"_alldiv",   &TST_alldiv,   0x000000000FFFFFFFll, 0x0000000000000001ll,  0, 0x000000000FFFFFFFll},
+    {"_alldiv",   &TST_alldiv,   0x0000000FFFFFFFFFll, 0x0000000000000010ll,  0, 0x00000000FFFFFFFFll},
+    {"_alldiv",   &TST_alldiv,   0x0000000000000100ll, 0x000000000FFFFFFFll,  0, 0x0000000000000000ll},
+    {"_alldiv",   &TST_alldiv,   0x00FFFFFFF0000000ll, 0x0000000010000000ll,  0, 0x000000000FFFFFFFll},
+    {"_alldiv",   &TST_alldiv,   0x07FFFFFF80000000ll, 0x0000000080000000ll,  0, 0x000000000FFFFFFFll},
+    {"_alldiv",   &TST_alldiv,   0xFFFFFFFFFFFFFFFEll, 0x0000000080000000ll,  0, 0x0000000000000000ll},
+    {"_alldiv",   &TST_alldiv,   0xFFFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll,  0, 0x0000000080000008ll},
+    {"_alldiv",   &TST_alldiv,   0x7FFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll,  0, 0xC000000080000008ll},
+    {"_alldiv",   &TST_alldiv,   0x7FFFFFFEFFFFFFF0ll, 0x0000FFFFFFFFFFFEll,  0, 0x0000000000007FFFll},
+    {"_alldiv",   &TST_alldiv,   0x7FFFFFFEFFFFFFF0ll, 0x7FFFFFFEFFFFFFF0ll,  0, 0x0000000000000001ll},
+
+    {"_allrem",   &TST_allrem,   0x0000000000000000ll, 0x0000000000000001ll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0x0000000000000000ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0xFFFFFFFFFFFFFFFFll, 0x0000000000000001ll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0x0000000000000001ll, 0x0000000000000001ll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0xFFFFFFFFFFFFFFFFll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0x000000000FFFFFFFll, 0x0000000000000001ll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0x0000000FFFFFFFFFll, 0x0000000000000010ll,  0, 0x000000000000000Fll},
+    {"_allrem",   &TST_allrem,   0x0000000000000100ll, 0x000000000FFFFFFFll,  0, 0x0000000000000100ll},
+    {"_allrem",   &TST_allrem,   0x00FFFFFFF0000000ll, 0x0000000010000000ll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0x07FFFFFF80000000ll, 0x0000000080000000ll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0xFFFFFFFFFFFFFFFEll, 0x0000000080000000ll,  0, 0xFFFFFFFFFFFFFFFEll},
+    {"_allrem",   &TST_allrem,   0xFFFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0x7FFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll,  0, 0x0000000000000000ll},
+    {"_allrem",   &TST_allrem,   0x7FFFFFFEFFFFFFF0ll, 0x0000FFFFFFFFFFFEll,  0, 0x0000FFFF0000FFEEll},
+    {"_allrem",   &TST_allrem,   0x7FFFFFFEFFFFFFF0ll, 0x7FFFFFFEFFFFFFF0ll,  0, 0x0000000000000000ll},
+
+
+    {"_ualldiv",  &TST_ualldiv,  0x0000000000000000ll, 0x0000000000000001ll,  0, 0x0000000000000000ll},
+    {"_ualldiv",  &TST_ualldiv,  0x0000000000000000ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_ualldiv",  &TST_ualldiv,  0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_ualldiv",  &TST_ualldiv,  0xFFFFFFFFFFFFFFFFll, 0x0000000000000001ll,  0, 0xFFFFFFFFFFFFFFFFll},
+    {"_ualldiv",  &TST_ualldiv,  0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_ualldiv",  &TST_ualldiv,  0x0000000000000001ll, 0x0000000000000001ll,  0, 0x0000000000000001ll},
+    {"_ualldiv",  &TST_ualldiv,  0xFFFFFFFFFFFFFFFFll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000001ll},
+    {"_ualldiv",  &TST_ualldiv,  0x000000000FFFFFFFll, 0x0000000000000001ll,  0, 0x000000000FFFFFFFll},
+    {"_ualldiv",  &TST_ualldiv,  0x0000000FFFFFFFFFll, 0x0000000000000010ll,  0, 0x00000000FFFFFFFFll},
+    {"_ualldiv",  &TST_ualldiv,  0x0000000000000100ll, 0x000000000FFFFFFFll,  0, 0x0000000000000000ll},
+    {"_ualldiv",  &TST_ualldiv,  0x00FFFFFFF0000000ll, 0x0000000010000000ll,  0, 0x000000000FFFFFFFll},
+    {"_ualldiv",  &TST_ualldiv,  0x07FFFFFF80000000ll, 0x0000000080000000ll,  0, 0x000000000FFFFFFFll},
+    {"_ualldiv",  &TST_ualldiv,  0xFFFFFFFFFFFFFFFEll, 0x0000000080000000ll,  0, 0x00000001FFFFFFFFll},
+    {"_ualldiv",  &TST_ualldiv,  0xFFFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll,  0, 0x0000000000000000ll},
+    {"_ualldiv",  &TST_ualldiv,  0x7FFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll,  0, 0x0000000000000000ll},
+    {"_ualldiv",  &TST_ualldiv,  0x7FFFFFFEFFFFFFF0ll, 0x0000FFFFFFFFFFFEll,  0, 0x0000000000007FFFll},
+    {"_ualldiv",  &TST_ualldiv,  0x7FFFFFFEFFFFFFF0ll, 0x7FFFFFFEFFFFFFF0ll,  0, 0x0000000000000001ll},
+
+    {"_uallrem",  &TST_uallrem,  0x0000000000000000ll, 0x0000000000000001ll,  0, 0x0000000000000000ll},
+    {"_uallrem",  &TST_uallrem,  0x0000000000000000ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_uallrem",  &TST_uallrem,  0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000001ll},
+    {"_uallrem",  &TST_uallrem,  0xFFFFFFFFFFFFFFFFll, 0x0000000000000001ll,  0, 0x0000000000000000ll},
+    {"_uallrem",  &TST_uallrem,  0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000001ll},
+    {"_uallrem",  &TST_uallrem,  0x0000000000000001ll, 0x0000000000000001ll,  0, 0x0000000000000000ll},
+    {"_uallrem",  &TST_uallrem,  0xFFFFFFFFFFFFFFFFll, 0xFFFFFFFFFFFFFFFFll,  0, 0x0000000000000000ll},
+    {"_uallrem",  &TST_uallrem,  0x000000000FFFFFFFll, 0x0000000000000001ll,  0, 0x0000000000000000ll},
+    {"_uallrem",  &TST_uallrem,  0x0000000FFFFFFFFFll, 0x0000000000000010ll,  0, 0x000000000000000Fll},
+    {"_uallrem",  &TST_uallrem,  0x0000000000000100ll, 0x000000000FFFFFFFll,  0, 0x0000000000000100ll},
+    {"_uallrem",  &TST_uallrem,  0x00FFFFFFF0000000ll, 0x0000000010000000ll,  0, 0x0000000000000000ll},
+    {"_uallrem",  &TST_uallrem,  0x07FFFFFF80000000ll, 0x0000000080000000ll,  0, 0x0000000000000000ll},
+    {"_uallrem",  &TST_uallrem,  0xFFFFFFFFFFFFFFFEll, 0x0000000080000000ll,  0, 0x000000007FFFFFFEll},
+    {"_uallrem",  &TST_uallrem,  0xFFFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll,  0, 0xFFFFFFFEFFFFFFF0ll},
+    {"_uallrem",  &TST_uallrem,  0x7FFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll,  0, 0x7FFFFFFEFFFFFFF0ll},
+    {"_uallrem",  &TST_uallrem,  0x7FFFFFFEFFFFFFF0ll, 0x0000FFFFFFFFFFFEll,  0, 0x0000FFFF0000FFEEll},
+    {"_uallrem",  &TST_uallrem,  0x7FFFFFFEFFFFFFF0ll, 0x7FFFFFFEFFFFFFF0ll,  0, 0x0000000000000000ll},
+
+    {NULL}
+};
+
+int
+Test64Bit (SDL_bool verbose)
+{
+    LL_Test *t;
+    int failed = 0;
+
+    for (t = LL_Tests; t->routine != NULL; t++) {
+        unsigned long long result = 0;
+        unsigned int *al = (unsigned int *)&t->a;
+        unsigned int *bl = (unsigned int *)&t->b;
+        unsigned int *el = (unsigned int *)&t->expected_result;
+        unsigned int *rl = (unsigned int *)&result;
+
+        if (!t->routine(&t->a, &t->b, t->arg, &result, &t->expected_result)) {
+            if (verbose)
+                SDL_Log("%s(0x%08X%08X, 0x%08X%08X, %3d, produced: 0x%08X%08X, expected: 0x%08X%08X\n",
+                        t->operation, al[1], al[0], bl[1], bl[0], t->arg, rl[1], rl[0], el[1], el[0]);
+            ++failed;
+        }
+    }
+    if (verbose && (failed == 0))
+        SDL_Log("All 64bit instrinsic tests passed\n");
+    return (failed ? 1 : 0);
+}
 
 int
 TestCPUInfo(SDL_bool verbose)
@@ -145,6 +359,8 @@ TestCPUInfo(SDL_bool verbose)
         SDL_Log("SSE4.1 %s\n", SDL_HasSSE41()? "detected" : "not detected");
         SDL_Log("SSE4.2 %s\n", SDL_HasSSE42()? "detected" : "not detected");
         SDL_Log("AVX %s\n", SDL_HasAVX()? "detected" : "not detected");
+        SDL_Log("AVX2 %s\n", SDL_HasAVX2()? "detected" : "not detected");
+        SDL_Log("NEON %s\n", SDL_HasNEON()? "detected" : "not detected");
         SDL_Log("System RAM %d MB\n", SDL_GetSystemRAM());
     }
     return (0);
@@ -197,6 +413,7 @@ main(int argc, char *argv[])
 
     status += TestTypes(verbose);
     status += TestEndian(verbose);
+    status += Test64Bit(verbose);
     status += TestCPUInfo(verbose);
     status += TestAssertions(verbose);
 
diff --git a/test/testpower.c b/test/testpower.c
index 300d21a..48d64f0 100644
--- a/test/testpower.c
+++ b/test/testpower.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testqsort.c b/test/testqsort.c
index 48659f3..8867539 100644
--- a/test/testqsort.c
+++ b/test/testqsort.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testrelative.c b/test/testrelative.c
index 59d23f6..5d2ab5d 100644
--- a/test/testrelative.c
+++ b/test/testrelative.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testrendercopyex.c b/test/testrendercopyex.c
index e348902..72a54e6 100644
--- a/test/testrendercopyex.c
+++ b/test/testrendercopyex.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testrendertarget.c b/test/testrendertarget.c
index c5e1dce..ec21f2e 100644
--- a/test/testrendertarget.c
+++ b/test/testrendertarget.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testresample.c b/test/testresample.c
index 0e92bbe..a54a47d 100644
--- a/test/testresample.c
+++ b/test/testresample.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -20,6 +20,7 @@ main(int argc, char **argv)
     Uint32 len = 0;
     Uint8 *data = NULL;
     int cvtfreq = 0;
+    int cvtchans = 0;
     int bitsize = 0;
     int blockalign = 0;
     int avgbytes = 0;
@@ -28,12 +29,13 @@ main(int argc, char **argv)
     /* Enable standard application logging */
     SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
 
-    if (argc != 4) {
-        SDL_Log("USAGE: %s in.wav out.wav newfreq\n", argv[0]);
+    if (argc != 5) {
+        SDL_Log("USAGE: %s in.wav out.wav newfreq newchans\n", argv[0]);
         return 1;
     }
 
     cvtfreq = SDL_atoi(argv[3]);
+    cvtchans = SDL_atoi(argv[4]);
 
     if (SDL_Init(SDL_INIT_AUDIO) == -1) {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init() failed: %s\n", SDL_GetError());
@@ -47,7 +49,7 @@ main(int argc, char **argv)
     }
 
     if (SDL_BuildAudioCVT(&cvt, spec.format, spec.channels, spec.freq,
-                          spec.format, spec.channels, cvtfreq) == -1) {
+                          spec.format, cvtchans, cvtfreq) == -1) {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "failed to build CVT: %s\n", SDL_GetError());
         SDL_FreeWAV(data);
         SDL_Quit();
@@ -83,16 +85,16 @@ main(int argc, char **argv)
     }
 
     bitsize = SDL_AUDIO_BITSIZE(spec.format);
-    blockalign = (bitsize / 8) * spec.channels;
+    blockalign = (bitsize / 8) * cvtchans;
     avgbytes = cvtfreq * blockalign;
 
     SDL_WriteLE32(io, 0x46464952);      /* RIFF */
-    SDL_WriteLE32(io, len * cvt.len_mult + 36);
+    SDL_WriteLE32(io, cvt.len_cvt + 36);
     SDL_WriteLE32(io, 0x45564157);      /* WAVE */
     SDL_WriteLE32(io, 0x20746D66);      /* fmt */
     SDL_WriteLE32(io, 16);      /* chunk size */
     SDL_WriteLE16(io, 1);       /* uncompressed */
-    SDL_WriteLE16(io, spec.channels);   /* channels */
+    SDL_WriteLE16(io, cvtchans);   /* channels */
     SDL_WriteLE32(io, cvtfreq); /* sample rate */
     SDL_WriteLE32(io, avgbytes);        /* average bytes per second */
     SDL_WriteLE16(io, blockalign);      /* block align */
diff --git a/test/testrumble.c b/test/testrumble.c
index ea7466d..a22c52e 100644
--- a/test/testrumble.c
+++ b/test/testrumble.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -54,6 +54,7 @@ main(int argc, char **argv)
     name = NULL;
     index = -1;
     if (argc > 1) {
+        size_t l;
         name = argv[1];
         if ((strcmp(name, "--help") == 0) || (strcmp(name, "-h") == 0)) {
             SDL_Log("USAGE: %s [device]\n"
@@ -63,9 +64,9 @@ main(int argc, char **argv)
             return 0;
         }
 
-        i = strlen(name);
-        if ((i < 3) && isdigit(name[0]) && ((i == 1) || isdigit(name[1]))) {
-            index = atoi(name);
+        l = SDL_strlen(name);
+        if ((l < 3) && SDL_isdigit(name[0]) && ((l == 1) || SDL_isdigit(name[1]))) {
+            index = SDL_atoi(name);
             name = NULL;
         }
     }
diff --git a/test/testscale.c b/test/testscale.c
index 9f5fdbf..34451d6 100644
--- a/test/testscale.c
+++ b/test/testscale.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testsem.c b/test/testsem.c
index b8d3b27..13438b1 100644
--- a/test/testsem.c
+++ b/test/testsem.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testshader.c b/test/testshader.c
index fc6da29..1700da1 100644
--- a/test/testshader.c
+++ b/test/testshader.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testshape.c b/test/testshape.c
index 476fac2..d54cc22 100644
--- a/test/testshape.c
+++ b/test/testshape.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -48,7 +48,6 @@ int main(int argc,char** argv)
     SDL_Renderer *renderer;
     SDL_Color black = {0,0,0,0xff};
     SDL_Event event;
-    int event_pending = 0;
     int should_exit = 0;
     unsigned int current_picture;
     int button_down;
@@ -81,7 +80,6 @@ int main(int argc,char** argv)
         pictures[i].surface = SDL_LoadBMP(argv[i+1]);
         pictures[i].name = argv[i+1];
         if(pictures[i].surface == NULL) {
-            j = 0;
             for(j=0;j<num_pictures;j++)
                 SDL_FreeSurface(pictures[j].surface);
             SDL_free(pictures);
@@ -130,8 +128,7 @@ int main(int argc,char** argv)
     for(i=0;i<num_pictures;i++) {
         pictures[i].texture = SDL_CreateTextureFromSurface(renderer,pictures[i].surface);
         if(pictures[i].texture == NULL) {
-            j = 0;
-            for(j=0;j<num_pictures;i++)
+            for(i=0;i<num_pictures;i++)
                 if(pictures[i].texture != NULL)
                     SDL_DestroyTexture(pictures[i].texture);
             for(i=0;i<num_pictures;i++)
@@ -145,9 +142,7 @@ int main(int argc,char** argv)
         }
     }
 
-    event_pending = 0;
     should_exit = 0;
-    event_pending = SDL_PollEvent(&event);
     current_picture = 0;
     button_down = 0;
     texture_dimensions.h = 0;
@@ -159,8 +154,7 @@ int main(int argc,char** argv)
     SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
     SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
     while(should_exit == 0) {
-        event_pending = SDL_PollEvent(&event);
-        if(event_pending == 1) {
+        while (SDL_PollEvent(&event)) {
             if(event.type == SDL_KEYDOWN) {
                 button_down = 1;
                 if(event.key.keysym.sym == SDLK_ESCAPE) {
@@ -178,9 +172,10 @@ int main(int argc,char** argv)
                 SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
                 SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
             }
-            if(event.type == SDL_QUIT)
+            if (event.type == SDL_QUIT) {
                 should_exit = 1;
-            event_pending = 0;
+                break;
+            }
         }
         render(renderer,pictures[current_picture].texture,texture_dimensions);
         SDL_Delay(10);
diff --git a/test/testsprite2.c b/test/testsprite2.c
index 7a33af3..14258f7 100644
--- a/test/testsprite2.c
+++ b/test/testsprite2.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
@@ -99,7 +99,12 @@ LoadSprite(const char *file)
             SDL_FreeSurface(temp);
             return (-1);
         }
-        SDL_SetTextureBlendMode(sprites[i], blendMode);
+        if (SDL_SetTextureBlendMode(sprites[i], blendMode) < 0) {
+            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set blend mode: %s\n", SDL_GetError());
+            SDL_FreeSurface(temp);
+            SDL_DestroyTexture(sprites[i]);
+            return (-1);
+        }
     }
     SDL_FreeSurface(temp);
 
@@ -295,6 +300,9 @@ main(int argc, char *argv[])
                     } else if (SDL_strcasecmp(argv[i + 1], "mod") == 0) {
                         blendMode = SDL_BLENDMODE_MOD;
                         consumed = 2;
+                    } else if (SDL_strcasecmp(argv[i + 1], "sub") == 0) {
+                        blendMode = SDL_ComposeCustomBlendMode(SDL_BLENDFACTOR_SRC_ALPHA, SDL_BLENDFACTOR_ONE, SDL_BLENDOPERATION_SUBTRACT, SDL_BLENDFACTOR_ZERO, SDL_BLENDFACTOR_ONE, SDL_BLENDOPERATION_SUBTRACT);
+                        consumed = 2;
                     }
                 }
             } else if (SDL_strcasecmp(argv[i], "--iterations") == 0) {
diff --git a/test/testspriteminimal.c b/test/testspriteminimal.c
index 05f9730..478c584 100644
--- a/test/testspriteminimal.c
+++ b/test/testspriteminimal.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/teststreaming.c b/test/teststreaming.c
index 86cc139..76a9fed 100644
--- a/test/teststreaming.c
+++ b/test/teststreaming.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testthread.c b/test/testthread.c
index 90e2c60..6557b2f 100644
--- a/test/testthread.c
+++ b/test/testthread.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testtimer.c b/test/testtimer.c
index 32b7490..261497b 100644
--- a/test/testtimer.c
+++ b/test/testtimer.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testver.c b/test/testver.c
index f0e3bcf..04a7a90 100644
--- a/test/testver.c
+++ b/test/testver.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testviewport.c b/test/testviewport.c
index 7ed4e6e..f9d0bd5 100644
--- a/test/testviewport.c
+++ b/test/testviewport.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/testvulkan.c b/test/testvulkan.c
new file mode 100644
index 0000000..95cbec8
--- /dev/null
+++ b/test/testvulkan.c
@@ -0,0 +1,1201 @@
+/*
+  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely.
+*/
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+
+#include "SDL_test_common.h"
+
+#if defined(__ANDROID__) && defined(__ARM_EABI__) && !defined(__ARM_ARCH_7A__)
+
+int main(int argc, char *argv[])
+{
+    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No Vulkan support on this system\n");
+    return 1;
+}
+
+#else
+
+#define VK_NO_PROTOTYPES
+#ifdef HAVE_VULKAN_H
+#include <vulkan/vulkan.h>
+#else
+/* SDL includes a copy for building on systems without the Vulkan SDK */
+#include "../src/video/khronos/vulkan/vulkan.h"
+#endif
+#include "SDL_vulkan.h"
+
+#ifndef UINT64_MAX /* VS2008 */
+#define UINT64_MAX 18446744073709551615
+#endif
+
+#define VULKAN_FUNCTIONS()                                              \
+    VULKAN_DEVICE_FUNCTION(vkAcquireNextImageKHR)                       \
+    VULKAN_DEVICE_FUNCTION(vkAllocateCommandBuffers)                    \
+    VULKAN_DEVICE_FUNCTION(vkBeginCommandBuffer)                        \
+    VULKAN_DEVICE_FUNCTION(vkCmdClearColorImage)                        \
+    VULKAN_DEVICE_FUNCTION(vkCmdPipelineBarrier)                        \
+    VULKAN_DEVICE_FUNCTION(vkCreateCommandPool)                         \
+    VULKAN_DEVICE_FUNCTION(vkCreateFence)                               \
+    VULKAN_DEVICE_FUNCTION(vkCreateImageView)                           \
+    VULKAN_DEVICE_FUNCTION(vkCreateSemaphore)                           \
+    VULKAN_DEVICE_FUNCTION(vkCreateSwapchainKHR)                        \
+    VULKAN_DEVICE_FUNCTION(vkDestroyCommandPool)                        \
+    VULKAN_DEVICE_FUNCTION(vkDestroyDevice)                             \
+    VULKAN_DEVICE_FUNCTION(vkDestroyFence)                              \
+    VULKAN_DEVICE_FUNCTION(vkDestroyImageView)                          \
+    VULKAN_DEVICE_FUNCTION(vkDestroySemaphore)                          \
+    VULKAN_DEVICE_FUNCTION(vkDestroySwapchainKHR)                       \
+    VULKAN_DEVICE_FUNCTION(vkDeviceWaitIdle)                            \
+    VULKAN_DEVICE_FUNCTION(vkEndCommandBuffer)                          \
+    VULKAN_DEVICE_FUNCTION(vkFreeCommandBuffers)                        \
+    VULKAN_DEVICE_FUNCTION(vkGetDeviceQueue)                            \
+    VULKAN_DEVICE_FUNCTION(vkGetFenceStatus)                            \
+    VULKAN_DEVICE_FUNCTION(vkGetSwapchainImagesKHR)                     \
+    VULKAN_DEVICE_FUNCTION(vkQueuePresentKHR)                           \
+    VULKAN_DEVICE_FUNCTION(vkQueueSubmit)                               \
+    VULKAN_DEVICE_FUNCTION(vkResetCommandBuffer)                        \
+    VULKAN_DEVICE_FUNCTION(vkResetFences)                               \
+    VULKAN_DEVICE_FUNCTION(vkWaitForFences)                             \
+    VULKAN_GLOBAL_FUNCTION(vkCreateInstance)                            \
+    VULKAN_GLOBAL_FUNCTION(vkEnumerateInstanceExtensionProperties)      \
+    VULKAN_GLOBAL_FUNCTION(vkEnumerateInstanceLayerProperties)          \
+    VULKAN_INSTANCE_FUNCTION(vkCreateDevice)                            \
+    VULKAN_INSTANCE_FUNCTION(vkDestroyInstance)                         \
+    VULKAN_INSTANCE_FUNCTION(vkDestroySurfaceKHR)                       \
+    VULKAN_INSTANCE_FUNCTION(vkEnumerateDeviceExtensionProperties)      \
+    VULKAN_INSTANCE_FUNCTION(vkEnumeratePhysicalDevices)                \
+    VULKAN_INSTANCE_FUNCTION(vkGetDeviceProcAddr)                       \
+    VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceFeatures)               \
+    VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceProperties)             \
+    VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceQueueFamilyProperties)  \
+    VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) \
+    VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceSurfaceFormatsKHR)      \
+    VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceSurfacePresentModesKHR) \
+    VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceSurfaceSupportKHR)
+
+#define VULKAN_DEVICE_FUNCTION(name) static PFN_##name name = NULL;
+#define VULKAN_GLOBAL_FUNCTION(name) static PFN_##name name = NULL;
+#define VULKAN_INSTANCE_FUNCTION(name) static PFN_##name name = NULL;
+VULKAN_FUNCTIONS()
+#undef VULKAN_DEVICE_FUNCTION
+#undef VULKAN_GLOBAL_FUNCTION
+#undef VULKAN_INSTANCE_FUNCTION
+static PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
+
+/* Based on the headers found in
+ * https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers
+ */
+#if VK_HEADER_VERSION < 22
+enum
+{
+    VK_ERROR_FRAGMENTED_POOL = -12,
+};
+#endif
+#if VK_HEADER_VERSION < 38
+enum {
+    VK_ERROR_OUT_OF_POOL_MEMORY_KHR = -1000069000
+};
+#endif
+
+static const char *getVulkanResultString(VkResult result)
+{
+    switch((int)result)
+    {
+    case VK_SUCCESS:
+        return "VK_SUCCESS";
+    case VK_NOT_READY:
+        return "VK_NOT_READY";
+    case VK_TIMEOUT:
+        return "VK_TIMEOUT";
+    case VK_EVENT_SET:
+        return "VK_EVENT_SET";
+    case VK_EVENT_RESET:
+        return "VK_EVENT_RESET";
+    case VK_INCOMPLETE:
+        return "VK_INCOMPLETE";
+    case VK_ERROR_OUT_OF_HOST_MEMORY:
+        return "VK_ERROR_OUT_OF_HOST_MEMORY";
+    case VK_ERROR_OUT_OF_DEVICE_MEMORY:
+        return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
+    case VK_ERROR_INITIALIZATION_FAILED:
+        return "VK_ERROR_INITIALIZATION_FAILED";
+    case VK_ERROR_DEVICE_LOST:
+        return "VK_ERROR_DEVICE_LOST";
+    case VK_ERROR_MEMORY_MAP_FAILED:
+        return "VK_ERROR_MEMORY_MAP_FAILED";
+    case VK_ERROR_LAYER_NOT_PRESENT:
+        return "VK_ERROR_LAYER_NOT_PRESENT";
+    case VK_ERROR_EXTENSION_NOT_PRESENT:
+        return "VK_ERROR_EXTENSION_NOT_PRESENT";
+    case VK_ERROR_FEATURE_NOT_PRESENT:
+        return "VK_ERROR_FEATURE_NOT_PRESENT";
+    case VK_ERROR_INCOMPATIBLE_DRIVER:
+        return "VK_ERROR_INCOMPATIBLE_DRIVER";
+    case VK_ERROR_TOO_MANY_OBJECTS:
+        return "VK_ERROR_TOO_MANY_OBJECTS";
+    case VK_ERROR_FORMAT_NOT_SUPPORTED:
+        return "VK_ERROR_FORMAT_NOT_SUPPORTED";
+    case VK_ERROR_FRAGMENTED_POOL:
+        return "VK_ERROR_FRAGMENTED_POOL";
+    case VK_ERROR_SURFACE_LOST_KHR:
+        return "VK_ERROR_SURFACE_LOST_KHR";
+    case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR:
+        return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR";
+    case VK_SUBOPTIMAL_KHR:
+        return "VK_SUBOPTIMAL_KHR";
+    case VK_ERROR_OUT_OF_DATE_KHR:
+        return "VK_ERROR_OUT_OF_DATE_KHR";
+    case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR:
+        return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR";
+    case VK_ERROR_VALIDATION_FAILED_EXT:
+        return "VK_ERROR_VALIDATION_FAILED_EXT";
+    case VK_ERROR_OUT_OF_POOL_MEMORY_KHR:
+        return "VK_ERROR_OUT_OF_POOL_MEMORY_KHR";
+    case VK_ERROR_INVALID_SHADER_NV:
+        return "VK_ERROR_INVALID_SHADER_NV";
+    case VK_RESULT_MAX_ENUM:
+    case VK_RESULT_RANGE_SIZE:
+        break;
+    }
+    if(result < 0)
+        return "VK_ERROR_<Unknown>";
+    return "VK_<Unknown>";
+}
+
+typedef struct VulkanContext
+{
+    VkInstance instance;
+    VkDevice device;
+    VkSurfaceKHR surface;
+    VkSwapchainKHR swapchain;
+    VkPhysicalDeviceProperties physicalDeviceProperties;
+    VkPhysicalDeviceFeatures physicalDeviceFeatures;
+    uint32_t graphicsQueueFamilyIndex;
+    uint32_t presentQueueFamilyIndex;
+    VkPhysicalDevice physicalDevice;
+    VkQueue graphicsQueue;
+    VkQueue presentQueue;
+    VkSemaphore imageAvailableSemaphore;
+    VkSemaphore renderingFinishedSemaphore;
+    VkSurfaceCapabilitiesKHR surfaceCapabilities;
+    VkSurfaceFormatKHR *surfaceFormats;
+    uint32_t surfaceFormatsAllocatedCount;
+    uint32_t surfaceFormatsCount;
+    uint32_t swapchainDesiredImageCount;
+    VkSurfaceFormatKHR surfaceFormat;
+    VkExtent2D swapchainSize;
+    VkCommandPool commandPool;
+    uint32_t swapchainImageCount;
+    VkImage *swapchainImages;
+    VkCommandBuffer *commandBuffers;
+    VkFence *fences;
+} VulkanContext;
+
+static SDLTest_CommonState *state;
+static VulkanContext vulkanContext = {0};
+
+static void shutdownVulkan(void);
+
+/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
+static void quit(int rc)
+{
+    shutdownVulkan();
+    SDLTest_CommonQuit(state);
+    exit(rc);
+}
+
+static void loadGlobalFunctions(void)
+{
+    vkGetInstanceProcAddr = SDL_Vulkan_GetVkGetInstanceProcAddr();
+    if(!vkGetInstanceProcAddr)
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "SDL_Vulkan_GetVkGetInstanceProcAddr(): %s\n",
+                     SDL_GetError());
+        quit(2);
+    }
+
+#define VULKAN_DEVICE_FUNCTION(name)
+#define VULKAN_GLOBAL_FUNCTION(name)                                                   \
+    name = (PFN_##name)vkGetInstanceProcAddr(VK_NULL_HANDLE, #name);                   \
+    if(!name)                                                                          \
+    {                                                                                  \
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,                                     \
+                     "vkGetInstanceProcAddr(VK_NULL_HANDLE, \"" #name "\") failed\n"); \
+        quit(2);                                                                       \
+    }
+#define VULKAN_INSTANCE_FUNCTION(name)
+    VULKAN_FUNCTIONS()
+#undef VULKAN_DEVICE_FUNCTION
+#undef VULKAN_GLOBAL_FUNCTION
+#undef VULKAN_INSTANCE_FUNCTION
+}
+
+static void createInstance(void)
+{
+    VkApplicationInfo appInfo = {0};
+    VkInstanceCreateInfo instanceCreateInfo = {0};
+    const char **extensions = NULL;
+    unsigned extensionCount = 0;
+	VkResult result;
+
+
+	appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
+    appInfo.apiVersion = VK_API_VERSION_1_0;
+    instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
+    instanceCreateInfo.pApplicationInfo = &appInfo;
+    if(!SDL_Vulkan_GetInstanceExtensions(state->windows[0], &extensionCount, NULL))
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "SDL_Vulkan_GetInstanceExtensions(): %s\n",
+                     SDL_GetError());
+        quit(2);
+    }
+    extensions = SDL_malloc(sizeof(const char *) * extensionCount);
+    if(!extensions)
+    {
+        SDL_OutOfMemory();
+        quit(2);
+    }
+    if(!SDL_Vulkan_GetInstanceExtensions(state->windows[0], &extensionCount, extensions))
+    {
+        SDL_free((void*)extensions);
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "SDL_Vulkan_GetInstanceExtensions(): %s\n",
+                     SDL_GetError());
+        quit(2);
+    }
+    instanceCreateInfo.enabledExtensionCount = extensionCount;
+    instanceCreateInfo.ppEnabledExtensionNames = extensions;
+    result = vkCreateInstance(&instanceCreateInfo, NULL, &vulkanContext.instance);
+    SDL_free((void*)extensions);
+    if(result != VK_SUCCESS)
+    {
+        vulkanContext.instance = VK_NULL_HANDLE;
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkCreateInstance(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+}
+
+static void loadInstanceFunctions(void)
+{
+#define VULKAN_DEVICE_FUNCTION(name)
+#define VULKAN_GLOBAL_FUNCTION(name)
+#define VULKAN_INSTANCE_FUNCTION(name)                                           \
+    name = (PFN_##name)vkGetInstanceProcAddr(vulkanContext.instance, #name);     \
+    if(!name)                                                                    \
+    {                                                                            \
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,                               \
+                     "vkGetInstanceProcAddr(instance, \"" #name "\") failed\n"); \
+        quit(2);                                                                 \
+    }
+    VULKAN_FUNCTIONS()
+#undef VULKAN_DEVICE_FUNCTION
+#undef VULKAN_GLOBAL_FUNCTION
+#undef VULKAN_INSTANCE_FUNCTION
+}
+
+static void createSurface(void)
+{
+    if(!SDL_Vulkan_CreateSurface(state->windows[0],
+                                 vulkanContext.instance,
+                                 &vulkanContext.surface))
+    {
+        vulkanContext.surface = VK_NULL_HANDLE;
+        SDL_LogError(
+            SDL_LOG_CATEGORY_APPLICATION, "SDL_Vulkan_CreateSurface(): %s\n", SDL_GetError());
+        quit(2);
+    }
+}
+
+static void findPhysicalDevice(void)
+{
+    uint32_t physicalDeviceCount = 0;
+	VkPhysicalDevice *physicalDevices;
+	VkQueueFamilyProperties *queueFamiliesProperties = NULL;
+    uint32_t queueFamiliesPropertiesAllocatedSize = 0;
+    VkExtensionProperties *deviceExtensions = NULL;
+    uint32_t deviceExtensionsAllocatedSize = 0;
+	uint32_t physicalDeviceIndex;
+
+    VkResult result =
+        vkEnumeratePhysicalDevices(vulkanContext.instance, &physicalDeviceCount, NULL);
+    if(result != VK_SUCCESS)
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkEnumeratePhysicalDevices(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+    if(physicalDeviceCount == 0)
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkEnumeratePhysicalDevices(): no physical devices\n");
+        quit(2);
+    }
+    physicalDevices = SDL_malloc(sizeof(VkPhysicalDevice) * physicalDeviceCount);
+    if(!physicalDevices)
+    {
+        SDL_OutOfMemory();
+        quit(2);
+    }
+    result =
+        vkEnumeratePhysicalDevices(vulkanContext.instance, &physicalDeviceCount, physicalDevices);
+    if(result != VK_SUCCESS)
+    {
+        SDL_free(physicalDevices);
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkEnumeratePhysicalDevices(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+    vulkanContext.physicalDevice = NULL;
+    for(physicalDeviceIndex = 0; physicalDeviceIndex < physicalDeviceCount;
+        physicalDeviceIndex++)
+    {
+        uint32_t queueFamiliesCount = 0;
+		uint32_t queueFamilyIndex;
+        uint32_t deviceExtensionCount = 0;
+		SDL_bool hasSwapchainExtension = SDL_FALSE;
+		uint32_t i;
+
+
+		VkPhysicalDevice physicalDevice = physicalDevices[physicalDeviceIndex];
+        vkGetPhysicalDeviceProperties(physicalDevice, &vulkanContext.physicalDeviceProperties);
+        if(VK_VERSION_MAJOR(vulkanContext.physicalDeviceProperties.apiVersion) < 1)
+            continue;
+        vkGetPhysicalDeviceFeatures(physicalDevice, &vulkanContext.physicalDeviceFeatures);
+        vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamiliesCount, NULL);
+        if(queueFamiliesCount == 0)
+            continue;
+        if(queueFamiliesPropertiesAllocatedSize < queueFamiliesCount)
+        {
+            SDL_free(queueFamiliesProperties);
+            queueFamiliesPropertiesAllocatedSize = queueFamiliesCount;
+            queueFamiliesProperties =
+                SDL_malloc(sizeof(VkQueueFamilyProperties) * queueFamiliesPropertiesAllocatedSize);
+            if(!queueFamiliesProperties)
+            {
+                SDL_free(physicalDevices);
+                SDL_free(deviceExtensions);
+                SDL_OutOfMemory();
+                quit(2);
+            }
+        }
+        vkGetPhysicalDeviceQueueFamilyProperties(
+            physicalDevice, &queueFamiliesCount, queueFamiliesProperties);
+        vulkanContext.graphicsQueueFamilyIndex = queueFamiliesCount;
+        vulkanContext.presentQueueFamilyIndex = queueFamiliesCount;
+        for(queueFamilyIndex = 0; queueFamilyIndex < queueFamiliesCount;
+            queueFamilyIndex++)
+        {
+            VkBool32 supported = 0;
+
+			if(queueFamiliesProperties[queueFamilyIndex].queueCount == 0)
+                continue;
+            if(queueFamiliesProperties[queueFamilyIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT)
+                vulkanContext.graphicsQueueFamilyIndex = queueFamilyIndex;
+            result = vkGetPhysicalDeviceSurfaceSupportKHR(
+                physicalDevice, queueFamilyIndex, vulkanContext.surface, &supported);
+            if(result != VK_SUCCESS)
+            {
+                SDL_free(physicalDevices);
+                SDL_free(queueFamiliesProperties);
+                SDL_free(deviceExtensions);
+                SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                             "vkGetPhysicalDeviceSurfaceSupportKHR(): %s\n",
+                             getVulkanResultString(result));
+                quit(2);
+            }
+            if(supported)
+            {
+                vulkanContext.presentQueueFamilyIndex = queueFamilyIndex;
+                if(queueFamiliesProperties[queueFamilyIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT)
+                    break; // use this queue because it can present and do graphics
+            }
+        }
+        if(vulkanContext.graphicsQueueFamilyIndex == queueFamiliesCount) // no good queues found
+            continue;
+        if(vulkanContext.presentQueueFamilyIndex == queueFamiliesCount) // no good queues found
+            continue;
+        result =
+            vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &deviceExtensionCount, NULL);
+        if(result != VK_SUCCESS)
+        {
+            SDL_free(physicalDevices);
+            SDL_free(queueFamiliesProperties);
+            SDL_free(deviceExtensions);
+            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                         "vkEnumerateDeviceExtensionProperties(): %s\n",
+                         getVulkanResultString(result));
+            quit(2);
+        }
+        if(deviceExtensionCount == 0)
+            continue;
+        if(deviceExtensionsAllocatedSize < deviceExtensionCount)
+        {
+            SDL_free(deviceExtensions);
+            deviceExtensionsAllocatedSize = deviceExtensionCount;
+            deviceExtensions =
+                SDL_malloc(sizeof(VkExtensionProperties) * deviceExtensionsAllocatedSize);
+            if(!deviceExtensions)
+            {
+                SDL_free(physicalDevices);
+                SDL_free(queueFamiliesProperties);
+                SDL_OutOfMemory();
+                quit(2);
+            }
+        }
+        result = vkEnumerateDeviceExtensionProperties(
+            physicalDevice, NULL, &deviceExtensionCount, deviceExtensions);
+        if(result != VK_SUCCESS)
+        {
+            SDL_free(physicalDevices);
+            SDL_free(queueFamiliesProperties);
+            SDL_free(deviceExtensions);
+            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                         "vkEnumerateDeviceExtensionProperties(): %s\n",
+                         getVulkanResultString(result));
+            quit(2);
+        }
+        for(i = 0; i < deviceExtensionCount; i++)
+        {
+            if(0 == SDL_strcmp(deviceExtensions[i].extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME))
+            {
+                hasSwapchainExtension = SDL_TRUE;
+                break;
+            }
+        }
+        if(!hasSwapchainExtension)
+            continue;
+        vulkanContext.physicalDevice = physicalDevice;
+        break;
+    }
+    SDL_free(physicalDevices);
+    SDL_free(queueFamiliesProperties);
+    SDL_free(deviceExtensions);
+    if(!vulkanContext.physicalDevice)
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vulkan: no viable physical devices found");
+        quit(2);
+    }
+}
+
+static void createDevice(void)
+{
+    VkDeviceQueueCreateInfo deviceQueueCreateInfo[1] = {0};
+    static const float queuePriority[] = {1.0f};
+    VkDeviceCreateInfo deviceCreateInfo = {0};
+    static const char *const deviceExtensionNames[] = {
+        VK_KHR_SWAPCHAIN_EXTENSION_NAME,
+    };
+	VkResult result;
+
+	deviceQueueCreateInfo->sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
+    deviceQueueCreateInfo->queueFamilyIndex = vulkanContext.graphicsQueueFamilyIndex;
+    deviceQueueCreateInfo->queueCount = 1;
+    deviceQueueCreateInfo->pQueuePriorities = &queuePriority[0];
+
+    deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
+    deviceCreateInfo.queueCreateInfoCount = 1;
+    deviceCreateInfo.pQueueCreateInfos = deviceQueueCreateInfo;
+    deviceCreateInfo.pEnabledFeatures = NULL;
+    deviceCreateInfo.enabledExtensionCount = SDL_arraysize(deviceExtensionNames);
+    deviceCreateInfo.ppEnabledExtensionNames = deviceExtensionNames;
+    result = vkCreateDevice(
+        vulkanContext.physicalDevice, &deviceCreateInfo, NULL, &vulkanContext.device);
+    if(result != VK_SUCCESS)
+    {
+        vulkanContext.device = VK_NULL_HANDLE;
+        SDL_LogError(
+            SDL_LOG_CATEGORY_APPLICATION, "vkCreateDevice(): %s\n", getVulkanResultString(result));
+        quit(2);
+    }
+}
+
+static void loadDeviceFunctions(void)
+{
+#define VULKAN_DEVICE_FUNCTION(name)                                         \
+    name = (PFN_##name)vkGetDeviceProcAddr(vulkanContext.device, #name);     \
+    if(!name)                                                                \
+    {                                                                        \
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,                           \
+                     "vkGetDeviceProcAddr(device, \"" #name "\") failed\n"); \
+        quit(2);                                                             \
+    }
+#define VULKAN_GLOBAL_FUNCTION(name)
+#define VULKAN_INSTANCE_FUNCTION(name)
+    VULKAN_FUNCTIONS()
+#undef VULKAN_DEVICE_FUNCTION
+#undef VULKAN_GLOBAL_FUNCTION
+#undef VULKAN_INSTANCE_FUNCTION
+}
+
+#undef VULKAN_FUNCTIONS
+
+static void getQueues(void)
+{
+    vkGetDeviceQueue(vulkanContext.device,
+                     vulkanContext.graphicsQueueFamilyIndex,
+                     0,
+                     &vulkanContext.graphicsQueue);
+    if(vulkanContext.graphicsQueueFamilyIndex != vulkanContext.presentQueueFamilyIndex)
+        vkGetDeviceQueue(vulkanContext.device,
+                         vulkanContext.presentQueueFamilyIndex,
+                         0,
+                         &vulkanContext.presentQueue);
+    else
+        vulkanContext.presentQueue = vulkanContext.graphicsQueue;
+}
+
+static void createSemaphore(VkSemaphore *semaphore)
+{
+	VkResult result;
+
+    VkSemaphoreCreateInfo createInfo = {0};
+    createInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
+    result = vkCreateSemaphore(vulkanContext.device, &createInfo, NULL, semaphore);
+    if(result != VK_SUCCESS)
+    {
+        *semaphore = VK_NULL_HANDLE;
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkCreateSemaphore(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+}
+
+static void createSemaphores(void)
+{
+    createSemaphore(&vulkanContext.imageAvailableSemaphore);
+    createSemaphore(&vulkanContext.renderingFinishedSemaphore);
+}
+
+static void getSurfaceCaps(void)
+{
+    VkResult result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
+        vulkanContext.physicalDevice, vulkanContext.surface, &vulkanContext.surfaceCapabilities);
+    if(result != VK_SUCCESS)
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkGetPhysicalDeviceSurfaceCapabilitiesKHR(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+
+    // check surface usage
+    if(!(vulkanContext.surfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT))
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "Vulkan surface doesn't support VK_IMAGE_USAGE_TRANSFER_DST_BIT\n");
+        quit(2);
+    }
+}
+
+static void getSurfaceFormats(void)
+{
+    VkResult result = vkGetPhysicalDeviceSurfaceFormatsKHR(vulkanContext.physicalDevice,
+                                                           vulkanContext.surface,
+                                                           &vulkanContext.surfaceFormatsCount,
+                                                           NULL);
+    if(result != VK_SUCCESS)
+    {
+        vulkanContext.surfaceFormatsCount = 0;
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkGetPhysicalDeviceSurfaceFormatsKHR(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+    if(vulkanContext.surfaceFormatsCount > vulkanContext.surfaceFormatsAllocatedCount)
+    {
+        vulkanContext.surfaceFormatsAllocatedCount = vulkanContext.surfaceFormatsCount;
+        SDL_free(vulkanContext.surfaceFormats);
+        vulkanContext.surfaceFormats =
+            SDL_malloc(sizeof(VkSurfaceFormatKHR) * vulkanContext.surfaceFormatsAllocatedCount);
+        if(!vulkanContext.surfaceFormats)
+        {
+            vulkanContext.surfaceFormatsCount = 0;
+            SDL_OutOfMemory();
+            quit(2);
+        }
+    }
+    result = vkGetPhysicalDeviceSurfaceFormatsKHR(vulkanContext.physicalDevice,
+                                                  vulkanContext.surface,
+                                                  &vulkanContext.surfaceFormatsCount,
+                                                  vulkanContext.surfaceFormats);
+    if(result != VK_SUCCESS)
+    {
+        vulkanContext.surfaceFormatsCount = 0;
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkGetPhysicalDeviceSurfaceFormatsKHR(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+}
+
+static void getSwapchainImages(void)
+{
+	VkResult result;
+
+    SDL_free(vulkanContext.swapchainImages);
+    vulkanContext.swapchainImages = NULL;
+    result = vkGetSwapchainImagesKHR(
+        vulkanContext.device, vulkanContext.swapchain, &vulkanContext.swapchainImageCount, NULL);
+    if(result != VK_SUCCESS)
+    {
+        vulkanContext.swapchainImageCount = 0;
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkGetSwapchainImagesKHR(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+    vulkanContext.swapchainImages = SDL_malloc(sizeof(VkImage) * vulkanContext.swapchainImageCount);
+    if(!vulkanContext.swapchainImages)
+    {
+        SDL_OutOfMemory();
+        quit(2);
+    }
+    result = vkGetSwapchainImagesKHR(vulkanContext.device,
+                                     vulkanContext.swapchain,
+                                     &vulkanContext.swapchainImageCount,
+                                     vulkanContext.swapchainImages);
+    if(result != VK_SUCCESS)
+    {
+        SDL_free(vulkanContext.swapchainImages);
+        vulkanContext.swapchainImages = NULL;
+        vulkanContext.swapchainImageCount = 0;
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkGetSwapchainImagesKHR(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+}
+
+static SDL_bool createSwapchain(void)
+{
+	uint32_t i;
+	int w, h;
+	VkSwapchainCreateInfoKHR createInfo = {0};
+	VkResult result;
+
+    // pick an image count
+    vulkanContext.swapchainDesiredImageCount = vulkanContext.surfaceCapabilities.minImageCount + 1;
+    if(vulkanContext.swapchainDesiredImageCount > vulkanContext.surfaceCapabilities.maxImageCount
+       && vulkanContext.surfaceCapabilities.maxImageCount > 0)
+        vulkanContext.swapchainDesiredImageCount = vulkanContext.surfaceCapabilities.maxImageCount;
+
+    // pick a format
+    if(vulkanContext.surfaceFormatsCount == 1
+       && vulkanContext.surfaceFormats[0].format == VK_FORMAT_UNDEFINED)
+    {
+        // aren't any preferred formats, so we pick
+        vulkanContext.surfaceFormat.colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
+        vulkanContext.surfaceFormat.format = VK_FORMAT_R8G8B8A8_UNORM;
+    }
+    else
+    {
+        vulkanContext.surfaceFormat = vulkanContext.surfaceFormats[0];
+        for(i = 0; i < vulkanContext.surfaceFormatsCount; i++)
+        {
+            if(vulkanContext.surfaceFormats[i].format == VK_FORMAT_R8G8B8A8_UNORM)
+            {
+                vulkanContext.surfaceFormat = vulkanContext.surfaceFormats[i];
+                break;
+            }
+        }
+    }
+
+    // get size
+    SDL_Vulkan_GetDrawableSize(state->windows[0], &w, &h);
+    vulkanContext.swapchainSize.width = w;
+    vulkanContext.swapchainSize.height = h;
+    if(w == 0 || h == 0)
+        return SDL_FALSE;
+
+    createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
+    createInfo.surface = vulkanContext.surface;
+    createInfo.minImageCount = vulkanContext.swapchainDesiredImageCount;
+    createInfo.imageFormat = vulkanContext.surfaceFormat.format;
+    createInfo.imageColorSpace = vulkanContext.surfaceFormat.colorSpace;
+    createInfo.imageExtent = vulkanContext.swapchainSize;
+    createInfo.imageArrayLayers = 1;
+    createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
+    createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
+    createInfo.preTransform = vulkanContext.surfaceCapabilities.currentTransform;
+    createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
+    createInfo.presentMode = VK_PRESENT_MODE_FIFO_KHR;
+    createInfo.clipped = VK_TRUE;
+    createInfo.oldSwapchain = vulkanContext.swapchain;
+    result =
+        vkCreateSwapchainKHR(vulkanContext.device, &createInfo, NULL, &vulkanContext.swapchain);
+    if(createInfo.oldSwapchain)
+        vkDestroySwapchainKHR(vulkanContext.device, createInfo.oldSwapchain, NULL);
+    if(result != VK_SUCCESS)
+    {
+        vulkanContext.swapchain = VK_NULL_HANDLE;
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkCreateSwapchainKHR(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+    getSwapchainImages();
+    return SDL_TRUE;
+}
+
+static void destroySwapchain(void)
+{
+    if(vulkanContext.swapchain)
+        vkDestroySwapchainKHR(vulkanContext.device, vulkanContext.swapchain, NULL);
+    vulkanContext.swapchain = VK_NULL_HANDLE;
+    SDL_free(vulkanContext.swapchainImages);
+    vulkanContext.swapchainImages = NULL;
+}
+
+static void destroyCommandBuffers(void)
+{
+    if(vulkanContext.commandBuffers)
+        vkFreeCommandBuffers(vulkanContext.device,
+                             vulkanContext.commandPool,
+                             vulkanContext.swapchainImageCount,
+                             vulkanContext.commandBuffers);
+    SDL_free(vulkanContext.commandBuffers);
+    vulkanContext.commandBuffers = NULL;
+}
+
+static void destroyCommandPool(void)
+{
+    if(vulkanContext.commandPool)
+        vkDestroyCommandPool(vulkanContext.device, vulkanContext.commandPool, NULL);
+    vulkanContext.commandPool = VK_NULL_HANDLE;
+}
+
+static void createCommandPool(void)
+{
+	VkResult result;
+
+    VkCommandPoolCreateInfo createInfo = {0};
+    createInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
+    createInfo.flags =
+        VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
+    createInfo.queueFamilyIndex = vulkanContext.graphicsQueueFamilyIndex;
+    result =
+        vkCreateCommandPool(vulkanContext.device, &createInfo, NULL, &vulkanContext.commandPool);
+    if(result != VK_SUCCESS)
+    {
+        vulkanContext.commandPool = VK_NULL_HANDLE;
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkCreateCommandPool(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+}
+
+static void createCommandBuffers(void)
+{
+	VkResult result;
+
+    VkCommandBufferAllocateInfo allocateInfo = {0};
+    allocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
+    allocateInfo.commandPool = vulkanContext.commandPool;
+    allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
+    allocateInfo.commandBufferCount = vulkanContext.swapchainImageCount;
+    vulkanContext.commandBuffers =
+        SDL_malloc(sizeof(VkCommandBuffer) * vulkanContext.swapchainImageCount);
+    result =
+        vkAllocateCommandBuffers(vulkanContext.device, &allocateInfo, vulkanContext.commandBuffers);
+    if(result != VK_SUCCESS)
+    {
+        SDL_free(vulkanContext.commandBuffers);
+        vulkanContext.commandBuffers = NULL;
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkAllocateCommandBuffers(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+}
+
+static void createFences(void)
+{
+	uint32_t i;
+
+    vulkanContext.fences = SDL_malloc(sizeof(VkFence) * vulkanContext.swapchainImageCount);
+    if(!vulkanContext.fences)
+    {
+        SDL_OutOfMemory();
+        quit(2);
+    }
+    for(i = 0; i < vulkanContext.swapchainImageCount; i++)
+    {
+		VkResult result;
+
+        VkFenceCreateInfo createInfo = {0};
+        createInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
+        createInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
+        result =
+            vkCreateFence(vulkanContext.device, &createInfo, NULL, &vulkanContext.fences[i]);
+        if(result != VK_SUCCESS)
+        {
+            for(; i > 0; i--)
+            {
+                vkDestroyFence(vulkanContext.device, vulkanContext.fences[i - 1], NULL);
+            }
+            SDL_free(vulkanContext.fences);
+            vulkanContext.fences = NULL;
+            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                         "vkCreateFence(): %s\n",
+                         getVulkanResultString(result));
+            quit(2);
+        }
+    }
+}
+
+static void destroyFences(void)
+{
+	uint32_t i;
+
+    if(!vulkanContext.fences)
+        return;
+    for(i = 0; i < vulkanContext.swapchainImageCount; i++)
+    {
+        vkDestroyFence(vulkanContext.device, vulkanContext.fences[i], NULL);
+    }
+    SDL_free(vulkanContext.fences);
+    vulkanContext.fences = NULL;
+}
+
+static void recordPipelineImageBarrier(VkCommandBuffer commandBuffer,
+                                       VkAccessFlags sourceAccessMask,
+                                       VkAccessFlags destAccessMask,
+                                       VkImageLayout sourceLayout,
+                                       VkImageLayout destLayout,
+                                       VkImage image)
+{
+    VkImageMemoryBarrier barrier = {0};
+    barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
+    barrier.srcAccessMask = sourceAccessMask;
+    barrier.dstAccessMask = destAccessMask;
+    barrier.oldLayout = sourceLayout;
+    barrier.newLayout = destLayout;
+    barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
+    barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
+    barrier.image = image;
+    barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
+    barrier.subresourceRange.baseMipLevel = 0;
+    barrier.subresourceRange.levelCount = 1;
+    barrier.subresourceRange.baseArrayLayer = 0;
+    barrier.subresourceRange.layerCount = 1;
+    vkCmdPipelineBarrier(commandBuffer,
+                         VK_PIPELINE_STAGE_TRANSFER_BIT,
+                         VK_PIPELINE_STAGE_TRANSFER_BIT,
+                         0,
+                         0,
+                         NULL,
+                         0,
+                         NULL,
+                         1,
+                         &barrier);
+}
+
+static void rerecordCommandBuffer(uint32_t frameIndex, const VkClearColorValue *clearColor)
+{
+    VkCommandBuffer commandBuffer = vulkanContext.commandBuffers[frameIndex];
+    VkImage image = vulkanContext.swapchainImages[frameIndex];
+	VkCommandBufferBeginInfo beginInfo = {0};
+    VkImageSubresourceRange clearRange = {0};
+
+    VkResult result = vkResetCommandBuffer(commandBuffer, 0);
+    if(result != VK_SUCCESS)
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkResetCommandBuffer(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+    beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
+    beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
+    result = vkBeginCommandBuffer(commandBuffer, &beginInfo);
+    if(result != VK_SUCCESS)
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkBeginCommandBuffer(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+    recordPipelineImageBarrier(commandBuffer,
+                               0,
+                               VK_ACCESS_TRANSFER_WRITE_BIT,
+                               VK_IMAGE_LAYOUT_UNDEFINED,
+                               VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
+                               image);
+    clearRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
+    clearRange.baseMipLevel = 0;
+    clearRange.levelCount = 1;
+    clearRange.baseArrayLayer = 0;
+    clearRange.layerCount = 1;
+    vkCmdClearColorImage(
+        commandBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, clearColor, 1, &clearRange);
+    recordPipelineImageBarrier(commandBuffer,
+                               VK_ACCESS_TRANSFER_WRITE_BIT,
+                               VK_ACCESS_MEMORY_READ_BIT,
+                               VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
+                               VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
+                               image);
+    result = vkEndCommandBuffer(commandBuffer);
+    if(result != VK_SUCCESS)
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkEndCommandBuffer(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+}
+
+static void destroySwapchainAndSwapchainSpecificStuff(SDL_bool doDestroySwapchain)
+{
+    destroyFences();
+    destroyCommandBuffers();
+    destroyCommandPool();
+    if(doDestroySwapchain)
+        destroySwapchain();
+}
+
+static SDL_bool createNewSwapchainAndSwapchainSpecificStuff(void)
+{
+    destroySwapchainAndSwapchainSpecificStuff(SDL_FALSE);
+    getSurfaceCaps();
+    getSurfaceFormats();
+    if(!createSwapchain())
+        return SDL_FALSE;
+    createCommandPool();
+    createCommandBuffers();
+    createFences();
+    return SDL_TRUE;
+}
+
+static void initVulkan(void)
+{
+    SDL_Vulkan_LoadLibrary(NULL);
+    SDL_memset(&vulkanContext, 0, sizeof(VulkanContext));
+    loadGlobalFunctions();
+    createInstance();
+    loadInstanceFunctions();
+    createSurface();
+    findPhysicalDevice();
+    createDevice();
+    loadDeviceFunctions();
+    getQueues();
+    createSemaphores();
+    createNewSwapchainAndSwapchainSpecificStuff();
+}
+
+static void shutdownVulkan(void)
+{
+    if(vulkanContext.device && vkDeviceWaitIdle)
+        vkDeviceWaitIdle(vulkanContext.device);
+    destroySwapchainAndSwapchainSpecificStuff(SDL_TRUE);
+    if(vulkanContext.imageAvailableSemaphore && vkDestroySemaphore)
+        vkDestroySemaphore(vulkanContext.device, vulkanContext.imageAvailableSemaphore, NULL);
+    if(vulkanContext.renderingFinishedSemaphore && vkDestroySemaphore)
+        vkDestroySemaphore(vulkanContext.device, vulkanContext.renderingFinishedSemaphore, NULL);
+    if(vulkanContext.device && vkDestroyDevice)
+        vkDestroyDevice(vulkanContext.device, NULL);
+    if(vulkanContext.surface && vkDestroySurfaceKHR)
+        vkDestroySurfaceKHR(vulkanContext.instance, vulkanContext.surface, NULL);
+    if(vulkanContext.instance && vkDestroyInstance)
+        vkDestroyInstance(vulkanContext.instance, NULL);
+    SDL_free(vulkanContext.surfaceFormats);
+    SDL_Vulkan_UnloadLibrary();
+}
+
+static SDL_bool render(void)
+{
+    uint32_t frameIndex;
+    VkResult result;
+    double currentTime;
+    VkClearColorValue clearColor = {0};
+    VkPipelineStageFlags waitDestStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
+    VkSubmitInfo submitInfo = {0};
+    VkPresentInfoKHR presentInfo = {0};
+    int w, h;
+
+    if(!vulkanContext.swapchain)
+    {
+        SDL_bool retval = createNewSwapchainAndSwapchainSpecificStuff();
+        if(!retval)
+            SDL_Delay(100);
+        return retval;
+    }
+    result = vkAcquireNextImageKHR(vulkanContext.device,
+                                            vulkanContext.swapchain,
+                                            UINT64_MAX,
+                                            vulkanContext.imageAvailableSemaphore,
+                                            VK_NULL_HANDLE,
+                                            &frameIndex);
+    if(result == VK_ERROR_OUT_OF_DATE_KHR)
+        return createNewSwapchainAndSwapchainSpecificStuff();
+    if(result != VK_SUBOPTIMAL_KHR && result != VK_SUCCESS)
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkAcquireNextImageKHR(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+    result = vkWaitForFences(
+        vulkanContext.device, 1, &vulkanContext.fences[frameIndex], VK_FALSE, UINT64_MAX);
+    if(result != VK_SUCCESS)
+    {
+        SDL_LogError(
+            SDL_LOG_CATEGORY_APPLICATION, "vkWaitForFences(): %s\n", getVulkanResultString(result));
+        quit(2);
+    }
+    result = vkResetFences(vulkanContext.device, 1, &vulkanContext.fences[frameIndex]);
+    if(result != VK_SUCCESS)
+    {
+        SDL_LogError(
+            SDL_LOG_CATEGORY_APPLICATION, "vkResetFences(): %s\n", getVulkanResultString(result));
+        quit(2);
+    }
+    currentTime = (double)SDL_GetPerformanceCounter() / SDL_GetPerformanceFrequency();
+    clearColor.float32[0] = (float)(0.5 + 0.5 * SDL_sin(currentTime));
+    clearColor.float32[1] = (float)(0.5 + 0.5 * SDL_sin(currentTime + M_PI * 2 / 3));
+    clearColor.float32[2] = (float)(0.5 + 0.5 * SDL_sin(currentTime + M_PI * 4 / 3));
+    clearColor.float32[3] = 1;
+    rerecordCommandBuffer(frameIndex, &clearColor);
+    submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
+    submitInfo.waitSemaphoreCount = 1;
+    submitInfo.pWaitSemaphores = &vulkanContext.imageAvailableSemaphore;
+    submitInfo.pWaitDstStageMask = &waitDestStageMask;
+    submitInfo.commandBufferCount = 1;
+    submitInfo.pCommandBuffers = &vulkanContext.commandBuffers[frameIndex];
+    submitInfo.signalSemaphoreCount = 1;
+    submitInfo.pSignalSemaphores = &vulkanContext.renderingFinishedSemaphore;
+    result = vkQueueSubmit(
+        vulkanContext.graphicsQueue, 1, &submitInfo, vulkanContext.fences[frameIndex]);
+    if(result != VK_SUCCESS)
+    {
+        SDL_LogError(
+            SDL_LOG_CATEGORY_APPLICATION, "vkQueueSubmit(): %s\n", getVulkanResultString(result));
+        quit(2);
+    }
+    presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
+    presentInfo.waitSemaphoreCount = 1;
+    presentInfo.pWaitSemaphores = &vulkanContext.renderingFinishedSemaphore;
+    presentInfo.swapchainCount = 1;
+    presentInfo.pSwapchains = &vulkanContext.swapchain;
+    presentInfo.pImageIndices = &frameIndex;
+    result = vkQueuePresentKHR(vulkanContext.presentQueue, &presentInfo);
+    if(result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR)
+    {
+        return createNewSwapchainAndSwapchainSpecificStuff();
+    }
+    if(result != VK_SUCCESS)
+    {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
+                     "vkQueuePresentKHR(): %s\n",
+                     getVulkanResultString(result));
+        quit(2);
+    }
+    SDL_Vulkan_GetDrawableSize(state->windows[0], &w, &h);
+    if(w != (int)vulkanContext.swapchainSize.width || h != (int)vulkanContext.swapchainSize.height)
+    {
+        return createNewSwapchainAndSwapchainSpecificStuff();
+    }
+    return SDL_TRUE;
+}
+
+int main(int argc, char *argv[])
+{
+    int fsaa, accel;
+    int i, done;
+    SDL_DisplayMode mode;
+    SDL_Event event;
+    Uint32 then, now, frames;
+    int dw, dh;
+
+    /* Enable standard application logging */
+    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
+
+    /* Initialize parameters */
+    fsaa = 0;
+    accel = -1;
+
+    /* Initialize test framework */
+    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
+    if(!state)
+    {
+        return 1;
+    }
+    for(i = 1; i < argc;)
+    {
+        int consumed;
+
+        consumed = SDLTest_CommonArg(state, i);
+        if(consumed < 0)
+        {
+            SDL_Log("Usage: %s %s\n", argv[0], SDLTest_CommonUsage(state));
+            quit(1);
+        }
+        i += consumed;
+    }
+
+    /* Set Vulkan parameters */
+    state->window_flags |= SDL_WINDOW_VULKAN;
+    state->num_windows = 1;
+    state->skip_renderer = 1;
+
+    if(!SDLTest_CommonInit(state))
+    {
+        quit(2);
+    }
+
+    SDL_GetCurrentDisplayMode(0, &mode);
+    SDL_Log("Screen BPP    : %d\n", SDL_BITSPERPIXEL(mode.format));
+    SDL_GetWindowSize(state->windows[0], &dw, &dh);
+    SDL_Log("Window Size   : %d,%d\n", dw, dh);
+    SDL_Vulkan_GetDrawableSize(state->windows[0], &dw, &dh);
+    SDL_Log("Draw Size     : %d,%d\n", dw, dh);
+    SDL_Log("\n");
+
+    initVulkan();
+
+    /* Main render loop */
+    frames = 0;
+    then = SDL_GetTicks();
+    done = 0;
+    while(!done)
+    {
+        /* Check for events */
+        ++frames;
+        while(SDL_PollEvent(&event))
+        {
+            SDLTest_CommonEvent(state, &event, &done);
+        }
+
+        if(!done)
+            render();
+    }
+
+    /* Print out some timing information */
+    now = SDL_GetTicks();
+    if(now > then)
+    {
+        SDL_Log("%2.2f frames per second\n", ((double)frames * 1000) / (now - then));
+    }
+    quit(0);
+    return 0;
+}
+
+#endif
diff --git a/test/testwm2.c b/test/testwm2.c
index cd19e9f..ab3eea2 100644
--- a/test/testwm2.c
+++ b/test/testwm2.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
diff --git a/test/torturethread.c b/test/torturethread.c
index 6b98a0a..4c2679b 100644
--- a/test/torturethread.c
+++ b/test/torturethread.c
@@ -1,5 +1,5 @@
 /*
-  Copyright (C) 1997-2016 Sam Lantinga <slouken at libsdl.org>
+  Copyright (C) 1997-2017 Sam Lantinga <slouken at libsdl.org>
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-sdl/packages/libsdl2.git



More information about the pkg-sdl-commits mailing list