diff -Nru nestopia-1.48/appveyor.yml nestopia-1.49/appveyor.yml --- nestopia-1.48/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/appveyor.yml 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,33 @@ +version: 0.1.{build} + +shallow_clone: true + +image: Visual Studio 2017 + +environment: + makefile_location: libretro + makefile_name: makefile + target_name: nestopia + +configuration: + - release + +platform: + - windows_msvc2017_uwp_x64 + - windows_msvc2017_uwp_x86 + - windows_msvc2017_uwp_arm + - windows_msvc2017_desktop_x64 + - windows_msvc2017_desktop_x86 + +init: + - set Path=C:\msys64\usr\bin;%Path% + +build_script: + - cd %makefile_location% + - make -f %makefile_name% platform=%platform% + +artifacts: + - path: '**\%target_name%*.dll' + - path: '**\%target_name%*.lib' + - path: '**\%target_name%*.pdb' + - path: '**\libretro.h' \ No newline at end of file diff -Nru nestopia-1.48/ChangeLog nestopia-1.49/ChangeLog --- nestopia-1.48/ChangeLog 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/ChangeLog 2018-06-24 23:26:58.000000000 +0000 @@ -1,4 +1,58 @@ ---------------------------------------------------------------- +1.49 +---------------------------------------------------------------- +Shell: + + Additions: + - Added more palettes to extras + - Game-specific custom palettes + - Scale factors up to 8x + - Added option to enable overclocking + - Added rewind controls to gamepad + - Famicom Mic support + - Optional JACK Audio support (McKayJT) + - Added .wav sample loading + + + Changes: + - Separated GTK+ and SDL input settings + - Removed deprecated functions from UI + - Use GTK+ OpenGL widget for GUI (Wayland support) + - Reworked Alternate Speed/Fast-Forward + - Allow mapping more than 9 joysticks (Lou-Cipher) + - Restructured build system, separated SDL and GTK builds + - Cursor options split int normal and special cursor options + + Fixes: + - Fixed automatic ROM patching, improved patching function (hugoarpin) + +libretro: + + Additions: + - Add support for multiline cheats and raw cheats (iLag) + - Add adapter autoselect using NstDatabase.xml (hunterk) + - Famicom Mic support + - Cheevos ram access support (meepingsnesroms) + - Add .wav sample loading + + Fixes: + - Fixed heap corruption bug with crosshair (Arto Vainiolehto) + - Fixed black screen when non-existent custom palette is selected + - Fixed crosshair and overscan with blargg filter + +Core: + + Additions: + - Added support for overclocking (meepingsnesroms) + + Fixes: + - Fixed NSF and FDS in Dendy mode (Eugene.S) + - Fixed coding mistake in PPU (zeromus) + - Modified submappers for VRC2/VRC4 games (GeneralFailer) + - Fixed compilation error in SetRamPowerState (Arto Vainiolehto) + - Fix for McAcc games (joepogo) + +---------------------------------------------------------------- 1.48 ---------------------------------------------------------------- Shell: @@ -25,7 +79,6 @@ Additions: - Added ability to load custom palettes - - Added turbo buttons - Added many palettes (Monroe88) - Added monochrome blargg NTSC filter (dalter) - Added Turbo A/B buttons diff -Nru nestopia-1.48/CMakeLists.txt nestopia-1.49/CMakeLists.txt --- nestopia-1.48/CMakeLists.txt 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/CMakeLists.txt 1970-01-01 00:00:00.000000000 +0000 @@ -1,433 +0,0 @@ -# set project name -project( nestopia ) -set( nestopia_VERSION 1.48-WIP ) - -# CMake requirements -# 3.1 is required for target_sources() -cmake_minimum_required( VERSION 3.1 ) - -# on macOS, MACOSX_RPATH is enabled by default on more recent versions -# of CMake. Disable this behaviour, and let user enable it if need be. -cmake_policy( SET CMP0042 OLD ) - -# Set Release type for builds where CMAKE_BUILD_TYPE is unset. -# This is usually a good default as this implictly enables -# -# CXXFLAGS = -O3 -DNDEBUG -# -if( NOT CMAKE_BUILD_TYPE ) - set( CMAKE_BUILD_TYPE "Release" ) -endif() - -# Adhere to GNU filesystem layout conventions -include( GNUInstallDirs ) - -add_executable( nestopia - # Core - source/core/NstApu.cpp - source/core/NstAssert.cpp - source/core/NstCartridge.cpp - source/core/NstCartridgeInes.cpp - source/core/NstCartridgeRomset.cpp - source/core/NstCartridgeUnif.cpp - source/core/NstCheats.cpp - source/core/NstChecksum.cpp - source/core/NstChips.cpp - source/core/NstCore.cpp - source/core/NstCpu.cpp - source/core/NstCrc32.cpp - source/core/NstFds.cpp - source/core/NstFile.cpp - source/core/NstImage.cpp - source/core/NstImageDatabase.cpp - source/core/NstLog.cpp - source/core/NstMachine.cpp - source/core/NstMemory.cpp - source/core/NstNsf.cpp - source/core/NstPatcher.cpp - source/core/NstPatcherIps.cpp - source/core/NstPatcherUps.cpp - source/core/NstPins.cpp - source/core/NstPpu.cpp - source/core/NstProperties.cpp - source/core/NstRam.cpp - source/core/NstSha1.cpp - source/core/NstSoundPcm.cpp - source/core/NstSoundPlayer.cpp - source/core/NstSoundRenderer.cpp - source/core/NstState.cpp - source/core/NstStream.cpp - source/core/NstTracker.cpp - source/core/NstTrackerMovie.cpp - source/core/NstTrackerRewinder.cpp - source/core/NstVector.cpp - source/core/NstVideoFilter2xSaI.cpp - source/core/NstVideoFilterHqX.cpp - source/core/NstVideoFilterNone.cpp - source/core/NstVideoFilterNtsc.cpp - source/core/NstVideoFilterNtscCfg.cpp - source/core/NstVideoFilterScaleX.cpp - source/core/NstVideoFilterxBR.cpp - source/core/NstVideoRenderer.cpp - source/core/NstVideoScreen.cpp - source/core/NstXml.cpp - source/core/NstZlib.cpp - # API - source/core/api/NstApiBarcodeReader.cpp - source/core/api/NstApiCartridge.cpp - source/core/api/NstApiCheats.cpp - source/core/api/NstApiDipSwitches.cpp - source/core/api/NstApiEmulator.cpp - source/core/api/NstApiFds.cpp - source/core/api/NstApiInput.cpp - source/core/api/NstApiMachine.cpp - source/core/api/NstApiMovie.cpp - source/core/api/NstApiNsf.cpp - source/core/api/NstApiRewinder.cpp - source/core/api/NstApiSound.cpp - source/core/api/NstApiTapeRecorder.cpp - source/core/api/NstApiUser.cpp - source/core/api/NstApiVideo.cpp - # Board - source/core/board/NstBoardAcclaimMcAcc.cpp - source/core/board/NstBoardAe.cpp - source/core/board/NstBoardAgci.cpp - source/core/board/NstBoardAveD1012.cpp - source/core/board/NstBoardAveNina.cpp - source/core/board/NstBoardAxRom.cpp - source/core/board/NstBoardBandai24c0x.cpp - source/core/board/NstBoardBandaiAerobicsStudio.cpp - source/core/board/NstBoardBandaiDatach.cpp - source/core/board/NstBoardBandaiKaraokeStudio.cpp - source/core/board/NstBoardBandaiLz93d50.cpp - source/core/board/NstBoardBandaiLz93d50ex.cpp - source/core/board/NstBoardBandaiOekaKids.cpp - source/core/board/NstBoardBenshengBs5.cpp - source/core/board/NstBoardBmc110in1.cpp - source/core/board/NstBoardBmc1200in1.cpp - source/core/board/NstBoardBmc150in1.cpp - source/core/board/NstBoardBmc15in1.cpp - source/core/board/NstBoardBmc20in1.cpp - source/core/board/NstBoardBmc21in1.cpp - source/core/board/NstBoardBmc22Games.cpp - source/core/board/NstBoardBmc31in1.cpp - source/core/board/NstBoardBmc35in1.cpp - source/core/board/NstBoardBmc36in1.cpp - source/core/board/NstBoardBmc64in1.cpp - source/core/board/NstBoardBmc72in1.cpp - source/core/board/NstBoardBmc76in1.cpp - source/core/board/NstBoardBmc800in1.cpp - source/core/board/NstBoardBmc8157.cpp - source/core/board/NstBoardBmc9999999in1.cpp - source/core/board/NstBoardBmcA65as.cpp - source/core/board/NstBoardBmcBallgames11in1.cpp - source/core/board/NstBoardBmcCh001.cpp - source/core/board/NstBoardBmcCtc65.cpp - source/core/board/NstBoardBmcFamily4646B.cpp - source/core/board/NstBoardBmcFk23c.cpp - source/core/board/NstBoardBmcGamestarA.cpp - source/core/board/NstBoardBmcGamestarB.cpp - source/core/board/NstBoardBmcGolden190in1.cpp - source/core/board/NstBoardBmcGoldenCard6in1.cpp - source/core/board/NstBoardBmcGoldenGame260in1.cpp - source/core/board/NstBoardBmcHero.cpp - source/core/board/NstBoardBmcMarioParty7in1.cpp - source/core/board/NstBoardBmcNovelDiamond.cpp - source/core/board/NstBoardBmcPowerjoy84in1.cpp - source/core/board/NstBoardBmcResetBased4in1.cpp - source/core/board/NstBoardBmcSuper22Games.cpp - source/core/board/NstBoardBmcSuper24in1.cpp - source/core/board/NstBoardBmcSuper40in1.cpp - source/core/board/NstBoardBmcSuper700in1.cpp - source/core/board/NstBoardBmcSuperBig7in1.cpp - source/core/board/NstBoardBmcSuperGun20in1.cpp - source/core/board/NstBoardBmcSuperHiK300in1.cpp - source/core/board/NstBoardBmcSuperHiK4in1.cpp - source/core/board/NstBoardBmcSuperVision16in1.cpp - source/core/board/NstBoardBmcT262.cpp - source/core/board/NstBoardBmcVrc4.cpp - source/core/board/NstBoardBmcVt5201.cpp - source/core/board/NstBoardBmcY2k64in1.cpp - source/core/board/NstBoardBtl2708.cpp - source/core/board/NstBoardBtl6035052.cpp - source/core/board/NstBoardBtlAx5705.cpp - source/core/board/NstBoardBtlDragonNinja.cpp - source/core/board/NstBoardBtlGeniusMerioBros.cpp - source/core/board/NstBoardBtlMarioBaby.cpp - source/core/board/NstBoardBtlPikachuY2k.cpp - source/core/board/NstBoardBtlShuiGuanPipe.cpp - source/core/board/NstBoardBtlSmb2a.cpp - source/core/board/NstBoardBtlSmb2b.cpp - source/core/board/NstBoardBtlSmb2c.cpp - source/core/board/NstBoardBtlSmb3.cpp - source/core/board/NstBoardBtlSuperBros11.cpp - source/core/board/NstBoardBtlT230.cpp - source/core/board/NstBoardBtlTobidaseDaisakusen.cpp - source/core/board/NstBoardBxRom.cpp - source/core/board/NstBoardCaltron.cpp - source/core/board/NstBoardCamerica.cpp - source/core/board/NstBoardCneDecathlon.cpp - source/core/board/NstBoardCnePsb.cpp - source/core/board/NstBoardCneShlz.cpp - source/core/board/NstBoardCony.cpp - source/core/board/NstBoard.cpp - source/core/board/NstBoardCxRom.cpp - source/core/board/NstBoardDiscrete.cpp - source/core/board/NstBoardDreamtech.cpp - source/core/board/NstBoardEvent.cpp - source/core/board/NstBoardFb.cpp - source/core/board/NstBoardFfe.cpp - source/core/board/NstBoardFujiya.cpp - source/core/board/NstBoardFukutake.cpp - source/core/board/NstBoardFutureMedia.cpp - source/core/board/NstBoardGouder.cpp - source/core/board/NstBoardGxRom.cpp - source/core/board/NstBoardHenggedianzi.cpp - source/core/board/NstBoardHes.cpp - source/core/board/NstBoardHosenkan.cpp - source/core/board/NstBoardIremG101.cpp - source/core/board/NstBoardIremH3001.cpp - source/core/board/NstBoardIremHolyDiver.cpp - source/core/board/NstBoardIremKaiketsu.cpp - source/core/board/NstBoardIremLrog017.cpp - source/core/board/NstBoardJalecoJf11.cpp - source/core/board/NstBoardJalecoJf13.cpp - source/core/board/NstBoardJalecoJf16.cpp - source/core/board/NstBoardJalecoJf17.cpp - source/core/board/NstBoardJalecoJf19.cpp - source/core/board/NstBoardJalecoSs88006.cpp - source/core/board/NstBoardJyCompany.cpp - source/core/board/NstBoardKaiser.cpp - source/core/board/NstBoardKasing.cpp - source/core/board/NstBoardKayH2288.cpp - source/core/board/NstBoardKayPandaPrince.cpp - source/core/board/NstBoardKonamiVrc1.cpp - source/core/board/NstBoardKonamiVrc2.cpp - source/core/board/NstBoardKonamiVrc3.cpp - source/core/board/NstBoardKonamiVrc4.cpp - source/core/board/NstBoardKonamiVrc6.cpp - source/core/board/NstBoardKonamiVrc7.cpp - source/core/board/NstBoardKonamiVsSystem.cpp - source/core/board/NstBoardMagicSeries.cpp - source/core/board/NstBoardMmc1.cpp - source/core/board/NstBoardMmc2.cpp - source/core/board/NstBoardMmc3.cpp - source/core/board/NstBoardMmc4.cpp - source/core/board/NstBoardMmc5.cpp - source/core/board/NstBoardMmc6.cpp - source/core/board/NstBoardNamcot163.cpp - source/core/board/NstBoardNamcot175.cpp - source/core/board/NstBoardNamcot34xx.cpp - source/core/board/NstBoardNanjing.cpp - source/core/board/NstBoardNihon.cpp - source/core/board/NstBoardNitra.cpp - source/core/board/NstBoardNtdec.cpp - source/core/board/NstBoardOpenCorp.cpp - source/core/board/NstBoardQj.cpp - source/core/board/NstBoardRcm.cpp - source/core/board/NstBoardRexSoftDb5z.cpp - source/core/board/NstBoardRexSoftSl1632.cpp - source/core/board/NstBoardRumbleStation.cpp - source/core/board/NstBoardSachen74x374.cpp - source/core/board/NstBoardSachenS8259.cpp - source/core/board/NstBoardSachenSa0036.cpp - source/core/board/NstBoardSachenSa0037.cpp - source/core/board/NstBoardSachenSa72007.cpp - source/core/board/NstBoardSachenSa72008.cpp - source/core/board/NstBoardSachenStreetHeroes.cpp - source/core/board/NstBoardSachenTca01.cpp - source/core/board/NstBoardSachenTcu.cpp - source/core/board/NstBoardSomeriTeamSl12.cpp - source/core/board/NstBoardSubor.cpp - source/core/board/NstBoardSunsoft1.cpp - source/core/board/NstBoardSunsoft2.cpp - source/core/board/NstBoardSunsoft3.cpp - source/core/board/NstBoardSunsoft4.cpp - source/core/board/NstBoardSunsoft5b.cpp - source/core/board/NstBoardSunsoftDcs.cpp - source/core/board/NstBoardSunsoftFme7.cpp - source/core/board/NstBoardSuperGameBoogerman.cpp - source/core/board/NstBoardSuperGameLionKing.cpp - source/core/board/NstBoardSuperGamePocahontas2.cpp - source/core/board/NstBoardTaitoTc0190fmc.cpp - source/core/board/NstBoardTaitoTc0190fmcPal16r4.cpp - source/core/board/NstBoardTaitoX1005.cpp - source/core/board/NstBoardTaitoX1017.cpp - source/core/board/NstBoardTengen.cpp - source/core/board/NstBoardTengenRambo1.cpp - source/core/board/NstBoardTxc.cpp - source/core/board/NstBoardTxcMxmdhtwo.cpp - source/core/board/NstBoardTxcPoliceman.cpp - source/core/board/NstBoardTxcTw.cpp - source/core/board/NstBoardTxRom.cpp - source/core/board/NstBoardUnlA9746.cpp - source/core/board/NstBoardUnlCc21.cpp - source/core/board/NstBoardUnlEdu2000.cpp - source/core/board/NstBoardUnlKingOfFighters96.cpp - source/core/board/NstBoardUnlKingOfFighters97.cpp - source/core/board/NstBoardUnlMortalKombat2.cpp - source/core/board/NstBoardUnlN625092.cpp - source/core/board/NstBoardUnlSuperFighter3.cpp - source/core/board/NstBoardUnlTf1201.cpp - source/core/board/NstBoardUnlWorldHero.cpp - source/core/board/NstBoardUnlXzy.cpp - source/core/board/NstBoardUxRom.cpp - source/core/board/NstBoardVsSystem.cpp - source/core/board/NstBoardWaixing.cpp - source/core/board/NstBoardWaixingFfv.cpp - source/core/board/NstBoardWaixingPs2.cpp - source/core/board/NstBoardWaixingSecurity.cpp - source/core/board/NstBoardWaixingSgz.cpp - source/core/board/NstBoardWaixingSgzlz.cpp - source/core/board/NstBoardWaixingSh2.cpp - source/core/board/NstBoardWaixingZs.cpp - source/core/board/NstBoardWhirlwind.cpp - source/core/board/NstBoardZz.cpp - # Input - source/core/input/NstInpAdapter.cpp - source/core/input/NstInpBandaiHyperShot.cpp - source/core/input/NstInpBarcodeWorld.cpp - source/core/input/NstInpCrazyClimber.cpp - source/core/input/NstInpDoremikkoKeyboard.cpp - source/core/input/NstInpExcitingBoxing.cpp - source/core/input/NstInpFamilyKeyboard.cpp - source/core/input/NstInpFamilyTrainer.cpp - source/core/input/NstInpHoriTrack.cpp - source/core/input/NstInpKonamiHyperShot.cpp - source/core/input/NstInpMahjong.cpp - source/core/input/NstInpMouse.cpp - source/core/input/NstInpOekaKidsTablet.cpp - source/core/input/NstInpPachinko.cpp - source/core/input/NstInpPad.cpp - source/core/input/NstInpPaddle.cpp - source/core/input/NstInpPartyTap.cpp - source/core/input/NstInpPokkunMoguraa.cpp - source/core/input/NstInpPowerGlove.cpp - source/core/input/NstInpPowerPad.cpp - source/core/input/NstInpRob.cpp - source/core/input/NstInpSuborKeyboard.cpp - source/core/input/NstInpTopRider.cpp - source/core/input/NstInpTurboFile.cpp - source/core/input/NstInpZapper.cpp - # VS System - source/core/vssystem/NstVsRbiBaseball.cpp - source/core/vssystem/NstVsSuperXevious.cpp - source/core/vssystem/NstVsSystem.cpp - source/core/vssystem/NstVsTkoBoxing.cpp - # Interface - source/unix/main.cpp - source/unix/cli.cpp - source/unix/audio.cpp - source/unix/video.cpp - source/unix/input.cpp - source/unix/config.cpp - source/unix/cheats.cpp - source/unix/cursor.cpp - source/unix/ini.cpp - source/unix/png.cpp -) - -# check whether compiler accepts -Wno-narrowing -# in order to silence C++11/14 narrowing warnings -include( CheckCXXCompilerFlag ) -check_cxx_compiler_flag( -Wno-narrowing HAS_NO_NARROWING ) -if ( HAS_NO_NARROWING ) - target_compile_options( nestopia PRIVATE -Wno-narrowing ) -endif() - -target_compile_definitions( nestopia PRIVATE -DDATADIR=\"${CMAKE_INSTALL_FULL_DATADIR}/nestopia\" -DDATAROOTDIR=\"${CMAKE_INSTALL_FULL_DATAROOTDIR}\" -DNST_PRAGMA_ONCE ) -target_include_directories( nestopia PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/source ) - -# pkg-config for a number of libraries -find_package( PkgConfig REQUIRED ) - -# zlib -find_package( ZLIB REQUIRED ) -target_include_directories( nestopia PRIVATE ${ZLIB_INCLUDE_DIRS} ) -target_link_libraries( nestopia ${ZLIB_LIBRARIES} ) - -# libarchive -find_package( LibArchive REQUIRED ) -target_include_directories( nestopia PRIVATE ${LibArchive_INCLUDE_DIRS} ) -target_link_libraries( nestopia ${LibArchive_LIBRARIES} ) - -# libao -pkg_check_modules( LibAO REQUIRED ao ) -target_include_directories( nestopia PRIVATE ${LibAO_INCLUDE_DIRS} ) -target_link_libraries( nestopia ${LibAO_LIBRARIES} ) - -# SDL2 -pkg_check_modules( SDL2 REQUIRED sdl2 ) -target_include_directories( nestopia PRIVATE ${SDL2_INCLUDE_DIRS} ) -target_link_libraries( nestopia ${SDL2_LIBRARIES} ) - -# LibEpoxy -pkg_check_modules( LibEpoxy REQUIRED epoxy ) -target_include_directories( nestopia PRIVATE ${LibEpoxy_INCLUDE_DIRS} ) -target_link_libraries( nestopia ${LibEpoxy_LIBRARIES} ) - -if( MINGW ) - # Building for MinGW - target_compile_definitions( nestopia PRIVATE -D_MINGW ) - -elseif( APPLE ) - # Building on macOS - target_compile_definitions( nestopia PRIVATE -D_APPLE ) - -elseif( UNIX ) - # most likely, building on Unix - # GTK+3 - option( ENABLE_GTK "Build GTK+3 based UI" ON ) - if( ENABLE_GTK ) - # GTK+3 - # compile options - target_compile_definitions( nestopia PRIVATE -D_GTK ) - - pkg_check_modules( GTK3 REQUIRED gtk+-3.0 ) - target_include_directories( nestopia PRIVATE ${GTK3_INCLUDE_DIRS} ) - target_link_libraries( nestopia ${GTK3_LIBRARIES} ) - - # check whether compiler accepts -Wno-deprecated-declarations - # in order to silence GTK+3 deprecation warnings - check_cxx_compiler_flag( -Wno-deprecated-declarations HAS_NO_DEPRECATED_DECLARATIONS ) - if ( HAS_NO_DEPRECATED_DECLARATIONS ) - target_compile_options( nestopia PRIVATE -Wno-deprecated-declarations ) - endif() - - # GTK+3 GUI files - target_sources( nestopia PRIVATE - source/unix/gtkui/gtkui.cpp - source/unix/gtkui/gtkui_archive.cpp - source/unix/gtkui/gtkui_callbacks.cpp - source/unix/gtkui/gtkui_cheats.cpp - source/unix/gtkui/gtkui_config.cpp - source/unix/gtkui/gtkui_dialogs.cpp - ) - endif() -endif() - -################ -# Installation # -################ -# program-specific files -install( TARGETS nestopia DESTINATION ${CMAKE_INSTALL_BINDIR} ) -install( FILES NstDatabase.xml DESTINATION ${CMAKE_INSTALL_DATADIR}/nestopia ) - -# freedesktop.org-specific files -install( FILES source/unix/icons/nestopia.desktop DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/applications ) -install( FILES source/unix/icons/32/nestopia.png DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/32x32/apps ) -install( FILES source/unix/icons/48/nestopia.png DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/48x48/apps ) -install( FILES source/unix/icons/64/nestopia.png DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/64x64/apps ) -install( FILES source/unix/icons/96/nestopia.png DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/96x96/apps ) -install( FILES source/unix/icons/128/nestopia.png DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/128x128/apps ) -install( FILES source/unix/icons/svg/nestopia.svg DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/scalable/apps ) -install( FILES source/unix/icons/svg/nespad.svg DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/scalable/apps ) - -# documentation -install( FILES AUTHORS ChangeLog README.md README.unix DESTINATION ${CMAKE_INSTALL_DOCDIR} ) -install( FILES readme.html DESTINATION ${CMAKE_INSTALL_DOCDIR}/html ) - -option( ENABLE_DOC "Install full documentation suite" ) -if( ENABLE_DOC ) - install( DIRECTORY doc/ DESTINATION ${CMAKE_INSTALL_DOCDIR}/html ) -endif() diff -Nru nestopia-1.48/configure.ac nestopia-1.49/configure.ac --- nestopia-1.48/configure.ac 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/configure.ac 2018-06-24 23:26:58.000000000 +0000 @@ -2,8 +2,8 @@ AC_PREREQ([2.69]) AC_INIT( [nestopia], - [1.48]) -AC_CONFIG_SRCDIR([source/unix/main.cpp]) + [1.49]) +AC_CONFIG_SRCDIR([source]) AC_LANG([C++]) @@ -51,7 +51,7 @@ dnl ================================== AS_IF([test "x${enable_flags_setting}" = "xyes" && test "x${enable_debug}" = "xno"], [ - AX_APPEND_COMPILE_FLAGS([${cxxflags_test} -Wno-narrowing -Wno-deprecated-declarations], [CXXFLAGS]) + AX_APPEND_COMPILE_FLAGS([${cxxflags_test} -Wno-narrowing], [CXXFLAGS]) CXXFLAGS=$( echo ${CXXFLAGS} | $SED -e 's/^ *//' -e 's/ *$//' ) AX_APPEND_COMPILE_FLAGS([${cppflags_test}], [CPPFLAGS]) @@ -73,24 +73,38 @@ dnl libarchive PKG_CHECK_MODULES([LIBARCHIVE], [libarchive]) -dnl libao -PKG_CHECK_MODULES([LIBAO], [ao]) - dnl SDL2 PKG_CHECK_MODULES([SDL2], [sdl2]) dnl LibEpoxy PKG_CHECK_MODULES([LIBEPOXY], [epoxy]) +dnl libao +AC_ARG_WITH([ao], + AS_HELP_STRING([--with-ao], [Build with libao audio support])) +AS_IF([test "x$with_ao" = "xyes"], [ + PKG_CHECK_MODULES([LIBAO],[ao]) +]) +AM_CONDITIONAL([ENABLE_LIBAO], [test "x$with_ao" = "xyes"]) + +dnl JACK audio +AC_ARG_WITH([jack], + AS_HELP_STRING([--with-jack], [Build with JACK audio support])) + +AS_IF([test "x$with_jack" = "xyes"], [ + PKG_CHECK_MODULES([JACK],[jack]) +]) +AM_CONDITIONAL([ENABLE_JACK], [test "x$with_jack" = "xyes"]) + dnl GTK3 AC_ARG_ENABLE([gui], - AS_HELP_STRING([--disable-gui], [Disable building GUI with GTK+3])) + AS_HELP_STRING([--enable-gui], [Enable building GUI with GTK+3])) -AS_IF([test "x$enable_gui" != "xno"], [ +AS_IF([test "x$enable_gui" = "xyes"], [ dnl GUI with GTK+3 requested PKG_CHECK_MODULES([GTK3], [gtk+-3.0]) ]) -AM_CONDITIONAL([ENABLE_GUI], [test "x$enable_gui" != "xno"]) +AM_CONDITIONAL([ENABLE_GUI], [test "x$enable_gui" = "xyes"]) dnl full HTML suite AC_ARG_ENABLE([doc], diff -Nru nestopia-1.48/debian/changelog nestopia-1.49/debian/changelog --- nestopia-1.48/debian/changelog 2018-05-14 12:25:46.000000000 +0000 +++ nestopia-1.49/debian/changelog 2018-06-28 06:49:22.000000000 +0000 @@ -1,3 +1,11 @@ +nestopia (1.49-1) unstable; urgency=medium + + * New upstream release, switching back to Autoconf and merging all + patches. + * Enable JACK support. + + -- Stephen Kitt Thu, 28 Jun 2018 08:49:22 +0200 + nestopia (1.48-3) unstable; urgency=medium * Add missing build-dependency on autoconf-archive. diff -Nru nestopia-1.48/debian/control nestopia-1.49/debian/control --- nestopia-1.48/debian/control 2018-05-14 11:48:16.000000000 +0000 +++ nestopia-1.49/debian/control 2018-06-28 06:48:44.000000000 +0000 @@ -5,13 +5,13 @@ Section: games Priority: optional Build-Depends: autoconf-archive, - cmake, debhelper (>= 11~), dh-exec, libao-dev, libarchive-dev, libglew-dev, libgtk-3-dev, + libjack-dev, libsdl2-dev Standards-Version: 4.1.4 Vcs-Browser: https://salsa.debian.org/games-team/nestopia diff -Nru nestopia-1.48/debian/copyright nestopia-1.49/debian/copyright --- nestopia-1.48/debian/copyright 2017-09-09 09:38:10.000000000 +0000 +++ nestopia-1.49/debian/copyright 2018-06-28 06:46:28.000000000 +0000 @@ -4,17 +4,26 @@ Files: * Copyright: 2003-2008 Martin Freij - 2012-2017 R. Danbrook + 2007-2008 R. Belmont + 2012-2018 R. Danbrook License: GPL-2.0+ -Files: libretro/libretro.h -Copyright: 2010-2014 The RetroArch team -License: Expat - -Files: libretro/msvc/msvc-2003-xbox1/stdint.h +Files: libretro/libretro-common/include/compat/msvc/stdint.h Copyright: 2006-2008 Alexander Chemeris License: BSD-3-clause +Files: libretro/libretro-common/include/libretro.h +Copyright: 2010-2017 The RetroArch team +License: Expat + +Files: source/common/ini.* +Copyright: 2009 Brush Technology +License: BSD-3-clause-Brush-Technology + +Files: source/common/png.* +Copyright: 2005-2015 Lode Vandevenne +License: Zlib + Files: source/core/NstVideoFilterxBR.cpp Copyright: 2011, 2012 Hyllian/Jararaca License: GPL-2.0+ @@ -23,20 +32,8 @@ Copyright: 2006-2007 Shay Green License: LGPL-2.1+ -Files: source/unix/* -Copyright: 2008 R. Belmont -License: GPL-2.0+ - -Files: source/unix/ini.* -Copyright: 2009 Brush Technology -License: BSD-3-clause-Brush-Technology - -Files: source/unix/png.* -Copyright: 2005-2015 Lode Vandevenne -License: Zlib - Files: debian/* -Copyright: 2011-2017 Stephen Kitt +Copyright: 2011-2018 Stephen Kitt License: GPL-2.0+ Files: debian/libretro-nestopia.metainfo.xml diff -Nru nestopia-1.48/debian/nestopia.docs nestopia-1.49/debian/nestopia.docs --- nestopia-1.48/debian/nestopia.docs 2017-09-08 20:48:52.000000000 +0000 +++ nestopia-1.49/debian/nestopia.docs 2018-06-28 06:33:28.000000000 +0000 @@ -1,3 +1,2 @@ readme.html README.md -README.unix diff -Nru nestopia-1.48/debian/patches/libretro-cppflags.patch nestopia-1.49/debian/patches/libretro-cppflags.patch --- nestopia-1.48/debian/patches/libretro-cppflags.patch 2017-09-09 09:47:50.000000000 +0000 +++ nestopia-1.49/debian/patches/libretro-cppflags.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -Description: Apply CPPFLAGS when building libretro -Author: Stephen Kitt - ---- a/libretro/Makefile -+++ b/libretro/Makefile -@@ -300,10 +300,10 @@ - endif - - %.o: %.cpp -- $(CXX) -c -o $@ $< $(CXXFLAGS) $(INCDIRS) -+ $(CXX) $(CPPFLAGS) -c -o $@ $< $(CXXFLAGS) $(INCDIRS) - - %.o: %.c -- $(CC) -c -o $@ $< $(CFLAGS) $(INCDIRS) -+ $(CC) $(CPPFLAGS) -c -o $@ $< $(CFLAGS) $(INCDIRS) - - clean-objs: - rm -f $(OBJS) diff -Nru nestopia-1.48/debian/patches/libretro_version.patch nestopia-1.49/debian/patches/libretro_version.patch --- nestopia-1.48/debian/patches/libretro_version.patch 2017-09-08 19:29:45.000000000 +0000 +++ nestopia-1.49/debian/patches/libretro_version.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -Description: fix the libretro version -Author: Sérgio Benjamim - ---- a/libretro/libretro.cpp -+++ b/libretro/libretro.cpp -@@ -17,7 +17,7 @@ - #include "../source/core/api/NstApiUser.hpp" - #include "../source/core/api/NstApiFds.hpp" - --#define NST_VERSION "1.48-WIP" -+#define NST_VERSION "1.48" - - #ifdef _WIN32 - #define snprintf _snprintf diff -Nru nestopia-1.48/debian/patches/series nestopia-1.49/debian/patches/series --- nestopia-1.48/debian/patches/series 2017-09-09 09:45:38.000000000 +0000 +++ nestopia-1.49/debian/patches/series 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -libretro_version.patch -libretro-cppflags.patch diff -Nru nestopia-1.48/debian/rules nestopia-1.49/debian/rules --- nestopia-1.48/debian/rules 2018-05-14 08:01:57.000000000 +0000 +++ nestopia-1.49/debian/rules 2018-06-28 06:48:50.000000000 +0000 @@ -23,6 +23,9 @@ %: dh $@ +override_dh_auto_configure: + dh_auto_configure -- --enable-gui --with-ao --with-jack + override_dh_auto_build: dh_auto_build dh_auto_build --sourcedirectory=libretro -- $(PLATFORM) Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/extras/Composite Direct (FBX).pal and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/extras/Composite Direct (FBX).pal differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/extras/NES Classic (FBX-FS).pal and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/extras/NES Classic (FBX-FS).pal differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/extras/Original Hardware (FBX).pal and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/extras/Original Hardware (FBX).pal differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/extras/PVM Style D93 (FBX).pal and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/extras/PVM Style D93 (FBX).pal differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/extras/PVM Style (FBX).pal and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/extras/PVM Style (FBX).pal differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/extras/Smooth (FBX).pal and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/extras/Smooth (FBX).pal differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/extras/Wavebeam.pal and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/extras/Wavebeam.pal differ diff -Nru nestopia-1.48/.gitignore nestopia-1.49/.gitignore --- nestopia-1.48/.gitignore 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/.gitignore 2018-06-24 23:26:58.000000000 +0000 @@ -24,6 +24,8 @@ depcomp install-sh missing +source/common/.deps/ +source/common/.dirstamp source/core/.deps/ source/core/.dirstamp source/core/api/.deps/ @@ -34,8 +36,10 @@ source/core/input/.dirstamp source/core/vssystem/.deps/ source/core/vssystem/.dirstamp +source/gtkui/.deps/ +source/sdl/.deps/ +source/sdl/.dirstamp source/unix/.deps/ source/unix/.dirstamp source/unix/gtkui/.deps/ source/unix/gtkui/.dirstamp - Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/icons/128/nestopia.png and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/icons/128/nestopia.png differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/icons/32/nestopia.png and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/icons/32/nestopia.png differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/icons/48/nestopia.png and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/icons/48/nestopia.png differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/icons/64/nestopia.png and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/icons/64/nestopia.png differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/icons/96/nestopia.png and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/icons/96/nestopia.png differ diff -Nru nestopia-1.48/icons/nestopia.desktop nestopia-1.49/icons/nestopia.desktop --- nestopia-1.48/icons/nestopia.desktop 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/icons/nestopia.desktop 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,8 @@ +[Desktop Entry] +Name=Nestopia +Comment=Accurate NES Emulator +Exec=nestopia %f +Icon=nestopia +Terminal=false +Type=Application +Categories=Game;Emulator; diff -Nru nestopia-1.48/icons/svg/nespad.svg nestopia-1.49/icons/svg/nespad.svg --- nestopia-1.48/icons/svg/nespad.svg 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/icons/svg/nespad.svg 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,729 @@ + + + +image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + eJzsvWlXKznPKHo/91r8h4QxkJDUPDBDBqYwbGbYTCEEyCYkIcPu7vPh/vYr2VVlV6WmDPucPu+6 +z346JCqXbMuyLMmSPZc8PV/efm291JblrJCY+mtuLt+pVXqtzkqCgBP7jUa/2+sgKHW2mBDVrICl +tveNJ6vkVa3TrbeaK/hMpE9L+H7qtNL5rHUS1/VGo1756i4mUov48KLea9Tg8XGt+1RtNXudVqNR +62S7v98XnfoBX6HSg1JyThJzkiBKCWNFEhOnR6RIpfm70u3W/xcUEDXZkBG40+o3X+vN953WPyuJ +ZTEh6UJCg/dUiTzeq5/Vuu4yQlYVFNlUsWhWVSQoLmYV04BXpKyiqQa+V2hV+1+1Zu+006rWut18 +q9HqdFcS+X8rzcRR5R2eVBK3tUaj9Xdip1GpfsI72/vqU6neqAEVviq9hEiJsr0vSk87/Xrj9bj/ +9VIDAskmActPBOllF7ABYvxO4PrT/heAzmu9HjQZ6iSkPdvd4ZsCUPIv9fOs9l4nAwW0e1i0MXda +7S8Yhm7M7uI7F7WvdgOIT4gkC2pWhZZq+Mm+20Whl5SWhgjYJTNhmvBXNhOaCThNXYQvMoFYbzBy +1n7Xa3+vJI5bzZpFs+1O75yOqaIIAv20Hp31gUUum/UedEQiMJNS7aj1WmvAGwxFqVEhxCL/RPZp +lbiodN5rPeCFVqPfI2xrOLXAwJQr/9ZwfEWrkpN2rXnRuiJNXRZFPaEpSAQpIRqCljBlOSFpBL9m +wkBrTrUi+7SQIybEY9eg42iewgCfdOrv9eaK3UT9abdTf2WjrgPr0w/SjazB/Wfa/1mthb73erWm +3XxguPwRxz9C9ugcay02X/OtLxyGLpk5wDlNYKpG6916yn6QZ4Ci37a6QQBPMGqnnXoTEU/9dUyf +GU+njT483O20+u395ltr6q8UlSEXnUoVSiZOXn7Vqj2QAxaAfTvv13u1bKXeXoxABT3s1BL0KbxO +fsLfN/wb5/1C7Q1mJUNAocXm71qj1eYQO5BK8zVxXem04yA/bVSalU6CPHBwl+u/4UkFiMWwM1gs +tMAvbSAceYmU8VQRUoB7FKuqSu8D5Fit+dp1sNOfnsZTYByU5/9+vbQa9e6Xg5CHON9jtq5X6zRP +mrSZnX73I3HRajUYIWgB6xEb5E6PvvOfqcQp7FcBPPzvIs9XYDV/71TaH/WqH36f505FAe/G4qIq +obpfje5HTmWDb/w36kFCv9Wbr/AKkXqMcq2vNuonifOPShvBWLLElWR41ScQ0rwQXl6OFM+jvGPS +Z7gw9/5t1GC1yB02W383ya/ECvTmJwjUSr/Re1hM5I4rX7VEBsqc10GDqDmFhMQJfrClUUzcVBBy +Bh9ZHfQGWNmymm5qhky+CJIk4aomiJpivXazjS+I9q9/8dcBfPsFsL8TopA4Svx8EBKvU/AQ0JI6 +XqEpVPCuTv2VyEFL8QvpFpCC61Q0dU4rDVhGa7Qbpy/x2+3VywgFbv4XUs6rsJ1W4b8d1hqnzuEG +qQxIXQMz2GVaZESeEAX6kEpuRPX/2HBA5oUG1WA12lYHQdkHjph7ytkA5Bv8Wa8ieSqdfy3AzVH5 +GFS+gMeridQ/X40mFFiGSdmpv/R7NVjIMqTwdqdTiYdmQrVw5aofoPd3ak2rlJTI7UMfncf40fsX +Jz15nPqq9SqvQBIdZhVovVV4fA4VgQrleuV3pdF33qm/hhduwuy0ykLDsHRmgiT7n0L5IQjeeX1b +qby0+r1h6M699B8k//j0lSPoW0eTNge2fhpKDEHsmV7tHyR0JIW9VPW0Twxvn38Frpa8VlfeiGE/ +xLBn/m9g/Y9er72Sy7X7nUa21XnPvVbh/191LAJUqTcaxB0x5ATpgKHd71QjXhucI+y9oabJHx54 ++sJEh/2/0jN0yg3btT/Zpmp15brV+fwvNQn58qxQ+p827+eb3afflU53NUC8umiAD7px5LBdcpKr +3P9xUjVbzVocKjVa1c/aaywy2UX/98iKqA6+1Il/XIzTSeCZ81rvmPQmRkf54v8nVJ8/KRmgb/XK +S6MWa2b8XyMUqv1ur/X1B8XCf6KXw4m+ld/xe4ll/zPay++VbgW9MmhpwzyMz6n/O+YNNOi/1p7/ +WVO5+/b3f395/y9Mk26jXv2fI8bpnq+SyJ3VKo2wYY835P8RsW3vX0f16t9Yvfr3v9IrVcyakmxE +duujVn//iCUvnaL/iQ5qopQVBCmaG/+uv/Y+YvXPKvmf6B7Inp1WK6xfL60e6FPl2luPbvnH6uLg +S/8ZlYLIynPipiGBNf8NnQKWuv9EO2wf/uQ8GObYbZp5tbZXYrEeV5rSBEOtrDZs79s7NTQYCwN3 +bPbzTj3FeqfaanSsMro9mV7b9awFE+wJVGnUu95J1W237GbImi1B2pXXV+/LX5XuJ+vC9n5iu99r +Jc4q3V6tw9ooOt0wE5VO76VV6bwmqhhQ5MWHJdqVdq2T6Na/+g2yW2eTUwB5hv9L2F84sp5f7T5h +uM9O65+bW/sFsh6TN3RTsr563sGILf4dl/7kpSxu3dO2i4Nsxpnaok2x0+0zL2X3uzYSa8eQe8+O +EHOtuKeterN3VmtctM6oSCLMlzptdevYOPJYYmQkdC7Uu+1G5d+jSsceHFs1sYPP4uMWbR4yDBVa +p2oJQ9DUrCq7GkhfJHFjHsHp8IbVbUJgT3txFLY7tco2iZxxHi7DkA3UwYXYYOTWEzS/gj9KjVar +c1Vp1rsfMB7kBU8tA2/iao1BRLWrerf+Um/Ue/+e9yq9WsR7uDqM8BppYMh7qZ9Htdd6/yvBouUe +Btlse18UE862LQkVS1hxaDBpTju1bq2X4HhKcKbe4HvlSvO9X3mvJU5bbQxfcnMqeYMg7PyuJS5q +//QSxdd6r0JbbrOsqspq4OxOiIn3Ts2RqKqkSEZwYclVOBLzC5O0Eleu16k0u+0KyPHqv4Cw/pro +MkEU2YKO4xyUbd6jJU/6vXa/50g2Ipi4kbKJp7peOqp1P6JeiWwS10/BNTb2epGoA0rgIyhZI/7E +uBRknQ1A/NlsVT9b0O13Gt9mac5OH70svteCfraae7weLAeWztcaDW4hE9WwgnlQebgJ7V+QTLGT +t7duzS4a3Fai47UrVcbLqmEaYsic3+EYTpNEJaToLs/1Ec11tUGWdE0PEyBnjEGjinLtVVRDD2ov +KetqsBFKtOI/PaakhJQl4tVVWNdhgVMThmjinyjBjnX5ynPrfUNR4qIhUneHqPY+iHRzOEQXrXas +5YUthvvN19o/pXqnO+w757Vqq2kPuG6qpN+yqA3TXJw9rmEwNH2IYSDDOIFxYKvtuAPBMHlGYrgG +4dprKzn2NAnmZlQuof+gWfUqzSqbV2EzpVSp1rab743o0qRL3uKGIg8x3owqAwMeLIHIS24JxK8a +vsXP+FUjuBgnfcIkFSnLS58UzWvh9PTP7f1Sv9GwlRcrAQae+mgsQuLNUYbatu7S+l3rtDEgbsDO +8bxRbdTbsDqi4/4fWB3foZou66vvK7A6NurNWqLb67Q+a3FL0/Aa2haBU9H4sh2iNyz/BmLBav1S +aXB8JwVQ84Lz/8A4hqxQ0aOI+R8OvcTo6VStOJybos6nYHvrmvMkpdA4CyvsUidWsSHVVue19upj +/yZyx62e+7kz1oDx9P3NO0AAvam0PaQAYOGi4Gdg+1Rgv5RjnqHcr9ZLFrSsBqfdD6ry3hds/QwU +2Hev5ewtS9i5AhVY73QXwxvTqcEc6Naw2Z2YqCOKdT/r7RfgSdvCZEM3gBBMDL5Pq45tgcHCB60X +DNVOIJV9tdHi6Tlq32TeXHDzhs0aKbG9nzjxTnIeCy3hi8S/zLn/dAbGINHjaGCBkVH1DhM8L7Wa +vfP+S5fmAQ021uqQj0jiMXATWWJPik3gHxdW1qx+r3VY6zR9Woz9pRkH9jrEMJIAZa4y93s0M82W +4uwtsAqr9S6zYfgmfr3UXqnJ49+zcqvKe3X4UVKZgXpa/6fWABHzVnO4ImoeSj6MWv3KAo1rbIVP +XWbPs4nr2ksi34KuvSbuU+fXJ6f3i4nfUvgMBVTtTuut3gibmlDoC94PnRIwwbtZutkfTzaQFyrN +ZsurPQ4Ueus3q0N5E3gM/7SzzUG/gadEq/3ajyrRjcRRbYXQEErgOmwrvap/Efd66Hjc+FJtIAjw +b7PWDZOOUKoh4ppfYRarEICu+1EB+VmLQIdZtiRyKaxQs/Ze4ZxdfoSAUi91ZHfPBPS2HkR7I6Sy +t2Yv2wWB5BWc3jKvDY51fVv9/vWZrcKaHFXmpVEb0C4GCnVR8oQUqnZes716Y1CGegt1q9XmgGE1 +WKjdqNqEFP0HmJYDLSb7Ebfgb1atf7FW593BFlrod1gHGh1erMRQJSImcrXd7mSJoyy0aViK3/ML +LuXa+UwVam+whr4mXv5NFDrA453wBiMCrsGgDvpOP281vlMGCr1Sv7qtBouB2Dxd80XmktNBytVL +vfdVQWvD7dkLGkqQD0CTHu6xhEkSLOpYLi+Y7G4TSAri8lanjhnyUW2Akm8gYT9anf9lW4gBxdrW +TkAkB0M7G5V2DFa3CoaxOxEPtSZGBr3GY3nyBoyEFVYd+xU6utyaLmQl1ZddsDQwFuqGkWyDZVHn +rYNaG1Wuw2WlRYpedNu+VDqhk5YJ4NbbG6wNbwNO0+DSPV60RxXucFMxRnG6sW5PysDy5PQET8tj +lGYtj1GYb3mM4q6W+wodV0f73RposTv4M2x20xW33XlrNUOlANEnvlC4dCNYBNSTWs+j8MiCX1FQ +nzoD0opsXfgVfY8l2FBro3KtN2ij+RekLpMondYtCHwVPar7Wo6TUGWPKPHUK9TqfYSawlzR6te/ +tux1ZeCGWQt4ygoxV9z7wgPVdHsNe8Uigt5pU4T8wvesF7i1M85L7VfUJRrN+O1qxxTD+A4VqewV +M2j1Jalp/DSPKMlNcUEOL8pPcN2IKOya3iF6UIvfVgrRhLzlfDWG11q3/t7kpb6f9ep4Y16seJ9Q +nKQkb6CGFqx0qdbi65PZtl/gvTIBFiW3MU08KGGb0QPuljw6XPOWw/XM5XAV+ZCQZos5cRP1JvHR +omri6Ixsn5Miph6I3BV1nu64jUV+k5YW3+1UXlF1IueP0F3bAfk44JSK13iPB8vtWOLbTcuFNTx6 +BCiOsCFwbWvTzpexXXhQBXae7POH72tbtcSgmbsy+lqM2hyf0ICP+aP19179dYCdBso1eZeuPRLn +ld+1I5BndRiwbY/fdNXHocSdXuBJnMfO0Ix67ID9cOqvHD7gQeio2j7P7+8baqGGYpNgTm+oz3p6 +8+olJ+TSR5n05kdPxm+SsvZjRXYe/HC+kQer8uZFb6fwZu5+7s2crVcKb8LthvNUSq+faR/JRXlv +PbmcWziDapLpjc+15OLxnZnMfNTh2fNbNpnur5wnM0c3heSycCQJufXbFKlfTeYXfw== + + + KF2pewStK3wqmyfPG/KOIRvanfZ1t7b8XGrp17Lwyp4Ke0+1PFTT6Wysv2xn2scHW4dmd8PYW7vO +llp3ylWxc38nFO5Ktxel9e31qri0rTetauTZ4TqHRKP963SUZObqcT+5bCwbyXQ1e479MhBWTGae +XtXkYv2zkVzs7dSxc4t855TMGX7bgZbcb5OObJh7s79Yl6Aa0qtu8mGhIC1sTBc8pbK5rrErbc7s +PcLP3YbwOn9bsDtS7nY6q92rzn3DOBRyyjmlKyMVvDl3I2/9SKWwmtd5kRDjhA1e5yG/tJWVy0Y/ +vbGbnGeDQWpVWmfnzaBaHzsPTx/nnlqd3hi768/q91Jb8K31Ubs7Dap1b6bxkrvzr3Ut+bM7c3V7 +itX4dvfH+sLGSv7ngV+t6dWqshZQqzYzc3V3rHpqJdWQipXbO6G0o5341jpd+mXMNuXVU79ahdJb +dS+w1nlJuS3S6enTXeX2Vdjd7dz697X0fSnlL15wXJXWwLgufK1YtZ4uLJBaaTXW0Mqdq9wHqRU4 +86XoHtqfnYfC1SnWujjIUMqD0steLvvX2t47gGo8FbNatWNhdSao1mrn0RBv/Gs9Li7NfGv9I1Yr +VMMq7s60d0pBte5tSk3xzr9WZfE2vdq4PPatdbpUwWPwPBXzQ3v4YyegVm1mTjXUzYBab5+EUuvi +gtWKveEq3p1dny/XPi59a939YVwF9nV+OZm1xrV4/1lyTZ5pPCimu7CV6WLFSwPd3Xv6sqes3vbW +Wt4/frBqvV1Oefqqq9nsHasVOY3v7t2OUP76ofvXuj/dN8q3VcO31pNGbS+wVqjmMPvdzvh3V/mZ +Fs7L333/Wg/lx3KptJn0rfViv77PasWxcVd8fqRdPAfVWhCuhEfTv9by8szF69PSql+tKGyuHte7 +gd29StWe2kG1HgnXy5s7AbUW09dbRidPaoVqvN29y1w8Btb6a/qivBNQ670mPFSe0361IqdNH1/W +P1fmjjO+RH58vHkKrLVV20y9B9V6JDwXywVSK+E076y9FKdvej/2/WrtdI6XZ6xaX+RFz+RJm0tF +mdZame7tslqJyrGWXOn05byAFWcGaj1ZT30/Fm+2oNb1jnflWWndZqxaP80lT61zbz+n30itUI20 +cyvuu2XFmVA8/rmLtS4PysXjZXvlyfe8FC4Wf2VprZupYobVihI611U/Fl7TloSSZ1fyh265WEuv +G8c/sdbcYK3a3PT67d4e1HqQ9NSalHZOPkitZGxWfmQ93f3VWi9+0lo3L8tl9/IOZP710SLrnbD3 +fJrnn0q9r6S00nzxPGWLtNSfT8qvX23/15VFmDwbai3oaQc44qge8JSqHMW1kyItMLBS360L5S1Z +Ik8H5f3dplA+21SCnm4L5ddDjTyFanwK5IWj5LUR9HpROKnunwU9fRLO8589z1NOs/mZEc6vZpIB +r//MChdbR6mgp6pwmfzO+j9dS+Jxp51+UrcKDEqtPeHqMrlOn7pnHD49EK7elzeDnpaF61lz2yHa +YIFj4Vor5oNePxXuZvSHoKe/hIebuyXPU45o97rw8OstE/D6vSk8Xq7KQU+3hCftyQx4+oRHA4vZ +pUM1oEAlJZrP0lHA05cZcWf+sRT09Fw8/DF9EEy0aks8/pTqAa+/Loq3vw7n/Z+qj82L1bXeXSDR +pO5pcmHxgOhaKbB0Unuu2d3dTmb3tjboU68UlHqN5Jpy8Mv/qbJ4j8JmTXr/EVTgIb22+nXGPc0v +L51ZRiFIt4126vUivdPqHlNJtrHenuOMt+J9bccWnR77jYjETmdTnNvK9RbypYtN/ZYYoIW74loW +YEIpv5Ot5vM7ucM0vHbetl57nmtgc2RaIVf1jLxAVfWDL2oPXbYbP5kQzR0ZzQWwM2/6xB4CUfu2 +5hi2M7n6+ssiTMXpIhhDK6cu0d2ZlhbWT5dtY+jkyK0LYMV2rerH0txasuVfq3J7E1zrdOk156kV +lzWnYqF0sfMjoFZQmk/qR5WgWp9Dat1dNt26wOv8/AyrtdNdSXedWmVXrcaecvNRXrVr3W24KDyd +4mtVzmehGlZxp/8sZgNrJTwXUCtYnGBX3PvXqtz+pGYUX7GLyF9SYK3EtAisFe2KV1Yr9sZVcS24 +VuP4x01wraikBFIYqkE95Smouz8GhnZmJWPVT75Z7L4SXo4IG6voaiyUyn05XrnFU1oO5Qa1CMqa +25/kmsSlPpjzCz/z1iyonO0QxZDKGZu4bO5viZlLMeN8/LTHxlI0LH9Sm59Yz+km4jjjfHcbp/Mt +bCBq+udbvIzC+g/UuTnygUN67bHWrBpOnBYV0LoskVJ2hQeblmtq9/IUfs7PWR+VmwIzATxOPSj8 +syAWH7q7ls/G6jPX6I3inPWROWpRAlGLwBbOrA/Ah3kXDXnS7+Q+aoU5ZGj4C5y5KeyHN8spEtCm +TDFDPyySipwrkTNxKeH7MQhPPqweEtPdt4enSdZDunoOdNL5OONtJJ8xBP37KGoMn/rEjLKaT00m +j7+UspYz0qOOIfEO0k6upoekVzBHrGY8qJgzJYzt/Xl+97Ydzl+MuSyGDuYv4U2cvo1B/XDSE10A +qB/FrbFn0KrgR3p7bKLp5ZZC2daAFLrNtF01OP0H9FjNECNSxI7scjicRruk0OI84c3A6Xmb6QW2 +yGoJiHryYZGPuGp9yFe8v/JOT16O+09Pahn5dG5TPCzH6BwdG75/rs4tz4R3jn7UTrPzG+3FtbY/ +mXdPv1C5DVifWL/mab/8ef6xKNS6n9fhXSK9GRwyDweRNcNphOzP7ruH8x5F3sVpMFqF3CRo8xS8 +cGNvar3LnMVBDkNTA8gX20s3EFsgKn6Rdk9AsT0wAV+k7xi99pt9bosAWlRCj9V+yIA+9RdACTzK +OOLJd28PCldK0kN/h2xTyZbzPmBU8cNqPvV+DzII9NAtD12oMjsp0iZqeHBtSwe2TXjLZ38GdPPk +h592xkbYIpp7WJTvgWH5NDrhi164FHIta9Cvm27QSuWrTbpVSTbCux4RS6ene6WKPcivu2JldmEv +hlLFqRyi3xYt0stMRtFr/SUV3iZisEOzpJ0788C/WY6aF6Truds0E7Z6shGMsZgAST9nQ7WNmSiL +gB/GCF1viDEkMq3ydDkZbELtV+3KDxUdm6GxuReY6IbxonMA29vC983kiBah8A3TzbeV1N3kiOaR +bkMTzfKE2T6b3sa3x7qVdm4eA+WRV3NmarMlOt3tfd9zL/5huq7/mr2Huzt74TKN1759FQjo0uf0 +pKbnHu7BHA5jTi8GjOY7OlPk2dXD8lgEirYMaSxHOIGesrH9DSG9CZQQQwzVk69Vw1piGx7hjYmS +B5EtIVt4N0/S2GQJFACkJZShPfbjyrf/mtXb6IYsf37GI9katc0o4h4nbGS9tEyaxfzg0KJf+yAP +KsX4NbjcH27N5qHbTA4jSYImyq99jy7iMQojm+VqU28mrijwhPMMzL39yYgCuhD82o8vCsJ72Esv ++PUQezM04aO0By/nKi22ELiZdzNV6IlLO79KE+hh90PitM54DtIA0x0sot3770COsJyQ8ekVOtn9 +6EWwED/0IL2GnOwuerlnetZe1lyT/evAPdkDzLhIX5Q8uzI9HcuZEup0+DoIMQUHHbl8JOQgu4nU +oxDlMIh25JJFekVcGNOj8nUgb15dHAV2jgibSF+IPGt+C+M4QiwpcADVXLXG7pJ3leU9t+F+PddQ +HfTdAj62k8i13iBt1OHcJQG+nQOPbyeEoWf8XRJuNXtz5bTnUbPlzcu5pIf+TiRkqKY9OA7tw6F8 +bEzYuFlr81IMdxt6teSgdfGQrIv26hnmEY2hJbcP3eviiPNm83J9cRx2pwzdPvQuiDHd2Dy7r/xI +uhdCrkusN3G6NKeMKAp4TjscWAFHEAVAGM/Kh22yA5UDFr8ANRcJ5F75ItYlUo2t6fosfgtQ9cwC +t6kL3/IAS31F95qbfcHuh5vzEXc3+H7tnn7xu1FxVsAQ9xZic7y04fMmhpcWsIXPwngSGiePOK4b +H0duMeXBErBTGI1oaajm+O+wE0TpifSL12zGQrQcozlWAEz4WkiwZcdYVh2i2Rrx4uKg2XlzMfb2 +BCdsAJvHMht5+cGGuXaNYu4UBlLzdV6Ks5Nlezk8dryfdAPTRl30SDeArcRQ72bIxkqEenFzObZ0 +I2MDCudQ+n2YdANUPtLNCrIYdg8KsA0l3QIUKHRoy2NLAdzXX5qEFBgMqAjmtEhEccRJOBYaD70a +R5JENycXaPsTg72VXrd5acAT5jNo6bA9JWsHEj9yTHFxeznokmdPGTSKlrwxYwCLMxixIrry8Gw/ +cCM7psZ2c8UkrrN6jrwnDNiiJS7zdUYJ3au4ARV+EodJgd3bdrjRHUPNJiPnDpgKFjaRiAIV/0As +ntXTQTRuVAXF4pjd4Rv5kYjixjQ5kSmB85FgG83JzRZH3kG8AGvxbtq7PlamyzFsngjbmxqFN9eT +0P7vg+MgmKoee30EbKHav9/iGOS5RWwjav/8uIrT6kSWtcr00WSWNUA0/mpEky+Oxg5OIs0J9uy5 +ou2iEYmB62P44ugnbMTp5eHXx5DFcSVForu96+NKakgjIyDQMA8t+dlz/AIRoVkstCNQHq2kgk1W +Qk0yPb0zM2gLD2yJEZVgnz0Cgm3oeR7YMDLJw90PYZLXTTQtfDTdu7ihJhMM6FUc/dNvG5Y3Cm9C +fd7BEXtBbeLYwu3rjJ5nfmactHNzu+xZpjzBGLH80IFm3G3YMsWHxqFM84mO85Jg5+bD68EeapK5 +fTZv+WyE8RQ3GgtRqWFjM9T2D2KL4OUhnCnSzu30/DB6hzfQkWfoW+KYi4stYNq/dP0ifblqeM6I +jL8kbQr2JnsnmT02Ho8RPz0+8Hib0pMvV1vjQPL2Nk4+dhtXlafCzGu/WDJntx5LFxunRZLLB9VM +Jp0vHZrLN8UlLY2VzsdHaA3m8k3xxxiMk84Xnss3xVIXx0vn42r1yeXjA5XHSucLz+Wb4lMXx0nn +C8/lcytQY6TzhefyTfGpi+Ok84Xn8k25UxdHT+cLz+WzlrXx0/nCc/kIQ08inS88l8/qzXDpfO4A +6JAEPMd/4GzhRSl8wXlg3zHaFMdBDM2KihU/aoVr7lZYQsG7CzBy4O3PglsxlsZxEJ8uDBW/HrJT ++LPgdkiNQCo7v20gzWcwlM1llIXlA4aG/PnuFIZgi4ryCujhQMZKjCS+2D0ccHSNQfin8MRV2iYu +Pi2kWVGOrpA2tT069LD5e0OInUc82GxshyM0/6QXHl9iGR4xQkyK42zwuRQo0r+x3VvQufsZT+f8 +w3ki0+6GjS/x8wtg2t3QnubBLhWyMc2oqLS7+PElwaITaOMTYjKSlUIYOm6iWJwAr40XqeVRK4iH +eSoiETOe/HqR+pHOlNh5r5Xpp+nowfBNeh2Q0KXwjMqhHG3otpTCHMQuj0qAo83taw== + + + RCU44/ao7CJhip6QkTFy5IKXOj49LlY+mtGL0jGGySl87A+V8BKSU+hSyPzybzCii/NxBefI1QKT +cLxqdlTk/W5Y5P3JmeORjhjDKSunMCryPn5OoW9Q+hSfkT9ETqHH6xnFETTIIhhbRIZP3IZRS/oq +eAt+6G5GH2MwDLbgvY9RiBaR/zMk0eRxsLn9xfSwTFcQFU3BikjfiaXm7nldxT5JS2zax0vdC5Eb +AQjI2ETZg2Sei5Gy+n3Pzx70i7mNYQ/2NiOST5hezRDwe9IEx/zwOFwINrqCzzkuHhPXGe4gskSl +7AWMEq/c7g1srIQYaoFpf77z1iMFIikS2xER6FWPStgbWO8C9BnskuLp0mCUqtsAC0shSBU63kzd +h+57z4/qU1yml1vDDGBoWEyHcnAs8upgRK5ehAAKTssaCE4aWU/7tR8499mcd6RAJKliz1u/ECeO +037tD+cLCslgc+8CAR8M2J4x+SA6R8/VpinnkFPfZg3lvQlpEwmymAxXhXlvppwTx+I1azjvjdeM +cvuN13te7w2mRY3jveE47etgbO+NPLuSmvWz9FzCJqZVcTC89ybYL/B1MLb3BjqnpEJCRuLnw8X0 +3kyFnQNF8uHG9d5gMpzMOSFHjUs6iOG9seZNZK5gsPcmVnaQo9kggYZKEAoNvMh5FOkpO9MrIjU2 +liJ9GBhzMTVMhuTKj4iBDLQcBiO65M1LPUYya4xjzw5ZlG5gBHGszi3G5VLiT/Nn1MOYwRBRaWwY +DOH2dY6Y4hctcantGZHiFyejNXQG00TMED9dnLATjkBBblMPQwfNZE84IAjMBe+GLMCCOYIPHIve +uhg5M89jrdnJeZPOzAsPu55YZl4kp00mM496BweS84ZHFJ6ZN0Qw7DiZebwOzSXnTTozb9AojBsY +OVRmXliola2ETiAzb4q/0MlnPk4oM8+KvPcm5006My9gbCadmRdhrQXtC+1etSaR+I9LXkT8euzQ +S0AlxtQ6Y4ReAjZpElIAaH4eY9PLVzXgAy4vJ6FjECwDccgjbBYTRG4TO7I5vj4bgmjsIwAIFmsy +8qsnt8szVIh14AHHvpH3sUKsQUvfWPLOx+J9PpyGVuxgjPl4O9Zht46v820h6oyX+KHQC9/eGRRD +pgWGQi98x05wDVHV837REkOz29WEjjomiKLOwolj4hJEQ85H/2XtaiLz8SpwceR9NjEVf4LtZaiD +IdMen40nZAJ6OBCwhLChzW6+Gnce1Fng+cxxaXg90STZ64kmyV5PKEn2/nsCSbLi9PJkkmQB0WSS +ZBHR+EmyiGUiSbKYRhd90LU3djAwjQwmSshRsLHil9zhPCgrBufjU2dsN5glbLi8vLFjhfyS8lzL +WpxYIXc341r33NgEGvgTSMrjpqeVl/dHkvJGtz2HSsoLdt5PNCnPCrKISNccOylvipwM+xi+tsS0 +4F66gTKKKrecXIiXfeWOuYg+/X7KuT3OZ5C9ByePfCScRbRv3y2koR3P2LCer943imZz6z1COXpn +YiowVR7T6WLsAYWdPIyCPUfWwKmgXNzorGtPmzznmbvZgg+7Dg93Zdr8DjmDxKdC/kL51Nmsnsx8 +/DrH2+QxsxgvXn9KLh2uislM4ewaL14/x4vXL5JLF9safjvFovnk8uGTKuRuPnVrcVpvffKNtv1T +7iv0aEYYb3u60u5OcwJPaVcCXHdhtsVfMetOu0u9zJ59Bib7KYv3YWl3j8uBtZKbyANq1WZIbtZU +cLLfY1jaXVINrhVvIndqlX3uKQxOgFtLPoRcK/dj64yr1XOFHt7OPRWY7Kd+LG1dL7WDUtFuw9Lu +3gVPrVPuewof9oKT/eY+c1cvQbVWQmrdFVbcWqc3t/H9YCaw1uT9jHYZROFMaLLfdGl/3jO0OG+X +Sf3km50U2H+NVe5kpuaJIA4qOn2ynoyBstN/+uRPG8deMxWV+dPsSQyvZ1KeNTbM5xwd3zuo3J7O +f3nj871+2JGSi6bonV7tQD+Vv4Ml+E6vLd+zqIMjuoKTiyKvqBncP/P1Do53vZ67TX1vgP+krtfz +G764brvThelxkjM5B/HPQvRtK67YwZC73bzX6sVw2w1xs15gD6ei78KLumglTg+n/E6DGzkrNtYd +K3EJH3H9xBDzRngrK/exSMX7SYNv5WNG4cQS+/ysj2F9NjES+/ysBH+33ViJfX5ZfYE69OiJfX5e +RMtBPMnEPr+sPjJvJpvY58c+zt7a5BL7gt3dE03s8wtP4ST0pBL7IiMhJ5PY57fPE7CLO05in3tc +aVZfyMbKqIl9Abu4k07sC8lYmWRiX9wzusZM7OPi/Z2sPv/t1bES+/wWJ+qBmmhin1+b+K3vCSX2 ++WX1eSK6JpHY5zeGzryZXGKfHyp7s3iCiX1+WX1+GStjJvaNTLThEvuiiDahxD6/rL5hiRYjsc8v +q28qINNrjMQ+P510ypv1PX5in5/s4RbpSSX2+W22UNtzool9bgTzkSbuiIl9fmMdvLEycmIfP0r2 +zkzYejNiYl+A7RlIkRET+zhyODrmVHBC2aiJfX5dmuJOTgrSV7FZY9qINF5gpTuQPpQqROodYYlq +diN+7RMbkTejRs++ipQbHpVjErf4RakcE7rFb8PnCj9flSMeqSLvAOZYlTohgy/Li0zVj8cHyAK1 +qDt7l+IN30fw8usf4B925V7UXb2+bRoMGcFmxZnYsdpkW6FxhU0IqbQhhE2gySTPmp85t8l04DWZ +BgObvD6zANvTc//fiMlzzM0cGGcTU1+PefmfzWnhQzD25X/UyxF1/1/MnL5JHBE+1uV/nJ4Wcv9f +/FSpgMv/hnVCjnj5n78T0nv/35D5UoOX/00NHHjud//fCBEksExw19jbOR6BQbkhyXOTy/FoH07m +THIyNis/xs4mOgyP72ABl5E5fX4RjsNGd+PAj31L0GFgpPFAAEzktX3BkSGx0+PIjX0RAXTxgtSQ +Ono8hg68b8y1f7KYGjSnMSnQtfK5rLWhNozQqx87vywsJB6aqoT70ocJtSIWwWRCrcjZBONzGtA8 +TpRVnETMCeykECwuVdaPBWIiGmYNDA4cQ0QjTcUBLGDnuufN0Jn2PLbgQxLjXF7vzfb9VUsNZPv+ +qkXvRsVPQPtVi3U/so/e5xNEDtiWYgk2bjELpOZ5k1AzxtjwxmbY5hRocYMh21f0ON/wfc9YzsL8 +QDzKiIkxlxO93PFycpc7XnpSKEaVAletoZT7ADOK3EU3jo7BsISHjw6DaALHGFBEo93w7bZvEFFI +NNJwYbEwUXxSKMbZLAadbHA+AswnhWIU5/0I9/75RqbwV/+NOB85VBO86zvq3r+Yqvq49/7Zqnrg +1X9Dpv4E3Ps3rIk74r1/Psua++q/cfo14LMZ7rI+L7boe/88DuLQbN+R7v2LfXz77v332PllyAKg +9UWcvBE/21ec9jUtHYYeLttXnB7ufnl/ZwrSvBYj7yMyEdNOvWcWwaiIYjm/IiK6CKLxsn0JFrp6 +jp/tex16tt0WWT2Hyb4fiNqJdYugS7Px5lINRu1gGtll+Irm6wbzi7OB3ofMxyETqW7IXlXwsuaf +SxWWLfcS7O2zOC22gQ/YPmLEJHqt+4DpCdg+Y0zPGIlUN8TEn5Dt+dQJt/MHbM+ARWollQ2JmIzU +GL3uB2hWaC7VsBrjC9249VYD4EkcP4eJcq/cSfDuXdwR8m7z2eBQPiYUpjxn3odkpo1zqtYg0SZ2 +GeZLl23lBu5GxdVs8lk9xjo6FfMCwZun+BelBu5GkXv6JnYZJrQp9JSR2Hm3bBpvqEdN3wqtQSh3 +Ox2ph7lRVsLggXmLqYYX+LGVTFezB5himCd5hlm5bM46wzfvIZr1zZUj1+mKcx1WK2Fo99V009KK +6Z+ZtzY9H5iZ1+k/Z4PzAbGaNendexNfml1N53ProJOtdheWhfhL9Ng3nkTEt+PzwFrnxYOnalCt +r4E5clBN1zjeOee6686R68581IIy84y9je/ZL6evnsy8RS4fcMq5PY4j8roUWKtQMoXjgFq1mdmz +L+nRr1aoBrsbkv44XeoqwbXuZp6vAmtdqKX0D87R5U0JzIbVWl4IrLXTvdxI+tUK1dBExK2H5QvX +0NZMu37yzRqMxfzd61ecco/9r6ZL2AQU1Wa+H4s3J5Eo1Q+L+6yFE1N07rc96igXZJH6GvDAlPqd +4DXLWfliRGdaBrvPjtLPwkSuXSigMVbybHpFRSOF3MrnUod9r3WL26y4AZ+De2WuhQAGrxR+hlBc +JbjgcQJP+VxME9vv9LMQeQMMF3AZTqphArei0uOWAg2w4dLjgiJBpzxnEMfiqiFjwIKjhrCHkYHw +cRMAQScPnzfxEwAjwuUsPS1es4KP6Bl23qwGh9FazRmMw3Ub4D6He9KL0CZhaRTDz9mN67m9zfTG +8YW5iVa8vwoPsYm7CV6czDbR7fLMBPxpxUkcQon5iPY0ngo62CxeSmJcJ6jlUg1MSYw4gjRePmL8 +vLUoq6YYGgMWz5/mDkURBzeHXqTv8F7HFjaV0gQt6Rd5Os5gxMjSr0wfcXJrMJxnyIO6gF4hB//b +zpwpmvgfzwPzabS99+p4fZIBSsoUPTYnMs8OVLqANSBWQhu3Ifm6G67SDZHQZvQ9y8nUOJleLxFH +MTD3GhWdwXl2wUcxxFDVXQrUgJd02LxEbgw9u5K+5wvEzi2NvPVnYAwDo4Y+jU5kqlBsjugM6AJj +YQtMoZ1y7lsbBtvQjB9GtMhsoqGINqnzUQBb4A7oSEQLyYwbyGJ2bxaPmJIYV23k829GSEl0T8/g +fMQpn+M/hkhJdDciOB9xynOf9JApiXHzEe2FINBGCsIx3EWDfntrQ6QkBoi9gXxEP4N9iJTE6KUm +KPphqJTEAJIO5CN6FKhhUxJjmYfe7VV3l4bKXIrIRwy2pE8u/fs10mWFvBT4g5cV8mbUQG7j5C4r +jHI/TOiyQrYQRMuPMS4r9Mq0P3RZoeVSHfViwLiXFTpuuz97WSHhNGzWn72skI+8/4OXFfq7H7BZ +Nd9rR4leTZsTdaoVf9uhEwY37oWHNqv633Y4bLRd4IWHo5xqNcKFh4Gdm8SpVuzCw7FioOJfeBie +ADg1gVOtyIWHEzjVKs6Fh/HyPce+8JARyM/p4cfQI114uBF62yFneIx34eGQCWWjXnjoZQv3bYcD +ATCjXngY3rmp0Ps9h7jwMPy2wxBf53AXHoZ3iarqE7jwMDIYdjIXHoZfCmbJtPEvPAyfxo6q7k2B +GvbCw/CVz6unjXzhoSv8aeC2Q1/7ZpQLD8Pjsriw6/EuPIyRSjKJCw/Dbzt01ptxLzwc8p7CUS88 +dGPx3nY46CAe8cLD4HA1q5rJXHgYvh9jybTxLzwMzY6hseqTylYLvu2QtwjGuvAwfJ+H6AKTuPAw +PMQ70HM77IWHQclo/FbEmCkXgC1CjLikQETKRS3swsMhpMA4Fx467OZ72+GAz2bUCw== + + + D8OxTAXeUzh+ygV32+F4qSSXgRa6Z7c5XmhvjAsPw2Nop5zzBZz5ONqFh+EnjzDDY8wLD53EL9+M +7Sk+aSl+CtTghYcxZNokLjwMv+1wfFXduvBwAunYcS48jGPiTuDCQxuLv8U9sKwNe+Fh5BWFIcJm +hAsPwxI97r8t23P8Cw99mcy57XA8mXYdV/nh9z3HuvAwXPnhoh/Gu/CQEdwvNXhY72DghYfD5+KO +dOGhLxZHFIdnrAxx4eHoEV0+Fx6Omqo/ZWVIjn3hoWs+Dtx2SKuZwIWHdlad/22Hlkwb/8LD8CAq +qtxO4MLDcOveJtrEEq/8bzscwtfpJpr3wsPRbc+hLjwMkof0tsNJhSjmw287nPIcrT/yhYfhtx1a +Ksf4Fx6GJ+n6L9IjXHgYftthlJ4WP0k39LZD3gk51oWHo2g2I1x4GDiaZAPIvfUdhi3iwsNYcZ3j +X3gYvlYQl6p3uaj1BnU3gAWvFdYyMRBG4riDbc1GeLtcyXk9wgALkffh8f7uJEqaSsJxVdvj8oIB +Os0zAeDap003eSKQ/AQnD6sy3cxbJAVUnuCkp1q+09k4q2/lemsH26JxfS4tbEwXSBHM6tpLX5xW +Osm5+/R8Er1GyYXHvY9kdv3Xdnp149tMr62e3aYv6p8toVj8lROKv5ZXhNLhj21cCEqtelnY/WEu +C+X94yeh/PX2Lpw0ah/C+ZFsChf79SvhsvvxJlwJvYZw9bjeF66Xr1LCXeZyUXh4mT4RHh9v3oSn +M7knPMs3C8LzUepHp9Mp5jrd+9Zqpy82r6CaTv/JSHUX9HnUE856mG26sFx/3TvZOzbftq4e7t6T +S/NzN6ezxmpjZ+70fPdg/uNzbnrazB2nZhrVuX3FnD95+XVTWFuykxKT/UxbOX4mw0JS4KCa5Hbp +4mJOmK29Avi05StOrLEhKa/dLia4lpPLO7cKd0GmdcPiyo6HXoRYSLTdHysKUKT/LTyvPS52OsfL +adbdgb4qizfpNXlhSyjtHO4IpbfqgbB7cvzVnXnUXjCZNmlVuPFdTK8bxz+FXOkpOUUzJH8IxSv9 +idx/KOROahmPEuaeRq6rDJ9TX8xLy3WOrUZMF6D5v/PJxbVjJbmcW7jCNOBCcrZg5JKZxa0thB0k +0z+mjzEX+BgfbCaXt+XXZOboZi+59D0Dfa18GxZr0/tFpTQK0VlxKS+uQjX5eiUnYteetlbLyQ4Z +oFJROjLg23lbzLy/b8C3q29i/gu5z+kseV2eNb96gpDK5shPlJAp69uv2hK8sbdIK3xb+E7TebOX +tiArqWX8uWz9LCsWDpAHvWL189sUcuq+sP3VKne3D6+vH0Ae9EyrnRv6IntA+mA/WMdquGeV2fy6 +/Sy/zB5IO3eXm/aD/Rx7ADrZ+7b94ER0HjzCoM01hNzu+hKBYTUI5mvfzWdYeb7q3f0s0DyzBGvb +fRoQzSxKD91ffXhwJpKf8uZlEn6ebi05CJ6I7khY4LSUwVJLoILXdohgQblogGwtGyCcTmB8T09y +6JHOkLUYfl4SvEt0gHKnP+Xc0fmnDO9eAP1n1mbwaRpqyH4JudvyMk+0Z7uaZxh97W65kKusza+8 +NxcuS2tF5RcnP6l03b35wVu3tolrr8Zl05afzwZhgUmgtEUsaeLigfHDNHZLWwu1i8L+63rStj2h +azeizcYXUrqQmeuXUnv7+9Ji42nGYrLbiuJ0vcIz2cvJMlIpA3TVm/DzMmdx/8uNIL6U9xfJ2Lz8 +FKlGnHt5lDbMfakF3yqy/e1VITis8f08IyiXyYoOP29y1rufPwX72yPjuRdYUcsbbHp+vsrcs8ek +/FR6Wvx5KD0ffc9Zvfn80oiIkXcM2VitPS6+5T+00slOw5gxOLfORqnfIAsx7ZJ1ZCv9Qf2FtodP +yPVusk6tVYtleo+CuCtupeBbRbS/vUqsHKzZZ9DD3i/F0xzszYfauyotLW6s6lfL00el56M5k1dv +yPKO+h+Thhvrbaap7Eg7t+kiW5AHVuNNHW/5XZlvSUrxeuf7CpbmpULaVJU1skhv5brtTXhwdFDo +V05P4MH6ZsmcPXvNPxzMkGT8MlvCcbwWLDtMPfiyRgnoTqQVNaMOFsl0skuBmITJnkXHASZQ33fx +aS5dvLrZQ9rcw08dpqwqpsgmEnyst+GnvkTqAnzniiUKV1LfZFwJp6lbyyQZHmXlHWhdVx178PQ1 +qkCB6Pzpa4W+PW7dU28I+8AHYmbhA2NkDhfJ3IBqyPQQM2YvjeC002iQpNP7bSJEsZUpkF8vnzuN +6WZJzDzqNXvVOBTSG/rVXv75c/tV3rxq79gCcGURB+gIJ69ODXZDpCvQ7mUKl6b3E3j9OENWA3H3 +Xcnizyz9uTe7lSscrLUEQHQiUIHJiendS8nS7Fx6H/HculU/SyMtr/MBHW6HJ7nNO1M4k3BZhRX1 +LrWVTDeUEt7YfYA/F+kBHGSpzUgldD8kF5d2Mnjh92Nysd7YSC43f9xjAQFX6k16JAfPy3QFXqCH +F1gHFRw1kRmWaXOExVlDELpXta2rw/X90lPvAmVa8Vk7+Sg9ZfZmtk/e18rbFwVltvD2o3tG2L6b +fFgoCK9zzUKns34349WsYtaKYyN0C82dk9Oth1JBVZ+3L1Z/pQr7P7WD7fN+anprbbOUdZTbb0Jp +oubmPuaaHVg6zpUYVVNdYLDPUvVpaWv1/uOpkD177uTf1psvsTuM+KRC9WRzYP+GHoMCE2U9LeTW +b607pov3pW9H9VqVNy96W/l6ab6zdbVw873V2uvcxq3a7o283UkW3DZa3Kp/FN7m2zMrcr7wUqw8 +V5/8qG4bHgGEvzdHHPNxOA3Ma+vADk65RT1JOU/ZR3fkZrH+LLmami3cVBeY6RbT9buP7Yur685q +zex8QneTH/r33lm5WKksZIt3r9MfZFJCNUafTs+l9+6c33D7EXzqr7Fo7kfwjcunpSKuATnmYGEh +I/F6P2LXUdg4vf9z7AbVRPdegmVY3HeW61t+pzKeTMXe2GJVSGa+29dUrIIts4ri9CS50L6cxQcn +KElnUd6eo2mzwdk3YOFlkpnk8wL28MqPEkQK/IFp72FBPnAstsQB6hc/t5rfuWeo/+w2BgtOkfNs +yLRvZUYb/TgdJnvSAX0eg/G8HUbDI6zPwG5XswXml8gqezsLw1dNAi6HGGkUbKd+Eie861GcNqrE +8Yj4Kdc9hfGl/JDLOsdp8Vf2GAuMZ3UhLPAHVBlPh6M4bUIrKlGgIvsch91Cq55ix7SNNdI+82v7 +a1xOG1qLIxZBkIhBQ0Xauan0PP59l8X3rq88nB6Z23uatgUfazs7z8czx+SnWTT60q7aF89Rs7ne +OS+DFbh5uL2nJjtg8RXOd4rSHpaqZoqdx5XH1btyc2O3cXVzD0V+CmgtfhA3mMuaQKNw9zBNjELr +BLPSU5qUs3UBYvRqMyvls62VYq2+85lK/SjundbFre/t3HZh/6veLRUa4o7l41MKdXscusdoNEyn +N1c35j29ZlVTdXCgdr7qdj6/87nQvC9k9YVubPVqrvWQHwxLCO8zZ+UfzhbuC7u7658w0vL3MJoN +VuzRLCatVCELhKqUk1nbUIGKuZ4zpSpwpAMJjsvaGDSf1LI2oWV1ypuO/Ue0KDzqeDJKRfiKjuvN +0PL2jxvsexsr+Z8HtvG2fhaX50PMqOGo763f3WsibP7AKoM+wVM23ZAF0M3nJnyb+O5YnIsn9oa8 +md/JChIsIrfH25m2sLVd/XFcKmym1YPtTOtSKPQrH9ew6Dwfb71dtFHrLHYeXk5WN8UrozDz2i8W +NpeKculiU7/9U+vNqKLAlr2cTeuRvQ4LTNim9VTtCRyLLflnZ2GV/b7HqQizMP94H77U0hBFttqO +4sIYY72ZwFLHd5got+F9xk3d5rLRGMdxQ3WBIUcapHx7Ntx/MAKnXUuFbHbtGpTrB3Fr9eDzbHjN +ajBk5I/oOGhGDTPPRuQ5qGbsKR6D51CzGWaejTjJSADMpATLeJw2jGAJmGSjyrQhJ5kdnBR3no04 +yZAFRrBgSERE5VsIi/noacnF4zsT3YB4CBD+3UGvHwlt2MJ9Fim5fF88R0diGX2Ch/ggi4Ei5/iz +hFESK8nM1aMQ11k45B7BqC4cEgY3vqM+StH7Y3sEbm0Ld3Fjb87QWRBlzv4ZSzqWhk2j7Saoa/ob +OWitjWFdxjWySHDSSO7LoRh/CH+aj649ij9tlF3JuFWH+tPGsDQ89f9xzy21r5g/zcfEs/xpn9Mj ++tM0eXE5m384MDAREyBvpxO0Zbjpvnm2dL99cfnrEXXoOJOdfCs9JTGo74VqG8SgozGhkexOFgKe +47dLT5+NpdJ2o/Irhpwj3wBRutRNrt+1rOCZynfWs/JOWVeKRy6+C6l8PflzMa62Q0UsflsWNm+S +FqftOJ7TIXlOXKj18h/6Qy18pvEqx3faCvdUv26SrRxetlBesTIOh9Ww2ejHVTnGHH0y9FM0m+gP +jn5srXO80SdDj8vanx19fpvoD44+GXqo5g+PPr9T+AdHn9RKY9X/5OiToR9tvRlm9DkpEDT6luIv +jR2XT6ohofk2Q1mWrPVmmk/zIUMwkI/njX/kF7313C/XvqdQm1ZzrC4Cm1OOCz/svapOmm8qwbG2 +ec4Wf2H/PpN1I/iwzDJgWqKnSd1L111GNPJ9htPd5u+kA24MyQ07xbWTomNp/RhE0J9xb6zM783v +8fHmyjm9G4eE0qU3MscSps8DR2T20vgt68ByDkyAb+cY0pnq0FhTIZW9Y1OLXwg+lubWks/cBUU2 +b3ykXmbP7mHQlF14ILqnB7nPhobkP3CR92urX2fO1L6lzhRzxk4DuDzm+RumkTU2O4uHaftenb2H +7PSvSzI96aVUGN1OmrOY2vzZ4LiJnCFgE03WTz6ta4mkvsimWHq1enKE8f7TnuuZkA5LHBF+duQX +mwgrIiMC3jD0SIhAki8812Q9K98OHR55OkjvPxw63PFEgObwROhtfHuIYDM0T4fK2jGjg/yzIRqM +DhjcmeVrta6ieggnAh8Ak2WzAOVBkdKhs3P7Mx4zbPVt/u4nGRGSSvcnCVS26XATwgy7p4yh7oMY +KhgBYWi8yX4MHPa99SEIaCpJOA5y13bUzAhDYGfkj9ORp04MBOHTk14BOU5HSG6aJTpH7chHMGt5 +ECAL+ONoJOPiCBBUV4yvHi2iDTvPT29bQwkK7M0Ajvv2eMLm9MkrrRyixR6R05eOfyN4BHceBB7N +5rTWjRyRpVkOx2b+u+VC8NHz42/sTfyOfPZHnGRT9llDG6etZDQxwubIaWfaRnD7xRAIe0e3VQ/R +bu8dDrrl2iuUHvZcKaG3TzG45MbDaZ5m3b58jyeAbmteLmGcFpdbbz+iuWSgEV6iffoyyhAdafb9 +qDll3YgZryOdUQUQ47Tb/vR4c/9uZibGIi117xmO5MLVh+v2zZeXsQQQWaRfat9RxA== + + + iGjER4AAshthrTdhxHj57I7HFi/NHrcnPZoQe/mOI4D8F2k0yvZSeIlCGo03bcBq7m0ZRJtkKY4s +oU6szH7d02S0hfVb1c6NwtP6SerispV45CRDWalSe05qFVaNRlmt+0kSR5esvFBxGq/k2MtYP/NZ +1Cz3ss5r6CBmqVV8ztGGkuKyR19TqRX7wcoSlyFafFxZsx9sZbgMUcy9sx+QjRXu2UP/cct+VuaS +VD05T8S+4qve3UpzGaJc1bulZVdaKbmZCcBlO0Nw90RAMz1tZXTSnKeZJT5hEWxokgNqJSye7i/b +lml/yTL8TstZUoTueNwAy56eCajui/Dxij9vKF5586JJc3ylxdnsopX5eLtPRjPNJ73enmQDMw6n +XGfee5IOvSeUMav99iw3VBLjFJ+6GIDyUuDcS5frK/nty/nV5/yHftjevthuXtO00p2fS4+UjRer +N3U7q+1CJhxmjc0zP8gv5QyXPUqTI1/OsjRxtHhfWKTfKtNXNJkUqH6+RL/t3Ml7JHECuGltn3wj +g0uI9vKu0kxR6jb6vMwCjl0RBs9YIA8A+XaKfuMSjT8rEpchyuU4f74rdiLsncr35kXevCztpYfM +9sWDp+iHNzV3jefI3k+yfwOtRLbbXqLfivcHafqNa3nvXSYwO7eTb45297XXKLzNdS+21jZvlO3D +G2HGGtfSk+oNHMvNkwxFW0IcNa0ZdFJbogztDAHhIGD8j2WcFAJBIG9eFyuEBTCbPWtJJnQsgGSi +173zwiknFZZ/poWcup6x6Ysp7Zkj0KzUfBbP4Lhxki4XrQNh1FLO/1AwdV8gFJ5yjqG2j/gi4gxP +rMl6JBnpK0iS15+k0WKmnEYHxyHNqxcz7+t26iQIMT7N3fxERxdN4Vye3f+wmf14kYw5Pflitzyd +tXoIooulcMIYbrWI1KLZ7DTbF6WV+nKI4XLHgpW6qZVRs3GQ26m88uyP/3dj6i/dMLSEoRpGInfW +b9Q6J536e72ZADqvTv2V294Xxcvma6vUqdUuav/0Cq1q/6vW7CVWErnt8/z+vqEWatXWay1hDcyz +7vBrxmIQS1rwB5a4fIHE179TeDN3P/dmztYrhTfhdsObu7Qo761jyMHZFL2EfY1GKWQ+6vDs+S2b +TPdXzjHCoJBcFo4kdC77HhTHiaA77etubfm51NKvZeHVswFH9I2N9ZftTPv4YOvQ7G4Ye2vX2VLr +Trkqdu7vhMJd6faitL69XiXCfvDQlbIZkeK69FDCfF+MnLjBeIkiNP/6JplarkxjDw/wYxUjJ06h +4/OexFYT9YfBbKcADWHKTiv2URImqCE4IsBHSZighuBWBNxKwgQ1BFsR8FMSJqghTDl5i4NKwgQ1 +BHeIatxjCYbWEIhAGxVlfA0BGTpISZighkAU6AAlYYIawhQ7X2JASZighsBFWw4oCRPUEKZI6iqv +JIQfyENZAPcK2alTfoHfG9pcvg9it3ZDArmRaA+7ZzcrDyetFDlLYmex0TndyvW0vZ2ikL3gIyG0 +5Avb4HQ2AhesE3is8Vq0pdVpy5rQN5/pKXp42iw5l46eu1OfPp13zt3p2iflZOlxduTMGPipLNKj +Jegyra6kxb3ZXxvUkHJEIbxxJRBBOWWd1Ig3y2TJuIm7j9k7Kjr9T1vfE8hpbc4xq/P2Azzzorfx +LWaE5rNzLASV1bjpmcnPta1GgzClZ0lQ7WFj39EeDrOcaZlp5wVbhfEcyAMDRCfv7vqS3cPjtL0P +Yakwj2TH59hSiHbbK3jixXHOOaiiZgm23TMOOTmwxb2s5vkNQxrIwfbUSF0Dh1nbHITngaS4IyDI +CjxbfFTDNvG6y2QTz/ZyJeerxqFnIzCZ7KUcj1b3dACHsrRLwt/sDcvW0uCG5fKRa9NTSpm3smvP +UptJzu3MOvmY1fkBHDu5I7bdI5ZudkV2Vosl8VAhsmLgcvWNyyLh81w9s7JBZoYNu/q2YbedXP2k +CYvZ2tozEbYgU48PXTNovF0Vsi5gl6wdSrpX+LG0db1UsfcKxWzwXiHOL2dsRtorXIy7RzZFTpnx +2yYTx3TfkyuhKRG25CkroZDbwrXooOQYHbBFn9xeITlFM5wImyufTZsIS3PU/cTRYXnMjeP1np/X +DJXbuPsxmyunvRE3ju2AW+u2G0pLstvrx1Ahm894ZFoqEAGyQBwc3c/FcRqBhufbwvfSODMDNfJ0 +eCOcfe9gHCupzFjUBCNg2QmDHLUjZSUboxGUBYJwkCMvR49JwLObBIKAyLTR4hoyCx8pNs/DJ7m1 +EHjnOa7ni3Fx+CMwe0tjChvUHtK+jQhiC6hmgBjldCYSB9+IAQSX4vKYERZ4aFYc1vI0Yoq/Aov4 +dsaZI0Sz8qMEVBN7GVye3RdpDNz07t6OjUObweiXb67c7s73olWu9EvkiKbNYEzVM1+0PL0UyWlh +/dq9THECyM1pcWkDaqM/lwSxKlTj5dbdd8XLKMPNW1BWvVxiT8/YHcHD04aft25O21suCWN1ZE8r +i0GcFnfu722eSRGN6GzkRAfBntLLXq65Fmnx5XEumrXCGvHynk4HNsJZpIPaYeFoi8OxlqcRWE11 +Vl8ea+5Xl9ez4dQki3SoEKtq+ZEEEDHFVTFFEtPs6emJkhXTn/oC2g2PthF51GRnozJXS3rjtJG1 +vPnUgXhrnYuY66VQbj31nLup0Ey2bGuonRhllieMO3wRTzlU14llijb1zw5x5NuvlXKOm1/gbdSF +D3pyLu2NdZ6ic5hixTGE0/yDcrrqPFjmH/AnKubcpvA7X43IPQMBi27R4yUedpl6cVzvGf7Bu/Lq +PMgSYwgFhUBdEjDdkS2PRdulinMPIT945DAVkL4/rDMbgSNXLKsic9SitjcwGbLFjxzZQRGrm/tI +uR+i9caPS4KU6gLOobR7Tx3L6bG4rCDzXCzzJ7dubq06fvuznUb2fWn7tPpWLhzuJ899LO48c11M +/cW7MByrXVrcK62NiNIPH7rtFn+U19nugto7na3tPtwZ79vn/dl68e71FP0uFyJjY95ffPsoO4fW +KlzXC5u6wy/Xy/bYSIUfeZQV1zl7AlwD8pcHtC6vRdupdE3Olm7hN9n5plAExdUvDX7eUQ+J9FQl +o3+XY5ewq3eCjeiO4znpWXp0/J93Mv+g8Dlrn0j7S3WcihqfVNU4nytmzEWY38LVrC2hXcHA52fe +Q0vtI02dU98fOE+RPL94gnR9gI/ba/Q3PIjON8m1FSHPH70rCFZ8WvSj9Hx1my+kjcVSqXh0ZbCh +ZQcw///Hwv7fdCxsF/caMbUDdxSfis1XfjcRwHMAOq/1+m1SRH3aqb3Xm+XKvzUQtGKC/hPgH37q +ZkKUjISkqvBDRWj5ZeqvVPf3u7SYKKOD6ym33ekV6tVevdWsdP5NrBDYzVH5GLcq6a8hH68mUv98 +NZpQYLnS63XqL/1erbtItj2xtk5lsFz1o9547dSaVikpkdtv9thj/Oj9265Zj1MfvV57JZdr9zuN +bKvznnut5mqNGtKnmxOzYm4xkTuHipvvbhS/K42+gwMfdFdeqwFlm5Uvu6jVTlo4818iwN9//539 +WyYkEE3TzAlSTpKWO69vy91/m73KP8vN7kx8WsB7QxCDlP5PUaPaqVV69d+1auvrq9XsErIMRYDq +MMxQrbohY/RPDO9fjPafX+0+XXzUu0U6C2J1Y+AdZzAv9wuJlYQlJaAkCCLhCcQEwO3X8WPqLyGx +jR83f0/91ccvJ/CR1SVV10DeZDVNE0T8q4qmiF90Q9REGb6Igmhqos+XmwqiQcklwX83/+KvA/j2 +C2B/J0QhcZT4+SAkXqfg4RmIOzWrKJqRUAwhq4qSlACLUzX1rKSbMgOWOaBkqFkJPhBov+0H419+ +CxKTgjVuSMnzj0q7dsEGjaNjp1btiaJpyBHEhAo1RYeOZxVZVEyV/yLoqqIjoVSbYt4vSDpJgOar +0BPF0OGLjvSQVSOry4QeFAY9kjUFKa45MFkzoN+GBAA5K4qCwkF0PasrRiKPr9kwTc+KqiJTXA5Q +zOqmlGDIVUCuqHKCNcGG5Pm22sAyAqGrpqYzoGiqUD3QwEbPAaxGADIGtFpb5mF2nxh2q9sD9MpP +aLQlSYgYbadqWVBgmHXVNVYOkB8sB+iQXCYdEgwGkUwFJiCg5YdLMgCDTKnCgDrUBXOVjZekA35J +Ndh4ORB+vBwgP14O0KG6g59B7GbwA+Y0mB8xp18Ofqfvg3Sb1JjJom6Ej9lSHzWsAk5VUZIVkUxM +U9ZM8tcwddS7soYGxFB9vuAM1bMwxRUtoUpSVtGAXjjqQBUTJKYDW8ZJrchACFU0soYkukFKFqQC +dpsBkdiaKStIRR4KBDdA94MaFAHekXR4pogJuxX0t4S4NEGGr4rpwMoIM7KCKukOTBPFrGIaDDED +WPUjJgtmN7TMg6zuOJidPjv1O5C8D7XK/rA3XCcKVHqDNBxYD2RD1wfWAwIksl8TdVv249t+MP5l +Pxi0YOkyiAv1odYJXQvnQosDdVWQyOqqm5ohky+CJOHqYcJkVogJIFgL6hl+CJZVgP9uthHPQUKE +xVmSYWlVEkdTIAMFGGRFhnUHVxQgHsxYWQVkDsyQsrJkgGyXjKxkCDIHULOqSXnJhsmmmDVAIiOB +FCOrosTiQWrWMLlSioydgblumFlNFkwOoGVNa9lwYKoJywFMvTIPgxVBFHGdoZhVBf6qKN5p5fZv +vo02rMzBJDAiFENxYKaYkIF1FU0yEzZJZFED+QOMaJHN+Y3SDVlfN0wGRLYRoaAGcsABwmCD3AD6 +U+TAUgxiN4Fgs4FcW0VVyhqyqXiAMAgSTCIHKKq4HooSow0HsSiIVThAm9RlF9AaEIpfVdiYsWbY +EFeDudF2gA6nuIEWPzlUcljOIaYDweHz8CrgepnA9JMkWY3S0sbXbw8cbRbnnGkoMMEkLSsp1qTT +6TLpwGBMFN2ghDOA1s5vBZdpQnILJCM+wSC0VWDQgMlcIIOOuAMDAK4MBCCp/G/AJ0h0xtkwDWiN +q0eZgwEPaYJCZhjFDKqDoZswWFbt9m+ujTaozEAgy0VgJRdIBCGskelFqCFLdO2yKWb/ptPN+Vmm +s89QcP5bMEANS6JqMqQcxKqZoLGBXAuRwWVZ9wJhRTVQE7OBCIFWSYwiDGLTLU9fpECbwGUXkI4C +Q2+PE2uFDXG1lxtiB+hwhxtosZBDI4fJkIjODzrD3JwZZgkNMcVAZdOjrMrChK0h4E5Dlt3WkAVz +WUMWjJk0CuiYhsZDZBN0P8WtX6PwUmXBYw5JMIiawenXCtV+eHvIhrjsIRvosodsILNqbPwcxGqG +yyCyG+yyiOx+MfxW1wdoNintGuzfCL2mT/RqaKNA9WlBIqMvmCrIEapYw/90ny842LJpomSGSY92 +h6EQ3U+ByagYaE/ZQJRdGkx5tHtsmAIDJGkC6A+6hsqlykOUrABLEpGDDhDmjkStKQ== + + + DgaqlAj0crALULWuoRVst8GG5PnW2kBkHVBKBQPUZAcIC2vWVGWRoecgtBEEmQ2zW1t2Aa1OMfR2 +xwdpNrnRNiMnOSiqpmwaBnH3iI62CtyXFQQNmglqnYEy74sHAo+LYN4Af4KSjgoW8KssoxxDuYuE +tyFVeE2Us6bIwWDNygInShweB2JXh+85QBg8ovA4mHQJyC5JXH02BN+zGuUUcprt4BnoXXV8sdqu +9D5EmMpiOMkD7RMO1TvgEYPwDG4EeAGpr0qvU//nPiXBggQUkI2MAP/Yr2XiiTNBCGWWTRMVO3mR +vCir94uc27LXqTS7b63Ol9tfue04WLFm9zMOYlevoPwg/2NfnEdOU2Cglk3aCtoiWZW4pmy/tl5q +Jy+/gK+PSO+8jCzatta/1My6eQWLN5FaTNxc837RkUWb2yEKyhHwMpFNTNCpMrCzqbgFnaoAGmK7 +2ECw4bMm2syOUOAgTNIxIJN0HMwSRQy9La5YKzhRx9rLiTqoGvRFNFQcMamDEUeMNEeSMogj6hiM +E3Uc0JbfDnpHxg9QbWKuPiHK1Rco6lRZg/VYkFyijgFtEQUWXRZURYWJMVUwQB1UTbewMyVL0DvS +TjezJum0I+0cCC/tHKAjpRxUtiRjNXLijjXMKeY03kY12McJCrwIWy2uwBOC1qr/X+ANL/AsaTe2 +9u6Wepx2LFDbyKXM20CXNm8DmUoOSAyFd5croP+CaHCr8+juMAyPu1w2FGBo3l0uG4Bf593lDoRX +5x0gr847QObytvFzEKsZLnXebrBLnbf7xZkLVt8H6TbBLY5IV8nIS54kaFlVx5ECyQLWtEmHW7fl +vAUkAwTCX5a5kmTIdGJ4AbsL6L9iELD/JeqjY0CwiQ1DZMNNgCLIRAH3rhz8IFUFTVATrBk2JM83 +2AZaw008XQ6QDa6Nn0HsZvDD7TTYtTti94vht/s+SLeJDTeo9FHL3Nn4E9/xSwPTKpZfWkKNwDBx +ZGF9FyXLkJeyqoZ+WBtYphxC/KgOEAlI130NlzRYFBlE5TY2bZhkOF5lDiijT11JMPQ4erjCslbY +EOQFp702sEwZBFQSrqQkSKA/aRLDz0EMxzXLgKqztclgdq8Yervng1QDZN0JzfxI4+5k2C0KzicK +UhBEFVEigIkNqhaBLgGcrXJApANoGYaKG1w2UELpLOO8VfSsIegaD4GxknTqbBkAlnmgrBOFk6GX +UfnVEWK3woYgMqe9NhCRkQmOG+nOuyAENAmdpjZ6B8C3bABYdgHtXjnonZ4PUG1CU1+RlIjhRiXe +WgnZgIHMRFEkuwaMKIGqoDGgjK5k3FtwusZBGFkGgWUeaFGUobeJzlrBDRhrLzdgsiDTLRM2YCaY ++CIZbGvAHAA/YAPAsgto98pB7/R8gGoTGjAVehDtaiNGiaHKKJjhrybRZdk0NQH6TvRH3Lem29bo +7RCQ79HDoYki2bdmQAk1FY0aY2gTaLriBoo67pbA2yDpZVOzYTJ6yhQF1jgZjCMOAsVUWUrc8sVc ++CSqzPgD7Ta6a+GAIHAVkewoqVkwY6kzFXpCIaT5V3xXZJj1pkx3XCyIVeyWL+aqwkswAJYmYPZo +phnh5iH7w7DmgsRAv64EiwbwH44XmGKw+sgMWHYBsaESbb3zth+MvTwJOw46FKVHkg6hJoRn7ygw +x9GIIT1iQBFGiHrgFdDYwPxUBoCKbDi8RTmGve4HJLylU5+xClTSTDEAyL8OK4So4QaYByhJpupu +EnvdF2h1s+zX98kxU4RSp6giCENTJ90RJFOm3lgMKNHp5gKJ00GIquJ2EopKHRb7W1qMAnmigcym +m/u+QJkFliFQUnGfU8ZNNgHFBxBHVihAhfmLkxS3MiRsIAJR80SIoGqetjhAvlpovgQ9DADaUqjM +v+4BgjVjEjJoskEnOzSUvquDXUiarAuUfCZICeLEwnAEkNFk4Ik1rqhEb9ZYsUG65ycz5Hqku8ot +PwhlDMktP2ygW34gZRTdLSt8YNzLk5AferD7hgvbAsbIwgzCscKYF4UuYAAUVU0mYQSiiSE9Oiip +gqoyyG+cfsDlOJNZMTAToV6JYDNkax1AoGoa1uJgUibWYeVDl+gAUJcpZwsqcU9quCIRTpJESSEe +TBIUhhAn9gXaK5uSZksMgzSEaEAEoinYNBWMQ2RfRCVZPljUbA1FIxWC1gRfUB4if6J7TjZkAlBl +ZF0ZEcgifc8BgvaCgTXE+UHoI8G0wyAFDftlKIQU0ECJvqdlTd0ebA17CjQ0AC2BiGhPY2c0waCK +gi5qln9XoaExSGpZQIoAZXRdVAl+EaN8kHoSaQw0SpKoS4Nhs4Flv0EPAr45qwxKFp2KGEUU6bqp +oaIm0nluSDhxgU10jBBzIL+t0UG/NSuFCiFODUAGiqFJuASBlF4asI6mUAHvVOsLtNpCpf7YcWZ0 +1gTu8niDHVVBAa4zbf2G7qNzQJgTikQaB+ZeVjesFU0ALkyoxCFlWByLhrJiYmdw6sCL0EU67KYG +Q2pSplUIX5qgmWmot4EQF3BTGyEKCUgAbcwUaNgLV0y2+AVQ0VAHwo/oBTdBBSdNBZ5SJcrYqJ8r +lgKpqBK61EHgGjJlR1DfDYCAWQ4Y6LQXqezGfpP5SUQBTEtCCMLYACEh5ggBHqUyRNY1+zWNxPRg +KVCBSSlDFkWKSdV1gMBMossJ6t6iSF8EwaCItFkgXETiicedSEf1vcVSFsweobLfsAUBbeZnD2UM +tRZVOtCyFSokC1RFxlFWRUsc6gosbldYDKgtKiJfDCOkDIIMFkyJttOGGRhPqtImof1BSGrS8AWs +wJF9sCyKtAKUQIIFFDSL8rS5FrZbvz5MdtJEqKq4caKIJhUVpqHTZcYEKapb3C0oKBBM3L1CtQBV +FBkogpLBAeLIWpH6igGvaLb5MwBEdckaRcUw0N+jUkUI9+VAzlubXwgRLaPGAL7TBEuJEnAY0fMs +kFHhGuMA+Xp1mDVosfoDFRYOy173AE3dUhtVE1U1aKEoa1RRgGXSIIH4wFsUQlaOPO2aqcl0lQNd +CZ6agjU37WKDlJ+YwiRG6MhMUopG1rFogZJk/oggMFRDYkBVhLardBLAGqJzAAwshtHErTUHBioK +SLsEw4OCwKCh4bZdrNIdDAyJFnRRtmAaBlPDYq5LKoeHQbjaGNBuE0GFgZms2Z7OVTnJIYHEUgw6 +2U0MPSc9h0aoBl3LTYH0AcMGrdhOWIIlMrH5gE+rGKqUlkqhoUsLJzYDYqi5QJZIBNK9YtTAdaAO +ViFIGpUmGkYgXtGWAKNYQBXsWa7BFrZbv15MVHZIEXo3YyNJtw1YAc09hVBTAs3NNDggCFlYXixL +UwfrJKHiUiJRwxfMdBI8jDBDI44IdI/gSge9kwxifmAEGWh6HATsVAEkL/IEAwJzoAOfQwXLtSyo +XIWo7wkSZUKnWTqaPpjX4DQdxl/EUWI9tCAWE4pEgLFiaLSjtomGnwZaNAfhWsqAdock9AMSZrU7 +LaELR9HdtIEaSVSlRUF80eYyRmXvYOT9RohfRiVsmsGa+MXDcI0nWQ6KpVljrLoskXkpSoRssOJL +VPAhUMftH6QlLD60gcTJiBAZTQauLRakSrkFLBWFLwYy1MQFmqEyLUWYr5FoI7LM2oUR1oagck1n +EJ5bHKBkBYOgB8ygAkTALSmuoRaENNTpj1PM6bMIbEP4xyEN6mjUFuYIiPq8QIeY0hhUQc3QEwMD +kZ/odI5hddLeqVTdAkGmU17QccmSGbBMB0xQRAajI2gFusGiadJphK5kAsGwvTx9D9ZMy30niSIp +pgkafVGRDN0NERV70jhAhW4zIwSEsUYgmmnSFy1nFM4eU7RrlETimcA1nlZImw56L67J2EFdlxUG +ybtIYQHLfvQJAr45stF5KMHMUy3Z6ABl4tSmaJxWuIGgRHNAQmdNpA43op2QDqIljQDctbbJjLRU +7CgWjloyLDRExKAaqtIXYWU17BdVXZMstykNUHcBYYVUEi6IgtowNz5oaZtOMxygbLWVAWR7+KlK +ZRHIksno3LZBZReIJELZINxXplViiJdkW77YUAG1eoQoxBcnoTvHtNGTBEvSSUEWrclPMRmiaroA +pmazBPpVRDpjwSJT7UY4QJ0s1QCQJCrdDYsryQaqM4YWZQydcpeIYZkI0FUyjOj70HgSk3Ay5zWn +lKwIlpwUyOxUaMIPlZzW6qiJguHpspLVNVXjKQNqriYqPATmHSiwdN5xQE2VrRo1MhYqDbHjmor6 +Mc1L5VZRjcYEENalzh+NpjUQ0SIrDGCtITB1JQYsu4A8S3jn1mT1nwg1GmoxXVGTAVFzGNIio6MX +A2QUXSRCVRJh6YdlgwGtbVNFMLiSkki6aCZkExOHdJGHSNSbW8UXHSAKPswUdlCZlpxlNdoQslmv +w4SWGazMwzD6isYWcBX4AtESpoIPFjB0NeoeIKzYGm542kBGFPSvmLILgr5FhSjsHBDtZEVNcKhg +2cR1gKvRgpBtaYVENtugMgcCQ1uwwhIc7D4wbmAm4fcFkRjhwSLamISCQZJ1N7dIdPPTwy3Qb012 +cQsmm6qEWVSMnGcAK/6CUMaGcePjVOoPxDHXFTtMwDAEMwjIsRF73ReIA6Pqntd9gVbbvUDickLK +SKqsOEPISGUB8q5a2TgP0Hly4xxnw0ICuUpWa0JyK2KMA2KaokGnGQOis1+GOQCmDlFtSdsNEHwS +epExHdGBYLdB/RQxuMCGlTkYUgJmOoE5L7uAIF5kVWJAhIioOBDi4/ayC0Kam6cvWkCrY2W/3k6O +2nF2Y4FFqPPANatg/VJ1Q3TPKtTGFYkrKeHqIoEBwqYVg3DzigG5OeTU6w/k5hBZvjFAxh/IzSH2 +ui+Qm0PsdV8gN7F4IJ1YqGbLMptHjFrcxGK1sok1QOrJDXWECSNpuJ0pa+5RVkHHILnN/CirKsah +cUNPIqVIKrIzygzCjTIDanR7p+wC4maBmmDonfXOaYUNyfPt5bmDATlGYK+7gaLM8xEYWbAkkKVQ +g/lGQsI4CGkv6YQD5FiAB1IWYPgtFmCtYCzAmstYYGAcJscCEUoZKIzQI52TPsgCOklikt0iiQEx +5Eag00jHDURFDwDyglQXcdtFDgDyr7Mm+QInLRDlCaRV9Wr/9CTDiAybjEolomc/kOjKIPXYEzdv +YuaH4VZ/ZNDJTEN2T2FZsOx6B4gBajTnw1aWOQhTljmgpSwzVLZEZTVyyjKe8kKPDmByl8GYXsxV +4Atkc10WRLrb4BIA8B04Q+GEh0MUR1lmEI3uY1V52jnKMkNl6cFcjUxZlkHjpykCnLrMAdnEZjX4 +wCY+2WUlxtIOM8o6ZYib8Zg4r4kefYMDsokogzosKqoaAOQmN6Z1mYIpBQBdrztN8gVOfMZHZCo7 +nnqZbFCQNqAvzKDH+TCgRk/JKXuAIFIwRFXE43GsTpETRHB/WrOlnUBz1GQwyskOug== + + + AySUB6MK/dvsXQnohv5Xhp+HkGYQbA7QanDZrxecN5t7Q8IgBoWygw0kPEp9a3iUgo6BU/5AnhgM +iG41cnqDTH2idI6SsxucflsQbD6jkOkEkmK8LrRF596V0XOHORsOfgbhiOEA+QY7xPAF2kQo+1Gm +PJlzgCwmjHsYFYlOJmdtoByVJcqExJsp6QxYdgGRbWzyOa/7AtnrDkuwhzL10H/xQH42Y9CTLMgB +QDpxKRAdhaqieoCqdbyZDZTRhyXQgQUNkQdo1G+KC5IDU2mgAgIERacrlIFRIjJxoVssL1vH1nDF +MNbA4LHLWVFCRc0BSDTYI89Vx/fRobQv0H7bDZSzAu2SjM52jrwccSxI3m8UJsp+ihAR848bS7Kt +gDsZWpZT3LVMMCAnvUHFp9lavkCeaqpIAz/8gfzrrEm+wEkvE0pElH18xTAqpDtaMVwaRTnEYGMS +PYV6jYwM9kVjBVUDc8lsYJkDor4ja3T33XndF8i//uaCK1lNtwIwWV0WsOwCarj9r3vQ+gLZ604o +H56qAyo3PAT7SxDtwGUCw8MDBVm1zgORyX6PGwb6qiRxQDxtUlLJ4RySFd7HIAL1zGMutQ3E7hOH +MUJobp5p0JwQhSRkkcMawWQSdStE0ymmWwHNDBWmteOWAYPg3oHorRH6Ieo0JJM03u653UP7d96H +OpMVHhNIzLZmRqQ36o/MDBW9VrgC4Gio6Dz/cgExuZ3meDpA5AJFlERypALuyCKAxG+qZNtaVBgk +T9P8ycLqABGZrFonrjnvYjSuSSaejd6GOK3I0xctoNXesl8nuOnBvaHQ5OEvF1CkFh9plGTtePgD +OVrYQJwj5CAIFVUs0no0+UU5wXXbgpDzJhwCWUDSepjTKmbjOe/i/hiGyzP0NsRFCwbk2sto4Qu0 +aFD2I8xkp0aEWhd7apjRx06ETg1rTpwNkai5PXA4c1a1cnQxDxWlMqaxk+105CZMU5bp6UKAlvIk +Or/xZCMdRBKV4k4xEGS6RHeBHXTwRcJoUhdMRTWfjCCe/CHjgSN+MAPmkO5G5weyGlwOyY4daoTV +CM2JnlSKx3IZxGHKCCYiy2uYwslRTFQFjIiUeJKxghzNGEqOaByQUUjECAdc3PxgjERcG/1gk6Ub +9DDCO0YYVhSBgdADo4iYeSEQwSwKGnUTkmw/geamiShCJXK0JEal0yQUEzcjcQnmCuIxCxou1DZG +LCfTNCRfGCLGEyBJJehAEqQAIPf2YMMnR7jIxHyecLKMA6e76Ib55iR2mKcb2uSSSNnIphtf0Kab +jZAjkR8IYyAsJ59DIH8ge3mg0ROjWZRTF9O3NFVP/D2FJyXi2onTT0aN6YueMEnO08HcemIYYusl +jRzOIICuBd0A+wMUK1QPEQKaMCprJqaZWhBYrQyMBMMDARENpugjgBwui5Xpon0QIwfT3WUMWErd +AEN3XrIOKdHwHFmsWSbzG3RmQJ3AcYZlkp6uizlIVToGeAAlBWlmgnZepCKAHpzJqKGgtz9vUcOB +CYqrEPGbDtAw7CiCocZRi1wEJ3InAXc2gU5j42QQyxIG4ZEtMcnyU9jAMt1NIkPoACUNE44E6kXQ +dVAROQimCtHzsweBZR4oW4zG8MPcIEdDsmbYELJXbzfYBiI2yQqWZ+9iaDb1ndn4HQjftgFg2QW0 +++Xgd/o+QLcJJbvjycARngo8CEOXTNeQyaCH0sOYuSGTMeJUkblxlElUpcJ6xgCMKAOwMgezyclw +2yRnTeCGizWWGy5YLWAeoYrkvIsaMCZmM/z/3+AiyC7DEPRBEYR5Cm4+3N8YYUa16CI01oG8DMwH +dD8Z6I4j17wU8A1HuqCbxFQDEtNTQ4oSM3NAVx6lFyeWpSok5uXllySWpBYApRTSi1KLS/KLUhWK +M/LLQSIgTXANqqqu/m68XACKqCfC + + + \ No newline at end of file diff -Nru nestopia-1.48/icons/svg/nestopia.svg nestopia-1.49/icons/svg/nestopia.svg --- nestopia-1.48/icons/svg/nestopia.svg 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/icons/svg/nestopia.svg 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,22 @@ + + + + + + + image/svg+xml + + + + + + + + + + + + + + + diff -Nru nestopia-1.48/libretro/jni/Android.mk nestopia-1.49/libretro/jni/Android.mk --- nestopia-1.48/libretro/jni/Android.mk 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/jni/Android.mk 2018-06-24 23:26:58.000000000 +0000 @@ -1,32 +1,21 @@ -GIT_VERSION := " $(shell git describe --dirty --always --tags)" - -LOCAL_SHORT_COMMANDS := true - LOCAL_PATH := $(call my-dir) -include $(CLEAR_VARS) - -LOCAL_MODULE := libretro +CORE_DIR = $(LOCAL_PATH)/../.. -ifeq ($(TARGET_ARCH),arm) -LOCAL_CFLAGS += -DANDROID_ARM -LOCAL_ARM_MODE := arm -endif +include $(CORE_DIR)/libretro/Makefile.common -ifeq ($(TARGET_ARCH),x86) -LOCAL_CFLAGS += -DANDROID_X86 -endif +COREFLAGS := -DANDROID -D__LIBRETRO__ $(INCFLAGS) -ifeq ($(TARGET_ARCH),mips) -LOCAL_CFLAGS += -DANDROID_MIPS +GIT_VERSION := " $(shell git rev-parse --short HEAD || echo unknown)" +ifneq ($(GIT_VERSION)," unknown") + COREFLAGS += -DGIT_VERSION=\"$(GIT_VERSION)\" endif -CORE_DIR = ../.. - -include $(CORE_DIR)/libretro/Makefile.common - -LOCAL_SRC_FILES += $(SOURCES_CXX) $(SOURCES_C) -LOCAL_CFLAGS += -DGIT_VERSION=\"$(GIT_VERSION)\" -LOCAL_CXXFLAGS += -DANDROID -D__LIBRETRO__ -DINLINE=inline -DHAVE_STDINT_H -DHAVE_INTTYPES_H -DNST_NO_ZLIB -fexceptions -DGIT_VERSION=\"$(GIT_VERSION)\" $(INCFLAGS) - +include $(CLEAR_VARS) +LOCAL_MODULE := retro +LOCAL_SRC_FILES := $(SOURCES_CXX) +LOCAL_CXXFLAGS := $(COREFLAGS) +LOCAL_LDFLAGS := -Wl,-version-script=$(CORE_DIR)/libretro/link.T +LOCAL_LDLIBS := -lz +LOCAL_CPP_FEATURES := exceptions include $(BUILD_SHARED_LIBRARY) diff -Nru nestopia-1.48/libretro/libretro-common/include/compat/msvc/stdint.h nestopia-1.49/libretro/libretro-common/include/compat/msvc/stdint.h --- nestopia-1.48/libretro/libretro-common/include/compat/msvc/stdint.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/libretro/libretro-common/include/compat/msvc/stdint.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,258 @@ +/* ISO C9x compliant stdint.h for Microsoft Visual Studio + * Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 + * + * Copyright (c) 2006-2008 Alexander Chemeris + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. The name of the author may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef __RARCH_STDINT_H +#define __RARCH_STDINT_H + +#if _MSC_VER && (_MSC_VER < 1600) +/* Pre-MSVC 2010 needs an implementation of stdint.h. */ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#include + +/* For Visual Studio 6 in C++ mode and for many Visual Studio versions when + * compiling for ARM we should wrap include with 'extern "C++" {}' + * or compiler give many errors like this: + * + * error C2733: second C linkage of overloaded function 'wmemchr' not allowed + */ +#ifdef __cplusplus +#if _MSC_VER <= 1200 +extern "C++" { +#else +extern "C" { +#endif +#endif +# include +#ifdef __cplusplus +} +#endif + +/* Define _W64 macros to mark types changing their size, like intptr_t. */ +#ifndef _W64 +# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 +# define _W64 __w64 +# else +# define _W64 +# endif +#endif + + +/* 7.18.1 Integer types. */ + +/* 7.18.1.1 Exact-width integer types. */ + +/* Visual Studio 6 and Embedded Visual C++ 4 doesn't + * realize that, e.g. char has the same size as __int8 + * so we give up on __intX for them. + */ +#if (_MSC_VER < 1300) + typedef signed char int8_t; + typedef signed short int16_t; + typedef signed int int32_t; + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; +#else + typedef signed __int8 int8_t; + typedef signed __int16 int16_t; + typedef signed __int32 int32_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; +#endif +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; + + +/* 7.18.1.2 Minimum-width integer types. */ +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; +typedef uint8_t uint_least8_t; +typedef uint16_t uint_least16_t; +typedef uint32_t uint_least32_t; +typedef uint64_t uint_least64_t; + +/* 7.18.1.3 Fastest minimum-width integer types. */ +typedef int8_t int_fast8_t; +typedef int16_t int_fast16_t; +typedef int32_t int_fast32_t; +typedef int64_t int_fast64_t; +typedef uint8_t uint_fast8_t; +typedef uint16_t uint_fast16_t; +typedef uint32_t uint_fast32_t; +typedef uint64_t uint_fast64_t; + +/* 7.18.1.4 Integer types capable of holding object pointers. */ +#ifdef _WIN64 /* [ */ + typedef signed __int64 intptr_t; + typedef unsigned __int64 uintptr_t; +#else /* _WIN64 ][ */ + typedef _W64 signed int intptr_t; + typedef _W64 unsigned int uintptr_t; +#endif /* _WIN64 ] */ + +/* 7.18.1.5 Greatest-width integer types. */ +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; + +/* 7.18.2 Limits of specified-width integer types. */ + +#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) +/* [ See footnote 220 at page 257 and footnote 221 at page 259. */ + +/* 7.18.2.1 Limits of exact-width integer types. */ +#define INT8_MIN ((int8_t)_I8_MIN) +#define INT8_MAX _I8_MAX +#define INT16_MIN ((int16_t)_I16_MIN) +#define INT16_MAX _I16_MAX +#define INT32_MIN ((int32_t)_I32_MIN) +#define INT32_MAX _I32_MAX +#define INT64_MIN ((int64_t)_I64_MIN) +#define INT64_MAX _I64_MAX +#define UINT8_MAX _UI8_MAX +#define UINT16_MAX _UI16_MAX +#define UINT32_MAX _UI32_MAX +#define UINT64_MAX _UI64_MAX + +/* 7.18.2.2 Limits of minimum-width integer types. */ +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MIN INT64_MIN +#define INT_LEAST64_MAX INT64_MAX +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX + +/* 7.18.2.3 Limits of fastest minimum-width integer types. */ +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MIN INT64_MIN +#define INT_FAST64_MAX INT64_MAX +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX + +/* 7.18.2.4 Limits of integer types capable of holding object pointers. */ +#ifdef _WIN64 /* [ */ +# define INTPTR_MIN INT64_MIN +# define INTPTR_MAX INT64_MAX +# define UINTPTR_MAX UINT64_MAX +#else /* _WIN64 ][ */ +# define INTPTR_MIN INT32_MIN +# define INTPTR_MAX INT32_MAX +# define UINTPTR_MAX UINT32_MAX +#endif /* _WIN64 ] */ + +/* 7.18.2.5 Limits of greatest-width integer types */ +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX + +/* 7.18.3 Limits of other integer types */ + +#ifdef _WIN64 /* [ */ +# define PTRDIFF_MIN _I64_MIN +# define PTRDIFF_MAX _I64_MAX +#else /* _WIN64 ][ */ +# define PTRDIFF_MIN _I32_MIN +# define PTRDIFF_MAX _I32_MAX +#endif /* _WIN64 ] */ + +#define SIG_ATOMIC_MIN INT_MIN +#define SIG_ATOMIC_MAX INT_MAX + +#ifndef SIZE_MAX /* [ */ +# ifdef _WIN64 /* [ */ +# define SIZE_MAX _UI64_MAX +# else /* _WIN64 ][ */ +# define SIZE_MAX _UI32_MAX +# endif /* _WIN64 ] */ +#endif /* SIZE_MAX ] */ + +/* WCHAR_MIN and WCHAR_MAX are also defined in */ +#ifndef WCHAR_MIN /* [ */ +# define WCHAR_MIN 0 +#endif /* WCHAR_MIN ] */ +#ifndef WCHAR_MAX // [ +# define WCHAR_MAX _UI16_MAX +#endif /* WCHAR_MAX ] */ + +#define WINT_MIN 0 +#define WINT_MAX _UI16_MAX + +#endif /* __STDC_LIMIT_MACROS ] */ + +/* 7.18.4 Limits of other integer types */ + +#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) +/* [ See footnote 224 at page 260 */ + +/* 7.18.4.1 Macros for minimum-width integer constants */ + +#define INT8_C(val) val##i8 +#define INT16_C(val) val##i16 +#define INT32_C(val) val##i32 +#define INT64_C(val) val##i64 + +#define UINT8_C(val) val##ui8 +#define UINT16_C(val) val##ui16 +#define UINT32_C(val) val##ui32 +#define UINT64_C(val) val##ui64 + +/* 7.18.4.2 Macros for greatest-width integer constants */ +#define INTMAX_C INT64_C +#define UINTMAX_C UINT64_C + +#endif +/* __STDC_CONSTANT_MACROS ] */ + +#else +/* Sanity for everything else. */ +#include +#endif + +#endif + diff -Nru nestopia-1.48/libretro/libretro-common/include/libretro.h nestopia-1.49/libretro/libretro-common/include/libretro.h --- nestopia-1.48/libretro/libretro-common/include/libretro.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/libretro/libretro-common/include/libretro.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,2323 @@ +/* Copyright (C) 2010-2017 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this libretro API header (libretro.h). + * --------------------------------------------------------------------------------------- + * + * Permission is hereby granted, free of charge, + * to any person obtaining a copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef LIBRETRO_H__ +#define LIBRETRO_H__ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef __cplusplus +#if defined(_MSC_VER) && !defined(SN_TARGET_PS3) +/* Hack applied for MSVC when compiling in C89 mode + * as it isn't C99-compliant. */ +#define bool unsigned char +#define true 1 +#define false 0 +#else +#include +#endif +#endif + +#ifndef RETRO_CALLCONV +# if defined(__GNUC__) && defined(__i386__) && !defined(__x86_64__) +# define RETRO_CALLCONV __attribute__((cdecl)) +# elif defined(_MSC_VER) && defined(_M_X86) && !defined(_M_X64) +# define RETRO_CALLCONV __cdecl +# else +# define RETRO_CALLCONV /* all other platforms only have one calling convention each */ +# endif +#endif + +#ifndef RETRO_API +# if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) +# ifdef RETRO_IMPORT_SYMBOLS +# ifdef __GNUC__ +# define RETRO_API RETRO_CALLCONV __attribute__((__dllimport__)) +# else +# define RETRO_API RETRO_CALLCONV __declspec(dllimport) +# endif +# else +# ifdef __GNUC__ +# define RETRO_API RETRO_CALLCONV __attribute__((__dllexport__)) +# else +# define RETRO_API RETRO_CALLCONV __declspec(dllexport) +# endif +# endif +# else +# if defined(__GNUC__) && __GNUC__ >= 4 && !defined(__CELLOS_LV2__) +# define RETRO_API RETRO_CALLCONV __attribute__((__visibility__("default"))) +# else +# define RETRO_API RETRO_CALLCONV +# endif +# endif +#endif + +/* Used for checking API/ABI mismatches that can break libretro + * implementations. + * It is not incremented for compatible changes to the API. + */ +#define RETRO_API_VERSION 1 + +/* + * Libretro's fundamental device abstractions. + * + * Libretro's input system consists of some standardized device types, + * such as a joypad (with/without analog), mouse, keyboard, lightgun + * and a pointer. + * + * The functionality of these devices are fixed, and individual cores + * map their own concept of a controller to libretro's abstractions. + * This makes it possible for frontends to map the abstract types to a + * real input device, and not having to worry about binding input + * correctly to arbitrary controller layouts. + */ + +#define RETRO_DEVICE_TYPE_SHIFT 8 +#define RETRO_DEVICE_MASK ((1 << RETRO_DEVICE_TYPE_SHIFT) - 1) +#define RETRO_DEVICE_SUBCLASS(base, id) (((id + 1) << RETRO_DEVICE_TYPE_SHIFT) | base) + +/* Input disabled. */ +#define RETRO_DEVICE_NONE 0 + +/* The JOYPAD is called RetroPad. It is essentially a Super Nintendo + * controller, but with additional L2/R2/L3/R3 buttons, similar to a + * PS1 DualShock. */ +#define RETRO_DEVICE_JOYPAD 1 + +/* The mouse is a simple mouse, similar to Super Nintendo's mouse. + * X and Y coordinates are reported relatively to last poll (poll callback). + * It is up to the libretro implementation to keep track of where the mouse + * pointer is supposed to be on the screen. + * The frontend must make sure not to interfere with its own hardware + * mouse pointer. + */ +#define RETRO_DEVICE_MOUSE 2 + +/* KEYBOARD device lets one poll for raw key pressed. + * It is poll based, so input callback will return with the current + * pressed state. + * For event/text based keyboard input, see + * RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK. + */ +#define RETRO_DEVICE_KEYBOARD 3 + +/* LIGHTGUN device is similar to Guncon-2 for PlayStation 2. + * It reports X/Y coordinates in screen space (similar to the pointer) + * in the range [-0x8000, 0x7fff] in both axes, with zero being center. + * As well as reporting on/off screen state. It features a trigger, + * start/select buttons, auxiliary action buttons and a + * directional pad. A forced off-screen shot can be requested for + * auto-reloading function in some games. + */ +#define RETRO_DEVICE_LIGHTGUN 4 + +/* The ANALOG device is an extension to JOYPAD (RetroPad). + * Similar to DualShock2 it adds two analog sticks and all buttons can + * be analog. This is treated as a separate device type as it returns + * axis values in the full analog range of [-0x8000, 0x7fff]. + * Positive X axis is right. Positive Y axis is down. + * Buttons are returned in the range [0, 0x7fff]. + * Only use ANALOG type when polling for analog values. + */ +#define RETRO_DEVICE_ANALOG 5 + +/* Abstracts the concept of a pointing mechanism, e.g. touch. + * This allows libretro to query in absolute coordinates where on the + * screen a mouse (or something similar) is being placed. + * For a touch centric device, coordinates reported are the coordinates + * of the press. + * + * Coordinates in X and Y are reported as: + * [-0x7fff, 0x7fff]: -0x7fff corresponds to the far left/top of the screen, + * and 0x7fff corresponds to the far right/bottom of the screen. + * The "screen" is here defined as area that is passed to the frontend and + * later displayed on the monitor. + * + * The frontend is free to scale/resize this screen as it sees fit, however, + * (X, Y) = (-0x7fff, -0x7fff) will correspond to the top-left pixel of the + * game image, etc. + * + * To check if the pointer coordinates are valid (e.g. a touch display + * actually being touched), PRESSED returns 1 or 0. + * + * If using a mouse on a desktop, PRESSED will usually correspond to the + * left mouse button, but this is a frontend decision. + * PRESSED will only return 1 if the pointer is inside the game screen. + * + * For multi-touch, the index variable can be used to successively query + * more presses. + * If index = 0 returns true for _PRESSED, coordinates can be extracted + * with _X, _Y for index = 0. One can then query _PRESSED, _X, _Y with + * index = 1, and so on. + * Eventually _PRESSED will return false for an index. No further presses + * are registered at this point. */ +#define RETRO_DEVICE_POINTER 6 + +/* Buttons for the RetroPad (JOYPAD). + * The placement of these is equivalent to placements on the + * Super Nintendo controller. + * L2/R2/L3/R3 buttons correspond to the PS1 DualShock. + * Also used as id values for RETRO_DEVICE_INDEX_ANALOG_BUTTON */ +#define RETRO_DEVICE_ID_JOYPAD_B 0 +#define RETRO_DEVICE_ID_JOYPAD_Y 1 +#define RETRO_DEVICE_ID_JOYPAD_SELECT 2 +#define RETRO_DEVICE_ID_JOYPAD_START 3 +#define RETRO_DEVICE_ID_JOYPAD_UP 4 +#define RETRO_DEVICE_ID_JOYPAD_DOWN 5 +#define RETRO_DEVICE_ID_JOYPAD_LEFT 6 +#define RETRO_DEVICE_ID_JOYPAD_RIGHT 7 +#define RETRO_DEVICE_ID_JOYPAD_A 8 +#define RETRO_DEVICE_ID_JOYPAD_X 9 +#define RETRO_DEVICE_ID_JOYPAD_L 10 +#define RETRO_DEVICE_ID_JOYPAD_R 11 +#define RETRO_DEVICE_ID_JOYPAD_L2 12 +#define RETRO_DEVICE_ID_JOYPAD_R2 13 +#define RETRO_DEVICE_ID_JOYPAD_L3 14 +#define RETRO_DEVICE_ID_JOYPAD_R3 15 + +/* Index / Id values for ANALOG device. */ +#define RETRO_DEVICE_INDEX_ANALOG_LEFT 0 +#define RETRO_DEVICE_INDEX_ANALOG_RIGHT 1 +#define RETRO_DEVICE_INDEX_ANALOG_BUTTON 2 +#define RETRO_DEVICE_ID_ANALOG_X 0 +#define RETRO_DEVICE_ID_ANALOG_Y 1 + +/* Id values for MOUSE. */ +#define RETRO_DEVICE_ID_MOUSE_X 0 +#define RETRO_DEVICE_ID_MOUSE_Y 1 +#define RETRO_DEVICE_ID_MOUSE_LEFT 2 +#define RETRO_DEVICE_ID_MOUSE_RIGHT 3 +#define RETRO_DEVICE_ID_MOUSE_WHEELUP 4 +#define RETRO_DEVICE_ID_MOUSE_WHEELDOWN 5 +#define RETRO_DEVICE_ID_MOUSE_MIDDLE 6 +#define RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELUP 7 +#define RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELDOWN 8 +#define RETRO_DEVICE_ID_MOUSE_BUTTON_4 9 +#define RETRO_DEVICE_ID_MOUSE_BUTTON_5 10 + +/* Id values for LIGHTGUN. */ +#define RETRO_DEVICE_ID_LIGHTGUN_SCREEN_X 13 /*Absolute Position*/ +#define RETRO_DEVICE_ID_LIGHTGUN_SCREEN_Y 14 /*Absolute*/ +#define RETRO_DEVICE_ID_LIGHTGUN_IS_OFFSCREEN 15 /*Status Check*/ +#define RETRO_DEVICE_ID_LIGHTGUN_TRIGGER 2 +#define RETRO_DEVICE_ID_LIGHTGUN_RELOAD 16 /*Forced off-screen shot*/ +#define RETRO_DEVICE_ID_LIGHTGUN_AUX_A 3 +#define RETRO_DEVICE_ID_LIGHTGUN_AUX_B 4 +#define RETRO_DEVICE_ID_LIGHTGUN_START 6 +#define RETRO_DEVICE_ID_LIGHTGUN_SELECT 7 +#define RETRO_DEVICE_ID_LIGHTGUN_AUX_C 8 +#define RETRO_DEVICE_ID_LIGHTGUN_DPAD_UP 9 +#define RETRO_DEVICE_ID_LIGHTGUN_DPAD_DOWN 10 +#define RETRO_DEVICE_ID_LIGHTGUN_DPAD_LEFT 11 +#define RETRO_DEVICE_ID_LIGHTGUN_DPAD_RIGHT 12 +/* deprecated */ +#define RETRO_DEVICE_ID_LIGHTGUN_X 0 /*Relative Position*/ +#define RETRO_DEVICE_ID_LIGHTGUN_Y 1 /*Relative*/ +#define RETRO_DEVICE_ID_LIGHTGUN_CURSOR 3 /*Use Aux:A*/ +#define RETRO_DEVICE_ID_LIGHTGUN_TURBO 4 /*Use Aux:B*/ +#define RETRO_DEVICE_ID_LIGHTGUN_PAUSE 5 /*Use Start*/ + +/* Id values for POINTER. */ +#define RETRO_DEVICE_ID_POINTER_X 0 +#define RETRO_DEVICE_ID_POINTER_Y 1 +#define RETRO_DEVICE_ID_POINTER_PRESSED 2 + +/* Returned from retro_get_region(). */ +#define RETRO_REGION_NTSC 0 +#define RETRO_REGION_PAL 1 + +/* Id values for LANGUAGE */ +enum retro_language +{ + RETRO_LANGUAGE_ENGLISH = 0, + RETRO_LANGUAGE_JAPANESE = 1, + RETRO_LANGUAGE_FRENCH = 2, + RETRO_LANGUAGE_SPANISH = 3, + RETRO_LANGUAGE_GERMAN = 4, + RETRO_LANGUAGE_ITALIAN = 5, + RETRO_LANGUAGE_DUTCH = 6, + RETRO_LANGUAGE_PORTUGUESE_BRAZIL = 7, + RETRO_LANGUAGE_PORTUGUESE_PORTUGAL = 8, + RETRO_LANGUAGE_RUSSIAN = 9, + RETRO_LANGUAGE_KOREAN = 10, + RETRO_LANGUAGE_CHINESE_TRADITIONAL = 11, + RETRO_LANGUAGE_CHINESE_SIMPLIFIED = 12, + RETRO_LANGUAGE_ESPERANTO = 13, + RETRO_LANGUAGE_POLISH = 14, + RETRO_LANGUAGE_VIETNAMESE = 15, + RETRO_LANGUAGE_LAST, + + /* Ensure sizeof(enum) == sizeof(int) */ + RETRO_LANGUAGE_DUMMY = INT_MAX +}; + +/* Passed to retro_get_memory_data/size(). + * If the memory type doesn't apply to the + * implementation NULL/0 can be returned. + */ +#define RETRO_MEMORY_MASK 0xff + +/* Regular save RAM. This RAM is usually found on a game cartridge, + * backed up by a battery. + * If save game data is too complex for a single memory buffer, + * the SAVE_DIRECTORY (preferably) or SYSTEM_DIRECTORY environment + * callback can be used. */ +#define RETRO_MEMORY_SAVE_RAM 0 + +/* Some games have a built-in clock to keep track of time. + * This memory is usually just a couple of bytes to keep track of time. + */ +#define RETRO_MEMORY_RTC 1 + +/* System ram lets a frontend peek into a game systems main RAM. */ +#define RETRO_MEMORY_SYSTEM_RAM 2 + +/* Video ram lets a frontend peek into a game systems video RAM (VRAM). */ +#define RETRO_MEMORY_VIDEO_RAM 3 + +/* Keysyms used for ID in input state callback when polling RETRO_KEYBOARD. */ +enum retro_key +{ + RETROK_UNKNOWN = 0, + RETROK_FIRST = 0, + RETROK_BACKSPACE = 8, + RETROK_TAB = 9, + RETROK_CLEAR = 12, + RETROK_RETURN = 13, + RETROK_PAUSE = 19, + RETROK_ESCAPE = 27, + RETROK_SPACE = 32, + RETROK_EXCLAIM = 33, + RETROK_QUOTEDBL = 34, + RETROK_HASH = 35, + RETROK_DOLLAR = 36, + RETROK_AMPERSAND = 38, + RETROK_QUOTE = 39, + RETROK_LEFTPAREN = 40, + RETROK_RIGHTPAREN = 41, + RETROK_ASTERISK = 42, + RETROK_PLUS = 43, + RETROK_COMMA = 44, + RETROK_MINUS = 45, + RETROK_PERIOD = 46, + RETROK_SLASH = 47, + RETROK_0 = 48, + RETROK_1 = 49, + RETROK_2 = 50, + RETROK_3 = 51, + RETROK_4 = 52, + RETROK_5 = 53, + RETROK_6 = 54, + RETROK_7 = 55, + RETROK_8 = 56, + RETROK_9 = 57, + RETROK_COLON = 58, + RETROK_SEMICOLON = 59, + RETROK_LESS = 60, + RETROK_EQUALS = 61, + RETROK_GREATER = 62, + RETROK_QUESTION = 63, + RETROK_AT = 64, + RETROK_LEFTBRACKET = 91, + RETROK_BACKSLASH = 92, + RETROK_RIGHTBRACKET = 93, + RETROK_CARET = 94, + RETROK_UNDERSCORE = 95, + RETROK_BACKQUOTE = 96, + RETROK_a = 97, + RETROK_b = 98, + RETROK_c = 99, + RETROK_d = 100, + RETROK_e = 101, + RETROK_f = 102, + RETROK_g = 103, + RETROK_h = 104, + RETROK_i = 105, + RETROK_j = 106, + RETROK_k = 107, + RETROK_l = 108, + RETROK_m = 109, + RETROK_n = 110, + RETROK_o = 111, + RETROK_p = 112, + RETROK_q = 113, + RETROK_r = 114, + RETROK_s = 115, + RETROK_t = 116, + RETROK_u = 117, + RETROK_v = 118, + RETROK_w = 119, + RETROK_x = 120, + RETROK_y = 121, + RETROK_z = 122, + RETROK_DELETE = 127, + + RETROK_KP0 = 256, + RETROK_KP1 = 257, + RETROK_KP2 = 258, + RETROK_KP3 = 259, + RETROK_KP4 = 260, + RETROK_KP5 = 261, + RETROK_KP6 = 262, + RETROK_KP7 = 263, + RETROK_KP8 = 264, + RETROK_KP9 = 265, + RETROK_KP_PERIOD = 266, + RETROK_KP_DIVIDE = 267, + RETROK_KP_MULTIPLY = 268, + RETROK_KP_MINUS = 269, + RETROK_KP_PLUS = 270, + RETROK_KP_ENTER = 271, + RETROK_KP_EQUALS = 272, + + RETROK_UP = 273, + RETROK_DOWN = 274, + RETROK_RIGHT = 275, + RETROK_LEFT = 276, + RETROK_INSERT = 277, + RETROK_HOME = 278, + RETROK_END = 279, + RETROK_PAGEUP = 280, + RETROK_PAGEDOWN = 281, + + RETROK_F1 = 282, + RETROK_F2 = 283, + RETROK_F3 = 284, + RETROK_F4 = 285, + RETROK_F5 = 286, + RETROK_F6 = 287, + RETROK_F7 = 288, + RETROK_F8 = 289, + RETROK_F9 = 290, + RETROK_F10 = 291, + RETROK_F11 = 292, + RETROK_F12 = 293, + RETROK_F13 = 294, + RETROK_F14 = 295, + RETROK_F15 = 296, + + RETROK_NUMLOCK = 300, + RETROK_CAPSLOCK = 301, + RETROK_SCROLLOCK = 302, + RETROK_RSHIFT = 303, + RETROK_LSHIFT = 304, + RETROK_RCTRL = 305, + RETROK_LCTRL = 306, + RETROK_RALT = 307, + RETROK_LALT = 308, + RETROK_RMETA = 309, + RETROK_LMETA = 310, + RETROK_LSUPER = 311, + RETROK_RSUPER = 312, + RETROK_MODE = 313, + RETROK_COMPOSE = 314, + + RETROK_HELP = 315, + RETROK_PRINT = 316, + RETROK_SYSREQ = 317, + RETROK_BREAK = 318, + RETROK_MENU = 319, + RETROK_POWER = 320, + RETROK_EURO = 321, + RETROK_UNDO = 322, + + RETROK_LAST, + + RETROK_DUMMY = INT_MAX /* Ensure sizeof(enum) == sizeof(int) */ +}; + +enum retro_mod +{ + RETROKMOD_NONE = 0x0000, + + RETROKMOD_SHIFT = 0x01, + RETROKMOD_CTRL = 0x02, + RETROKMOD_ALT = 0x04, + RETROKMOD_META = 0x08, + + RETROKMOD_NUMLOCK = 0x10, + RETROKMOD_CAPSLOCK = 0x20, + RETROKMOD_SCROLLOCK = 0x40, + + RETROKMOD_DUMMY = INT_MAX /* Ensure sizeof(enum) == sizeof(int) */ +}; + +/* If set, this call is not part of the public libretro API yet. It can + * change or be removed at any time. */ +#define RETRO_ENVIRONMENT_EXPERIMENTAL 0x10000 +/* Environment callback to be used internally in frontend. */ +#define RETRO_ENVIRONMENT_PRIVATE 0x20000 + +/* Environment commands. */ +#define RETRO_ENVIRONMENT_SET_ROTATION 1 /* const unsigned * -- + * Sets screen rotation of graphics. + * Is only implemented if rotation can be accelerated by hardware. + * Valid values are 0, 1, 2, 3, which rotates screen by 0, 90, 180, + * 270 degrees counter-clockwise respectively. + */ +#define RETRO_ENVIRONMENT_GET_OVERSCAN 2 /* bool * -- + * Boolean value whether or not the implementation should use overscan, + * or crop away overscan. + */ +#define RETRO_ENVIRONMENT_GET_CAN_DUPE 3 /* bool * -- + * Boolean value whether or not frontend supports frame duping, + * passing NULL to video frame callback. + */ + + /* Environ 4, 5 are no longer supported (GET_VARIABLE / SET_VARIABLES), + * and reserved to avoid possible ABI clash. + */ + +#define RETRO_ENVIRONMENT_SET_MESSAGE 6 /* const struct retro_message * -- + * Sets a message to be displayed in implementation-specific manner + * for a certain amount of 'frames'. + * Should not be used for trivial messages, which should simply be + * logged via RETRO_ENVIRONMENT_GET_LOG_INTERFACE (or as a + * fallback, stderr). + */ +#define RETRO_ENVIRONMENT_SHUTDOWN 7 /* N/A (NULL) -- + * Requests the frontend to shutdown. + * Should only be used if game has a specific + * way to shutdown the game from a menu item or similar. + */ +#define RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL 8 + /* const unsigned * -- + * Gives a hint to the frontend how demanding this implementation + * is on a system. E.g. reporting a level of 2 means + * this implementation should run decently on all frontends + * of level 2 and up. + * + * It can be used by the frontend to potentially warn + * about too demanding implementations. + * + * The levels are "floating". + * + * This function can be called on a per-game basis, + * as certain games an implementation can play might be + * particularly demanding. + * If called, it should be called in retro_load_game(). + */ +#define RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY 9 + /* const char ** -- + * Returns the "system" directory of the frontend. + * This directory can be used to store system specific + * content such as BIOSes, configuration data, etc. + * The returned value can be NULL. + * If so, no such directory is defined, + * and it's up to the implementation to find a suitable directory. + * + * NOTE: Some cores used this folder also for "save" data such as + * memory cards, etc, for lack of a better place to put it. + * This is now discouraged, and if possible, cores should try to + * use the new GET_SAVE_DIRECTORY. + */ +#define RETRO_ENVIRONMENT_SET_PIXEL_FORMAT 10 + /* const enum retro_pixel_format * -- + * Sets the internal pixel format used by the implementation. + * The default pixel format is RETRO_PIXEL_FORMAT_0RGB1555. + * This pixel format however, is deprecated (see enum retro_pixel_format). + * If the call returns false, the frontend does not support this pixel + * format. + * + * This function should be called inside retro_load_game() or + * retro_get_system_av_info(). + */ +#define RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS 11 + /* const struct retro_input_descriptor * -- + * Sets an array of retro_input_descriptors. + * It is up to the frontend to present this in a usable way. + * The array is terminated by retro_input_descriptor::description + * being set to NULL. + * This function can be called at any time, but it is recommended + * to call it as early as possible. + */ +#define RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK 12 + /* const struct retro_keyboard_callback * -- + * Sets a callback function used to notify core about keyboard events. + */ +#define RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE 13 + /* const struct retro_disk_control_callback * -- + * Sets an interface which frontend can use to eject and insert + * disk images. + * This is used for games which consist of multiple images and + * must be manually swapped out by the user (e.g. PSX). + */ +#define RETRO_ENVIRONMENT_SET_HW_RENDER 14 + /* struct retro_hw_render_callback * -- + * Sets an interface to let a libretro core render with + * hardware acceleration. + * Should be called in retro_load_game(). + * If successful, libretro cores will be able to render to a + * frontend-provided framebuffer. + * The size of this framebuffer will be at least as large as + * max_width/max_height provided in get_av_info(). + * If HW rendering is used, pass only RETRO_HW_FRAME_BUFFER_VALID or + * NULL to retro_video_refresh_t. + */ +#define RETRO_ENVIRONMENT_GET_VARIABLE 15 + /* struct retro_variable * -- + * Interface to acquire user-defined information from environment + * that cannot feasibly be supported in a multi-system way. + * 'key' should be set to a key which has already been set by + * SET_VARIABLES. + * 'data' will be set to a value or NULL. + */ +#define RETRO_ENVIRONMENT_SET_VARIABLES 16 + /* const struct retro_variable * -- + * Allows an implementation to signal the environment + * which variables it might want to check for later using + * GET_VARIABLE. + * This allows the frontend to present these variables to + * a user dynamically. + * This should be called as early as possible (ideally in + * retro_set_environment). + * + * 'data' points to an array of retro_variable structs + * terminated by a { NULL, NULL } element. + * retro_variable::key should be namespaced to not collide + * with other implementations' keys. E.g. A core called + * 'foo' should use keys named as 'foo_option'. + * retro_variable::value should contain a human readable + * description of the key as well as a '|' delimited list + * of expected values. + * + * The number of possible options should be very limited, + * i.e. it should be feasible to cycle through options + * without a keyboard. + * + * First entry should be treated as a default. + * + * Example entry: + * { "foo_option", "Speed hack coprocessor X; false|true" } + * + * Text before first ';' is description. This ';' must be + * followed by a space, and followed by a list of possible + * values split up with '|'. + * + * Only strings are operated on. The possible values will + * generally be displayed and stored as-is by the frontend. + */ +#define RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE 17 + /* bool * -- + * Result is set to true if some variables are updated by + * frontend since last call to RETRO_ENVIRONMENT_GET_VARIABLE. + * Variables should be queried with GET_VARIABLE. + */ +#define RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME 18 + /* const bool * -- + * If true, the libretro implementation supports calls to + * retro_load_game() with NULL as argument. + * Used by cores which can run without particular game data. + * This should be called within retro_set_environment() only. + */ +#define RETRO_ENVIRONMENT_GET_LIBRETRO_PATH 19 + /* const char ** -- + * Retrieves the absolute path from where this libretro + * implementation was loaded. + * NULL is returned if the libretro was loaded statically + * (i.e. linked statically to frontend), or if the path cannot be + * determined. + * Mostly useful in cooperation with SET_SUPPORT_NO_GAME as assets can + * be loaded without ugly hacks. + */ + + /* Environment 20 was an obsolete version of SET_AUDIO_CALLBACK. + * It was not used by any known core at the time, + * and was removed from the API. */ +#define RETRO_ENVIRONMENT_SET_AUDIO_CALLBACK 22 + /* const struct retro_audio_callback * -- + * Sets an interface which is used to notify a libretro core about audio + * being available for writing. + * The callback can be called from any thread, so a core using this must + * have a thread safe audio implementation. + * It is intended for games where audio and video are completely + * asynchronous and audio can be generated on the fly. + * This interface is not recommended for use with emulators which have + * highly synchronous audio. + * + * The callback only notifies about writability; the libretro core still + * has to call the normal audio callbacks + * to write audio. The audio callbacks must be called from within the + * notification callback. + * The amount of audio data to write is up to the implementation. + * Generally, the audio callback will be called continously in a loop. + * + * Due to thread safety guarantees and lack of sync between audio and + * video, a frontend can selectively disallow this interface based on + * internal configuration. A core using this interface must also + * implement the "normal" audio interface. + * + * A libretro core using SET_AUDIO_CALLBACK should also make use of + * SET_FRAME_TIME_CALLBACK. + */ +#define RETRO_ENVIRONMENT_SET_FRAME_TIME_CALLBACK 21 + /* const struct retro_frame_time_callback * -- + * Lets the core know how much time has passed since last + * invocation of retro_run(). + * The frontend can tamper with the timing to fake fast-forward, + * slow-motion, frame stepping, etc. + * In this case the delta time will use the reference value + * in frame_time_callback.. + */ +#define RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE 23 + /* struct retro_rumble_interface * -- + * Gets an interface which is used by a libretro core to set + * state of rumble motors in controllers. + * A strong and weak motor is supported, and they can be + * controlled indepedently. + */ +#define RETRO_ENVIRONMENT_GET_INPUT_DEVICE_CAPABILITIES 24 + /* uint64_t * -- + * Gets a bitmask telling which device type are expected to be + * handled properly in a call to retro_input_state_t. + * Devices which are not handled or recognized always return + * 0 in retro_input_state_t. + * Example bitmask: caps = (1 << RETRO_DEVICE_JOYPAD) | (1 << RETRO_DEVICE_ANALOG). + * Should only be called in retro_run(). + */ +#define RETRO_ENVIRONMENT_GET_SENSOR_INTERFACE (25 | RETRO_ENVIRONMENT_EXPERIMENTAL) + /* struct retro_sensor_interface * -- + * Gets access to the sensor interface. + * The purpose of this interface is to allow + * setting state related to sensors such as polling rate, + * enabling/disable it entirely, etc. + * Reading sensor state is done via the normal + * input_state_callback API. + */ +#define RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE (26 | RETRO_ENVIRONMENT_EXPERIMENTAL) + /* struct retro_camera_callback * -- + * Gets an interface to a video camera driver. + * A libretro core can use this interface to get access to a + * video camera. + * New video frames are delivered in a callback in same + * thread as retro_run(). + * + * GET_CAMERA_INTERFACE should be called in retro_load_game(). + * + * Depending on the camera implementation used, camera frames + * will be delivered as a raw framebuffer, + * or as an OpenGL texture directly. + * + * The core has to tell the frontend here which types of + * buffers can be handled properly. + * An OpenGL texture can only be handled when using a + * libretro GL core (SET_HW_RENDER). + * It is recommended to use a libretro GL core when + * using camera interface. + * + * The camera is not started automatically. The retrieved start/stop + * functions must be used to explicitly + * start and stop the camera driver. + */ +#define RETRO_ENVIRONMENT_GET_LOG_INTERFACE 27 + /* struct retro_log_callback * -- + * Gets an interface for logging. This is useful for + * logging in a cross-platform way + * as certain platforms cannot use stderr for logging. + * It also allows the frontend to + * show logging information in a more suitable way. + * If this interface is not used, libretro cores should + * log to stderr as desired. + */ +#define RETRO_ENVIRONMENT_GET_PERF_INTERFACE 28 + /* struct retro_perf_callback * -- + * Gets an interface for performance counters. This is useful + * for performance logging in a cross-platform way and for detecting + * architecture-specific features, such as SIMD support. + */ +#define RETRO_ENVIRONMENT_GET_LOCATION_INTERFACE 29 + /* struct retro_location_callback * -- + * Gets access to the location interface. + * The purpose of this interface is to be able to retrieve + * location-based information from the host device, + * such as current latitude / longitude. + */ +#define RETRO_ENVIRONMENT_GET_CONTENT_DIRECTORY 30 /* Old name, kept for compatibility. */ +#define RETRO_ENVIRONMENT_GET_CORE_ASSETS_DIRECTORY 30 + /* const char ** -- + * Returns the "core assets" directory of the frontend. + * This directory can be used to store specific assets that the + * core relies upon, such as art assets, + * input data, etc etc. + * The returned value can be NULL. + * If so, no such directory is defined, + * and it's up to the implementation to find a suitable directory. + */ +#define RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY 31 + /* const char ** -- + * Returns the "save" directory of the frontend. + * This directory can be used to store SRAM, memory cards, + * high scores, etc, if the libretro core + * cannot use the regular memory interface (retro_get_memory_data()). + * + * NOTE: libretro cores used to check GET_SYSTEM_DIRECTORY for + * similar things before. + * They should still check GET_SYSTEM_DIRECTORY if they want to + * be backwards compatible. + * The path here can be NULL. It should only be non-NULL if the + * frontend user has set a specific save path. + */ +#define RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO 32 + /* const struct retro_system_av_info * -- + * Sets a new av_info structure. This can only be called from + * within retro_run(). + * This should *only* be used if the core is completely altering the + * internal resolutions, aspect ratios, timings, sampling rate, etc. + * Calling this can require a full reinitialization of video/audio + * drivers in the frontend, + * + * so it is important to call it very sparingly, and usually only with + * the users explicit consent. + * An eventual driver reinitialize will happen so that video and + * audio callbacks + * happening after this call within the same retro_run() call will + * target the newly initialized driver. + * + * This callback makes it possible to support configurable resolutions + * in games, which can be useful to + * avoid setting the "worst case" in max_width/max_height. + * + * ***HIGHLY RECOMMENDED*** Do not call this callback every time + * resolution changes in an emulator core if it's + * expected to be a temporary change, for the reasons of possible + * driver reinitialization. + * This call is not a free pass for not trying to provide + * correct values in retro_get_system_av_info(). If you need to change + * things like aspect ratio or nominal width/height, + * use RETRO_ENVIRONMENT_SET_GEOMETRY, which is a softer variant + * of SET_SYSTEM_AV_INFO. + * + * If this returns false, the frontend does not acknowledge a + * changed av_info struct. + */ +#define RETRO_ENVIRONMENT_SET_PROC_ADDRESS_CALLBACK 33 + /* const struct retro_get_proc_address_interface * -- + * Allows a libretro core to announce support for the + * get_proc_address() interface. + * This interface allows for a standard way to extend libretro where + * use of environment calls are too indirect, + * e.g. for cases where the frontend wants to call directly into the core. + * + * If a core wants to expose this interface, SET_PROC_ADDRESS_CALLBACK + * **MUST** be called from within retro_set_environment(). + */ +#define RETRO_ENVIRONMENT_SET_SUBSYSTEM_INFO 34 + /* const struct retro_subsystem_info * -- + * This environment call introduces the concept of libretro "subsystems". + * A subsystem is a variant of a libretro core which supports + * different kinds of games. + * The purpose of this is to support e.g. emulators which might + * have special needs, e.g. Super Nintendo's Super GameBoy, Sufami Turbo. + * It can also be used to pick among subsystems in an explicit way + * if the libretro implementation is a multi-system emulator itself. + * + * Loading a game via a subsystem is done with retro_load_game_special(), + * and this environment call allows a libretro core to expose which + * subsystems are supported for use with retro_load_game_special(). + * A core passes an array of retro_game_special_info which is terminated + * with a zeroed out retro_game_special_info struct. + * + * If a core wants to use this functionality, SET_SUBSYSTEM_INFO + * **MUST** be called from within retro_set_environment(). + */ +#define RETRO_ENVIRONMENT_SET_CONTROLLER_INFO 35 + /* const struct retro_controller_info * -- + * This environment call lets a libretro core tell the frontend + * which controller types are recognized in calls to + * retro_set_controller_port_device(). + * + * Some emulators such as Super Nintendo + * support multiple lightgun types which must be specifically + * selected from. + * It is therefore sometimes necessary for a frontend to be able + * to tell the core about a special kind of input device which is + * not covered by the libretro input API. + * + * In order for a frontend to understand the workings of an input device, + * it must be a specialized type + * of the generic device types already defined in the libretro API. + * + * Which devices are supported can vary per input port. + * The core must pass an array of const struct retro_controller_info which + * is terminated with a blanked out struct. Each element of the struct + * corresponds to an ascending port index to + * retro_set_controller_port_device(). + * Even if special device types are set in the libretro core, + * libretro should only poll input based on the base input device types. + */ +#define RETRO_ENVIRONMENT_SET_MEMORY_MAPS (36 | RETRO_ENVIRONMENT_EXPERIMENTAL) + /* const struct retro_memory_map * -- + * This environment call lets a libretro core tell the frontend + * about the memory maps this core emulates. + * This can be used to implement, for example, cheats in a core-agnostic way. + * + * Should only be used by emulators; it doesn't make much sense for + * anything else. + * It is recommended to expose all relevant pointers through + * retro_get_memory_* as well. + * + * Can be called from retro_init and retro_load_game. + */ +#define RETRO_ENVIRONMENT_SET_GEOMETRY 37 + /* const struct retro_game_geometry * -- + * This environment call is similar to SET_SYSTEM_AV_INFO for changing + * video parameters, but provides a guarantee that drivers will not be + * reinitialized. + * This can only be called from within retro_run(). + * + * The purpose of this call is to allow a core to alter nominal + * width/heights as well as aspect ratios on-the-fly, which can be + * useful for some emulators to change in run-time. + * + * max_width/max_height arguments are ignored and cannot be changed + * with this call as this could potentially require a reinitialization or a + * non-constant time operation. + * If max_width/max_height are to be changed, SET_SYSTEM_AV_INFO is required. + * + * A frontend must guarantee that this environment call completes in + * constant time. + */ +#define RETRO_ENVIRONMENT_GET_USERNAME 38 + /* const char ** + * Returns the specified username of the frontend, if specified by the user. + * This username can be used as a nickname for a core that has online facilities + * or any other mode where personalization of the user is desirable. + * The returned value can be NULL. + * If this environ callback is used by a core that requires a valid username, + * a default username should be specified by the core. + */ +#define RETRO_ENVIRONMENT_GET_LANGUAGE 39 + /* unsigned * -- + * Returns the specified language of the frontend, if specified by the user. + * It can be used by the core for localization purposes. + */ +#define RETRO_ENVIRONMENT_GET_CURRENT_SOFTWARE_FRAMEBUFFER (40 | RETRO_ENVIRONMENT_EXPERIMENTAL) + /* struct retro_framebuffer * -- + * Returns a preallocated framebuffer which the core can use for rendering + * the frame into when not using SET_HW_RENDER. + * The framebuffer returned from this call must not be used + * after the current call to retro_run() returns. + * + * The goal of this call is to allow zero-copy behavior where a core + * can render directly into video memory, avoiding extra bandwidth cost by copying + * memory from core to video memory. + * + * If this call succeeds and the core renders into it, + * the framebuffer pointer and pitch can be passed to retro_video_refresh_t. + * If the buffer from GET_CURRENT_SOFTWARE_FRAMEBUFFER is to be used, + * the core must pass the exact + * same pointer as returned by GET_CURRENT_SOFTWARE_FRAMEBUFFER; + * i.e. passing a pointer which is offset from the + * buffer is undefined. The width, height and pitch parameters + * must also match exactly to the values obtained from GET_CURRENT_SOFTWARE_FRAMEBUFFER. + * + * It is possible for a frontend to return a different pixel format + * than the one used in SET_PIXEL_FORMAT. This can happen if the frontend + * needs to perform conversion. + * + * It is still valid for a core to render to a different buffer + * even if GET_CURRENT_SOFTWARE_FRAMEBUFFER succeeds. + * + * A frontend must make sure that the pointer obtained from this function is + * writeable (and readable). + */ + +#define RETRO_ENVIRONMENT_SET_HW_SHARED_CONTEXT (44 | RETRO_ENVIRONMENT_EXPERIMENTAL) + /* N/A (null) * -- + * The frontend will try to use a 'shared' hardware context (mostly applicable + * to OpenGL) when a hardware context is being set up. + * + * Returns true if the frontend supports shared hardware contexts and false + * if the frontend does not support shared hardware contexts. + * + * This will do nothing on its own until SET_HW_RENDER env callbacks are + * being used. + */ + +#define RETRO_ENVIRONMENT_GET_VFS_INTERFACE (45 | RETRO_ENVIRONMENT_EXPERIMENTAL) + /* struct retro_vfs_interface_info * -- + * Gets access to the VFS interface. + * VFS presence needs to be queried prior to load_game or any + * get_system/save/other_directory being called to let front end know + * core supports VFS before it starts handing out paths. + * It is recomended to do so in retro_set_environment */ + +/* VFS functionality */ + +/* File paths: + * File paths passed as parameters when using this api shall be well formed unix-style, + * using "/" (unquoted forward slash) as directory separator regardless of the platform's native separator. + * Paths shall also include at least one forward slash ("game.bin" is an invalid path, use "./game.bin" instead). + * Other than the directory separator, cores shall not make assumptions about path format: + * "C:/path/game.bin", "http://example.com/game.bin", "#game/game.bin", "./game.bin" (without quotes) are all valid paths. + * Cores may replace the basename or remove path components from the end, and/or add new components; + * however, cores shall not append "./", "../" or multiple consecutive forward slashes ("//") to paths they request to front end. + * The frontend is encouraged to make such paths work as well as it can, but is allowed to give up if the core alters paths too much. + * Frontends are encouraged, but not required, to support native file system paths (modulo replacing the directory separator, if applicable). + * Cores are allowed to try using them, but must remain functional if the front rejects such requests. + * Cores are encouraged to use the libretro-common filestream functions for file I/O, + * as they seamlessly integrate with VFS, deal with directory separator replacement as appropriate + * and provide platform-specific fallbacks in cases where front ends do not support VFS. */ + +/* Opaque file handle + * Introduced in VFS API v1 */ +struct retro_vfs_file_handle; + +/* File open flags + * Introduced in VFS API v1 */ +#define RETRO_VFS_FILE_ACCESS_READ (1 << 0) /* Read only mode */ +#define RETRO_VFS_FILE_ACCESS_WRITE (1 << 1) /* Write only mode, discard contents and overwrites existing file unless RETRO_VFS_FILE_ACCESS_UPDATE is also specified */ +#define RETRO_VFS_FILE_ACCESS_READ_WRITE (RETRO_VFS_FILE_ACCESS_READ | RETRO_VFS_FILE_ACCESS_WRITE) /* Read-write mode, discard contents and overwrites existing file unless RETRO_VFS_FILE_ACCESS_UPDATE is also specified*/ +#define RETRO_VFS_FILE_ACCESS_UPDATE_EXISTING (1 << 2) /* Prevents discarding content of existing files opened for writing */ + +/* These are only hints. The frontend may choose to ignore them. Other than RAM/CPU/etc use, + and how they react to unlikely external interference (for example someone else writing to that file, + or the file's server going down), behavior will not change. */ +#define RETRO_VFS_FILE_ACCESS_HINT_NONE (0) +/* Indicate that the file will be accessed many times. The frontend should aggressively cache everything. */ +#define RETRO_VFS_FILE_ACCESS_HINT_FREQUENT_ACCESS (1 << 0) + +/* Seek positions */ +#define RETRO_VFS_SEEK_POSITION_START 0 +#define RETRO_VFS_SEEK_POSITION_CURRENT 1 +#define RETRO_VFS_SEEK_POSITION_END 2 + +/* Get path from opaque handle. Returns the exact same path passed to file_open when getting the handle + * Introduced in VFS API v1 */ +typedef const char *(RETRO_CALLCONV *retro_vfs_get_path_t)(struct retro_vfs_file_handle *stream); + +/* Open a file for reading or writing. If path points to a directory, this will + * fail. Returns the opaque file handle, or NULL for error. + * Introduced in VFS API v1 */ +typedef struct retro_vfs_file_handle *(RETRO_CALLCONV *retro_vfs_open_t)(const char *path, unsigned mode, unsigned hints); + +/* Close the file and release its resources. Must be called if open_file returns non-NULL. Returns 0 on succes, -1 on failure. + * Whether the call succeeds ot not, the handle passed as parameter becomes invalid and should no longer be used. + * Introduced in VFS API v1 */ +typedef int (RETRO_CALLCONV *retro_vfs_close_t)(struct retro_vfs_file_handle *stream); + +/* Return the size of the file in bytes, or -1 for error. + * Introduced in VFS API v1 */ +typedef int64_t (RETRO_CALLCONV *retro_vfs_size_t)(struct retro_vfs_file_handle *stream); + +/* Get the current read / write position for the file. Returns - 1 for error. + * Introduced in VFS API v1 */ +typedef int64_t (RETRO_CALLCONV *retro_vfs_tell_t)(struct retro_vfs_file_handle *stream); + +/* Set the current read/write position for the file. Returns the new position, -1 for error. + * Introduced in VFS API v1 */ +typedef int64_t (RETRO_CALLCONV *retro_vfs_seek_t)(struct retro_vfs_file_handle *stream, int64_t offset, int seek_position); + +/* Read data from a file. Returns the number of bytes read, or -1 for error. + * Introduced in VFS API v1 */ +typedef int64_t (RETRO_CALLCONV *retro_vfs_read_t)(struct retro_vfs_file_handle *stream, void *s, uint64_t len); + +/* Write data to a file. Returns the number of bytes written, or -1 for error. + * Introduced in VFS API v1 */ +typedef int64_t (RETRO_CALLCONV *retro_vfs_write_t)(struct retro_vfs_file_handle *stream, const void *s, uint64_t len); + +/* Flush pending writes to file, if using buffered IO. Returns 0 on sucess, or -1 on failure. + * Introduced in VFS API v1 */ +typedef int (RETRO_CALLCONV *retro_vfs_flush_t)(struct retro_vfs_file_handle *stream); + +/* Delete the specified file. Returns 0 on success, -1 on failure + * Introduced in VFS API v1 */ +typedef int (RETRO_CALLCONV *retro_vfs_remove_t)(const char *path); + +/* Rename the specified file. Returns 0 on success, -1 on failure + * Introduced in VFS API v1 */ +typedef int (RETRO_CALLCONV *retro_vfs_rename_t)(const char *old_path, const char *new_path); + +struct retro_vfs_interface +{ + retro_vfs_get_path_t get_path; + retro_vfs_open_t open; + retro_vfs_close_t close; + retro_vfs_size_t size; + retro_vfs_tell_t tell; + retro_vfs_seek_t seek; + retro_vfs_read_t read; + retro_vfs_write_t write; + retro_vfs_flush_t flush; + retro_vfs_remove_t remove; + retro_vfs_rename_t rename; +}; + +struct retro_vfs_interface_info +{ + /* Set by core: should this be higher than the version the front end supports, + * front end will return false in the RETRO_ENVIRONMENT_GET_VFS_INTERFACE call + * Introduced in VFS API v1 */ + uint32_t required_interface_version; + + /* Frontend writes interface pointer here. The frontend also sets the actual + * version, must be at least required_interface_version. + * Introduced in VFS API v1 */ + struct retro_vfs_interface *iface; +}; + +enum retro_hw_render_interface_type +{ + RETRO_HW_RENDER_INTERFACE_VULKAN = 0, + RETRO_HW_RENDER_INTERFACE_DUMMY = INT_MAX +}; + +/* Base struct. All retro_hw_render_interface_* types + * contain at least these fields. */ +struct retro_hw_render_interface +{ + enum retro_hw_render_interface_type interface_type; + unsigned interface_version; +}; +#define RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE (41 | RETRO_ENVIRONMENT_EXPERIMENTAL) + /* const struct retro_hw_render_interface ** -- + * Returns an API specific rendering interface for accessing API specific data. + * Not all HW rendering APIs support or need this. + * The contents of the returned pointer is specific to the rendering API + * being used. See the various headers like libretro_vulkan.h, etc. + * + * GET_HW_RENDER_INTERFACE cannot be called before context_reset has been called. + * Similarly, after context_destroyed callback returns, + * the contents of the HW_RENDER_INTERFACE are invalidated. + */ + +#define RETRO_ENVIRONMENT_SET_SUPPORT_ACHIEVEMENTS (42 | RETRO_ENVIRONMENT_EXPERIMENTAL) + /* const bool * -- + * If true, the libretro implementation supports achievements + * either via memory descriptors set with RETRO_ENVIRONMENT_SET_MEMORY_MAPS + * or via retro_get_memory_data/retro_get_memory_size. + * + * This must be called before the first call to retro_run. + */ + +enum retro_hw_render_context_negotiation_interface_type +{ + RETRO_HW_RENDER_CONTEXT_NEGOTIATION_INTERFACE_VULKAN = 0, + RETRO_HW_RENDER_CONTEXT_NEGOTIATION_INTERFACE_DUMMY = INT_MAX +}; + +/* Base struct. All retro_hw_render_context_negotiation_interface_* types + * contain at least these fields. */ +struct retro_hw_render_context_negotiation_interface +{ + enum retro_hw_render_context_negotiation_interface_type interface_type; + unsigned interface_version; +}; +#define RETRO_ENVIRONMENT_SET_HW_RENDER_CONTEXT_NEGOTIATION_INTERFACE (43 | RETRO_ENVIRONMENT_EXPERIMENTAL) + /* const struct retro_hw_render_context_negotiation_interface * -- + * Sets an interface which lets the libretro core negotiate with frontend how a context is created. + * The semantics of this interface depends on which API is used in SET_HW_RENDER earlier. + * This interface will be used when the frontend is trying to create a HW rendering context, + * so it will be used after SET_HW_RENDER, but before the context_reset callback. + */ + +/* Serialized state is incomplete in some way. Set if serialization is + * usable in typical end-user cases but should not be relied upon to + * implement frame-sensitive frontend features such as netplay or + * rerecording. */ +#define RETRO_SERIALIZATION_QUIRK_INCOMPLETE (1 << 0) +/* The core must spend some time initializing before serialization is + * supported. retro_serialize() will initially fail; retro_unserialize() + * and retro_serialize_size() may or may not work correctly either. */ +#define RETRO_SERIALIZATION_QUIRK_MUST_INITIALIZE (1 << 1) +/* Serialization size may change within a session. */ +#define RETRO_SERIALIZATION_QUIRK_CORE_VARIABLE_SIZE (1 << 2) +/* Set by the frontend to acknowledge that it supports variable-sized + * states. */ +#define RETRO_SERIALIZATION_QUIRK_FRONT_VARIABLE_SIZE (1 << 3) +/* Serialized state can only be loaded during the same session. */ +#define RETRO_SERIALIZATION_QUIRK_SINGLE_SESSION (1 << 4) +/* Serialized state cannot be loaded on an architecture with a different + * endianness from the one it was saved on. */ +#define RETRO_SERIALIZATION_QUIRK_ENDIAN_DEPENDENT (1 << 5) +/* Serialized state cannot be loaded on a different platform from the one it + * was saved on for reasons other than endianness, such as word size + * dependence */ +#define RETRO_SERIALIZATION_QUIRK_PLATFORM_DEPENDENT (1 << 6) + +#define RETRO_ENVIRONMENT_SET_SERIALIZATION_QUIRKS 44 + /* uint64_t * -- + * Sets quirk flags associated with serialization. The frontend will zero any flags it doesn't + * recognize or support. Should be set in either retro_init or retro_load_game, but not both. + */ + +#define RETRO_MEMDESC_CONST (1 << 0) /* The frontend will never change this memory area once retro_load_game has returned. */ +#define RETRO_MEMDESC_BIGENDIAN (1 << 1) /* The memory area contains big endian data. Default is little endian. */ +#define RETRO_MEMDESC_ALIGN_2 (1 << 16) /* All memory access in this area is aligned to their own size, or 2, whichever is smaller. */ +#define RETRO_MEMDESC_ALIGN_4 (2 << 16) +#define RETRO_MEMDESC_ALIGN_8 (3 << 16) +#define RETRO_MEMDESC_MINSIZE_2 (1 << 24) /* All memory in this region is accessed at least 2 bytes at the time. */ +#define RETRO_MEMDESC_MINSIZE_4 (2 << 24) +#define RETRO_MEMDESC_MINSIZE_8 (3 << 24) +struct retro_memory_descriptor +{ + uint64_t flags; + + /* Pointer to the start of the relevant ROM or RAM chip. + * It's strongly recommended to use 'offset' if possible, rather than + * doing math on the pointer. + * + * If the same byte is mapped my multiple descriptors, their descriptors + * must have the same pointer. + * If 'start' does not point to the first byte in the pointer, put the + * difference in 'offset' instead. + * + * May be NULL if there's nothing usable here (e.g. hardware registers and + * open bus). No flags should be set if the pointer is NULL. + * It's recommended to minimize the number of descriptors if possible, + * but not mandatory. */ + void *ptr; + size_t offset; + + /* This is the location in the emulated address space + * where the mapping starts. */ + size_t start; + + /* Which bits must be same as in 'start' for this mapping to apply. + * The first memory descriptor to claim a certain byte is the one + * that applies. + * A bit which is set in 'start' must also be set in this. + * Can be zero, in which case each byte is assumed mapped exactly once. + * In this case, 'len' must be a power of two. */ + size_t select; + + /* If this is nonzero, the set bits are assumed not connected to the + * memory chip's address pins. */ + size_t disconnect; + + /* This one tells the size of the current memory area. + * If, after start+disconnect are applied, the address is higher than + * this, the highest bit of the address is cleared. + * + * If the address is still too high, the next highest bit is cleared. + * Can be zero, in which case it's assumed to be infinite (as limited + * by 'select' and 'disconnect'). */ + size_t len; + + /* To go from emulated address to physical address, the following + * order applies: + * Subtract 'start', pick off 'disconnect', apply 'len', add 'offset'. */ + + /* The address space name must consist of only a-zA-Z0-9_-, + * should be as short as feasible (maximum length is 8 plus the NUL), + * and may not be any other address space plus one or more 0-9A-F + * at the end. + * However, multiple memory descriptors for the same address space is + * allowed, and the address space name can be empty. NULL is treated + * as empty. + * + * Address space names are case sensitive, but avoid lowercase if possible. + * The same pointer may exist in multiple address spaces. + * + * Examples: + * blank+blank - valid (multiple things may be mapped in the same namespace) + * 'Sp'+'Sp' - valid (multiple things may be mapped in the same namespace) + * 'A'+'B' - valid (neither is a prefix of each other) + * 'S'+blank - valid ('S' is not in 0-9A-F) + * 'a'+blank - valid ('a' is not in 0-9A-F) + * 'a'+'A' - valid (neither is a prefix of each other) + * 'AR'+blank - valid ('R' is not in 0-9A-F) + * 'ARB'+blank - valid (the B can't be part of the address either, because + * there is no namespace 'AR') + * blank+'B' - not valid, because it's ambigous which address space B1234 + * would refer to. + * The length can't be used for that purpose; the frontend may want + * to append arbitrary data to an address, without a separator. */ + const char *addrspace; + + /* TODO: When finalizing this one, add a description field, which should be + * "WRAM" or something roughly equally long. */ + + /* TODO: When finalizing this one, replace 'select' with 'limit', which tells + * which bits can vary and still refer to the same address (limit = ~select). + * TODO: limit? range? vary? something else? */ + + /* TODO: When finalizing this one, if 'len' is above what 'select' (or + * 'limit') allows, it's bankswitched. Bankswitched data must have both 'len' + * and 'select' != 0, and the mappings don't tell how the system switches the + * banks. */ + + /* TODO: When finalizing this one, fix the 'len' bit removal order. + * For len=0x1800, pointer 0x1C00 should go to 0x1400, not 0x0C00. + * Algorithm: Take bits highest to lowest, but if it goes above len, clear + * the most recent addition and continue on the next bit. + * TODO: Can the above be optimized? Is "remove the lowest bit set in both + * pointer and 'len'" equivalent? */ + + /* TODO: Some emulators (MAME?) emulate big endian systems by only accessing + * the emulated memory in 32-bit chunks, native endian. But that's nothing + * compared to Darek Mihocka + * (section Emulation 103 - Nearly Free Byte Reversal) - he flips the ENTIRE + * RAM backwards! I'll want to represent both of those, via some flags. + * + * I suspect MAME either didn't think of that idea, or don't want the #ifdef. + * Not sure which, nor do I really care. */ + + /* TODO: Some of those flags are unused and/or don't really make sense. Clean + * them up. */ +}; + +/* The frontend may use the largest value of 'start'+'select' in a + * certain namespace to infer the size of the address space. + * + * If the address space is larger than that, a mapping with .ptr=NULL + * should be at the end of the array, with .select set to all ones for + * as long as the address space is big. + * + * Sample descriptors (minus .ptr, and RETRO_MEMFLAG_ on the flags): + * SNES WRAM: + * .start=0x7E0000, .len=0x20000 + * (Note that this must be mapped before the ROM in most cases; some of the + * ROM mappers + * try to claim $7E0000, or at least $7E8000.) + * SNES SPC700 RAM: + * .addrspace="S", .len=0x10000 + * SNES WRAM mirrors: + * .flags=MIRROR, .start=0x000000, .select=0xC0E000, .len=0x2000 + * .flags=MIRROR, .start=0x800000, .select=0xC0E000, .len=0x2000 + * SNES WRAM mirrors, alternate equivalent descriptor: + * .flags=MIRROR, .select=0x40E000, .disconnect=~0x1FFF + * (Various similar constructions can be created by combining parts of + * the above two.) + * SNES LoROM (512KB, mirrored a couple of times): + * .flags=CONST, .start=0x008000, .select=0x408000, .disconnect=0x8000, .len=512*1024 + * .flags=CONST, .start=0x400000, .select=0x400000, .disconnect=0x8000, .len=512*1024 + * SNES HiROM (4MB): + * .flags=CONST, .start=0x400000, .select=0x400000, .len=4*1024*1024 + * .flags=CONST, .offset=0x8000, .start=0x008000, .select=0x408000, .len=4*1024*1024 + * SNES ExHiROM (8MB): + * .flags=CONST, .offset=0, .start=0xC00000, .select=0xC00000, .len=4*1024*1024 + * .flags=CONST, .offset=4*1024*1024, .start=0x400000, .select=0xC00000, .len=4*1024*1024 + * .flags=CONST, .offset=0x8000, .start=0x808000, .select=0xC08000, .len=4*1024*1024 + * .flags=CONST, .offset=4*1024*1024+0x8000, .start=0x008000, .select=0xC08000, .len=4*1024*1024 + * Clarify the size of the address space: + * .ptr=NULL, .select=0xFFFFFF + * .len can be implied by .select in many of them, but was included for clarity. + */ + +struct retro_memory_map +{ + const struct retro_memory_descriptor *descriptors; + unsigned num_descriptors; +}; + +struct retro_controller_description +{ + /* Human-readable description of the controller. Even if using a generic + * input device type, this can be set to the particular device type the + * core uses. */ + const char *desc; + + /* Device type passed to retro_set_controller_port_device(). If the device + * type is a sub-class of a generic input device type, use the + * RETRO_DEVICE_SUBCLASS macro to create an ID. + * + * E.g. RETRO_DEVICE_SUBCLASS(RETRO_DEVICE_JOYPAD, 1). */ + unsigned id; +}; + +struct retro_controller_info +{ + const struct retro_controller_description *types; + unsigned num_types; +}; + +struct retro_subsystem_memory_info +{ + /* The extension associated with a memory type, e.g. "psram". */ + const char *extension; + + /* The memory type for retro_get_memory(). This should be at + * least 0x100 to avoid conflict with standardized + * libretro memory types. */ + unsigned type; +}; + +struct retro_subsystem_rom_info +{ + /* Describes what the content is (SGB BIOS, GB ROM, etc). */ + const char *desc; + + /* Same definition as retro_get_system_info(). */ + const char *valid_extensions; + + /* Same definition as retro_get_system_info(). */ + bool need_fullpath; + + /* Same definition as retro_get_system_info(). */ + bool block_extract; + + /* This is set if the content is required to load a game. + * If this is set to false, a zeroed-out retro_game_info can be passed. */ + bool required; + + /* Content can have multiple associated persistent + * memory types (retro_get_memory()). */ + const struct retro_subsystem_memory_info *memory; + unsigned num_memory; +}; + +struct retro_subsystem_info +{ + /* Human-readable string of the subsystem type, e.g. "Super GameBoy" */ + const char *desc; + + /* A computer friendly short string identifier for the subsystem type. + * This name must be [a-z]. + * E.g. if desc is "Super GameBoy", this can be "sgb". + * This identifier can be used for command-line interfaces, etc. + */ + const char *ident; + + /* Infos for each content file. The first entry is assumed to be the + * "most significant" content for frontend purposes. + * E.g. with Super GameBoy, the first content should be the GameBoy ROM, + * as it is the most "significant" content to a user. + * If a frontend creates new file paths based on the content used + * (e.g. savestates), it should use the path for the first ROM to do so. */ + const struct retro_subsystem_rom_info *roms; + + /* Number of content files associated with a subsystem. */ + unsigned num_roms; + + /* The type passed to retro_load_game_special(). */ + unsigned id; +}; + +typedef void (RETRO_CALLCONV *retro_proc_address_t)(void); + +/* libretro API extension functions: + * (None here so far). + * + * Get a symbol from a libretro core. + * Cores should only return symbols which are actual + * extensions to the libretro API. + * + * Frontends should not use this to obtain symbols to standard + * libretro entry points (static linking or dlsym). + * + * The symbol name must be equal to the function name, + * e.g. if void retro_foo(void); exists, the symbol must be called "retro_foo". + * The returned function pointer must be cast to the corresponding type. + */ +typedef retro_proc_address_t (RETRO_CALLCONV *retro_get_proc_address_t)(const char *sym); + +struct retro_get_proc_address_interface +{ + retro_get_proc_address_t get_proc_address; +}; + +enum retro_log_level +{ + RETRO_LOG_DEBUG = 0, + RETRO_LOG_INFO, + RETRO_LOG_WARN, + RETRO_LOG_ERROR, + + RETRO_LOG_DUMMY = INT_MAX +}; + +/* Logging function. Takes log level argument as well. */ +typedef void (RETRO_CALLCONV *retro_log_printf_t)(enum retro_log_level level, + const char *fmt, ...); + +struct retro_log_callback +{ + retro_log_printf_t log; +}; + +/* Performance related functions */ + +/* ID values for SIMD CPU features */ +#define RETRO_SIMD_SSE (1 << 0) +#define RETRO_SIMD_SSE2 (1 << 1) +#define RETRO_SIMD_VMX (1 << 2) +#define RETRO_SIMD_VMX128 (1 << 3) +#define RETRO_SIMD_AVX (1 << 4) +#define RETRO_SIMD_NEON (1 << 5) +#define RETRO_SIMD_SSE3 (1 << 6) +#define RETRO_SIMD_SSSE3 (1 << 7) +#define RETRO_SIMD_MMX (1 << 8) +#define RETRO_SIMD_MMXEXT (1 << 9) +#define RETRO_SIMD_SSE4 (1 << 10) +#define RETRO_SIMD_SSE42 (1 << 11) +#define RETRO_SIMD_AVX2 (1 << 12) +#define RETRO_SIMD_VFPU (1 << 13) +#define RETRO_SIMD_PS (1 << 14) +#define RETRO_SIMD_AES (1 << 15) +#define RETRO_SIMD_VFPV3 (1 << 16) +#define RETRO_SIMD_VFPV4 (1 << 17) +#define RETRO_SIMD_POPCNT (1 << 18) +#define RETRO_SIMD_MOVBE (1 << 19) +#define RETRO_SIMD_CMOV (1 << 20) +#define RETRO_SIMD_ASIMD (1 << 21) + +typedef uint64_t retro_perf_tick_t; +typedef int64_t retro_time_t; + +struct retro_perf_counter +{ + const char *ident; + retro_perf_tick_t start; + retro_perf_tick_t total; + retro_perf_tick_t call_cnt; + + bool registered; +}; + +/* Returns current time in microseconds. + * Tries to use the most accurate timer available. + */ +typedef retro_time_t (RETRO_CALLCONV *retro_perf_get_time_usec_t)(void); + +/* A simple counter. Usually nanoseconds, but can also be CPU cycles. + * Can be used directly if desired (when creating a more sophisticated + * performance counter system). + * */ +typedef retro_perf_tick_t (RETRO_CALLCONV *retro_perf_get_counter_t)(void); + +/* Returns a bit-mask of detected CPU features (RETRO_SIMD_*). */ +typedef uint64_t (RETRO_CALLCONV *retro_get_cpu_features_t)(void); + +/* Asks frontend to log and/or display the state of performance counters. + * Performance counters can always be poked into manually as well. + */ +typedef void (RETRO_CALLCONV *retro_perf_log_t)(void); + +/* Register a performance counter. + * ident field must be set with a discrete value and other values in + * retro_perf_counter must be 0. + * Registering can be called multiple times. To avoid calling to + * frontend redundantly, you can check registered field first. */ +typedef void (RETRO_CALLCONV *retro_perf_register_t)(struct retro_perf_counter *counter); + +/* Starts a registered counter. */ +typedef void (RETRO_CALLCONV *retro_perf_start_t)(struct retro_perf_counter *counter); + +/* Stops a registered counter. */ +typedef void (RETRO_CALLCONV *retro_perf_stop_t)(struct retro_perf_counter *counter); + +/* For convenience it can be useful to wrap register, start and stop in macros. + * E.g.: + * #ifdef LOG_PERFORMANCE + * #define RETRO_PERFORMANCE_INIT(perf_cb, name) static struct retro_perf_counter name = {#name}; if (!name.registered) perf_cb.perf_register(&(name)) + * #define RETRO_PERFORMANCE_START(perf_cb, name) perf_cb.perf_start(&(name)) + * #define RETRO_PERFORMANCE_STOP(perf_cb, name) perf_cb.perf_stop(&(name)) + * #else + * ... Blank macros ... + * #endif + * + * These can then be used mid-functions around code snippets. + * + * extern struct retro_perf_callback perf_cb; * Somewhere in the core. + * + * void do_some_heavy_work(void) + * { + * RETRO_PERFORMANCE_INIT(cb, work_1; + * RETRO_PERFORMANCE_START(cb, work_1); + * heavy_work_1(); + * RETRO_PERFORMANCE_STOP(cb, work_1); + * + * RETRO_PERFORMANCE_INIT(cb, work_2); + * RETRO_PERFORMANCE_START(cb, work_2); + * heavy_work_2(); + * RETRO_PERFORMANCE_STOP(cb, work_2); + * } + * + * void retro_deinit(void) + * { + * perf_cb.perf_log(); * Log all perf counters here for example. + * } + */ + +struct retro_perf_callback +{ + retro_perf_get_time_usec_t get_time_usec; + retro_get_cpu_features_t get_cpu_features; + + retro_perf_get_counter_t get_perf_counter; + retro_perf_register_t perf_register; + retro_perf_start_t perf_start; + retro_perf_stop_t perf_stop; + retro_perf_log_t perf_log; +}; + +/* FIXME: Document the sensor API and work out behavior. + * It will be marked as experimental until then. + */ +enum retro_sensor_action +{ + RETRO_SENSOR_ACCELEROMETER_ENABLE = 0, + RETRO_SENSOR_ACCELEROMETER_DISABLE, + + RETRO_SENSOR_DUMMY = INT_MAX +}; + +/* Id values for SENSOR types. */ +#define RETRO_SENSOR_ACCELEROMETER_X 0 +#define RETRO_SENSOR_ACCELEROMETER_Y 1 +#define RETRO_SENSOR_ACCELEROMETER_Z 2 + +typedef bool (RETRO_CALLCONV *retro_set_sensor_state_t)(unsigned port, + enum retro_sensor_action action, unsigned rate); + +typedef float (RETRO_CALLCONV *retro_sensor_get_input_t)(unsigned port, unsigned id); + +struct retro_sensor_interface +{ + retro_set_sensor_state_t set_sensor_state; + retro_sensor_get_input_t get_sensor_input; +}; + +enum retro_camera_buffer +{ + RETRO_CAMERA_BUFFER_OPENGL_TEXTURE = 0, + RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER, + + RETRO_CAMERA_BUFFER_DUMMY = INT_MAX +}; + +/* Starts the camera driver. Can only be called in retro_run(). */ +typedef bool (RETRO_CALLCONV *retro_camera_start_t)(void); + +/* Stops the camera driver. Can only be called in retro_run(). */ +typedef void (RETRO_CALLCONV *retro_camera_stop_t)(void); + +/* Callback which signals when the camera driver is initialized + * and/or deinitialized. + * retro_camera_start_t can be called in initialized callback. + */ +typedef void (RETRO_CALLCONV *retro_camera_lifetime_status_t)(void); + +/* A callback for raw framebuffer data. buffer points to an XRGB8888 buffer. + * Width, height and pitch are similar to retro_video_refresh_t. + * First pixel is top-left origin. + */ +typedef void (RETRO_CALLCONV *retro_camera_frame_raw_framebuffer_t)(const uint32_t *buffer, + unsigned width, unsigned height, size_t pitch); + +/* A callback for when OpenGL textures are used. + * + * texture_id is a texture owned by camera driver. + * Its state or content should be considered immutable, except for things like + * texture filtering and clamping. + * + * texture_target is the texture target for the GL texture. + * These can include e.g. GL_TEXTURE_2D, GL_TEXTURE_RECTANGLE, and possibly + * more depending on extensions. + * + * affine points to a packed 3x3 column-major matrix used to apply an affine + * transform to texture coordinates. (affine_matrix * vec3(coord_x, coord_y, 1.0)) + * After transform, normalized texture coord (0, 0) should be bottom-left + * and (1, 1) should be top-right (or (width, height) for RECTANGLE). + * + * GL-specific typedefs are avoided here to avoid relying on gl.h in + * the API definition. + */ +typedef void (RETRO_CALLCONV *retro_camera_frame_opengl_texture_t)(unsigned texture_id, + unsigned texture_target, const float *affine); + +struct retro_camera_callback +{ + /* Set by libretro core. + * Example bitmask: caps = (1 << RETRO_CAMERA_BUFFER_OPENGL_TEXTURE) | (1 << RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER). + */ + uint64_t caps; + + /* Desired resolution for camera. Is only used as a hint. */ + unsigned width; + unsigned height; + + /* Set by frontend. */ + retro_camera_start_t start; + retro_camera_stop_t stop; + + /* Set by libretro core if raw framebuffer callbacks will be used. */ + retro_camera_frame_raw_framebuffer_t frame_raw_framebuffer; + + /* Set by libretro core if OpenGL texture callbacks will be used. */ + retro_camera_frame_opengl_texture_t frame_opengl_texture; + + /* Set by libretro core. Called after camera driver is initialized and + * ready to be started. + * Can be NULL, in which this callback is not called. + */ + retro_camera_lifetime_status_t initialized; + + /* Set by libretro core. Called right before camera driver is + * deinitialized. + * Can be NULL, in which this callback is not called. + */ + retro_camera_lifetime_status_t deinitialized; +}; + +/* Sets the interval of time and/or distance at which to update/poll + * location-based data. + * + * To ensure compatibility with all location-based implementations, + * values for both interval_ms and interval_distance should be provided. + * + * interval_ms is the interval expressed in milliseconds. + * interval_distance is the distance interval expressed in meters. + */ +typedef void (RETRO_CALLCONV *retro_location_set_interval_t)(unsigned interval_ms, + unsigned interval_distance); + +/* Start location services. The device will start listening for changes to the + * current location at regular intervals (which are defined with + * retro_location_set_interval_t). */ +typedef bool (RETRO_CALLCONV *retro_location_start_t)(void); + +/* Stop location services. The device will stop listening for changes + * to the current location. */ +typedef void (RETRO_CALLCONV *retro_location_stop_t)(void); + +/* Get the position of the current location. Will set parameters to + * 0 if no new location update has happened since the last time. */ +typedef bool (RETRO_CALLCONV *retro_location_get_position_t)(double *lat, double *lon, + double *horiz_accuracy, double *vert_accuracy); + +/* Callback which signals when the location driver is initialized + * and/or deinitialized. + * retro_location_start_t can be called in initialized callback. + */ +typedef void (RETRO_CALLCONV *retro_location_lifetime_status_t)(void); + +struct retro_location_callback +{ + retro_location_start_t start; + retro_location_stop_t stop; + retro_location_get_position_t get_position; + retro_location_set_interval_t set_interval; + + retro_location_lifetime_status_t initialized; + retro_location_lifetime_status_t deinitialized; +}; + +enum retro_rumble_effect +{ + RETRO_RUMBLE_STRONG = 0, + RETRO_RUMBLE_WEAK = 1, + + RETRO_RUMBLE_DUMMY = INT_MAX +}; + +/* Sets rumble state for joypad plugged in port 'port'. + * Rumble effects are controlled independently, + * and setting e.g. strong rumble does not override weak rumble. + * Strength has a range of [0, 0xffff]. + * + * Returns true if rumble state request was honored. + * Calling this before first retro_run() is likely to return false. */ +typedef bool (RETRO_CALLCONV *retro_set_rumble_state_t)(unsigned port, + enum retro_rumble_effect effect, uint16_t strength); + +struct retro_rumble_interface +{ + retro_set_rumble_state_t set_rumble_state; +}; + +/* Notifies libretro that audio data should be written. */ +typedef void (RETRO_CALLCONV *retro_audio_callback_t)(void); + +/* True: Audio driver in frontend is active, and callback is + * expected to be called regularily. + * False: Audio driver in frontend is paused or inactive. + * Audio callback will not be called until set_state has been + * called with true. + * Initial state is false (inactive). + */ +typedef void (RETRO_CALLCONV *retro_audio_set_state_callback_t)(bool enabled); + +struct retro_audio_callback +{ + retro_audio_callback_t callback; + retro_audio_set_state_callback_t set_state; +}; + +/* Notifies a libretro core of time spent since last invocation + * of retro_run() in microseconds. + * + * It will be called right before retro_run() every frame. + * The frontend can tamper with timing to support cases like + * fast-forward, slow-motion and framestepping. + * + * In those scenarios the reference frame time value will be used. */ +typedef int64_t retro_usec_t; +typedef void (RETRO_CALLCONV *retro_frame_time_callback_t)(retro_usec_t usec); +struct retro_frame_time_callback +{ + retro_frame_time_callback_t callback; + /* Represents the time of one frame. It is computed as + * 1000000 / fps, but the implementation will resolve the + * rounding to ensure that framestepping, etc is exact. */ + retro_usec_t reference; +}; + +/* Pass this to retro_video_refresh_t if rendering to hardware. + * Passing NULL to retro_video_refresh_t is still a frame dupe as normal. + * */ +#define RETRO_HW_FRAME_BUFFER_VALID ((void*)-1) + +/* Invalidates the current HW context. + * Any GL state is lost, and must not be deinitialized explicitly. + * If explicit deinitialization is desired by the libretro core, + * it should implement context_destroy callback. + * If called, all GPU resources must be reinitialized. + * Usually called when frontend reinits video driver. + * Also called first time video driver is initialized, + * allowing libretro core to initialize resources. + */ +typedef void (RETRO_CALLCONV *retro_hw_context_reset_t)(void); + +/* Gets current framebuffer which is to be rendered to. + * Could change every frame potentially. + */ +typedef uintptr_t (RETRO_CALLCONV *retro_hw_get_current_framebuffer_t)(void); + +/* Get a symbol from HW context. */ +typedef retro_proc_address_t (RETRO_CALLCONV *retro_hw_get_proc_address_t)(const char *sym); + +enum retro_hw_context_type +{ + RETRO_HW_CONTEXT_NONE = 0, + /* OpenGL 2.x. Driver can choose to use latest compatibility context. */ + RETRO_HW_CONTEXT_OPENGL = 1, + /* OpenGL ES 2.0. */ + RETRO_HW_CONTEXT_OPENGLES2 = 2, + /* Modern desktop core GL context. Use version_major/ + * version_minor fields to set GL version. */ + RETRO_HW_CONTEXT_OPENGL_CORE = 3, + /* OpenGL ES 3.0 */ + RETRO_HW_CONTEXT_OPENGLES3 = 4, + /* OpenGL ES 3.1+. Set version_major/version_minor. For GLES2 and GLES3, + * use the corresponding enums directly. */ + RETRO_HW_CONTEXT_OPENGLES_VERSION = 5, + + /* Vulkan, see RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE. */ + RETRO_HW_CONTEXT_VULKAN = 6, + + RETRO_HW_CONTEXT_DUMMY = INT_MAX +}; + +struct retro_hw_render_callback +{ + /* Which API to use. Set by libretro core. */ + enum retro_hw_context_type context_type; + + /* Called when a context has been created or when it has been reset. + * An OpenGL context is only valid after context_reset() has been called. + * + * When context_reset is called, OpenGL resources in the libretro + * implementation are guaranteed to be invalid. + * + * It is possible that context_reset is called multiple times during an + * application lifecycle. + * If context_reset is called without any notification (context_destroy), + * the OpenGL context was lost and resources should just be recreated + * without any attempt to "free" old resources. + */ + retro_hw_context_reset_t context_reset; + + /* Set by frontend. + * TODO: This is rather obsolete. The frontend should not + * be providing preallocated framebuffers. */ + retro_hw_get_current_framebuffer_t get_current_framebuffer; + + /* Set by frontend. + * Can return all relevant functions, including glClear on Windows. */ + retro_hw_get_proc_address_t get_proc_address; + + /* Set if render buffers should have depth component attached. + * TODO: Obsolete. */ + bool depth; + + /* Set if stencil buffers should be attached. + * TODO: Obsolete. */ + bool stencil; + + /* If depth and stencil are true, a packed 24/8 buffer will be added. + * Only attaching stencil is invalid and will be ignored. */ + + /* Use conventional bottom-left origin convention. If false, + * standard libretro top-left origin semantics are used. + * TODO: Move to GL specific interface. */ + bool bottom_left_origin; + + /* Major version number for core GL context or GLES 3.1+. */ + unsigned version_major; + + /* Minor version number for core GL context or GLES 3.1+. */ + unsigned version_minor; + + /* If this is true, the frontend will go very far to avoid + * resetting context in scenarios like toggling fullscreen, etc. + * TODO: Obsolete? Maybe frontend should just always assume this ... + */ + bool cache_context; + + /* The reset callback might still be called in extreme situations + * such as if the context is lost beyond recovery. + * + * For optimal stability, set this to false, and allow context to be + * reset at any time. + */ + + /* A callback to be called before the context is destroyed in a + * controlled way by the frontend. */ + retro_hw_context_reset_t context_destroy; + + /* OpenGL resources can be deinitialized cleanly at this step. + * context_destroy can be set to NULL, in which resources will + * just be destroyed without any notification. + * + * Even when context_destroy is non-NULL, it is possible that + * context_reset is called without any destroy notification. + * This happens if context is lost by external factors (such as + * notified by GL_ARB_robustness). + * + * In this case, the context is assumed to be already dead, + * and the libretro implementation must not try to free any OpenGL + * resources in the subsequent context_reset. + */ + + /* Creates a debug context. */ + bool debug_context; +}; + +/* Callback type passed in RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK. + * Called by the frontend in response to keyboard events. + * down is set if the key is being pressed, or false if it is being released. + * keycode is the RETROK value of the char. + * character is the text character of the pressed key. (UTF-32). + * key_modifiers is a set of RETROKMOD values or'ed together. + * + * The pressed/keycode state can be indepedent of the character. + * It is also possible that multiple characters are generated from a + * single keypress. + * Keycode events should be treated separately from character events. + * However, when possible, the frontend should try to synchronize these. + * If only a character is posted, keycode should be RETROK_UNKNOWN. + * + * Similarily if only a keycode event is generated with no corresponding + * character, character should be 0. + */ +typedef void (RETRO_CALLCONV *retro_keyboard_event_t)(bool down, unsigned keycode, + uint32_t character, uint16_t key_modifiers); + +struct retro_keyboard_callback +{ + retro_keyboard_event_t callback; +}; + +/* Callbacks for RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE. + * Should be set for implementations which can swap out multiple disk + * images in runtime. + * + * If the implementation can do this automatically, it should strive to do so. + * However, there are cases where the user must manually do so. + * + * Overview: To swap a disk image, eject the disk image with + * set_eject_state(true). + * Set the disk index with set_image_index(index). Insert the disk again + * with set_eject_state(false). + */ + +/* If ejected is true, "ejects" the virtual disk tray. + * When ejected, the disk image index can be set. + */ +typedef bool (RETRO_CALLCONV *retro_set_eject_state_t)(bool ejected); + +/* Gets current eject state. The initial state is 'not ejected'. */ +typedef bool (RETRO_CALLCONV *retro_get_eject_state_t)(void); + +/* Gets current disk index. First disk is index 0. + * If return value is >= get_num_images(), no disk is currently inserted. + */ +typedef unsigned (RETRO_CALLCONV *retro_get_image_index_t)(void); + +/* Sets image index. Can only be called when disk is ejected. + * The implementation supports setting "no disk" by using an + * index >= get_num_images(). + */ +typedef bool (RETRO_CALLCONV *retro_set_image_index_t)(unsigned index); + +/* Gets total number of images which are available to use. */ +typedef unsigned (RETRO_CALLCONV *retro_get_num_images_t)(void); + +struct retro_game_info; + +/* Replaces the disk image associated with index. + * Arguments to pass in info have same requirements as retro_load_game(). + * Virtual disk tray must be ejected when calling this. + * + * Replacing a disk image with info = NULL will remove the disk image + * from the internal list. + * As a result, calls to get_image_index() can change. + * + * E.g. replace_image_index(1, NULL), and previous get_image_index() + * returned 4 before. + * Index 1 will be removed, and the new index is 3. + */ +typedef bool (RETRO_CALLCONV *retro_replace_image_index_t)(unsigned index, + const struct retro_game_info *info); + +/* Adds a new valid index (get_num_images()) to the internal disk list. + * This will increment subsequent return values from get_num_images() by 1. + * This image index cannot be used until a disk image has been set + * with replace_image_index. */ +typedef bool (RETRO_CALLCONV *retro_add_image_index_t)(void); + +struct retro_disk_control_callback +{ + retro_set_eject_state_t set_eject_state; + retro_get_eject_state_t get_eject_state; + + retro_get_image_index_t get_image_index; + retro_set_image_index_t set_image_index; + retro_get_num_images_t get_num_images; + + retro_replace_image_index_t replace_image_index; + retro_add_image_index_t add_image_index; +}; + +enum retro_pixel_format +{ + /* 0RGB1555, native endian. + * 0 bit must be set to 0. + * This pixel format is default for compatibility concerns only. + * If a 15/16-bit pixel format is desired, consider using RGB565. */ + RETRO_PIXEL_FORMAT_0RGB1555 = 0, + + /* XRGB8888, native endian. + * X bits are ignored. */ + RETRO_PIXEL_FORMAT_XRGB8888 = 1, + + /* RGB565, native endian. + * This pixel format is the recommended format to use if a 15/16-bit + * format is desired as it is the pixel format that is typically + * available on a wide range of low-power devices. + * + * It is also natively supported in APIs like OpenGL ES. */ + RETRO_PIXEL_FORMAT_RGB565 = 2, + + /* Ensure sizeof() == sizeof(int). */ + RETRO_PIXEL_FORMAT_UNKNOWN = INT_MAX +}; + +struct retro_message +{ + const char *msg; /* Message to be displayed. */ + unsigned frames; /* Duration in frames of message. */ +}; + +/* Describes how the libretro implementation maps a libretro input bind + * to its internal input system through a human readable string. + * This string can be used to better let a user configure input. */ +struct retro_input_descriptor +{ + /* Associates given parameters with a description. */ + unsigned port; + unsigned device; + unsigned index; + unsigned id; + + /* Human readable description for parameters. + * The pointer must remain valid until + * retro_unload_game() is called. */ + const char *description; +}; + +struct retro_system_info +{ + /* All pointers are owned by libretro implementation, and pointers must + * remain valid until retro_deinit() is called. */ + + const char *library_name; /* Descriptive name of library. Should not + * contain any version numbers, etc. */ + const char *library_version; /* Descriptive version of core. */ + + const char *valid_extensions; /* A string listing probably content + * extensions the core will be able to + * load, separated with pipe. + * I.e. "bin|rom|iso". + * Typically used for a GUI to filter + * out extensions. */ + + /* If true, retro_load_game() is guaranteed to provide a valid pathname + * in retro_game_info::path. + * ::data and ::size are both invalid. + * + * If false, ::data and ::size are guaranteed to be valid, but ::path + * might not be valid. + * + * This is typically set to true for libretro implementations that must + * load from file. + * Implementations should strive for setting this to false, as it allows + * the frontend to perform patching, etc. */ + bool need_fullpath; + + /* If true, the frontend is not allowed to extract any archives before + * loading the real content. + * Necessary for certain libretro implementations that load games + * from zipped archives. */ + bool block_extract; +}; + +struct retro_game_geometry +{ + unsigned base_width; /* Nominal video width of game. */ + unsigned base_height; /* Nominal video height of game. */ + unsigned max_width; /* Maximum possible width of game. */ + unsigned max_height; /* Maximum possible height of game. */ + + float aspect_ratio; /* Nominal aspect ratio of game. If + * aspect_ratio is <= 0.0, an aspect ratio + * of base_width / base_height is assumed. + * A frontend could override this setting, + * if desired. */ +}; + +struct retro_system_timing +{ + double fps; /* FPS of video content. */ + double sample_rate; /* Sampling rate of audio. */ +}; + +struct retro_system_av_info +{ + struct retro_game_geometry geometry; + struct retro_system_timing timing; +}; + +struct retro_variable +{ + /* Variable to query in RETRO_ENVIRONMENT_GET_VARIABLE. + * If NULL, obtains the complete environment string if more + * complex parsing is necessary. + * The environment string is formatted as key-value pairs + * delimited by semicolons as so: + * "key1=value1;key2=value2;..." + */ + const char *key; + + /* Value to be obtained. If key does not exist, it is set to NULL. */ + const char *value; +}; + +struct retro_game_info +{ + const char *path; /* Path to game, UTF-8 encoded. + * Sometimes used as a reference for building other paths. + * May be NULL if game was loaded from stdin or similar, + * but in this case some cores will be unable to load `data`. + * So, it is preferable to fabricate something here instead + * of passing NULL, which will help more cores to succeed. + * retro_system_info::need_fullpath requires + * that this path is valid. */ + const void *data; /* Memory buffer of loaded game. Will be NULL + * if need_fullpath was set. */ + size_t size; /* Size of memory buffer. */ + const char *meta; /* String of implementation specific meta-data. */ +}; + +#define RETRO_MEMORY_ACCESS_WRITE (1 << 0) + /* The core will write to the buffer provided by retro_framebuffer::data. */ +#define RETRO_MEMORY_ACCESS_READ (1 << 1) + /* The core will read from retro_framebuffer::data. */ +#define RETRO_MEMORY_TYPE_CACHED (1 << 0) + /* The memory in data is cached. + * If not cached, random writes and/or reading from the buffer is expected to be very slow. */ +struct retro_framebuffer +{ + void *data; /* The framebuffer which the core can render into. + Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER. + The initial contents of data are unspecified. */ + unsigned width; /* The framebuffer width used by the core. Set by core. */ + unsigned height; /* The framebuffer height used by the core. Set by core. */ + size_t pitch; /* The number of bytes between the beginning of a scanline, + and beginning of the next scanline. + Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER. */ + enum retro_pixel_format format; /* The pixel format the core must use to render into data. + This format could differ from the format used in + SET_PIXEL_FORMAT. + Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER. */ + + unsigned access_flags; /* How the core will access the memory in the framebuffer. + RETRO_MEMORY_ACCESS_* flags. + Set by core. */ + unsigned memory_flags; /* Flags telling core how the memory has been mapped. + RETRO_MEMORY_TYPE_* flags. + Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER. */ +}; + +/* Callbacks */ + +/* Environment callback. Gives implementations a way of performing + * uncommon tasks. Extensible. */ +typedef bool (RETRO_CALLCONV *retro_environment_t)(unsigned cmd, void *data); + +/* Render a frame. Pixel format is 15-bit 0RGB1555 native endian + * unless changed (see RETRO_ENVIRONMENT_SET_PIXEL_FORMAT). + * + * Width and height specify dimensions of buffer. + * Pitch specifices length in bytes between two lines in buffer. + * + * For performance reasons, it is highly recommended to have a frame + * that is packed in memory, i.e. pitch == width * byte_per_pixel. + * Certain graphic APIs, such as OpenGL ES, do not like textures + * that are not packed in memory. + */ +typedef void (RETRO_CALLCONV *retro_video_refresh_t)(const void *data, unsigned width, + unsigned height, size_t pitch); + +/* Renders a single audio frame. Should only be used if implementation + * generates a single sample at a time. + * Format is signed 16-bit native endian. + */ +typedef void (RETRO_CALLCONV *retro_audio_sample_t)(int16_t left, int16_t right); + +/* Renders multiple audio frames in one go. + * + * One frame is defined as a sample of left and right channels, interleaved. + * I.e. int16_t buf[4] = { l, r, l, r }; would be 2 frames. + * Only one of the audio callbacks must ever be used. + */ +typedef size_t (RETRO_CALLCONV *retro_audio_sample_batch_t)(const int16_t *data, + size_t frames); + +/* Polls input. */ +typedef void (RETRO_CALLCONV *retro_input_poll_t)(void); + +/* Queries for input for player 'port'. device will be masked with + * RETRO_DEVICE_MASK. + * + * Specialization of devices such as RETRO_DEVICE_JOYPAD_MULTITAP that + * have been set with retro_set_controller_port_device() + * will still use the higher level RETRO_DEVICE_JOYPAD to request input. + */ +typedef int16_t (RETRO_CALLCONV *retro_input_state_t)(unsigned port, unsigned device, + unsigned index, unsigned id); + +/* Sets callbacks. retro_set_environment() is guaranteed to be called + * before retro_init(). + * + * The rest of the set_* functions are guaranteed to have been called + * before the first call to retro_run() is made. */ +RETRO_API void retro_set_environment(retro_environment_t); +RETRO_API void retro_set_video_refresh(retro_video_refresh_t); +RETRO_API void retro_set_audio_sample(retro_audio_sample_t); +RETRO_API void retro_set_audio_sample_batch(retro_audio_sample_batch_t); +RETRO_API void retro_set_input_poll(retro_input_poll_t); +RETRO_API void retro_set_input_state(retro_input_state_t); + +/* Library global initialization/deinitialization. */ +RETRO_API void retro_init(void); +RETRO_API void retro_deinit(void); + +/* Must return RETRO_API_VERSION. Used to validate ABI compatibility + * when the API is revised. */ +RETRO_API unsigned retro_api_version(void); + +/* Gets statically known system info. Pointers provided in *info + * must be statically allocated. + * Can be called at any time, even before retro_init(). */ +RETRO_API void retro_get_system_info(struct retro_system_info *info); + +/* Gets information about system audio/video timings and geometry. + * Can be called only after retro_load_game() has successfully completed. + * NOTE: The implementation of this function might not initialize every + * variable if needed. + * E.g. geom.aspect_ratio might not be initialized if core doesn't + * desire a particular aspect ratio. */ +RETRO_API void retro_get_system_av_info(struct retro_system_av_info *info); + +/* Sets device to be used for player 'port'. + * By default, RETRO_DEVICE_JOYPAD is assumed to be plugged into all + * available ports. + * Setting a particular device type is not a guarantee that libretro cores + * will only poll input based on that particular device type. It is only a + * hint to the libretro core when a core cannot automatically detect the + * appropriate input device type on its own. It is also relevant when a + * core can change its behavior depending on device type. */ +RETRO_API void retro_set_controller_port_device(unsigned port, unsigned device); + +/* Resets the current game. */ +RETRO_API void retro_reset(void); + +/* Runs the game for one video frame. + * During retro_run(), input_poll callback must be called at least once. + * + * If a frame is not rendered for reasons where a game "dropped" a frame, + * this still counts as a frame, and retro_run() should explicitly dupe + * a frame if GET_CAN_DUPE returns true. + * In this case, the video callback can take a NULL argument for data. + */ +RETRO_API void retro_run(void); + +/* Returns the amount of data the implementation requires to serialize + * internal state (save states). + * Between calls to retro_load_game() and retro_unload_game(), the + * returned size is never allowed to be larger than a previous returned + * value, to ensure that the frontend can allocate a save state buffer once. + */ +RETRO_API size_t retro_serialize_size(void); + +/* Serializes internal state. If failed, or size is lower than + * retro_serialize_size(), it should return false, true otherwise. */ +RETRO_API bool retro_serialize(void *data, size_t size); +RETRO_API bool retro_unserialize(const void *data, size_t size); + +RETRO_API void retro_cheat_reset(void); +RETRO_API void retro_cheat_set(unsigned index, bool enabled, const char *code); + +/* Loads a game. */ +RETRO_API bool retro_load_game(const struct retro_game_info *game); + +/* Loads a "special" kind of game. Should not be used, + * except in extreme cases. */ +RETRO_API bool retro_load_game_special( + unsigned game_type, + const struct retro_game_info *info, size_t num_info +); + +/* Unloads a currently loaded game. */ +RETRO_API void retro_unload_game(void); + +/* Gets region of game. */ +RETRO_API unsigned retro_get_region(void); + +/* Gets region of memory. */ +RETRO_API void *retro_get_memory_data(unsigned id); +RETRO_API size_t retro_get_memory_size(unsigned id); + +#ifdef __cplusplus +} +#endif + +#endif diff -Nru nestopia-1.48/libretro/libretro.cpp nestopia-1.49/libretro/libretro.cpp --- nestopia-1.48/libretro/libretro.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/libretro.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -17,12 +17,12 @@ #include "../source/core/api/NstApiUser.hpp" #include "../source/core/api/NstApiFds.hpp" -#define NST_VERSION "1.48-WIP" +#include "../source/core/NstMachine.hpp" -#ifdef _WIN32 -#define snprintf _snprintf -#endif +#define NST_VERSION "1.49" +#define MIN(a,b) ((a)<(b)?(a):(b)) +#define MAX(a,b) ((a)>(b)?(a):(b)) #define NES_NTSC_PAR ((Api::Video::Output::WIDTH - (overscan_h ? 16 : 0)) * (8.0 / 7.0)) / (Api::Video::Output::HEIGHT - (overscan_v ? 16 : 0)) #define NES_PAL_PAR ((Api::Video::Output::WIDTH - (overscan_h ? 16 : 0)) * (2950000.0 / 2128137.0)) / (Api::Video::Output::HEIGHT - (overscan_v ? 16 : 0)) #define NES_4_3_DAR (4.0 / 3.0); @@ -43,14 +43,15 @@ #endif static uint32_t* video_buffer = NULL; -static int16_t audio_buffer[(44100 / 50)]; -static int16_t audio_stereo_buffer[2 * (44100 / 50)]; +static int16_t audio_buffer[(48000 / 50)]; +static int16_t audio_stereo_buffer[2 * (48000 / 50)]; static Api::Emulator emulator; static Api::Machine *machine; static Api::Fds *fds; static char g_basename[256]; static char g_rom_dir[256]; static char *g_save_dir; +static char samp_dir[256]; static unsigned blargg_ntsc; static bool fds_auto_insert; static bool overscan_v; @@ -64,13 +65,15 @@ static Api::Video::Output *video; static Api::Sound::Output *audio; static Api::Input::Controllers *input; +static unsigned input_type[4]; static Api::Machine::FavoredSystem favsystem; static void *sram; static unsigned long sram_size; static bool is_pal; static bool dbpresent; -static unsigned char *custpal[64*3]; +static byte custpal[64*3]; +static char slash; static const byte cxa2025as_palette[64][3] = { @@ -195,19 +198,57 @@ int crossx = 0; int crossy = 0; +#define CROSSHAIR_SIZE 3 + void draw_crosshair(int x, int y) { uint32_t w = 0xFFFFFFFF; uint32_t b = 0x00000000; + int current_width = 256; - for(int i = -3; i < 4; i++) { - video_buffer[256 * y + x + i] = b; - video_buffer[256 * (y + i) + x] = b; + if (blargg_ntsc){ + x *= 2.36; + current_width = 602; } - - for(int i = -2; i < 3; i += 2) { - video_buffer[256 * y + x + i] = w; - video_buffer[256 * (y + i) + x] = w; + + for (int i = MAX(-CROSSHAIR_SIZE, -x); i <= MIN(CROSSHAIR_SIZE, current_width - x); i++) { + video_buffer[current_width * y + x + i] = i % 2 == 0 ? w : b; + } + + for (int i = MAX(-CROSSHAIR_SIZE, -y); i <= MIN(CROSSHAIR_SIZE, 239 - y); i++) { + video_buffer[current_width * (y + i) + x] = i % 2 == 0 ? w : b; + } +} + +static void load_wav(const char* sampgame, Api::User::File& file) +{ + char samp_path[292]; + + snprintf(samp_path, sizeof(samp_path), "%s%c%s%c%02d.wav", samp_dir, slash, sampgame, slash, file.GetId()); + + std::ifstream samp_file(samp_path, std::ifstream::in|std::ifstream::binary); + + if (samp_file) { + samp_file.seekg(0, samp_file.end); + int length = samp_file.tellg(); + samp_file.seekg(0, samp_file.beg); + char wavfile[length]; + samp_file.read(wavfile, length); + + // Check to see if it has a valid header + char fmt[4] = { 0x66, 0x6d, 0x74, 0x20}; + char subchunk2id[4] = { 0x64, 0x61, 0x74, 0x61}; + if (memcmp(&wavfile[0x00], "RIFF", 4) != 0) { return; } + if (memcmp(&wavfile[0x08], "WAVE", 4) != 0) { return; } + if (memcmp(&wavfile[0x0c], &fmt, 4) != 0) { return; } + if (memcmp(&wavfile[0x24], &subchunk2id, 4) != 0) { return; } + + // Load the sample into the emulator + char *dataptr = &wavfile[0x2c]; + int blockalign = wavfile[0x21] << 8 | wavfile[0x20]; + int numchannels = wavfile[0x17] << 8 | wavfile[0x16]; + int bitspersample = wavfile[0x23] << 8 | wavfile[0x22]; + file.SetSampleContent(dataptr, (length - 44) / blockalign, 0, bitspersample, 44100); } } @@ -215,7 +256,6 @@ { const void *addr; unsigned long addr_size; - char slash; #ifdef _WIN32 slash = '\\'; @@ -225,6 +265,17 @@ switch (file.GetAction()) { + case Api::User::File::LOAD_SAMPLE_MOERO_PRO_YAKYUU: + load_wav("moepro", file); break; + case Api::User::File::LOAD_SAMPLE_MOERO_PRO_YAKYUU_88: + load_wav("moepro88", file); break; + case Api::User::File::LOAD_SAMPLE_MOERO_PRO_TENNIS: + load_wav("mptennis", file); break; + case Api::User::File::LOAD_SAMPLE_TERAO_NO_DOSUKOI_OOZUMOU: + load_wav("terao", file); break; + case Api::User::File::LOAD_SAMPLE_AEROBICS_STUDIO: + load_wav("ftaerobi", file); break; + case Api::User::File::LOAD_BATTERY: case Api::User::File::LOAD_EEPROM: case Api::User::File::LOAD_TAPE: @@ -244,7 +295,7 @@ case Api::User::File::LOAD_FDS: { char base[256]; - snprintf(base, sizeof(base), "%s%c%s.sav", g_save_dir, slash, g_basename); + sprintf(base, "%s%c%s.sav", g_save_dir, slash, g_basename); if (log_cb) log_cb(RETRO_LOG_INFO, "Want to load FDS sav from: %s\n", base); std::ifstream in_tmp(base,std::ifstream::in|std::ifstream::binary); @@ -258,7 +309,7 @@ case Api::User::File::SAVE_FDS: { char base[256]; - snprintf(base, sizeof(base), "%s%c%s.sav", g_save_dir, slash, g_basename); + sprintf(base, "%s%c%s.sav", g_save_dir, slash, g_basename); if (log_cb) log_cb(RETRO_LOG_INFO, "Want to save FDS sav to: %s\n", base); std::ofstream out_tmp(base,std::ifstream::out|std::ifstream::binary); @@ -300,8 +351,12 @@ return RETRO_API_VERSION; } -void retro_set_controller_port_device(unsigned, unsigned) +void retro_set_controller_port_device(unsigned port, unsigned device) { + if (port >= 4) + return; + + input_type[port] = device; } void retro_get_system_info(struct retro_system_info *info) @@ -333,7 +388,7 @@ void retro_get_system_av_info(struct retro_system_av_info *info) { - const retro_system_timing timing = { is_pal ? 50.0 : 60.0, 44100.0 }; + const retro_system_timing timing = { is_pal ? 50.0 : 60.0, 48000.0 }; info->timing = timing; // It's better if the size is based on NTSC_WIDTH if the filter is on @@ -354,8 +409,10 @@ static const struct retro_variable vars[] = { { "nestopia_blargg_ntsc_filter", "Blargg NTSC filter; disabled|composite|svideo|rgb|monochrome" }, - { "nestopia_palette", "Palette; consumer|canonical|alternative|rgb|cxa2025as|pal|composite-direct-fbx|pvm-style-d93-fbx|ntsc-hardware-fbx|nes-classic-fbx-fs|raw|custom" }, + { "nestopia_palette", "Palette; cxa2025as|consumer|canonical|alternative|rgb|pal|composite-direct-fbx|pvm-style-d93-fbx|ntsc-hardware-fbx|nes-classic-fbx-fs|raw|custom" }, { "nestopia_nospritelimit", "Remove 8-sprites-per-scanline hardware limit; disabled|enabled" }, + { "nestopia_overclock", "CPU Speed (Overclock); 1x|2x" }, + { "nestopia_select_adapter", "4 Player Adapter; auto|ntsc|famicom" }, { "nestopia_fds_auto_insert", "Automatically insert first FDS disk on reset; enabled|disabled" }, { "nestopia_overscan_v", "Mask Overscan (Vertical); enabled|disabled" }, { "nestopia_overscan_h", "Mask Overscan (Horizontal); disabled|enabled" }, @@ -431,23 +488,40 @@ input->pad[1].buttons = 0; input->pad[2].buttons = 0; input->pad[3].buttons = 0; + input->pad[1].mic = 0; input->zapper.fire = 0; input->vsSystem.insertCoin = 0; if (Api::Input(emulator).GetConnectedController(1) == 5) { static int zapx = overscan_h ? 8 : 0; static int zapy = overscan_v ? 8 : 0; - zapx += input_state_cb(1, RETRO_DEVICE_LIGHTGUN, 0, RETRO_DEVICE_ID_LIGHTGUN_X); - zapy += input_state_cb(1, RETRO_DEVICE_LIGHTGUN, 0, RETRO_DEVICE_ID_LIGHTGUN_Y); - - if (zapx >= 256) { crossx = 255; } - else if (zapx <= 0) { crossx = 0; } + int min_x = overscan_h ? 8 : 0; + int max_x = overscan_h ? 247 : 255; + int min_y = overscan_v ? 8 : 0; + int max_y = overscan_v ? 231 : 239; + + if (zapx > max_x) + zapx = max_x; + else if (zapx < min_x) + zapx = min_x; + else + zapx += input_state_cb(1, RETRO_DEVICE_LIGHTGUN, 0, RETRO_DEVICE_ID_LIGHTGUN_X); + + if (zapy > max_y) + zapy = max_y; + else if (zapy < min_y) + zapy = min_y; + else + zapy += input_state_cb(1, RETRO_DEVICE_LIGHTGUN, 0, RETRO_DEVICE_ID_LIGHTGUN_Y); + + if (zapx > max_x) { crossx = max_x; } + else if (zapx < min_x) { crossx = min_x; } else {crossx = zapx; } - - if (zapy >= 240) { crossy = 239; } - else if (zapy <= 0) { crossy = 0; } + + if (zapy > max_y) { crossy = max_y; } + else if (zapy < min_y) { crossy = min_y; } else {crossy = zapy; } - + if (input_state_cb(1, RETRO_DEVICE_LIGHTGUN, 0, RETRO_DEVICE_ID_LIGHTGUN_TRIGGER)) { input->zapper.x = zapx; input->zapper.y = zapy; @@ -474,6 +548,9 @@ if (tstate) tstate--; else tstate = tpulse; + if (input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3)) + input->pad[1].mic |= 0x04; + if (input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2)) input->vsSystem.insertCoin |= Core::Input::Controllers::VsSystem::COIN_1; @@ -569,7 +646,7 @@ } } if (audio) delete audio; - audio = new Api::Sound::Output(audio_buffer, is_pal ? 44100 / 50 : 44100 / 60); + audio = new Api::Sound::Output(audio_buffer, is_pal ? 48000 / 50 : 48000 / 60); var.key = "nestopia_genie_distortion"; @@ -603,6 +680,16 @@ video.EnableUnlimSprites(true); } + var.key = "nestopia_overclock"; + + if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var)) + { + if (strcmp(var.value, "1x") == 0) + video.EnableOverclocking(false); + else if (strcmp(var.value, "2x") == 0) + video.EnableOverclocking(true); + } + var.key = "nestopia_fds_auto_insert"; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var)) @@ -765,6 +852,29 @@ aspect_ratio_mode = 0; } + var.key = "nestopia_select_adapter"; + if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) + { + if (!strcmp(var.value, "auto")) { + if (dbpresent) + { + Api::Input(emulator).AutoSelectController(2); + Api::Input(emulator).AutoSelectController(3); + Api::Input(emulator).AutoSelectAdapter(); + } + } + else if (!strcmp(var.value, "ntsc")) { + Api::Input(emulator).ConnectController(2, Api::Input::PAD3); + Api::Input(emulator).ConnectController(3, Api::Input::PAD4); + Api::Input(emulator).ConnectAdapter(Api::Input::ADAPTER_NES); + } + else if (!strcmp(var.value, "famicom")) { + Api::Input(emulator).ConnectController(2, Api::Input::PAD3); + Api::Input(emulator).ConnectController(3, Api::Input::PAD4); + Api::Input(emulator).ConnectAdapter(Api::Input::ADAPTER_FAMICOM); + } + } + var.key = "nestopia_turbo_pulse"; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var)) @@ -795,7 +905,7 @@ if (Api::Input(emulator).GetConnectedController(1) == 5) draw_crosshair(crossx, crossy); - unsigned frames = is_pal ? 44100 / 50 : 44100 / 60; + unsigned frames = is_pal ? 48000 / 50 : 48000 / 60; for (unsigned i = 0; i < frames; i++) audio_stereo_buffer[(i << 1) + 0] = audio_stereo_buffer[(i << 1) + 1] = audio_buffer[i]; audio_batch_cb(audio_stereo_buffer, frames); @@ -810,8 +920,10 @@ } // Absolute mess of inline if statements... - video_cb(video_buffer + (overscan_v ? ((overscan_h ? 8 : 0) + (blargg_ntsc ? Api::Video::Output::NTSC_WIDTH : Api::Video::Output::WIDTH) * 8) : (overscan_h ? 8 : 0) + 0), - video_width - (overscan_h ? 16 : 0), + int dif = blargg_ntsc ? 18 : 8; + + video_cb(video_buffer + (overscan_v ? ((overscan_h ? dif : 0) + (blargg_ntsc ? Api::Video::Output::NTSC_WIDTH : Api::Video::Output::WIDTH) * 8) : (overscan_h ? dif : 0) + 0), + video_width - (overscan_h ? 2 * dif : 0), Api::Video::Output::HEIGHT - (overscan_v ? 16 : 0), pitch); } @@ -877,6 +989,7 @@ { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "(FDS) Eject Disk" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2, "(VSSystem) Coin 1" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2, "(VSSystem) Coin 2" }, + { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3, "(Famicom) Microphone" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" }, { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" }, @@ -937,7 +1050,9 @@ if (!environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) || !dir) return false; - snprintf(palette_path, sizeof(palette_path), "%s%ccustom.pal", dir, slash); + sprintf(samp_dir, "%s%cnestopia%csamples", dir, slash, slash); + + sprintf(palette_path, "%s%ccustom.pal", dir, slash); if (log_cb) log_cb(RETRO_LOG_INFO, "Custom palette path: %s\n", palette_path); @@ -946,18 +1061,19 @@ if (custompalette->is_open()) { - custompalette->read((char*)custpal, 64*3); + custompalette->read((char*)custpal, sizeof(custpal)); if (log_cb) log_cb(RETRO_LOG_WARN, "custom.pal loaded from system directory.\n"); } else { + memcpy(custpal, cxa2025as_palette, sizeof(custpal)); if (log_cb) log_cb(RETRO_LOG_WARN, "custom.pal not found in system directory.\n"); } delete custompalette; - snprintf(db_path, sizeof(db_path), "%s%cNstDatabase.xml", dir, slash); + sprintf(db_path, "%s%cNstDatabase.xml", dir, slash); if (log_cb) log_cb(RETRO_LOG_INFO, "NstDatabase.xml path: %s\n", db_path); @@ -1006,7 +1122,7 @@ /* search for BIOS in system directory */ bool found = false; - snprintf(fds_bios_path, sizeof(fds_bios_path), "%s%cdisksys.rom", dir, slash); + sprintf(fds_bios_path, "%s%cdisksys.rom", dir, slash); if (log_cb) log_cb(RETRO_LOG_INFO, "FDS BIOS path: %s\n", fds_bios_path); @@ -1055,23 +1171,19 @@ Api::Sound isound(emulator); isound.SetSampleBits(16); - isound.SetSampleRate(44100); + isound.SetSampleRate(48000); isound.SetSpeaker(Api::Sound::SPEAKER_MONO); if (dbpresent) { Api::Input(emulator).AutoSelectController(0); Api::Input(emulator).AutoSelectController(1); - Api::Input(emulator).AutoSelectController(2); - Api::Input(emulator).AutoSelectController(3); } else { Api::Input(emulator).ConnectController(0, Api::Input::PAD1); Api::Input(emulator).ConnectController(1, Api::Input::PAD2); //Api::Input(emulator).ConnectController(1, Api::Input::ZAPPER); - Api::Input(emulator).ConnectController(2, Api::Input::PAD3); - Api::Input(emulator).ConnectController(3, Api::Input::PAD4); } machine->Power(true); @@ -1169,18 +1281,33 @@ void *retro_get_memory_data(unsigned id) { - if (id != RETRO_MEMORY_SAVE_RAM) - return 0; + Core::Machine& machineGet = emulator; + switch(id) + { + case RETRO_MEMORY_SAVE_RAM: + return sram; + + case RETRO_MEMORY_SYSTEM_RAM: + return (void*)&machineGet.cpu.GetRam()[0]; + + } - return sram; + return NULL; } size_t retro_get_memory_size(unsigned id) { - if (id != RETRO_MEMORY_SAVE_RAM) - return 0; + Core::Machine& machineGet = emulator; + switch(id) + { + case RETRO_MEMORY_SAVE_RAM: + return sram_size; + + case RETRO_MEMORY_SYSTEM_RAM: + return machineGet.cpu.RAM_SIZE; + } - return sram_size; + return 0; } void retro_cheat_reset(void) @@ -1193,9 +1320,36 @@ { Nes::Api::Cheats cheater(emulator); Nes::Api::Cheats::Code ggCode; + char codeCopy[256]; + char *part; - if (Nes::Api::Cheats::GameGenieDecode(code, ggCode) == RESULT_OK) - cheater.SetCode(ggCode); - if (Nes::Api::Cheats::ProActionRockyDecode(code, ggCode) == RESULT_OK) - cheater.SetCode(ggCode); + if (code == NULL) return; + strcpy(codeCopy,code); + part = strtok(codeCopy,"+,;._ "); + + while (part) + { + if ((strlen(part) == 7) && (part[4]==':')) + { + part[4]='\0'; + ggCode.address=strtoul(part,NULL,16); + ggCode.value=strtoul(part+5,NULL,16); + cheater.SetCode(ggCode); + } + else if ((strlen(part)==10) && (part[4]=='?') && (part[7]==':')) + { + part[4]='\0'; + part[7]='\0'; + ggCode.address=strtoul(part,NULL,16); + ggCode.compare=strtoul(part+5,NULL,16); + ggCode.useCompare=true; + ggCode.value=strtoul(part+8,NULL,16); + cheater.SetCode(ggCode); + } + else if (Nes::Api::Cheats::GameGenieDecode(part, ggCode) == RESULT_OK) + cheater.SetCode(ggCode); + else if (Nes::Api::Cheats::ProActionRockyDecode(part, ggCode) == RESULT_OK) + cheater.SetCode(ggCode); + part = strtok(NULL,"+,;._ "); + } } diff -Nru nestopia-1.48/libretro/libretro.h nestopia-1.49/libretro/libretro.h --- nestopia-1.48/libretro/libretro.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/libretro.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,1926 +0,0 @@ -/* Copyright (C) 2010-2014 The RetroArch team - * - * --------------------------------------------------------------------------------------- - * The following license statement only applies to this libretro API header (libretro.h). - * --------------------------------------------------------------------------------------- - * - * Permission is hereby granted, free of charge, - * to any person obtaining a copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#ifndef LIBRETRO_H__ -#define LIBRETRO_H__ - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef __cplusplus -#if defined(_MSC_VER) && !defined(SN_TARGET_PS3) -/* Hack applied for MSVC when compiling in C89 mode - * as it isn't C99-compliant. */ -#define bool unsigned char -#define true 1 -#define false 0 -#else -#include -#endif -#endif - -/* Used for checking API/ABI mismatches that can break libretro - * implementations. - * It is not incremented for compatible changes to the API. - */ -#define RETRO_API_VERSION 1 - -/* - * Libretro's fundamental device abstractions. - * - * Libretro's input system consists of some standardized device types, - * such as a joypad (with/without analog), mouse, keyboard, lightgun - * and a pointer. - * - * The functionality of these devices are fixed, and individual cores - * map their own concept of a controller to libretro's abstractions. - * This makes it possible for frontends to map the abstract types to a - * real input device, and not having to worry about binding input - * correctly to arbitrary controller layouts. - */ - -#define RETRO_DEVICE_TYPE_SHIFT 8 -#define RETRO_DEVICE_MASK ((1 << RETRO_DEVICE_TYPE_SHIFT) - 1) -#define RETRO_DEVICE_SUBCLASS(base, id) (((id + 1) << RETRO_DEVICE_TYPE_SHIFT) | base) - -/* Input disabled. */ -#define RETRO_DEVICE_NONE 0 - -/* The JOYPAD is called RetroPad. It is essentially a Super Nintendo - * controller, but with additional L2/R2/L3/R3 buttons, similar to a - * PS1 DualShock. */ -#define RETRO_DEVICE_JOYPAD 1 - -/* The mouse is a simple mouse, similar to Super Nintendo's mouse. - * X and Y coordinates are reported relatively to last poll (poll callback). - * It is up to the libretro implementation to keep track of where the mouse - * pointer is supposed to be on the screen. - * The frontend must make sure not to interfere with its own hardware - * mouse pointer. - */ -#define RETRO_DEVICE_MOUSE 2 - -/* KEYBOARD device lets one poll for raw key pressed. - * It is poll based, so input callback will return with the current - * pressed state. - * For event/text based keyboard input, see - * RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK. - */ -#define RETRO_DEVICE_KEYBOARD 3 - -/* Lightgun X/Y coordinates are reported relatively to last poll, - * similar to mouse. */ -#define RETRO_DEVICE_LIGHTGUN 4 - -/* The ANALOG device is an extension to JOYPAD (RetroPad). - * Similar to DualShock it adds two analog sticks. - * This is treated as a separate device type as it returns values in the - * full analog range of [-0x8000, 0x7fff]. Positive X axis is right. - * Positive Y axis is down. - * Only use ANALOG type when polling for analog values of the axes. - */ -#define RETRO_DEVICE_ANALOG 5 - -/* Abstracts the concept of a pointing mechanism, e.g. touch. - * This allows libretro to query in absolute coordinates where on the - * screen a mouse (or something similar) is being placed. - * For a touch centric device, coordinates reported are the coordinates - * of the press. - * - * Coordinates in X and Y are reported as: - * [-0x7fff, 0x7fff]: -0x7fff corresponds to the far left/top of the screen, - * and 0x7fff corresponds to the far right/bottom of the screen. - * The "screen" is here defined as area that is passed to the frontend and - * later displayed on the monitor. - * - * The frontend is free to scale/resize this screen as it sees fit, however, - * (X, Y) = (-0x7fff, -0x7fff) will correspond to the top-left pixel of the - * game image, etc. - * - * To check if the pointer coordinates are valid (e.g. a touch display - * actually being touched), PRESSED returns 1 or 0. - * - * If using a mouse on a desktop, PRESSED will usually correspond to the - * left mouse button, but this is a frontend decision. - * PRESSED will only return 1 if the pointer is inside the game screen. - * - * For multi-touch, the index variable can be used to successively query - * more presses. - * If index = 0 returns true for _PRESSED, coordinates can be extracted - * with _X, _Y for index = 0. One can then query _PRESSED, _X, _Y with - * index = 1, and so on. - * Eventually _PRESSED will return false for an index. No further presses - * are registered at this point. */ -#define RETRO_DEVICE_POINTER 6 - -/* Buttons for the RetroPad (JOYPAD). - * The placement of these is equivalent to placements on the - * Super Nintendo controller. - * L2/R2/L3/R3 buttons correspond to the PS1 DualShock. */ -#define RETRO_DEVICE_ID_JOYPAD_B 0 -#define RETRO_DEVICE_ID_JOYPAD_Y 1 -#define RETRO_DEVICE_ID_JOYPAD_SELECT 2 -#define RETRO_DEVICE_ID_JOYPAD_START 3 -#define RETRO_DEVICE_ID_JOYPAD_UP 4 -#define RETRO_DEVICE_ID_JOYPAD_DOWN 5 -#define RETRO_DEVICE_ID_JOYPAD_LEFT 6 -#define RETRO_DEVICE_ID_JOYPAD_RIGHT 7 -#define RETRO_DEVICE_ID_JOYPAD_A 8 -#define RETRO_DEVICE_ID_JOYPAD_X 9 -#define RETRO_DEVICE_ID_JOYPAD_L 10 -#define RETRO_DEVICE_ID_JOYPAD_R 11 -#define RETRO_DEVICE_ID_JOYPAD_L2 12 -#define RETRO_DEVICE_ID_JOYPAD_R2 13 -#define RETRO_DEVICE_ID_JOYPAD_L3 14 -#define RETRO_DEVICE_ID_JOYPAD_R3 15 - -/* Index / Id values for ANALOG device. */ -#define RETRO_DEVICE_INDEX_ANALOG_LEFT 0 -#define RETRO_DEVICE_INDEX_ANALOG_RIGHT 1 -#define RETRO_DEVICE_ID_ANALOG_X 0 -#define RETRO_DEVICE_ID_ANALOG_Y 1 - -/* Id values for MOUSE. */ -#define RETRO_DEVICE_ID_MOUSE_X 0 -#define RETRO_DEVICE_ID_MOUSE_Y 1 -#define RETRO_DEVICE_ID_MOUSE_LEFT 2 -#define RETRO_DEVICE_ID_MOUSE_RIGHT 3 -#define RETRO_DEVICE_ID_MOUSE_WHEELUP 4 -#define RETRO_DEVICE_ID_MOUSE_WHEELDOWN 5 -#define RETRO_DEVICE_ID_MOUSE_MIDDLE 6 - -/* Id values for LIGHTGUN types. */ -#define RETRO_DEVICE_ID_LIGHTGUN_X 0 -#define RETRO_DEVICE_ID_LIGHTGUN_Y 1 -#define RETRO_DEVICE_ID_LIGHTGUN_TRIGGER 2 -#define RETRO_DEVICE_ID_LIGHTGUN_CURSOR 3 -#define RETRO_DEVICE_ID_LIGHTGUN_TURBO 4 -#define RETRO_DEVICE_ID_LIGHTGUN_PAUSE 5 -#define RETRO_DEVICE_ID_LIGHTGUN_START 6 - -/* Id values for POINTER. */ -#define RETRO_DEVICE_ID_POINTER_X 0 -#define RETRO_DEVICE_ID_POINTER_Y 1 -#define RETRO_DEVICE_ID_POINTER_PRESSED 2 - -/* Returned from retro_get_region(). */ -#define RETRO_REGION_NTSC 0 -#define RETRO_REGION_PAL 1 - -/* Id values for LANGUAGE */ -enum retro_language -{ - RETRO_LANGUAGE_ENGLISH = 0, - RETRO_LANGUAGE_JAPANESE = 1, - RETRO_LANGUAGE_FRENCH = 2, - RETRO_LANGUAGE_SPANISH = 3, - RETRO_LANGUAGE_GERMAN = 4, - RETRO_LANGUAGE_ITALIAN = 5, - RETRO_LANGUAGE_DUTCH = 6, - RETRO_LANGUAGE_PORTUGUESE = 7, - RETRO_LANGUAGE_RUSSIAN = 8, - RETRO_LANGUAGE_KOREAN = 9, - RETRO_LANGUAGE_CHINESE_TRADITIONAL = 10, - RETRO_LANGUAGE_CHINESE_SIMPLIFIED = 11, - RETRO_LANGUAGE_LAST, - - /* Ensure sizeof(enum) == sizeof(int) */ - RETRO_LANGUAGE_DUMMY = INT_MAX -}; - -/* Passed to retro_get_memory_data/size(). - * If the memory type doesn't apply to the - * implementation NULL/0 can be returned. - */ -#define RETRO_MEMORY_MASK 0xff - -/* Regular save RAM. This RAM is usually found on a game cartridge, - * backed up by a battery. - * If save game data is too complex for a single memory buffer, - * the SAVE_DIRECTORY (preferably) or SYSTEM_DIRECTORY environment - * callback can be used. */ -#define RETRO_MEMORY_SAVE_RAM 0 - -/* Some games have a built-in clock to keep track of time. - * This memory is usually just a couple of bytes to keep track of time. - */ -#define RETRO_MEMORY_RTC 1 - -/* System ram lets a frontend peek into a game systems main RAM. */ -#define RETRO_MEMORY_SYSTEM_RAM 2 - -/* Video ram lets a frontend peek into a game systems video RAM (VRAM). */ -#define RETRO_MEMORY_VIDEO_RAM 3 - -/* Keysyms used for ID in input state callback when polling RETRO_KEYBOARD. */ -enum retro_key -{ - RETROK_UNKNOWN = 0, - RETROK_FIRST = 0, - RETROK_BACKSPACE = 8, - RETROK_TAB = 9, - RETROK_CLEAR = 12, - RETROK_RETURN = 13, - RETROK_PAUSE = 19, - RETROK_ESCAPE = 27, - RETROK_SPACE = 32, - RETROK_EXCLAIM = 33, - RETROK_QUOTEDBL = 34, - RETROK_HASH = 35, - RETROK_DOLLAR = 36, - RETROK_AMPERSAND = 38, - RETROK_QUOTE = 39, - RETROK_LEFTPAREN = 40, - RETROK_RIGHTPAREN = 41, - RETROK_ASTERISK = 42, - RETROK_PLUS = 43, - RETROK_COMMA = 44, - RETROK_MINUS = 45, - RETROK_PERIOD = 46, - RETROK_SLASH = 47, - RETROK_0 = 48, - RETROK_1 = 49, - RETROK_2 = 50, - RETROK_3 = 51, - RETROK_4 = 52, - RETROK_5 = 53, - RETROK_6 = 54, - RETROK_7 = 55, - RETROK_8 = 56, - RETROK_9 = 57, - RETROK_COLON = 58, - RETROK_SEMICOLON = 59, - RETROK_LESS = 60, - RETROK_EQUALS = 61, - RETROK_GREATER = 62, - RETROK_QUESTION = 63, - RETROK_AT = 64, - RETROK_LEFTBRACKET = 91, - RETROK_BACKSLASH = 92, - RETROK_RIGHTBRACKET = 93, - RETROK_CARET = 94, - RETROK_UNDERSCORE = 95, - RETROK_BACKQUOTE = 96, - RETROK_a = 97, - RETROK_b = 98, - RETROK_c = 99, - RETROK_d = 100, - RETROK_e = 101, - RETROK_f = 102, - RETROK_g = 103, - RETROK_h = 104, - RETROK_i = 105, - RETROK_j = 106, - RETROK_k = 107, - RETROK_l = 108, - RETROK_m = 109, - RETROK_n = 110, - RETROK_o = 111, - RETROK_p = 112, - RETROK_q = 113, - RETROK_r = 114, - RETROK_s = 115, - RETROK_t = 116, - RETROK_u = 117, - RETROK_v = 118, - RETROK_w = 119, - RETROK_x = 120, - RETROK_y = 121, - RETROK_z = 122, - RETROK_DELETE = 127, - - RETROK_KP0 = 256, - RETROK_KP1 = 257, - RETROK_KP2 = 258, - RETROK_KP3 = 259, - RETROK_KP4 = 260, - RETROK_KP5 = 261, - RETROK_KP6 = 262, - RETROK_KP7 = 263, - RETROK_KP8 = 264, - RETROK_KP9 = 265, - RETROK_KP_PERIOD = 266, - RETROK_KP_DIVIDE = 267, - RETROK_KP_MULTIPLY = 268, - RETROK_KP_MINUS = 269, - RETROK_KP_PLUS = 270, - RETROK_KP_ENTER = 271, - RETROK_KP_EQUALS = 272, - - RETROK_UP = 273, - RETROK_DOWN = 274, - RETROK_RIGHT = 275, - RETROK_LEFT = 276, - RETROK_INSERT = 277, - RETROK_HOME = 278, - RETROK_END = 279, - RETROK_PAGEUP = 280, - RETROK_PAGEDOWN = 281, - - RETROK_F1 = 282, - RETROK_F2 = 283, - RETROK_F3 = 284, - RETROK_F4 = 285, - RETROK_F5 = 286, - RETROK_F6 = 287, - RETROK_F7 = 288, - RETROK_F8 = 289, - RETROK_F9 = 290, - RETROK_F10 = 291, - RETROK_F11 = 292, - RETROK_F12 = 293, - RETROK_F13 = 294, - RETROK_F14 = 295, - RETROK_F15 = 296, - - RETROK_NUMLOCK = 300, - RETROK_CAPSLOCK = 301, - RETROK_SCROLLOCK = 302, - RETROK_RSHIFT = 303, - RETROK_LSHIFT = 304, - RETROK_RCTRL = 305, - RETROK_LCTRL = 306, - RETROK_RALT = 307, - RETROK_LALT = 308, - RETROK_RMETA = 309, - RETROK_LMETA = 310, - RETROK_LSUPER = 311, - RETROK_RSUPER = 312, - RETROK_MODE = 313, - RETROK_COMPOSE = 314, - - RETROK_HELP = 315, - RETROK_PRINT = 316, - RETROK_SYSREQ = 317, - RETROK_BREAK = 318, - RETROK_MENU = 319, - RETROK_POWER = 320, - RETROK_EURO = 321, - RETROK_UNDO = 322, - - RETROK_LAST, - - RETROK_DUMMY = INT_MAX /* Ensure sizeof(enum) == sizeof(int) */ -}; - -enum retro_mod -{ - RETROKMOD_NONE = 0x0000, - - RETROKMOD_SHIFT = 0x01, - RETROKMOD_CTRL = 0x02, - RETROKMOD_ALT = 0x04, - RETROKMOD_META = 0x08, - - RETROKMOD_NUMLOCK = 0x10, - RETROKMOD_CAPSLOCK = 0x20, - RETROKMOD_SCROLLOCK = 0x40, - - RETROKMOD_DUMMY = INT_MAX /* Ensure sizeof(enum) == sizeof(int) */ -}; - -/* If set, this call is not part of the public libretro API yet. It can - * change or be removed at any time. */ -#define RETRO_ENVIRONMENT_EXPERIMENTAL 0x10000 -/* Environment callback to be used internally in frontend. */ -#define RETRO_ENVIRONMENT_PRIVATE 0x20000 - -/* Environment commands. */ -#define RETRO_ENVIRONMENT_SET_ROTATION 1 /* const unsigned * -- - * Sets screen rotation of graphics. - * Is only implemented if rotation can be accelerated by hardware. - * Valid values are 0, 1, 2, 3, which rotates screen by 0, 90, 180, - * 270 degrees counter-clockwise respectively. - */ -#define RETRO_ENVIRONMENT_GET_OVERSCAN 2 /* bool * -- - * Boolean value whether or not the implementation should use overscan, - * or crop away overscan. - */ -#define RETRO_ENVIRONMENT_GET_CAN_DUPE 3 /* bool * -- - * Boolean value whether or not frontend supports frame duping, - * passing NULL to video frame callback. - */ - - /* Environ 4, 5 are no longer supported (GET_VARIABLE / SET_VARIABLES), - * and reserved to avoid possible ABI clash. - */ - -#define RETRO_ENVIRONMENT_SET_MESSAGE 6 /* const struct retro_message * -- - * Sets a message to be displayed in implementation-specific manner - * for a certain amount of 'frames'. - * Should not be used for trivial messages, which should simply be - * logged via RETRO_ENVIRONMENT_GET_LOG_INTERFACE (or as a - * fallback, stderr). - */ -#define RETRO_ENVIRONMENT_SHUTDOWN 7 /* N/A (NULL) -- - * Requests the frontend to shutdown. - * Should only be used if game has a specific - * way to shutdown the game from a menu item or similar. - */ -#define RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL 8 - /* const unsigned * -- - * Gives a hint to the frontend how demanding this implementation - * is on a system. E.g. reporting a level of 2 means - * this implementation should run decently on all frontends - * of level 2 and up. - * - * It can be used by the frontend to potentially warn - * about too demanding implementations. - * - * The levels are "floating". - * - * This function can be called on a per-game basis, - * as certain games an implementation can play might be - * particularly demanding. - * If called, it should be called in retro_load_game(). - */ -#define RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY 9 - /* const char ** -- - * Returns the "system" directory of the frontend. - * This directory can be used to store system specific - * content such as BIOSes, configuration data, etc. - * The returned value can be NULL. - * If so, no such directory is defined, - * and it's up to the implementation to find a suitable directory. - * - * NOTE: Some cores used this folder also for "save" data such as - * memory cards, etc, for lack of a better place to put it. - * This is now discouraged, and if possible, cores should try to - * use the new GET_SAVE_DIRECTORY. - */ -#define RETRO_ENVIRONMENT_SET_PIXEL_FORMAT 10 - /* const enum retro_pixel_format * -- - * Sets the internal pixel format used by the implementation. - * The default pixel format is RETRO_PIXEL_FORMAT_0RGB1555. - * This pixel format however, is deprecated (see enum retro_pixel_format). - * If the call returns false, the frontend does not support this pixel - * format. - * - * This function should be called inside retro_load_game() or - * retro_get_system_av_info(). - */ -#define RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS 11 - /* const struct retro_input_descriptor * -- - * Sets an array of retro_input_descriptors. - * It is up to the frontend to present this in a usable way. - * The array is terminated by retro_input_descriptor::description - * being set to NULL. - * This function can be called at any time, but it is recommended - * to call it as early as possible. - */ -#define RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK 12 - /* const struct retro_keyboard_callback * -- - * Sets a callback function used to notify core about keyboard events. - */ -#define RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE 13 - /* const struct retro_disk_control_callback * -- - * Sets an interface which frontend can use to eject and insert - * disk images. - * This is used for games which consist of multiple images and - * must be manually swapped out by the user (e.g. PSX). - */ -#define RETRO_ENVIRONMENT_SET_HW_RENDER 14 - /* struct retro_hw_render_callback * -- - * Sets an interface to let a libretro core render with - * hardware acceleration. - * Should be called in retro_load_game(). - * If successful, libretro cores will be able to render to a - * frontend-provided framebuffer. - * The size of this framebuffer will be at least as large as - * max_width/max_height provided in get_av_info(). - * If HW rendering is used, pass only RETRO_HW_FRAME_BUFFER_VALID or - * NULL to retro_video_refresh_t. - */ -#define RETRO_ENVIRONMENT_GET_VARIABLE 15 - /* struct retro_variable * -- - * Interface to acquire user-defined information from environment - * that cannot feasibly be supported in a multi-system way. - * 'key' should be set to a key which has already been set by - * SET_VARIABLES. - * 'data' will be set to a value or NULL. - */ -#define RETRO_ENVIRONMENT_SET_VARIABLES 16 - /* const struct retro_variable * -- - * Allows an implementation to signal the environment - * which variables it might want to check for later using - * GET_VARIABLE. - * This allows the frontend to present these variables to - * a user dynamically. - * This should be called as early as possible (ideally in - * retro_set_environment). - * - * 'data' points to an array of retro_variable structs - * terminated by a { NULL, NULL } element. - * retro_variable::key should be namespaced to not collide - * with other implementations' keys. E.g. A core called - * 'foo' should use keys named as 'foo_option'. - * retro_variable::value should contain a human readable - * description of the key as well as a '|' delimited list - * of expected values. - * - * The number of possible options should be very limited, - * i.e. it should be feasible to cycle through options - * without a keyboard. - * - * First entry should be treated as a default. - * - * Example entry: - * { "foo_option", "Speed hack coprocessor X; false|true" } - * - * Text before first ';' is description. This ';' must be - * followed by a space, and followed by a list of possible - * values split up with '|'. - * - * Only strings are operated on. The possible values will - * generally be displayed and stored as-is by the frontend. - */ -#define RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE 17 - /* bool * -- - * Result is set to true if some variables are updated by - * frontend since last call to RETRO_ENVIRONMENT_GET_VARIABLE. - * Variables should be queried with GET_VARIABLE. - */ -#define RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME 18 - /* const bool * -- - * If true, the libretro implementation supports calls to - * retro_load_game() with NULL as argument. - * Used by cores which can run without particular game data. - * This should be called within retro_set_environment() only. - */ -#define RETRO_ENVIRONMENT_GET_LIBRETRO_PATH 19 - /* const char ** -- - * Retrieves the absolute path from where this libretro - * implementation was loaded. - * NULL is returned if the libretro was loaded statically - * (i.e. linked statically to frontend), or if the path cannot be - * determined. - * Mostly useful in cooperation with SET_SUPPORT_NO_GAME as assets can - * be loaded without ugly hacks. - */ - - /* Environment 20 was an obsolete version of SET_AUDIO_CALLBACK. - * It was not used by any known core at the time, - * and was removed from the API. */ -#define RETRO_ENVIRONMENT_SET_AUDIO_CALLBACK 22 - /* const struct retro_audio_callback * -- - * Sets an interface which is used to notify a libretro core about audio - * being available for writing. - * The callback can be called from any thread, so a core using this must - * have a thread safe audio implementation. - * It is intended for games where audio and video are completely - * asynchronous and audio can be generated on the fly. - * This interface is not recommended for use with emulators which have - * highly synchronous audio. - * - * The callback only notifies about writability; the libretro core still - * has to call the normal audio callbacks - * to write audio. The audio callbacks must be called from within the - * notification callback. - * The amount of audio data to write is up to the implementation. - * Generally, the audio callback will be called continously in a loop. - * - * Due to thread safety guarantees and lack of sync between audio and - * video, a frontend can selectively disallow this interface based on - * internal configuration. A core using this interface must also - * implement the "normal" audio interface. - * - * A libretro core using SET_AUDIO_CALLBACK should also make use of - * SET_FRAME_TIME_CALLBACK. - */ -#define RETRO_ENVIRONMENT_SET_FRAME_TIME_CALLBACK 21 - /* const struct retro_frame_time_callback * -- - * Lets the core know how much time has passed since last - * invocation of retro_run(). - * The frontend can tamper with the timing to fake fast-forward, - * slow-motion, frame stepping, etc. - * In this case the delta time will use the reference value - * in frame_time_callback.. - */ -#define RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE 23 - /* struct retro_rumble_interface * -- - * Gets an interface which is used by a libretro core to set - * state of rumble motors in controllers. - * A strong and weak motor is supported, and they can be - * controlled indepedently. - */ -#define RETRO_ENVIRONMENT_GET_INPUT_DEVICE_CAPABILITIES 24 - /* uint64_t * -- - * Gets a bitmask telling which device type are expected to be - * handled properly in a call to retro_input_state_t. - * Devices which are not handled or recognized always return - * 0 in retro_input_state_t. - * Example bitmask: caps = (1 << RETRO_DEVICE_JOYPAD) | (1 << RETRO_DEVICE_ANALOG). - * Should only be called in retro_run(). - */ -#define RETRO_ENVIRONMENT_GET_SENSOR_INTERFACE (25 | RETRO_ENVIRONMENT_EXPERIMENTAL) - /* struct retro_sensor_interface * -- - * Gets access to the sensor interface. - * The purpose of this interface is to allow - * setting state related to sensors such as polling rate, - * enabling/disable it entirely, etc. - * Reading sensor state is done via the normal - * input_state_callback API. - */ -#define RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE (26 | RETRO_ENVIRONMENT_EXPERIMENTAL) - /* struct retro_camera_callback * -- - * Gets an interface to a video camera driver. - * A libretro core can use this interface to get access to a - * video camera. - * New video frames are delivered in a callback in same - * thread as retro_run(). - * - * GET_CAMERA_INTERFACE should be called in retro_load_game(). - * - * Depending on the camera implementation used, camera frames - * will be delivered as a raw framebuffer, - * or as an OpenGL texture directly. - * - * The core has to tell the frontend here which types of - * buffers can be handled properly. - * An OpenGL texture can only be handled when using a - * libretro GL core (SET_HW_RENDER). - * It is recommended to use a libretro GL core when - * using camera interface. - * - * The camera is not started automatically. The retrieved start/stop - * functions must be used to explicitly - * start and stop the camera driver. - */ -#define RETRO_ENVIRONMENT_GET_LOG_INTERFACE 27 - /* struct retro_log_callback * -- - * Gets an interface for logging. This is useful for - * logging in a cross-platform way - * as certain platforms cannot use use stderr for logging. - * It also allows the frontend to - * show logging information in a more suitable way. - * If this interface is not used, libretro cores should - * log to stderr as desired. - */ -#define RETRO_ENVIRONMENT_GET_PERF_INTERFACE 28 - /* struct retro_perf_callback * -- - * Gets an interface for performance counters. This is useful - * for performance logging in a cross-platform way and for detecting - * architecture-specific features, such as SIMD support. - */ -#define RETRO_ENVIRONMENT_GET_LOCATION_INTERFACE 29 - /* struct retro_location_callback * -- - * Gets access to the location interface. - * The purpose of this interface is to be able to retrieve - * location-based information from the host device, - * such as current latitude / longitude. - */ -#define RETRO_ENVIRONMENT_GET_CONTENT_DIRECTORY 30 - /* const char ** -- - * Returns the "content" directory of the frontend. - * This directory can be used to store specific assets that the - * core relies upon, such as art assets, - * input data, etc etc. - * The returned value can be NULL. - * If so, no such directory is defined, - * and it's up to the implementation to find a suitable directory. - */ -#define RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY 31 - /* const char ** -- - * Returns the "save" directory of the frontend. - * This directory can be used to store SRAM, memory cards, - * high scores, etc, if the libretro core - * cannot use the regular memory interface (retro_get_memory_data()). - * - * NOTE: libretro cores used to check GET_SYSTEM_DIRECTORY for - * similar things before. - * They should still check GET_SYSTEM_DIRECTORY if they want to - * be backwards compatible. - * The path here can be NULL. It should only be non-NULL if the - * frontend user has set a specific save path. - */ -#define RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO 32 - /* const struct retro_system_av_info * -- - * Sets a new av_info structure. This can only be called from - * within retro_run(). - * This should *only* be used if the core is completely altering the - * internal resolutions, aspect ratios, timings, sampling rate, etc. - * Calling this can require a full reinitialization of video/audio - * drivers in the frontend, - * - * so it is important to call it very sparingly, and usually only with - * the users explicit consent. - * An eventual driver reinitialize will happen so that video and - * audio callbacks - * happening after this call within the same retro_run() call will - * target the newly initialized driver. - * - * This callback makes it possible to support configurable resolutions - * in games, which can be useful to - * avoid setting the "worst case" in max_width/max_height. - * - * ***HIGHLY RECOMMENDED*** Do not call this callback every time - * resolution changes in an emulator core if it's - * expected to be a temporary change, for the reasons of possible - * driver reinitialization. - * This call is not a free pass for not trying to provide - * correct values in retro_get_system_av_info(). If you need to change - * things like aspect ratio or nominal width/height, - * use RETRO_ENVIRONMENT_SET_GEOMETRY, which is a softer variant - * of SET_SYSTEM_AV_INFO. - * - * If this returns false, the frontend does not acknowledge a - * changed av_info struct. - */ -#define RETRO_ENVIRONMENT_SET_PROC_ADDRESS_CALLBACK 33 - /* const struct retro_get_proc_address_interface * -- - * Allows a libretro core to announce support for the - * get_proc_address() interface. - * This interface allows for a standard way to extend libretro where - * use of environment calls are too indirect, - * e.g. for cases where the frontend wants to call directly into the core. - * - * If a core wants to expose this interface, SET_PROC_ADDRESS_CALLBACK - * **MUST** be called from within retro_set_environment(). - */ -#define RETRO_ENVIRONMENT_SET_SUBSYSTEM_INFO 34 - /* const struct retro_subsystem_info * -- - * This environment call introduces the concept of libretro "subsystems". - * A subsystem is a variant of a libretro core which supports - * different kinds of games. - * The purpose of this is to support e.g. emulators which might - * have special needs, e.g. Super Nintendo's Super GameBoy, Sufami Turbo. - * It can also be used to pick among subsystems in an explicit way - * if the libretro implementation is a multi-system emulator itself. - * - * Loading a game via a subsystem is done with retro_load_game_special(), - * and this environment call allows a libretro core to expose which - * subsystems are supported for use with retro_load_game_special(). - * A core passes an array of retro_game_special_info which is terminated - * with a zeroed out retro_game_special_info struct. - * - * If a core wants to use this functionality, SET_SUBSYSTEM_INFO - * **MUST** be called from within retro_set_environment(). - */ -#define RETRO_ENVIRONMENT_SET_CONTROLLER_INFO 35 - /* const struct retro_controller_info * -- - * This environment call lets a libretro core tell the frontend - * which controller types are recognized in calls to - * retro_set_controller_port_device(). - * - * Some emulators such as Super Nintendo - * support multiple lightgun types which must be specifically - * selected from. - * It is therefore sometimes necessary for a frontend to be able - * to tell the core about a special kind of input device which is - * not covered by the libretro input API. - * - * In order for a frontend to understand the workings of an input device, - * it must be a specialized type - * of the generic device types already defined in the libretro API. - * - * Which devices are supported can vary per input port. - * The core must pass an array of const struct retro_controller_info which - * is terminated with a blanked out struct. Each element of the struct - * corresponds to an ascending port index to - * retro_set_controller_port_device(). - * Even if special device types are set in the libretro core, - * libretro should only poll input based on the base input device types. - */ -#define RETRO_ENVIRONMENT_SET_MEMORY_MAPS (36 | RETRO_ENVIRONMENT_EXPERIMENTAL) - /* const struct retro_memory_map * -- - * This environment call lets a libretro core tell the frontend - * about the memory maps this core emulates. - * This can be used to implement, for example, cheats in a core-agnostic way. - * - * Should only be used by emulators; it doesn't make much sense for - * anything else. - * It is recommended to expose all relevant pointers through - * retro_get_memory_* as well. - * - * Can be called from retro_init and retro_load_game. - */ -#define RETRO_ENVIRONMENT_SET_GEOMETRY 37 - /* const struct retro_game_geometry * -- - * This environment call is similar to SET_SYSTEM_AV_INFO for changing - * video parameters, but provides a guarantee that drivers will not be - * reinitialized. - * This can only be called from within retro_run(). - * - * The purpose of this call is to allow a core to alter nominal - * width/heights as well as aspect ratios on-the-fly, which can be - * useful for some emulators to change in run-time. - * - * max_width/max_height arguments are ignored and cannot be changed - * with this call as this could potentially require a reinitialization or a - * non-constant time operation. - * If max_width/max_height are to be changed, SET_SYSTEM_AV_INFO is required. - * - * A frontend must guarantee that this environment call completes in - * constant time. - */ -#define RETRO_ENVIRONMENT_GET_USERNAME 38 - /* const char ** - * Returns the specified username of the frontend, if specified by the user. - * This username can be used as a nickname for a core that has online facilities - * or any other mode where personalization of the user is desirable. - * The returned value can be NULL. - * If this environ callback is used by a core that requires a valid username, - * a default username should be specified by the core. - */ -#define RETRO_ENVIRONMENT_GET_LANGUAGE 39 - /* unsigned * -- - * Returns the specified language of the frontend, if specified by the user. - * It can be used by the core for localization purposes. - */ - -#define RETRO_MEMDESC_CONST (1 << 0) /* The frontend will never change this memory area once retro_load_game has returned. */ -#define RETRO_MEMDESC_BIGENDIAN (1 << 1) /* The memory area contains big endian data. Default is little endian. */ -#define RETRO_MEMDESC_ALIGN_2 (1 << 16) /* All memory access in this area is aligned to their own size, or 2, whichever is smaller. */ -#define RETRO_MEMDESC_ALIGN_4 (2 << 16) -#define RETRO_MEMDESC_ALIGN_8 (3 << 16) -#define RETRO_MEMDESC_MINSIZE_2 (1 << 24) /* All memory in this region is accessed at least 2 bytes at the time. */ -#define RETRO_MEMDESC_MINSIZE_4 (2 << 24) -#define RETRO_MEMDESC_MINSIZE_8 (3 << 24) -struct retro_memory_descriptor -{ - uint64_t flags; - - /* Pointer to the start of the relevant ROM or RAM chip. - * It's strongly recommended to use 'offset' if possible, rather than - * doing math on the pointer. - * - * If the same byte is mapped my multiple descriptors, their descriptors - * must have the same pointer. - * If 'start' does not point to the first byte in the pointer, put the - * difference in 'offset' instead. - * - * May be NULL if there's nothing usable here (e.g. hardware registers and - * open bus). No flags should be set if the pointer is NULL. - * It's recommended to minimize the number of descriptors if possible, - * but not mandatory. */ - void *ptr; - size_t offset; - - /* This is the location in the emulated address space - * where the mapping starts. */ - size_t start; - - /* Which bits must be same as in 'start' for this mapping to apply. - * The first memory descriptor to claim a certain byte is the one - * that applies. - * A bit which is set in 'start' must also be set in this. - * Can be zero, in which case each byte is assumed mapped exactly once. - * In this case, 'len' must be a power of two. */ - size_t select; - - /* If this is nonzero, the set bits are assumed not connected to the - * memory chip's address pins. */ - size_t disconnect; - - /* This one tells the size of the current memory area. - * If, after start+disconnect are applied, the address is higher than - * this, the highest bit of the address is cleared. - * - * If the address is still too high, the next highest bit is cleared. - * Can be zero, in which case it's assumed to be infinite (as limited - * by 'select' and 'disconnect'). */ - size_t len; - - /* To go from emulated address to physical address, the following - * order applies: - * Subtract 'start', pick off 'disconnect', apply 'len', add 'offset'. - * - * The address space name must consist of only a-zA-Z0-9_-, - * should be as short as feasible (maximum length is 8 plus the NUL), - * and may not be any other address space plus one or more 0-9A-F - * at the end. - * However, multiple memory descriptors for the same address space is - * allowed, and the address space name can be empty. NULL is treated - * as empty. - * - * Address space names are case sensitive, but avoid lowercase if possible. - * The same pointer may exist in multiple address spaces. - * - * Examples: - * blank+blank - valid (multiple things may be mapped in the same namespace) - * 'Sp'+'Sp' - valid (multiple things may be mapped in the same namespace) - * 'A'+'B' - valid (neither is a prefix of each other) - * 'S'+blank - valid ('S' is not in 0-9A-F) - * 'a'+blank - valid ('a' is not in 0-9A-F) - * 'a'+'A' - valid (neither is a prefix of each other) - * 'AR'+blank - valid ('R' is not in 0-9A-F) - * 'ARB'+blank - valid (the B can't be part of the address either, because - * there is no namespace 'AR') - * blank+'B' - not valid, because it's ambigous which address space B1234 - * would refer to. - * The length can't be used for that purpose; the frontend may want - * to append arbitrary data to an address, without a separator. */ - const char *addrspace; -}; - -/* The frontend may use the largest value of 'start'+'select' in a - * certain namespace to infer the size of the address space. - * - * If the address space is larger than that, a mapping with .ptr=NULL - * should be at the end of the array, with .select set to all ones for - * as long as the address space is big. - * - * Sample descriptors (minus .ptr, and RETRO_MEMFLAG_ on the flags): - * SNES WRAM: - * .start=0x7E0000, .len=0x20000 - * (Note that this must be mapped before the ROM in most cases; some of the - * ROM mappers - * try to claim $7E0000, or at least $7E8000.) - * SNES SPC700 RAM: - * .addrspace="S", .len=0x10000 - * SNES WRAM mirrors: - * .flags=MIRROR, .start=0x000000, .select=0xC0E000, .len=0x2000 - * .flags=MIRROR, .start=0x800000, .select=0xC0E000, .len=0x2000 - * SNES WRAM mirrors, alternate equivalent descriptor: - * .flags=MIRROR, .select=0x40E000, .disconnect=~0x1FFF - * (Various similar constructions can be created by combining parts of - * the above two.) - * SNES LoROM (512KB, mirrored a couple of times): - * .flags=CONST, .start=0x008000, .select=0x408000, .disconnect=0x8000, .len=512*1024 - * .flags=CONST, .start=0x400000, .select=0x400000, .disconnect=0x8000, .len=512*1024 - * SNES HiROM (4MB): - * .flags=CONST, .start=0x400000, .select=0x400000, .len=4*1024*1024 - * .flags=CONST, .offset=0x8000, .start=0x008000, .select=0x408000, .len=4*1024*1024 - * SNES ExHiROM (8MB): - * .flags=CONST, .offset=0, .start=0xC00000, .select=0xC00000, .len=4*1024*1024 - * .flags=CONST, .offset=4*1024*1024, .start=0x400000, .select=0xC00000, .len=4*1024*1024 - * .flags=CONST, .offset=0x8000, .start=0x808000, .select=0xC08000, .len=4*1024*1024 - * .flags=CONST, .offset=4*1024*1024+0x8000, .start=0x008000, .select=0xC08000, .len=4*1024*1024 - * Clarify the size of the address space: - * .ptr=NULL, .select=0xFFFFFF - * .len can be implied by .select in many of them, but was included for clarity. - */ - -struct retro_memory_map -{ - const struct retro_memory_descriptor *descriptors; - unsigned num_descriptors; -}; - -struct retro_controller_description -{ - /* Human-readable description of the controller. Even if using a generic - * input device type, this can be set to the particular device type the - * core uses. */ - const char *desc; - - /* Device type passed to retro_set_controller_port_device(). If the device - * type is a sub-class of a generic input device type, use the - * RETRO_DEVICE_SUBCLASS macro to create an ID. - * - * E.g. RETRO_DEVICE_SUBCLASS(RETRO_DEVICE_JOYPAD, 1). */ - unsigned id; -}; - -struct retro_controller_info -{ - const struct retro_controller_description *types; - unsigned num_types; -}; - -struct retro_subsystem_memory_info -{ - /* The extension associated with a memory type, e.g. "psram". */ - const char *extension; - - /* The memory type for retro_get_memory(). This should be at - * least 0x100 to avoid conflict with standardized - * libretro memory types. */ - unsigned type; -}; - -struct retro_subsystem_rom_info -{ - /* Describes what the content is (SGB BIOS, GB ROM, etc). */ - const char *desc; - - /* Same definition as retro_get_system_info(). */ - const char *valid_extensions; - - /* Same definition as retro_get_system_info(). */ - bool need_fullpath; - - /* Same definition as retro_get_system_info(). */ - bool block_extract; - - /* This is set if the content is required to load a game. - * If this is set to false, a zeroed-out retro_game_info can be passed. */ - bool required; - - /* Content can have multiple associated persistent - * memory types (retro_get_memory()). */ - const struct retro_subsystem_memory_info *memory; - unsigned num_memory; -}; - -struct retro_subsystem_info -{ - /* Human-readable string of the subsystem type, e.g. "Super GameBoy" */ - const char *desc; - - /* A computer friendly short string identifier for the subsystem type. - * This name must be [a-z]. - * E.g. if desc is "Super GameBoy", this can be "sgb". - * This identifier can be used for command-line interfaces, etc. - */ - const char *ident; - - /* Infos for each content file. The first entry is assumed to be the - * "most significant" content for frontend purposes. - * E.g. with Super GameBoy, the first content should be the GameBoy ROM, - * as it is the most "significant" content to a user. - * If a frontend creates new file paths based on the content used - * (e.g. savestates), it should use the path for the first ROM to do so. */ - const struct retro_subsystem_rom_info *roms; - - /* Number of content files associated with a subsystem. */ - unsigned num_roms; - - /* The type passed to retro_load_game_special(). */ - unsigned id; -}; - -typedef void (*retro_proc_address_t)(void); - -/* libretro API extension functions: - * (None here so far). - * - * Get a symbol from a libretro core. - * Cores should only return symbols which are actual - * extensions to the libretro API. - * - * Frontends should not use this to obtain symbols to standard - * libretro entry points (static linking or dlsym). - * - * The symbol name must be equal to the function name, - * e.g. if void retro_foo(void); exists, the symbol must be called "retro_foo". - * The returned function pointer must be cast to the corresponding type. - */ -typedef retro_proc_address_t (*retro_get_proc_address_t)(const char *sym); - -struct retro_get_proc_address_interface -{ - retro_get_proc_address_t get_proc_address; -}; - -enum retro_log_level -{ - RETRO_LOG_DEBUG = 0, - RETRO_LOG_INFO, - RETRO_LOG_WARN, - RETRO_LOG_ERROR, - - RETRO_LOG_DUMMY = INT_MAX -}; - -/* Logging function. Takes log level argument as well. */ -typedef void (*retro_log_printf_t)(enum retro_log_level level, - const char *fmt, ...); - -struct retro_log_callback -{ - retro_log_printf_t log; -}; - -/* Performance related functions */ - -/* ID values for SIMD CPU features */ -#define RETRO_SIMD_SSE (1 << 0) -#define RETRO_SIMD_SSE2 (1 << 1) -#define RETRO_SIMD_VMX (1 << 2) -#define RETRO_SIMD_VMX128 (1 << 3) -#define RETRO_SIMD_AVX (1 << 4) -#define RETRO_SIMD_NEON (1 << 5) -#define RETRO_SIMD_SSE3 (1 << 6) -#define RETRO_SIMD_SSSE3 (1 << 7) -#define RETRO_SIMD_MMX (1 << 8) -#define RETRO_SIMD_MMXEXT (1 << 9) -#define RETRO_SIMD_SSE4 (1 << 10) -#define RETRO_SIMD_SSE42 (1 << 11) -#define RETRO_SIMD_AVX2 (1 << 12) -#define RETRO_SIMD_VFPU (1 << 13) -#define RETRO_SIMD_PS (1 << 14) -#define RETRO_SIMD_AES (1 << 15) - -typedef uint64_t retro_perf_tick_t; -typedef int64_t retro_time_t; - -struct retro_perf_counter -{ - const char *ident; - retro_perf_tick_t start; - retro_perf_tick_t total; - retro_perf_tick_t call_cnt; - - bool registered; -}; - -/* Returns current time in microseconds. - * Tries to use the most accurate timer available. - */ -typedef retro_time_t (*retro_perf_get_time_usec_t)(void); - -/* A simple counter. Usually nanoseconds, but can also be CPU cycles. - * Can be used directly if desired (when creating a more sophisticated - * performance counter system). - * */ -typedef retro_perf_tick_t (*retro_perf_get_counter_t)(void); - -/* Returns a bit-mask of detected CPU features (RETRO_SIMD_*). */ -typedef uint64_t (*retro_get_cpu_features_t)(void); - -/* Asks frontend to log and/or display the state of performance counters. - * Performance counters can always be poked into manually as well. - */ -typedef void (*retro_perf_log_t)(void); - -/* Register a performance counter. - * ident field must be set with a discrete value and other values in - * retro_perf_counter must be 0. - * Registering can be called multiple times. To avoid calling to - * frontend redundantly, you can check registered field first. */ -typedef void (*retro_perf_register_t)(struct retro_perf_counter *counter); - -/* Starts a registered counter. */ -typedef void (*retro_perf_start_t)(struct retro_perf_counter *counter); - -/* Stops a registered counter. */ -typedef void (*retro_perf_stop_t)(struct retro_perf_counter *counter); - -/* For convenience it can be useful to wrap register, start and stop in macros. - * E.g.: - * #ifdef LOG_PERFORMANCE - * #define RETRO_PERFORMANCE_INIT(perf_cb, name) static struct retro_perf_counter name = {#name}; if (!name.registered) perf_cb.perf_register(&(name)) - * #define RETRO_PERFORMANCE_START(perf_cb, name) perf_cb.perf_start(&(name)) - * #define RETRO_PERFORMANCE_STOP(perf_cb, name) perf_cb.perf_stop(&(name)) - * #else - * ... Blank macros ... - * #endif - * - * These can then be used mid-functions around code snippets. - * - * extern struct retro_perf_callback perf_cb; * Somewhere in the core. - * - * void do_some_heavy_work(void) - * { - * RETRO_PERFORMANCE_INIT(cb, work_1; - * RETRO_PERFORMANCE_START(cb, work_1); - * heavy_work_1(); - * RETRO_PERFORMANCE_STOP(cb, work_1); - * - * RETRO_PERFORMANCE_INIT(cb, work_2); - * RETRO_PERFORMANCE_START(cb, work_2); - * heavy_work_2(); - * RETRO_PERFORMANCE_STOP(cb, work_2); - * } - * - * void retro_deinit(void) - * { - * perf_cb.perf_log(); * Log all perf counters here for example. - * } - */ - -struct retro_perf_callback -{ - retro_perf_get_time_usec_t get_time_usec; - retro_get_cpu_features_t get_cpu_features; - - retro_perf_get_counter_t get_perf_counter; - retro_perf_register_t perf_register; - retro_perf_start_t perf_start; - retro_perf_stop_t perf_stop; - retro_perf_log_t perf_log; -}; - -/* FIXME: Document the sensor API and work out behavior. - * It will be marked as experimental until then. - */ -enum retro_sensor_action -{ - RETRO_SENSOR_ACCELEROMETER_ENABLE = 0, - RETRO_SENSOR_ACCELEROMETER_DISABLE, - - RETRO_SENSOR_DUMMY = INT_MAX -}; - -/* Id values for SENSOR types. */ -#define RETRO_SENSOR_ACCELEROMETER_X 0 -#define RETRO_SENSOR_ACCELEROMETER_Y 1 -#define RETRO_SENSOR_ACCELEROMETER_Z 2 - -typedef bool (*retro_set_sensor_state_t)(unsigned port, - enum retro_sensor_action action, unsigned rate); - -typedef float (*retro_sensor_get_input_t)(unsigned port, unsigned id); - -struct retro_sensor_interface -{ - retro_set_sensor_state_t set_sensor_state; - retro_sensor_get_input_t get_sensor_input; -}; - -enum retro_camera_buffer -{ - RETRO_CAMERA_BUFFER_OPENGL_TEXTURE = 0, - RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER, - - RETRO_CAMERA_BUFFER_DUMMY = INT_MAX -}; - -/* Starts the camera driver. Can only be called in retro_run(). */ -typedef bool (*retro_camera_start_t)(void); - -/* Stops the camera driver. Can only be called in retro_run(). */ -typedef void (*retro_camera_stop_t)(void); - -/* Callback which signals when the camera driver is initialized - * and/or deinitialized. - * retro_camera_start_t can be called in initialized callback. - */ -typedef void (*retro_camera_lifetime_status_t)(void); - -/* A callback for raw framebuffer data. buffer points to an XRGB8888 buffer. - * Width, height and pitch are similar to retro_video_refresh_t. - * First pixel is top-left origin. - */ -typedef void (*retro_camera_frame_raw_framebuffer_t)(const uint32_t *buffer, - unsigned width, unsigned height, size_t pitch); - -/* A callback for when OpenGL textures are used. - * - * texture_id is a texture owned by camera driver. - * Its state or content should be considered immutable, except for things like - * texture filtering and clamping. - * - * texture_target is the texture target for the GL texture. - * These can include e.g. GL_TEXTURE_2D, GL_TEXTURE_RECTANGLE, and possibly - * more depending on extensions. - * - * affine points to a packed 3x3 column-major matrix used to apply an affine - * transform to texture coordinates. (affine_matrix * vec3(coord_x, coord_y, 1.0)) - * After transform, normalized texture coord (0, 0) should be bottom-left - * and (1, 1) should be top-right (or (width, height) for RECTANGLE). - * - * GL-specific typedefs are avoided here to avoid relying on gl.h in - * the API definition. - */ -typedef void (*retro_camera_frame_opengl_texture_t)(unsigned texture_id, - unsigned texture_target, const float *affine); - -struct retro_camera_callback -{ - /* Set by libretro core. - * Example bitmask: caps = (1 << RETRO_CAMERA_BUFFER_OPENGL_TEXTURE) | (1 << RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER). - */ - uint64_t caps; - - unsigned width; /* Desired resolution for camera. Is only used as a hint. */ - unsigned height; - retro_camera_start_t start; /* Set by frontend. */ - retro_camera_stop_t stop; /* Set by frontend. */ - - /* Set by libretro core if raw framebuffer callbacks will be used. */ - retro_camera_frame_raw_framebuffer_t frame_raw_framebuffer; - /* Set by libretro core if OpenGL texture callbacks will be used. */ - retro_camera_frame_opengl_texture_t frame_opengl_texture; - - /* Set by libretro core. Called after camera driver is initialized and - * ready to be started. - * Can be NULL, in which this callback is not called. - */ - retro_camera_lifetime_status_t initialized; - - /* Set by libretro core. Called right before camera driver is - * deinitialized. - * Can be NULL, in which this callback is not called. - */ - retro_camera_lifetime_status_t deinitialized; -}; - -/* Sets the interval of time and/or distance at which to update/poll - * location-based data. - * - * To ensure compatibility with all location-based implementations, - * values for both interval_ms and interval_distance should be provided. - * - * interval_ms is the interval expressed in milliseconds. - * interval_distance is the distance interval expressed in meters. - */ -typedef void (*retro_location_set_interval_t)(unsigned interval_ms, - unsigned interval_distance); - -/* Start location services. The device will start listening for changes to the - * current location at regular intervals (which are defined with - * retro_location_set_interval_t). */ -typedef bool (*retro_location_start_t)(void); - -/* Stop location services. The device will stop listening for changes - * to the current location. */ -typedef void (*retro_location_stop_t)(void); - -/* Get the position of the current location. Will set parameters to - * 0 if no new location update has happened since the last time. */ -typedef bool (*retro_location_get_position_t)(double *lat, double *lon, - double *horiz_accuracy, double *vert_accuracy); - -/* Callback which signals when the location driver is initialized - * and/or deinitialized. - * retro_location_start_t can be called in initialized callback. - */ -typedef void (*retro_location_lifetime_status_t)(void); - -struct retro_location_callback -{ - retro_location_start_t start; - retro_location_stop_t stop; - retro_location_get_position_t get_position; - retro_location_set_interval_t set_interval; - - retro_location_lifetime_status_t initialized; - retro_location_lifetime_status_t deinitialized; -}; - -enum retro_rumble_effect -{ - RETRO_RUMBLE_STRONG = 0, - RETRO_RUMBLE_WEAK = 1, - - RETRO_RUMBLE_DUMMY = INT_MAX -}; - -/* Sets rumble state for joypad plugged in port 'port'. - * Rumble effects are controlled independently, - * and setting e.g. strong rumble does not override weak rumble. - * Strength has a range of [0, 0xffff]. - * - * Returns true if rumble state request was honored. - * Calling this before first retro_run() is likely to return false. */ -typedef bool (*retro_set_rumble_state_t)(unsigned port, - enum retro_rumble_effect effect, uint16_t strength); - -struct retro_rumble_interface -{ - retro_set_rumble_state_t set_rumble_state; -}; - -/* Notifies libretro that audio data should be written. */ -typedef void (*retro_audio_callback_t)(void); - -/* True: Audio driver in frontend is active, and callback is - * expected to be called regularily. - * False: Audio driver in frontend is paused or inactive. - * Audio callback will not be called until set_state has been - * called with true. - * Initial state is false (inactive). - */ -typedef void (*retro_audio_set_state_callback_t)(bool enabled); - -struct retro_audio_callback -{ - retro_audio_callback_t callback; - retro_audio_set_state_callback_t set_state; -}; - -/* Notifies a libretro core of time spent since last invocation - * of retro_run() in microseconds. - * - * It will be called right before retro_run() every frame. - * The frontend can tamper with timing to support cases like - * fast-forward, slow-motion and framestepping. - * - * In those scenarios the reference frame time value will be used. */ -typedef int64_t retro_usec_t; -typedef void (*retro_frame_time_callback_t)(retro_usec_t usec); -struct retro_frame_time_callback -{ - retro_frame_time_callback_t callback; - /* Represents the time of one frame. It is computed as - * 1000000 / fps, but the implementation will resolve the - * rounding to ensure that framestepping, etc is exact. */ - retro_usec_t reference; -}; - -/* Pass this to retro_video_refresh_t if rendering to hardware. - * Passing NULL to retro_video_refresh_t is still a frame dupe as normal. - * */ -#define RETRO_HW_FRAME_BUFFER_VALID ((void*)-1) - -/* Invalidates the current HW context. - * Any GL state is lost, and must not be deinitialized explicitly. - * If explicit deinitialization is desired by the libretro core, - * it should implement context_destroy callback. - * If called, all GPU resources must be reinitialized. - * Usually called when frontend reinits video driver. - * Also called first time video driver is initialized, - * allowing libretro core to initialize resources. - */ -typedef void (*retro_hw_context_reset_t)(void); - -/* Gets current framebuffer which is to be rendered to. - * Could change every frame potentially. - */ -typedef uintptr_t (*retro_hw_get_current_framebuffer_t)(void); - -/* Get a symbol from HW context. */ -typedef retro_proc_address_t (*retro_hw_get_proc_address_t)(const char *sym); - -enum retro_hw_context_type -{ - RETRO_HW_CONTEXT_NONE = 0, - /* OpenGL 2.x. Driver can choose to use latest compatibility context. */ - RETRO_HW_CONTEXT_OPENGL = 1, - /* OpenGL ES 2.0. */ - RETRO_HW_CONTEXT_OPENGLES2 = 2, - /* Modern desktop core GL context. Use version_major/ - * version_minor fields to set GL version. */ - RETRO_HW_CONTEXT_OPENGL_CORE = 3, - /* OpenGL ES 3.0 */ - RETRO_HW_CONTEXT_OPENGLES3 = 4, - /* OpenGL ES 3.1+. Set version_major/version_minor. For GLES2 and GLES3, - * use the corresponding enums directly. */ - RETRO_HW_CONTEXT_OPENGLES_VERSION = 5, - - RETRO_HW_CONTEXT_DUMMY = INT_MAX -}; - -struct retro_hw_render_callback -{ - /* Which API to use. Set by libretro core. */ - enum retro_hw_context_type context_type; - - /* Called when a context has been created or when it has been reset. - * An OpenGL context is only valid after context_reset() has been called. - * - * When context_reset is called, OpenGL resources in the libretro - * implementation are guaranteed to be invalid. - * - * It is possible that context_reset is called multiple times during an - * application lifecycle. - * If context_reset is called without any notification (context_destroy), - * the OpenGL context was lost and resources should just be recreated - * without any attempt to "free" old resources. - */ - retro_hw_context_reset_t context_reset; - - /* Set by frontend. */ - retro_hw_get_current_framebuffer_t get_current_framebuffer; - - /* Set by frontend. */ - retro_hw_get_proc_address_t get_proc_address; - - /* Set if render buffers should have depth component attached. */ - bool depth; - - /* Set if stencil buffers should be attached. */ - bool stencil; - - /* If depth and stencil are true, a packed 24/8 buffer will be added. - * Only attaching stencil is invalid and will be ignored. */ - - /* Use conventional bottom-left origin convention. If false, - * standard libretro top-left origin semantics are used. */ - bool bottom_left_origin; - - /* Major version number for core GL context or GLES 3.1+. */ - unsigned version_major; - - /* Minor version number for core GL context or GLES 3.1+. */ - unsigned version_minor; - - /* If this is true, the frontend will go very far to avoid - * resetting context in scenarios like toggling fullscreen, etc. - */ - bool cache_context; - - /* The reset callback might still be called in extreme situations - * such as if the context is lost beyond recovery. - * - * For optimal stability, set this to false, and allow context to be - * reset at any time. - */ - - /* A callback to be called before the context is destroyed in a - * controlled way by the frontend. */ - retro_hw_context_reset_t context_destroy; - - /* OpenGL resources can be deinitialized cleanly at this step. - * context_destroy can be set to NULL, in which resources will - * just be destroyed without any notification. - * - * Even when context_destroy is non-NULL, it is possible that - * context_reset is called without any destroy notification. - * This happens if context is lost by external factors (such as - * notified by GL_ARB_robustness). - * - * In this case, the context is assumed to be already dead, - * and the libretro implementation must not try to free any OpenGL - * resources in the subsequent context_reset. - */ - - /* Creates a debug context. */ - bool debug_context; -}; - -/* Callback type passed in RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK. - * Called by the frontend in response to keyboard events. - * down is set if the key is being pressed, or false if it is being released. - * keycode is the RETROK value of the char. - * character is the text character of the pressed key. (UTF-32). - * key_modifiers is a set of RETROKMOD values or'ed together. - * - * The pressed/keycode state can be indepedent of the character. - * It is also possible that multiple characters are generated from a - * single keypress. - * Keycode events should be treated separately from character events. - * However, when possible, the frontend should try to synchronize these. - * If only a character is posted, keycode should be RETROK_UNKNOWN. - * - * Similarily if only a keycode event is generated with no corresponding - * character, character should be 0. - */ -typedef void (*retro_keyboard_event_t)(bool down, unsigned keycode, - uint32_t character, uint16_t key_modifiers); - -struct retro_keyboard_callback -{ - retro_keyboard_event_t callback; -}; - -/* Callbacks for RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE. - * Should be set for implementations which can swap out multiple disk - * images in runtime. - * - * If the implementation can do this automatically, it should strive to do so. - * However, there are cases where the user must manually do so. - * - * Overview: To swap a disk image, eject the disk image with - * set_eject_state(true). - * Set the disk index with set_image_index(index). Insert the disk again - * with set_eject_state(false). - */ - -/* If ejected is true, "ejects" the virtual disk tray. - * When ejected, the disk image index can be set. - */ -typedef bool (*retro_set_eject_state_t)(bool ejected); - -/* Gets current eject state. The initial state is 'not ejected'. */ -typedef bool (*retro_get_eject_state_t)(void); - -/* Gets current disk index. First disk is index 0. - * If return value is >= get_num_images(), no disk is currently inserted. - */ -typedef unsigned (*retro_get_image_index_t)(void); - -/* Sets image index. Can only be called when disk is ejected. - * The implementation supports setting "no disk" by using an - * index >= get_num_images(). - */ -typedef bool (*retro_set_image_index_t)(unsigned index); - -/* Gets total number of images which are available to use. */ -typedef unsigned (*retro_get_num_images_t)(void); - -struct retro_game_info; - -/* Replaces the disk image associated with index. - * Arguments to pass in info have same requirements as retro_load_game(). - * Virtual disk tray must be ejected when calling this. - * - * Replacing a disk image with info = NULL will remove the disk image - * from the internal list. - * As a result, calls to get_image_index() can change. - * - * E.g. replace_image_index(1, NULL), and previous get_image_index() - * returned 4 before. - * Index 1 will be removed, and the new index is 3. - */ -typedef bool (*retro_replace_image_index_t)(unsigned index, - const struct retro_game_info *info); - -/* Adds a new valid index (get_num_images()) to the internal disk list. - * This will increment subsequent return values from get_num_images() by 1. - * This image index cannot be used until a disk image has been set - * with replace_image_index. */ -typedef bool (*retro_add_image_index_t)(void); - -struct retro_disk_control_callback -{ - retro_set_eject_state_t set_eject_state; - retro_get_eject_state_t get_eject_state; - - retro_get_image_index_t get_image_index; - retro_set_image_index_t set_image_index; - retro_get_num_images_t get_num_images; - - retro_replace_image_index_t replace_image_index; - retro_add_image_index_t add_image_index; -}; - -enum retro_pixel_format -{ - /* 0RGB1555, native endian. - * 0 bit must be set to 0. - * This pixel format is default for compatibility concerns only. - * If a 15/16-bit pixel format is desired, consider using RGB565. */ - RETRO_PIXEL_FORMAT_0RGB1555 = 0, - - /* XRGB8888, native endian. - * X bits are ignored. */ - RETRO_PIXEL_FORMAT_XRGB8888 = 1, - - /* RGB565, native endian. - * This pixel format is the recommended format to use if a 15/16-bit - * format is desired as it is the pixel format that is typically - * available on a wide range of low-power devices. - * - * It is also natively supported in APIs like OpenGL ES. */ - RETRO_PIXEL_FORMAT_RGB565 = 2, - - /* Ensure sizeof() == sizeof(int). */ - RETRO_PIXEL_FORMAT_UNKNOWN = INT_MAX -}; - -struct retro_message -{ - const char *msg; /* Message to be displayed. */ - unsigned frames; /* Duration in frames of message. */ -}; - -/* Describes how the libretro implementation maps a libretro input bind - * to its internal input system through a human readable string. - * This string can be used to better let a user configure input. */ -struct retro_input_descriptor -{ - /* Associates given parameters with a description. */ - unsigned port; - unsigned device; - unsigned index; - unsigned id; - - /* Human readable description for parameters. - * The pointer must remain valid until - * retro_unload_game() is called. */ - const char *description; -}; - -struct retro_system_info -{ - /* All pointers are owned by libretro implementation, and pointers must - * remain valid until retro_deinit() is called. */ - - const char *library_name; /* Descriptive name of library. Should not - * contain any version numbers, etc. */ - const char *library_version; /* Descriptive version of core. */ - - const char *valid_extensions; /* A string listing probably content - * extensions the core will be able to - * load, separated with pipe. - * I.e. "bin|rom|iso". - * Typically used for a GUI to filter - * out extensions. */ - - /* If true, retro_load_game() is guaranteed to provide a valid pathname - * in retro_game_info::path. - * ::data and ::size are both invalid. - * - * If false, ::data and ::size are guaranteed to be valid, but ::path - * might not be valid. - * - * This is typically set to true for libretro implementations that must - * load from file. - * Implementations should strive for setting this to false, as it allows - * the frontend to perform patching, etc. */ - bool need_fullpath; - - /* If true, the frontend is not allowed to extract any archives before - * loading the real content. - * Necessary for certain libretro implementations that load games - * from zipped archives. */ - bool block_extract; -}; - -struct retro_game_geometry -{ - unsigned base_width; /* Nominal video width of game. */ - unsigned base_height; /* Nominal video height of game. */ - unsigned max_width; /* Maximum possible width of game. */ - unsigned max_height; /* Maximum possible height of game. */ - - float aspect_ratio; /* Nominal aspect ratio of game. If - * aspect_ratio is <= 0.0, an aspect ratio - * of base_width / base_height is assumed. - * A frontend could override this setting, - * if desired. */ -}; - -struct retro_system_timing -{ - double fps; /* FPS of video content. */ - double sample_rate; /* Sampling rate of audio. */ -}; - -struct retro_system_av_info -{ - struct retro_game_geometry geometry; - struct retro_system_timing timing; -}; - -struct retro_variable -{ - /* Variable to query in RETRO_ENVIRONMENT_GET_VARIABLE. - * If NULL, obtains the complete environment string if more - * complex parsing is necessary. - * The environment string is formatted as key-value pairs - * delimited by semicolons as so: - * "key1=value1;key2=value2;..." - */ - const char *key; - - /* Value to be obtained. If key does not exist, it is set to NULL. */ - const char *value; -}; - -struct retro_game_info -{ - const char *path; /* Path to game, UTF-8 encoded. - * Usually used as a reference. - * May be NULL if rom was loaded from stdin - * or similar. - * retro_system_info::need_fullpath guaranteed - * that this path is valid. */ - const void *data; /* Memory buffer of loaded game. Will be NULL - * if need_fullpath was set. */ - size_t size; /* Size of memory buffer. */ - const char *meta; /* String of implementation specific meta-data. */ -}; - -/* Callbacks */ - -/* Environment callback. Gives implementations a way of performing - * uncommon tasks. Extensible. */ -typedef bool (*retro_environment_t)(unsigned cmd, void *data); - -/* Render a frame. Pixel format is 15-bit 0RGB1555 native endian - * unless changed (see RETRO_ENVIRONMENT_SET_PIXEL_FORMAT). - * - * Width and height specify dimensions of buffer. - * Pitch specifices length in bytes between two lines in buffer. - * - * For performance reasons, it is highly recommended to have a frame - * that is packed in memory, i.e. pitch == width * byte_per_pixel. - * Certain graphic APIs, such as OpenGL ES, do not like textures - * that are not packed in memory. - */ -typedef void (*retro_video_refresh_t)(const void *data, unsigned width, - unsigned height, size_t pitch); - -/* Renders a single audio frame. Should only be used if implementation - * generates a single sample at a time. - * Format is signed 16-bit native endian. - */ -typedef void (*retro_audio_sample_t)(int16_t left, int16_t right); - -/* Renders multiple audio frames in one go. - * - * One frame is defined as a sample of left and right channels, interleaved. - * I.e. int16_t buf[4] = { l, r, l, r }; would be 2 frames. - * Only one of the audio callbacks must ever be used. - */ -typedef size_t (*retro_audio_sample_batch_t)(const int16_t *data, - size_t frames); - -/* Polls input. */ -typedef void (*retro_input_poll_t)(void); - -/* Queries for input for player 'port'. device will be masked with - * RETRO_DEVICE_MASK. - * - * Specialization of devices such as RETRO_DEVICE_JOYPAD_MULTITAP that - * have been set with retro_set_controller_port_device() - * will still use the higher level RETRO_DEVICE_JOYPAD to request input. - */ -typedef int16_t (*retro_input_state_t)(unsigned port, unsigned device, - unsigned index, unsigned id); - -/* Sets callbacks. retro_set_environment() is guaranteed to be called - * before retro_init(). - * - * The rest of the set_* functions are guaranteed to have been called - * before the first call to retro_run() is made. */ -void retro_set_environment(retro_environment_t); -void retro_set_video_refresh(retro_video_refresh_t); -void retro_set_audio_sample(retro_audio_sample_t); -void retro_set_audio_sample_batch(retro_audio_sample_batch_t); -void retro_set_input_poll(retro_input_poll_t); -void retro_set_input_state(retro_input_state_t); - -/* Library global initialization/deinitialization. */ -void retro_init(void); -void retro_deinit(void); - -/* Must return RETRO_API_VERSION. Used to validate ABI compatibility - * when the API is revised. */ -unsigned retro_api_version(void); - -/* Gets statically known system info. Pointers provided in *info - * must be statically allocated. - * Can be called at any time, even before retro_init(). */ -void retro_get_system_info(struct retro_system_info *info); - -/* Gets information about system audio/video timings and geometry. - * Can be called only after retro_load_game() has successfully completed. - * NOTE: The implementation of this function might not initialize every - * variable if needed. - * E.g. geom.aspect_ratio might not be initialized if core doesn't - * desire a particular aspect ratio. */ -void retro_get_system_av_info(struct retro_system_av_info *info); - -/* Sets device to be used for player 'port'. - * By default, RETRO_DEVICE_JOYPAD is assumed to be plugged into all - * available ports. - * Setting a particular device type is not a guarantee that libretro cores - * will only poll input based on that particular device type. It is only a - * hint to the libretro core when a core cannot automatically detect the - * appropriate input device type on its own. It is also relevant when a - * core can change its behavior depending on device type. */ -void retro_set_controller_port_device(unsigned port, unsigned device); - -/* Resets the current game. */ -void retro_reset(void); - -/* Runs the game for one video frame. - * During retro_run(), input_poll callback must be called at least once. - * - * If a frame is not rendered for reasons where a game "dropped" a frame, - * this still counts as a frame, and retro_run() should explicitly dupe - * a frame if GET_CAN_DUPE returns true. - * In this case, the video callback can take a NULL argument for data. - */ -void retro_run(void); - -/* Returns the amount of data the implementation requires to serialize - * internal state (save states). - * Between calls to retro_load_game() and retro_unload_game(), the - * returned size is never allowed to be larger than a previous returned - * value, to ensure that the frontend can allocate a save state buffer once. - */ -size_t retro_serialize_size(void); - -/* Serializes internal state. If failed, or size is lower than - * retro_serialize_size(), it should return false, true otherwise. */ -bool retro_serialize(void *data, size_t size); -bool retro_unserialize(const void *data, size_t size); - -void retro_cheat_reset(void); -void retro_cheat_set(unsigned index, bool enabled, const char *code); - -/* Loads a game. */ -bool retro_load_game(const struct retro_game_info *game); - -/* Loads a "special" kind of game. Should not be used, - * except in extreme cases. */ -bool retro_load_game_special( - unsigned game_type, - const struct retro_game_info *info, size_t num_info -); - -/* Unloads a currently loaded game. */ -void retro_unload_game(void); - -/* Gets region of game. */ -unsigned retro_get_region(void); - -/* Gets region of memory. */ -void *retro_get_memory_data(unsigned id); -size_t retro_get_memory_size(unsigned id); - -#ifdef __cplusplus -} -#endif - -#endif diff -Nru nestopia-1.48/libretro/Makefile nestopia-1.49/libretro/Makefile --- nestopia-1.48/libretro/Makefile 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/Makefile 2018-06-24 23:26:58.000000000 +0000 @@ -2,6 +2,13 @@ GIT_VERSION := " $(shell git rev-parse --short HEAD)" HAS_GCC = 1 +SPACE := +SPACE := $(SPACE) $(SPACE) +BACKSLASH := +BACKSLASH := \$(BACKSLASH) +filter_out1 = $(filter-out $(firstword $1),$1) +filter_out2 = $(call filter_out1,$(call filter_out1,$1)) + ifeq ($(platform),) platform = unix ifeq ($(shell uname -a),) @@ -32,11 +39,23 @@ LIBRETRO_DIR := libretro TARGET_NAME := nestopia +SPACE := +SPACE := $(SPACE) $(SPACE) +BACKSLASH := +BACKSLASH := \$(BACKSLASH) +filter_out1 = $(filter-out $(firstword $1),$1) +filter_out2 = $(call filter_out1,$(call filter_out1,$1)) +unixpath = $(subst \,/,$1) +unixcygpath = /$(subst :,,$(call unixpath,$1)) + # Unix ifeq ($(platform), unix) TARGET := $(TARGET_NAME)_libretro.so fpic := -fPIC SHARED := -shared -Wl,-version-script=link.T -Wl,-no-undefined +ifeq ($(shell uname -s), Haiku) + LDFLAGS += -lroot +endif # OS X else ifeq ($(platform), osx) @@ -63,9 +82,14 @@ ifeq ($(IOSSDK),) IOSSDK := $(shell xcodebuild -version -sdk iphoneos Path) endif - CC = cc -arch armv7 -isysroot $(IOSSDK) - CXX = c++ -arch armv7 -isysroot $(IOSSDK) -ifeq ($(platform),ios9) + ifeq ($(platform),"ios-arm64") + CC = cc -arch arm64 -isysroot $(IOSSDK) + CCX = c++ -arch arm64 -isysroot $(IOSSDK) + else + CC = cc -arch armv7 -isysroot $(IOSSDK) + CXX = c++ -arch armv7 -isysroot $(IOSSDK) + endif +ifeq ($(platform),$(filter $(platform),ios9 ios-arm64)) CC += -miphoneos-version-min=8.0 CXX += -miphoneos-version-min=8.0 PLATFORM_DEFINES += -miphoneos-version-min=8.0 @@ -146,7 +170,6 @@ PLATFORM_DEFINES += -march=armv6k -mtune=mpcore -mfloat-abi=hard PLATFORM_DEFINES += -mword-relocations PLATFORM_DEFINES += -fomit-frame-pointer -fstrict-aliasing -ffast-math - CXXFLAGS += -fno-rtti STATIC_LINKING = 1 # Raspberry Pi 2 (Raspbian) @@ -174,6 +197,149 @@ PLATFORM_DEFINES := -D__CELLOS_LV2__ STATIC_LINKING = 1 +# Windows MSVC 2003 Xbox 1 +else ifeq ($(platform), xbox1_msvc2003) +TARGET := $(TARGET_NAME)_libretro_xdk1.lib +CC = CL.exe +CXX = CL.exe +LD = lib.exe + +export INCLUDE := $(XDK)/xbox/include +export LIB := $(XDK)/xbox/lib +PATH := $(call unixcygpath,$(XDK)/xbox/bin/vc71):$(PATH) +PSS_STYLE :=2 +CFLAGS += -D_XBOX -D_XBOX1 +CXXFLAGS += -D_XBOX -D_XBOX1 +STATIC_LINKING=1 +HAS_GCC := 0 +# Windows MSVC 2010 Xbox 360 +else ifeq ($(platform), xbox360_msvc2010) +TARGET := $(TARGET_NAME)_libretro_xdk360.lib +MSVCBINDIRPREFIX = $(XEDK)/bin/win32 +CC = "$(MSVCBINDIRPREFIX)/cl.exe" +CXX = "$(MSVCBINDIRPREFIX)/cl.exe" +LD = "$(MSVCBINDIRPREFIX)/lib.exe" + +export INCLUDE := $(XEDK)/include/xbox +export LIB := $(XEDK)/lib/xbox +PSS_STYLE :=2 +CFLAGS += -D_XBOX -D_XBOX360 +CXXFLAGS += -D_XBOX -D_XBOX360 +STATIC_LINKING=1 +HAS_GCC := 0 + +# Windows MSVC 2003 x86 +else ifeq ($(platform), windows_msvc2003_x86) + CC = cl.exe + CXX = cl.exe + +PATH := $(shell IFS=$$'\n'; cygpath "$(VS71COMNTOOLS)../../Vc7/bin"):$(PATH) +PATH := $(PATH):$(shell IFS=$$'\n'; cygpath "$(VS71COMNTOOLS)../IDE") +INCLUDE := $(shell IFS=$$'\n'; cygpath "$(VS71COMNTOOLS)../../Vc7/include") +LIB := $(shell IFS=$$'\n'; cygpath -w "$(VS71COMNTOOLS)../../Vc7/lib") +BIN := $(shell IFS=$$'\n'; cygpath "$(VS71COMNTOOLS)../../Vc7/bin") + +WindowsSdkDir := $(INETSDK) + +export INCLUDE := $(INCLUDE);$(INETSDK)/Include;libretro-common/include/compat/msvc +export LIB := $(LIB);$(WindowsSdkDir);$(INETSDK)/Lib +TARGET := $(TARGET_NAME)_libretro.dll +PSS_STYLE :=2 +LDFLAGS += -DLL +CFLAGS += -D_CRT_SECURE_NO_DEPRECATE +WINDOWS_VERSION=1 + +# Windows MSVC 2017 all architectures +else ifneq (,$(findstring windows_msvc2017,$(platform))) + + PlatformSuffix = $(subst windows_msvc2017_,,$(platform)) + ifneq (,$(findstring desktop,$(PlatformSuffix))) + WinPartition = desktop + MSVC2017CompileFlags = -DWINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP + LDFLAGS += -MANIFEST -LTCG:incremental -NXCOMPAT -DYNAMICBASE -DEBUG -OPT:REF -INCREMENTAL:NO -SUBSYSTEM:WINDOWS -MANIFESTUAC:"level='asInvoker' uiAccess='false'" -OPT:ICF -ERRORREPORT:PROMPT -NOLOGO -TLBID:1 + LIBS += kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib + else ifneq (,$(findstring uwp,$(PlatformSuffix))) + WinPartition = uwp + MSVC2017CompileFlags = -DWINAPI_FAMILY=WINAPI_FAMILY_APP -D_WINDLL -D_UNICODE -DUNICODE -D__WRL_NO_DEFAULT_LIB__ -EHsc + LDFLAGS += -APPCONTAINER -NXCOMPAT -DYNAMICBASE -MANIFEST:NO -LTCG -OPT:REF -SUBSYSTEM:CONSOLE -MANIFESTUAC:NO -OPT:ICF -ERRORREPORT:PROMPT -NOLOGO -TLBID:1 -DEBUG:FULL -WINMD:NO + LIBS += WindowsApp.lib + endif + + CFLAGS += $(MSVC2017CompileFlags) + CXXFLAGS += $(MSVC2017CompileFlags) + + TargetArchMoniker = $(subst $(WinPartition)_,,$(PlatformSuffix)) + + CC = cl.exe + CXX = cl.exe + LD = link.exe + + reg_query = $(call filter_out2,$(subst $2,,$(shell reg query "$2" -v "$1" 2>nul))) + fix_path = $(subst $(SPACE),\ ,$(subst \,/,$1)) + + ProgramFiles86w := $(shell cmd /c "echo %PROGRAMFILES(x86)%") + ProgramFiles86 := $(shell cygpath "$(ProgramFiles86w)") + + WindowsSdkDir ?= $(call reg_query,InstallationFolder,HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SDKs\Windows\v10.0) + WindowsSdkDir ?= $(call reg_query,InstallationFolder,HKEY_CURRENT_USER\SOFTWARE\Wow6432Node\Microsoft\Microsoft SDKs\Windows\v10.0) + WindowsSdkDir ?= $(call reg_query,InstallationFolder,HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0) + WindowsSdkDir ?= $(call reg_query,InstallationFolder,HKEY_CURRENT_USER\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0) + WindowsSdkDir := $(WindowsSdkDir) + + WindowsSDKVersion ?= $(firstword $(foreach folder,$(subst $(subst \,/,$(WindowsSdkDir)Include/),,$(wildcard $(call fix_path,$(WindowsSdkDir)Include\*))),$(if $(wildcard $(call fix_path,$(WindowsSdkDir)Include/$(folder)/um/Windows.h)),$(folder),)))$(BACKSLASH) + WindowsSDKVersion := $(WindowsSDKVersion) + + VsInstallBuildTools = $(ProgramFiles86)/Microsoft Visual Studio/2017/BuildTools + VsInstallEnterprise = $(ProgramFiles86)/Microsoft Visual Studio/2017/Enterprise + VsInstallProfessional = $(ProgramFiles86)/Microsoft Visual Studio/2017/Professional + VsInstallCommunity = $(ProgramFiles86)/Microsoft Visual Studio/2017/Community + + VsInstallRoot ?= $(shell if [ -d "$(VsInstallBuildTools)" ]; then echo "$(VsInstallBuildTools)"; fi) + ifeq ($(VsInstallRoot), ) + VsInstallRoot = $(shell if [ -d "$(VsInstallEnterprise)" ]; then echo "$(VsInstallEnterprise)"; fi) + endif + ifeq ($(VsInstallRoot), ) + VsInstallRoot = $(shell if [ -d "$(VsInstallProfessional)" ]; then echo "$(VsInstallProfessional)"; fi) + endif + ifeq ($(VsInstallRoot), ) + VsInstallRoot = $(shell if [ -d "$(VsInstallCommunity)" ]; then echo "$(VsInstallCommunity)"; fi) + endif + VsInstallRoot := $(VsInstallRoot) + + VcCompilerToolsVer := $(shell cat "$(VsInstallRoot)/VC/Auxiliary/Build/Microsoft.VCToolsVersion.default.txt" | grep -o '[0-9\.]*') + VcCompilerToolsDir := $(VsInstallRoot)/VC/Tools/MSVC/$(VcCompilerToolsVer) + + WindowsSDKSharedIncludeDir := $(shell cygpath -w "$(WindowsSdkDir)\Include\$(WindowsSDKVersion)\shared") + WindowsSDKUCRTIncludeDir := $(shell cygpath -w "$(WindowsSdkDir)\Include\$(WindowsSDKVersion)\ucrt") + WindowsSDKUMIncludeDir := $(shell cygpath -w "$(WindowsSdkDir)\Include\$(WindowsSDKVersion)\um") + WindowsSDKUCRTLibDir := $(shell cygpath -w "$(WindowsSdkDir)\Lib\$(WindowsSDKVersion)\ucrt\$(TargetArchMoniker)") + WindowsSDKUMLibDir := $(shell cygpath -w "$(WindowsSdkDir)\Lib\$(WindowsSDKVersion)\um\$(TargetArchMoniker)") + + # For some reason the HostX86 compiler doesn't like compiling for x64 + # ("no such file" opening a shared library), and vice-versa. + # Work around it for now by using the strictly x86 compiler for x86, and x64 for x64. + # NOTE: What about ARM? + ifneq (,$(findstring x64,$(TargetArchMoniker))) + VCCompilerToolsBinDir := $(VcCompilerToolsDir)\bin\HostX64 + else + VCCompilerToolsBinDir := $(VcCompilerToolsDir)\bin\HostX86 + endif + + PATH := $(shell IFS=$$'\n'; cygpath "$(VCCompilerToolsBinDir)/$(TargetArchMoniker)"):$(PATH) + PATH := $(PATH):$(shell IFS=$$'\n'; cygpath "$(VsInstallRoot)/Common7/IDE") + INCLUDE := $(shell IFS=$$'\n'; cygpath -w "$(VcCompilerToolsDir)/include") + LIB := $(shell IFS=$$'\n'; cygpath -w "$(VcCompilerToolsDir)/lib/$(TargetArchMoniker)") + ifneq (,$(findstring uwp,$(PlatformSuffix))) + LIB := $(shell IFS=$$'\n'; cygpath -w "$(LIB)/store") + endif + + export INCLUDE := $(INCLUDE);$(WindowsSDKSharedIncludeDir);$(WindowsSDKUCRTIncludeDir);$(WindowsSDKUMIncludeDir) + export LIB := $(LIB);$(WindowsSDKUCRTLibDir);$(WindowsSDKUMLibDir) + TARGET := $(TARGET_NAME)_libretro.dll + PSS_STYLE :=2 + LDFLAGS += -DLL + HAS_GCC := 0 + # Xbox 360 else ifeq ($(platform), xenon) TARGET := $(TARGET_NAME)_libretro_xenon360.a @@ -213,6 +379,13 @@ PLATFORM_DEFINES += -U__INT32_TYPE__ -U __UINT32_TYPE__ -D__INT32_TYPE__=int STATIC_LINKING = 1 +# Nintendo Switch (libtransistor) +else ifeq ($(platform), switch) + EXT=a + TARGET := $(TARGET_NAME)_libretro_$(platform).$(EXT) + include $(LIBTRANSISTOR_HOME)/libtransistor.mk + STATIC_LINKING=1 + # ARM else ifneq (,$(findstring armv,$(platform))) TARGET := $(TARGET_NAME)_libretro.so @@ -240,6 +413,159 @@ TARGET := $(TARGET_NAME)_libretro_$(platform).bc STATIC_LINKING = 1 +# Windows MSVC 2017 all architectures +else ifneq (,$(findstring windows_msvc2017,$(platform))) + + PlatformSuffix = $(subst windows_msvc2017_,,$(platform)) + ifneq (,$(findstring desktop,$(PlatformSuffix))) + WinPartition = desktop + CFLAGS += -DWINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP + LDFLAGS += -MANIFEST -LTCG:incremental -NXCOMPAT -DYNAMICBASE -DEBUG -OPT:REF -INCREMENTAL:NO -SUBSYSTEM:WINDOWS -MANIFESTUAC:"level='asInvoker' uiAccess='false'" -OPT:ICF -ERRORREPORT:PROMPT -NOLOGO -TLBID:1 + LIBS += kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib + else ifneq (,$(findstring uwp,$(PlatformSuffix))) + WinPartition = uwp + CFLAGS += -DWINAPI_FAMILY=WINAPI_FAMILY_APP -DWINDLL -D_UNICODE -DUNICODE -DWRL_NO_DEFAULT_LIB + LDFLAGS += -APPCONTAINER -NXCOMPAT -DYNAMICBASE -MANIFEST:NO -LTCG -OPT:REF -SUBSYSTEM:CONSOLE -MANIFESTUAC:NO -OPT:ICF -ERRORREPORT:PROMPT -NOLOGO -TLBID:1 -DEBUG:FULL -WINMD:NO + LIBS += WindowsApp.lib + endif + + TargetArchMoniker = $(subst $(WinPartition)_,,$(PlatformSuffix)) + + CC = cl.exe + CXX = cl.exe + + reg_query = $(call filter_out2,$(subst $2,,$(shell reg query "$2" -v "$1" 2>nul))) + fix_path = $(subst $(SPACE),\ ,$(subst \,/,$1)) + + ProgramFiles86w := $(shell cmd /c "echo %PROGRAMFILES(x86)%") + ProgramFiles86 := $(shell cygpath "$(ProgramFiles86w)") + + WindowsSdkDir ?= $(call reg_query,InstallationFolder,HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SDKs\Windows\v10.0) + WindowsSdkDir ?= $(call reg_query,InstallationFolder,HKEY_CURRENT_USER\SOFTWARE\Wow6432Node\Microsoft\Microsoft SDKs\Windows\v10.0) + WindowsSdkDir ?= $(call reg_query,InstallationFolder,HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0) + WindowsSdkDir ?= $(call reg_query,InstallationFolder,HKEY_CURRENT_USER\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0) + WindowsSdkDir := $(WindowsSdkDir) + + WindowsSDKVersion ?= $(firstword $(foreach folder,$(subst $(subst \,/,$(WindowsSdkDir)Include/),,$(wildcard $(call fix_path,$(WindowsSdkDir)Include\*))),$(if $(wildcard $(call fix_path,$(WindowsSdkDir)Include/$(folder)/um/Windows.h)),$(folder),)))$(BACKSLASH) + WindowsSDKVersion := $(WindowsSDKVersion) + + VsInstallBuildTools = $(ProgramFiles86)/Microsoft Visual Studio/2017/BuildTools + VsInstallEnterprise = $(ProgramFiles86)/Microsoft Visual Studio/2017/Enterprise + VsInstallProfessional = $(ProgramFiles86)/Microsoft Visual Studio/2017/Professional + VsInstallCommunity = $(ProgramFiles86)/Microsoft Visual Studio/2017/Community + + VsInstallRoot ?= $(shell if [ -d "$(VsInstallBuildTools)" ]; then echo "$(VsInstallBuildTools)"; fi) + ifeq ($(VsInstallRoot), ) + VsInstallRoot = $(shell if [ -d "$(VsInstallEnterprise)" ]; then echo "$(VsInstallEnterprise)"; fi) + endif + ifeq ($(VsInstallRoot), ) + VsInstallRoot = $(shell if [ -d "$(VsInstallProfessional)" ]; then echo "$(VsInstallProfessional)"; fi) + endif + ifeq ($(VsInstallRoot), ) + VsInstallRoot = $(shell if [ -d "$(VsInstallCommunity)" ]; then echo "$(VsInstallCommunity)"; fi) + endif + VsInstallRoot := $(VsInstallRoot) + + VcCompilerToolsVer := $(shell cat "$(VsInstallRoot)/VC/Auxiliary/Build/Microsoft.VCToolsVersion.default.txt" | grep -o '[0-9\.]*') + VcCompilerToolsDir := $(VsInstallRoot)/VC/Tools/MSVC/$(VcCompilerToolsVer) + + WindowsSDKSharedIncludeDir := $(shell cygpath -w "$(WindowsSdkDir)\Include\$(WindowsSDKVersion)\shared") + WindowsSDKUCRTIncludeDir := $(shell cygpath -w "$(WindowsSdkDir)\Include\$(WindowsSDKVersion)\ucrt") + WindowsSDKUMIncludeDir := $(shell cygpath -w "$(WindowsSdkDir)\Include\$(WindowsSDKVersion)\um") + WindowsSDKUCRTLibDir := $(shell cygpath -w "$(WindowsSdkDir)\Lib\$(WindowsSDKVersion)\ucrt\$(TargetArchMoniker)") + WindowsSDKUMLibDir := $(shell cygpath -w "$(WindowsSdkDir)\Lib\$(WindowsSDKVersion)\um\$(TargetArchMoniker)") + + # For some reason the HostX86 compiler doesn't like compiling for x64 + # ("no such file" opening a shared library), and vice-versa. + # Work around it for now by using the strictly x86 compiler for x86, and x64 for x64. + # NOTE: What about ARM? + ifneq (,$(findstring x64,$(TargetArchMoniker))) + VCCompilerToolsBinDir := $(VcCompilerToolsDir)\bin\HostX64 + else + VCCompilerToolsBinDir := $(VcCompilerToolsDir)\bin\HostX86 + endif + + PATH := $(shell IFS=$$'\n'; cygpath "$(VCCompilerToolsBinDir)/$(TargetArchMoniker)"):$(PATH) + PATH := $(PATH):$(shell IFS=$$'\n'; cygpath "$(VsInstallRoot)/Common7/IDE") + INCLUDE := $(shell IFS=$$'\n'; cygpath -w "$(VcCompilerToolsDir)/include") + LIB := $(shell IFS=$$'\n'; cygpath -w "$(VcCompilerToolsDir)/lib/$(TargetArchMoniker)") + + export INCLUDE := $(INCLUDE);$(WindowsSDKSharedIncludeDir);$(WindowsSDKUCRTIncludeDir);$(WindowsSDKUMIncludeDir) + export LIB := $(LIB);$(WindowsSDKUCRTLibDir);$(WindowsSDKUMLibDir) + TARGET := $(TARGET_NAME)_libretro.dll + PSS_STYLE :=2 + LDFLAGS += -DLL + HAS_GCC := 0 + +# Windows MSVC 2010 x64 +else ifeq ($(platform), windows_msvc2010_x64) + CC = cl.exe + CXX = cl.exe + HAS_GCC := 0 + +PATH := $(shell IFS=$$'\n'; cygpath "$(VS100COMNTOOLS)../../VC/bin/amd64"):$(PATH) +PATH := $(PATH):$(shell IFS=$$'\n'; cygpath "$(VS100COMNTOOLS)../IDE") +LIB := $(shell IFS=$$'\n'; cygpath "$(VS100COMNTOOLS)../../VC/lib/amd64") +INCLUDE := $(shell IFS=$$'\n'; cygpath "$(VS100COMNTOOLS)../../VC/include") + +WindowsSdkDir := $(shell reg query "HKLM\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A" -v "InstallationFolder" | grep -o '[A-Z]:\\.*')lib/x64 +WindowsSdkDir ?= $(shell reg query "HKLM\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.1A" -v "InstallationFolder" | grep -o '[A-Z]:\\.*')lib/x64 + +WindowsSdkDirInc := $(shell reg query "HKLM\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A" -v "InstallationFolder" | grep -o '[A-Z]:\\.*')Include +WindowsSdkDirInc ?= $(shell reg query "HKLM\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.1A" -v "InstallationFolder" | grep -o '[A-Z]:\\.*')Include + + +INCFLAGS_PLATFORM = -I"$(WindowsSdkDirInc)" +export INCLUDE := $(INCLUDE) +export LIB := $(LIB);$(WindowsSdkDir) +TARGET := $(TARGET_NAME)_libretro.dll +PSS_STYLE :=2 +LDFLAGS += -DLL + HAS_GCC := 0 +# Windows MSVC 2010 x86 +else ifeq ($(platform), windows_msvc2010_x86) + CC = cl.exe + CXX = cl.exe + HAS_GCC := 0 + +PATH := $(shell IFS=$$'\n'; cygpath "$(VS100COMNTOOLS)../../VC/bin"):$(PATH) +PATH := $(PATH):$(shell IFS=$$'\n'; cygpath "$(VS100COMNTOOLS)../IDE") +LIB := $(shell IFS=$$'\n'; cygpath -w "$(VS100COMNTOOLS)../../VC/lib") +INCLUDE := $(shell IFS=$$'\n'; cygpath "$(VS100COMNTOOLS)../../VC/include") + +WindowsSdkDir := $(shell reg query "HKLM\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A" -v "InstallationFolder" | grep -o '[A-Z]:\\.*')lib +WindowsSdkDir ?= $(shell reg query "HKLM\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.1A" -v "InstallationFolder" | grep -o '[A-Z]:\\.*')lib + +WindowsSdkDirInc := $(shell reg query "HKLM\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A" -v "InstallationFolder" | grep -o '[A-Z]:\\.*')Include +WindowsSdkDirInc ?= $(shell reg query "HKLM\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.1A" -v "InstallationFolder" | grep -o '[A-Z]:\\.*')Include + + +INCFLAGS_PLATFORM = -I"$(WindowsSdkDirInc)" +export INCLUDE := $(INCLUDE) +export LIB := $(LIB);$(WindowsSdkDir) +TARGET := $(TARGET_NAME)_libretro.dll +PSS_STYLE :=2 +LDFLAGS += -DLL +# Windows MSVC 2005 x86 +else ifeq ($(platform), windows_msvc2005_x86) + CC = cl.exe + CXX = cl.exe + HAS_GCC := 0 + +PATH := $(shell IFS=$$'\n'; cygpath "$(VS80COMNTOOLS)../../VC/bin"):$(PATH) +PATH := $(PATH):$(shell IFS=$$'\n'; cygpath "$(VS80COMNTOOLS)../IDE") +INCLUDE := $(shell IFS=$$'\n'; cygpath "$(VS80COMNTOOLS)../../VC/include") +LIB := $(shell IFS=$$'\n'; cygpath -w "$(VS80COMNTOOLS)../../VC/lib") +BIN := $(shell IFS=$$'\n'; cygpath "$(VS80COMNTOOLS)../../VC/bin") + +WindowsSdkDir := $(INETSDK) + +export INCLUDE := $(INCLUDE);$(INETSDK)/Include;libretro-common/include/compat/msvc +export LIB := $(LIB);$(WindowsSdkDir);$(INETSDK)/Lib +TARGET := $(TARGET_NAME)_libretro.dll +PSS_STYLE :=2 +LDFLAGS += -DLL +CFLAGS += -D_CRT_SECURE_NO_DEPRECATE # Windows else TARGET := $(TARGET_NAME)_libretro.dll @@ -253,36 +579,75 @@ CXXFLAGS += -DGIT_VERSION=\"$(GIT_VERSION)\" ifeq ($(DEBUG), 1) - CFLAGS += -O0 -g - CXXFLAGS += -O0 -g -else ifeq ($(platform), ps3) - CFLAGS += -O2 - CXXFLAGS += -O2 +ifneq (,$(findstring msvc,$(platform))) + ifeq ($(STATIC_LINKING),1) + CFLAGS += -MTd + CXXFLAGS += -MTd else - CFLAGS += -O3 - CXXFLAGS += -O3 + CFLAGS += -MDd + CXXFLAGS += -MDd +endif + +CFLAGS += -Od -Zi -DDEBUG -D_DEBUG +CXXFLAGS += -Od -Zi -DDEBUG -D_DEBUG + else + CFLAGS += -O0 -g -DDEBUG + CXXFLAGS += -O0 -g -DDEBUG +endif +else +ifneq (,$(findstring msvc,$(platform))) +ifeq ($(STATIC_LINKING),1) + CFLAGS += -MT + CXXFLAGS += -MT +else + CFLAGS += -MD + CXXFLAGS += -MD +endif + +CFLAGS += -O2 -DNDEBUG +CXXFLAGS += -O2 -DNDEBUG +else + CFLAGS += -O2 -DNDEBUG + CXXFLAGS += -O2 -DNDEBUG +endif endif CORE_DIR = .. include Makefile.common -OBJS := $(SOURCES_CXX:.cpp=.o) +OBJECTS := $(SOURCES_CXX:.cpp=.o) ifeq ($(HAS_GCC), 1) -GCC_FLAGS := -Wno-deprecated -Wno-write-strings + C_VER = -std=gnu99 -CXXFLAGS += -std=gnu++98 -else +CXXFLAGS += -std=c++98 +CXXFLAGS += -fno-rtti endif -DEFINES := -D__LIBRETRO__ $(PLATFORM_DEFINES) $(GCC_FLAGS) $(GCC_WARNINGS) -DNST_NO_ZLIB $(INCFLAGS) +DEFINES := -D__LIBRETRO__ $(PLATFORM_DEFINES) $(GCC_FLAGS) $(GCC_WARNINGS) -DNST_NO_ZLIB $(INCFLAGS) $(INCFLAGS_PLATFORM) CFLAGS += $(fpic) $(DEFINES) $(C_VER) -CXXFLAGS += $(fpic) $(DEFINES) -fno-rtti +CXXFLAGS += $(fpic) $(DEFINES) INCDIRS := -I$(CORE_DIR) -I$(CORE_DIR)/source +OBJOUT = -o +LINKOUT = -o + +ifneq (,$(findstring msvc,$(platform))) + OBJOUT = -Fo + LINKOUT = -out: +ifeq ($(STATIC_LINKING),1) + LD ?= lib.exe + STATIC_LINKING=0 +else + LD = link.exe +endif +else + LD = $(CXX) +endif + ifeq ($(platform), theos_ios) COMMON_FLAGS := -DIOS $(DEFINES) $(INCFLAGS) $(INCDIRS) -I$(THEOS_INCLUDE_PATH) -Wno-error $(LIBRARY_NAME)_CFLAGS += $(CFLAGS) $(COMMON_FLAGS) @@ -292,24 +657,24 @@ else all: $(TARGET) -$(TARGET): $(OBJS) +$(TARGET): $(OBJECTS) ifeq ($(STATIC_LINKING), 1) - $(AR) rcs $@ $(OBJS) + $(AR) rcs $@ $(OBJECTS) else - $(CXX) -o $@ $(SHARED) $(OBJS) $(LDFLAGS) $(LIBS) + $(LD) $(LINKOUT)$@ $(SHARED) $(OBJECTS) $(LDFLAGS) $(LIBS) endif %.o: %.cpp - $(CXX) -c -o $@ $< $(CXXFLAGS) $(INCDIRS) + $(CXX) $(CPPFLAGS) -c $(OBJOUT)$@ $< $(CXXFLAGS) $(INCDIRS) %.o: %.c - $(CC) -c -o $@ $< $(CFLAGS) $(INCDIRS) + $(CC) $(CPPFLAGS) -c $(OBJOUT)$@ $< $(CFLAGS) $(INCDIRS) clean-objs: - rm -f $(OBJS) + rm -f $(OBJECTS) clean: - rm -f $(OBJS) + rm -f $(OBJECTS) rm -f $(TARGET) install: diff -Nru nestopia-1.48/libretro/Makefile.common nestopia-1.49/libretro/Makefile.common --- nestopia-1.48/libretro/Makefile.common 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/Makefile.common 2018-06-24 23:26:58.000000000 +0000 @@ -1,6 +1,13 @@ -INCFLAGS := -I$(CORE_DIR)/libretro -I$(CORE_DIR) +LIBRETRO_COMM_DIR := $(CORE_DIR)/libretro/libretro-common +INCFLAGS := -I$(CORE_DIR)/libretro -I$(CORE_DIR) -I$(LIBRETRO_COMM_DIR)/include + +ifneq (,$(findstring msvc2003,$(platform))) +INCFLAGS += -I$(LIBRETRO_COMM_DIR)/include/compat/msvc +endif # Core +SOURCES_CXX = + SOURCES_CXX += $(CORE_DIR)/source/core/NstApu.cpp SOURCES_CXX += $(CORE_DIR)/source/core/NstAssert.cpp SOURCES_CXX += $(CORE_DIR)/source/core/NstCartridge.cpp @@ -183,6 +190,7 @@ SOURCES_CXX += $(CORE_DIR)/source/core/board/NstBoardKonamiVrc6.cpp SOURCES_CXX += $(CORE_DIR)/source/core/board/NstBoardKonamiVrc7.cpp SOURCES_CXX += $(CORE_DIR)/source/core/board/NstBoardKonamiVsSystem.cpp +SOURCES_CXX += $(CORE_DIR)/source/core/board/NstBoardMagicKidGoogoo.cpp SOURCES_CXX += $(CORE_DIR)/source/core/board/NstBoardMagicSeries.cpp SOURCES_CXX += $(CORE_DIR)/source/core/board/NstBoardMmc1.cpp SOURCES_CXX += $(CORE_DIR)/source/core/board/NstBoardMmc2.cpp diff -Nru nestopia-1.48/libretro/msvc/msvc-2003-xbox1/msvc-2003-xbox1.vcproj nestopia-1.49/libretro/msvc/msvc-2003-xbox1/msvc-2003-xbox1.vcproj --- nestopia-1.48/libretro/msvc/msvc-2003-xbox1/msvc-2003-xbox1.vcproj 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2003-xbox1/msvc-2003-xbox1.vcproj 1970-01-01 00:00:00.000000000 +0000 @@ -1,1079 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff -Nru nestopia-1.48/libretro/msvc/msvc-2003-xbox1/stdint.h nestopia-1.49/libretro/msvc/msvc-2003-xbox1/stdint.h --- nestopia-1.48/libretro/msvc/msvc-2003-xbox1/stdint.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2003-xbox1/stdint.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,249 +0,0 @@ -// ISO C9x compliant stdint.h for Microsoft Visual Studio -// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 -// -// Copyright (c) 2006-2008 Alexander Chemeris -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// 3. The name of the author may be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -/////////////////////////////////////////////////////////////////////////////// -#ifndef __RARCH_STDINT_H -#define __RARCH_STDINT_H - -#if _MSC_VER && (_MSC_VER < 1600) -//pre-MSVC 2010 needs an implementation of stdint.h - -#if _MSC_VER > 1000 -#pragma once -#endif - -#include - -// For Visual Studio 6 in C++ mode and for many Visual Studio versions when -// compiling for ARM we should wrap include with 'extern "C++" {}' -// or compiler give many errors like this: -// error C2733: second C linkage of overloaded function 'wmemchr' not allowed -#ifdef __cplusplus -extern "C" { -#endif -# include -#ifdef __cplusplus -} -#endif - -// Define _W64 macros to mark types changing their size, like intptr_t. -#ifndef _W64 -# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 -# define _W64 __w64 -# else -# define _W64 -# endif -#endif - - -// 7.18.1 Integer types - -// 7.18.1.1 Exact-width integer types - -// Visual Studio 6 and Embedded Visual C++ 4 doesn't -// realize that, e.g. char has the same size as __int8 -// so we give up on __intX for them. -#if (_MSC_VER < 1300) - typedef signed char int8_t; - typedef signed short int16_t; - typedef signed int int32_t; - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned int uint32_t; -#else - typedef signed __int8 int8_t; - typedef signed __int16 int16_t; - typedef signed __int32 int32_t; - typedef unsigned __int8 uint8_t; - typedef unsigned __int16 uint16_t; - typedef unsigned __int32 uint32_t; -#endif -typedef signed __int64 int64_t; -typedef unsigned __int64 uint64_t; - - -// 7.18.1.2 Minimum-width integer types -typedef int8_t int_least8_t; -typedef int16_t int_least16_t; -typedef int32_t int_least32_t; -typedef int64_t int_least64_t; -typedef uint8_t uint_least8_t; -typedef uint16_t uint_least16_t; -typedef uint32_t uint_least32_t; -typedef uint64_t uint_least64_t; - -// 7.18.1.3 Fastest minimum-width integer types -typedef int8_t int_fast8_t; -typedef int16_t int_fast16_t; -typedef int32_t int_fast32_t; -typedef int64_t int_fast64_t; -typedef uint8_t uint_fast8_t; -typedef uint16_t uint_fast16_t; -typedef uint32_t uint_fast32_t; -typedef uint64_t uint_fast64_t; - -// 7.18.1.4 Integer types capable of holding object pointers -#ifdef _WIN64 // [ - typedef signed __int64 intptr_t; - typedef unsigned __int64 uintptr_t; -#else // _WIN64 ][ - typedef _W64 signed int intptr_t; - typedef _W64 unsigned int uintptr_t; -#endif // _WIN64 ] - -// 7.18.1.5 Greatest-width integer types -typedef int64_t intmax_t; -typedef uint64_t uintmax_t; - - -// 7.18.2 Limits of specified-width integer types - -#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 - -// 7.18.2.1 Limits of exact-width integer types -#define INT8_MIN ((int8_t)_I8_MIN) -#define INT8_MAX _I8_MAX -#define INT16_MIN ((int16_t)_I16_MIN) -#define INT16_MAX _I16_MAX -#define INT32_MIN ((int32_t)_I32_MIN) -#define INT32_MAX _I32_MAX -#define INT64_MIN ((int64_t)_I64_MIN) -#define INT64_MAX _I64_MAX -#define UINT8_MAX _UI8_MAX -#define UINT16_MAX _UI16_MAX -#define UINT32_MAX _UI32_MAX -#define UINT64_MAX _UI64_MAX - -// 7.18.2.2 Limits of minimum-width integer types -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MIN INT64_MIN -#define INT_LEAST64_MAX INT64_MAX -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX - -// 7.18.2.3 Limits of fastest minimum-width integer types -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST16_MAX INT16_MAX -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST32_MAX INT32_MAX -#define INT_FAST64_MIN INT64_MIN -#define INT_FAST64_MAX INT64_MAX -#define UINT_FAST8_MAX UINT8_MAX -#define UINT_FAST16_MAX UINT16_MAX -#define UINT_FAST32_MAX UINT32_MAX -#define UINT_FAST64_MAX UINT64_MAX - -// 7.18.2.4 Limits of integer types capable of holding object pointers -#ifdef _WIN64 // [ -# define INTPTR_MIN INT64_MIN -# define INTPTR_MAX INT64_MAX -# define UINTPTR_MAX UINT64_MAX -#else // _WIN64 ][ -# define INTPTR_MIN INT32_MIN -# define INTPTR_MAX INT32_MAX -# define UINTPTR_MAX UINT32_MAX -#endif // _WIN64 ] - -// 7.18.2.5 Limits of greatest-width integer types -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX - -// 7.18.3 Limits of other integer types - -#ifdef _WIN64 // [ -# define PTRDIFF_MIN _I64_MIN -# define PTRDIFF_MAX _I64_MAX -#else // _WIN64 ][ -# define PTRDIFF_MIN _I32_MIN -# define PTRDIFF_MAX _I32_MAX -#endif // _WIN64 ] - -#define SIG_ATOMIC_MIN INT_MIN -#define SIG_ATOMIC_MAX INT_MAX - -#ifndef SIZE_MAX // [ -# ifdef _WIN64 // [ -# define SIZE_MAX _UI64_MAX -# else // _WIN64 ][ -# define SIZE_MAX _UI32_MAX -# endif // _WIN64 ] -#endif // SIZE_MAX ] - -// WCHAR_MIN and WCHAR_MAX are also defined in -#ifndef WCHAR_MIN // [ -# define WCHAR_MIN 0 -#endif // WCHAR_MIN ] -#ifndef WCHAR_MAX // [ -# define WCHAR_MAX _UI16_MAX -#endif // WCHAR_MAX ] - -#define WINT_MIN 0 -#define WINT_MAX _UI16_MAX - -#endif // __STDC_LIMIT_MACROS ] - - -// 7.18.4 Limits of other integer types - -#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 - -// 7.18.4.1 Macros for minimum-width integer constants - -#define INT8_C(val) val##i8 -#define INT16_C(val) val##i16 -#define INT32_C(val) val##i32 -#define INT64_C(val) val##i64 - -#define UINT8_C(val) val##ui8 -#define UINT16_C(val) val##ui16 -#define UINT32_C(val) val##ui32 -#define UINT64_C(val) val##ui64 - -// 7.18.4.2 Macros for greatest-width integer constants -#define INTMAX_C INT64_C -#define UINTMAX_C UINT64_C - -#endif // __STDC_CONSTANT_MACROS ] - -#else -//sanity for everything else -#include -#endif - -#endif diff -Nru nestopia-1.48/libretro/msvc/msvc-2003-xbox1.bat nestopia-1.49/libretro/msvc/msvc-2003-xbox1.bat --- nestopia-1.48/libretro/msvc/msvc-2003-xbox1.bat 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2003-xbox1.bat 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -@SET VSINSTALLDIR=C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\IDE -@SET VCINSTALLDIR=C:\Program Files\Microsoft Visual Studio .NET 2003 -@SET FrameworkDir=C:\WINDOWS\Microsoft.NET\Framework -@SET FrameworkVersion=v1.1.4322 -@SET FrameworkSDKDir=C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1 -@rem Root of Visual Studio common files. - -@if "%VSINSTALLDIR%"=="" goto Usage -@if "%VCINSTALLDIR%"=="" set VCINSTALLDIR=%VSINSTALLDIR% - -@rem -@rem Root of Visual Studio ide installed files. -@rem -@set DevEnvDir=%VSINSTALLDIR% - -@rem -@rem Root of Visual C++ installed files. -@rem -@set MSVCDir=%VCINSTALLDIR%\VC7 - -@rem -@echo Setting environment for using Microsoft Visual Studio .NET 2003 tools. -@echo (If you have another version of Visual Studio or Visual C++ installed and wish -@echo to use its tools from the command line, run vcvars32.bat for that version.) -@rem - -@REM %VCINSTALLDIR%\Common7\Tools dir is added only for real setup. - -@set PATH=%DevEnvDir%;%MSVCDir%\BIN;%VCINSTALLDIR%\Common7\Tools;%VCINSTALLDIR%\Common7\Tools\bin\prerelease;%VCINSTALLDIR%\Common7\Tools\bin;%FrameworkSDKDir%\bin;%FrameworkDir%\%FrameworkVersion%;%PATH%; -@set INCLUDE=%MSVCDir%\ATLMFC\INCLUDE;%MSVCDir%\INCLUDE;%FrameworkSDKDir%\include;%INCLUDE%;%XDK%\xbox\include -@set LIB=%MSVCDir%\ATLMFC\LIB;%MSVCDir%\LIB;%MSVCDir%\PlatformSDK\lib;%XDK%\lib;%XDK%\xbox\lib;%LIB% - -@goto end - -:Usage - -@echo. VSINSTALLDIR variable is not set. -@echo. -@echo SYNTAX: %0 - -@goto end - -:end - -devenv /clean Release_LTCG msvc-2003-xbox1.sln -devenv /build Release_LTCG msvc-2003-xbox1.sln -exit diff -Nru nestopia-1.48/libretro/msvc/msvc-2003-xbox1.sln nestopia-1.49/libretro/msvc/msvc-2003-xbox1.sln --- nestopia-1.48/libretro/msvc/msvc-2003-xbox1.sln 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2003-xbox1.sln 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "msvc-2003-xbox1", "msvc-2003-xbox1/msvc-2003-xbox1.vcproj", "{E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Profile = Profile - Profile_FastCap = Profile_FastCap - Release = Release - Release_LTCG = Release_LTCG - EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}.Debug.ActiveCfg = Debug|Xbox - {E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}.Debug.Build.0 = Debug|Xbox - {E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}.Profile.ActiveCfg = Profile|Xbox - {E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}.Profile.Build.0 = Profile|Xbox - {E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}.Profile_FastCap.ActiveCfg = Profile_FastCap|Xbox - {E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}.Profile_FastCap.Build.0 = Profile_FastCap|Xbox - {E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}.Release.ActiveCfg = Release|Xbox - {E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}.Release.Build.0 = Release|Xbox - {E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}.Release_LTCG.ActiveCfg = Release_LTCG|Xbox - {E3D2A7C9-228F-4706-AFCD-992D7B39ADCF}.Release_LTCG.Build.0 = Release_LTCG|Xbox - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution - EndGlobalSection -EndGlobal diff -Nru nestopia-1.48/libretro/msvc/msvc-2010/libretro.def nestopia-1.49/libretro/msvc/msvc-2010/libretro.def --- nestopia-1.48/libretro/msvc/msvc-2010/libretro.def 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2010/libretro.def 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -LIBRARY "msvc-2010" -EXPORTS -retro_set_environment -retro_set_video_refresh -retro_set_audio_sample -retro_set_audio_sample_batch -retro_set_input_poll -retro_set_input_state -retro_init -retro_deinit -retro_api_version -retro_get_system_info -retro_get_system_av_info -retro_set_controller_port_device -retro_reset -retro_run -retro_serialize_size -retro_serialize -retro_unserialize -retro_cheat_reset -retro_cheat_set -retro_load_game -retro_load_game_special -retro_unload_game -retro_get_region -retro_get_memory_data -retro_get_memory_size - diff -Nru nestopia-1.48/libretro/msvc/msvc-2010/msvc-2010.vcxproj nestopia-1.49/libretro/msvc/msvc-2010/msvc-2010.vcxproj --- nestopia-1.48/libretro/msvc/msvc-2010/msvc-2010.vcxproj 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2010/msvc-2010.vcxproj 1970-01-01 00:00:00.000000000 +0000 @@ -1,373 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {C4D4209C-05D5-404F-8925-BD7ABA58D686} - Win32Proj - - - - DynamicLibrary - Unicode - - - DynamicLibrary - Unicode - - - - - - - - - - - - - $(OutDir)msvc-2010$(TargetExt) - $(SolutionDir)msvc-2010\$(Configuration)\ - - - $(OutDir)msvc-2010$(TargetExt) - $(SolutionDir)msvc-2010\$(Configuration)\ - - - - NotUsing - Level3 - ProgramDatabase - Disabled - false - true - false - MultiThreadedDebug - _DEBUG;_WIN32;_LIB;%(PreprocessorDefinitions);__LIBRETRO__;NST_NO_ZLIB;_SECURE_SCL=0 - Callcap - $(SolutionDir)\..\..\source;%(AdditionalIncludeDirectories) - - - true - libretro.def - - - - - Level3 - NotUsing - Full - true - true - ProgramDatabase - Size - false - false - MultiThreaded - NDEBUG;_WIN32;_LIB;%(PreprocessorDefinitions);NST_NO_ZLIB;__LIBRETRO__;_SECURE_SCL=0 - $(SolutionDir)\..\..\source;%(AdditionalIncludeDirectories) - - - true - true - true - libretro.def - - - - - - diff -Nru nestopia-1.48/libretro/msvc/msvc-2010/msvc-2010.vcxproj.filters nestopia-1.49/libretro/msvc/msvc-2010/msvc-2010.vcxproj.filters --- nestopia-1.48/libretro/msvc/msvc-2010/msvc-2010.vcxproj.filters 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2010/msvc-2010.vcxproj.filters 1970-01-01 00:00:00.000000000 +0000 @@ -1,882 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {bb2769c3-f85a-46ed-b7fa-9b479cacb927} - - - {cfd4b486-09df-4d1c-8ae5-d39d256c047a} - - - {f3d53a31-83d2-40ac-8c5d-ad9324f3d392} - - - {89661cd6-755f-4ecd-89a3-ac7caf2d908c} - - - {21634da5-491c-4dd3-b53b-cc17f64c07e2} - - - {763265c6-4c2c-4a36-9561-d7bc02c13c07} - - - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\vssystem - - - Source Files\core\vssystem - - - Source Files\core\vssystem - - - Source Files\core\vssystem - - - Source Files\libretro - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - diff -Nru nestopia-1.48/libretro/msvc/msvc-2010-360/msvc-2010-360.vcxproj nestopia-1.49/libretro/msvc/msvc-2010-360/msvc-2010-360.vcxproj --- nestopia-1.48/libretro/msvc/msvc-2010-360/msvc-2010-360.vcxproj 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2010-360/msvc-2010-360.vcxproj 1970-01-01 00:00:00.000000000 +0000 @@ -1,510 +0,0 @@ - - - - - CodeAnalysis - Xbox 360 - - - Debug - Xbox 360 - - - Profile - Xbox 360 - - - Profile_FastCap - Xbox 360 - - - Release - Xbox 360 - - - Release_LTCG - Xbox 360 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {C4D4209C-05D5-404F-8925-BD7ABA58D686} - Xbox360Proj - - - - StaticLibrary - MultiByte - - - StaticLibrary - MultiByte - - - StaticLibrary - MultiByte - - - StaticLibrary - MultiByte - - - StaticLibrary - MultiByte - - - StaticLibrary - true - MultiByte - - - - - - - - - - - - - - - - - - - - - - - - - $(OutDir)msvc-2010-360.lib - - - $(OutDir)msvc-2010-360.lib - - - $(OutDir)msvc-2010-360.lib - - - $(OutDir)msvc-2010-360.lib - - - $(OutDir)msvc-2010-360.lib - - - $(OutDir)msvc-2010-360.lib - - - - NotUsing - Level3 - ProgramDatabase - Disabled - false - true - false - MultiThreadedDebug - _DEBUG;_XBOX;_LIB;%(PreprocessorDefinitions);__LIBRETRO__;NST_NO_ZLIB;_SECURE_SCL=0 - Callcap - $(SolutionDir)\..\..\source;%(AdditionalIncludeDirectories) - - - true - - - - - NotUsing - Level4 - ProgramDatabase - Disabled - false - true - AnalyzeOnly - false - MultiThreadedDebug - _DEBUG;_XBOX;_LIB;%(PreprocessorDefinitions);NST_MSVC_OPTIMIZE;__LIBRETRO__;NST_NO_ZLIB;_SECURE_SCL=0 - Callcap - - - true - - - - - Level3 - NotUsing - Full - true - false - true - ProgramDatabase - Size - false - MultiThreaded - NDEBUG;_XBOX;PROFILE;_LIB;%(PreprocessorDefinitions);__LIBRETRO__;NST_MSVC_OPTIMIZE;NST_NO_ZLIB;_SECURE_SCL=0 - Callcap - $(SolutionDir)\..\..\source;%(AdditionalIncludeDirectories) - - - true - false - xapilib.lib;%(IgnoreSpecificDefaultLibraries) - true - - - - - Level3 - NotUsing - Full - true - false - true - ProgramDatabase - Fastcap - Size - false - MultiThreaded - NDEBUG;_XBOX;PROFILE;FASTCAP;_LIB;%(PreprocessorDefinitions);__LIBRETRO__;NST_MSVC_OPTIMIZE;NST_NO_ZLIB;_SECURE_SCL=0 - $(SolutionDir)\..\..\source;%(AdditionalIncludeDirectories) - - - true - false - true - - - - - Level3 - NotUsing - Full - true - true - ProgramDatabase - Size - false - false - MultiThreaded - NDEBUG;_XBOX;_LIB;%(PreprocessorDefinitions);NST_NO_ZLIB;__LIBRETRO__;_SECURE_SCL=0 - $(SolutionDir)\..\..\source;%(AdditionalIncludeDirectories) - - - true - true - true - - - - - Level3 - NotUsing - Full - true - true - ProgramDatabase - Size - false - false - MultiThreaded - NDEBUG;_XBOX;LTCG;_LIB;%(PreprocessorDefinitions);__LIBRETRO__;NST_NO_ZLIB;_SECURE_SCL=0 - $(SolutionDir)\..\..\source;%(AdditionalIncludeDirectories) - - - true - true - true - - - - - - diff -Nru nestopia-1.48/libretro/msvc/msvc-2010-360/msvc-2010-360.vcxproj.filters nestopia-1.49/libretro/msvc/msvc-2010-360/msvc-2010-360.vcxproj.filters --- nestopia-1.48/libretro/msvc/msvc-2010-360/msvc-2010-360.vcxproj.filters 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2010-360/msvc-2010-360.vcxproj.filters 1970-01-01 00:00:00.000000000 +0000 @@ -1,882 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {bb2769c3-f85a-46ed-b7fa-9b479cacb927} - - - {cfd4b486-09df-4d1c-8ae5-d39d256c047a} - - - {f3d53a31-83d2-40ac-8c5d-ad9324f3d392} - - - {89661cd6-755f-4ecd-89a3-ac7caf2d908c} - - - {21634da5-491c-4dd3-b53b-cc17f64c07e2} - - - {763265c6-4c2c-4a36-9561-d7bc02c13c07} - - - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\board - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\input - - - Source Files\core\vssystem - - - Source Files\core\vssystem - - - Source Files\core\vssystem - - - Source Files\core\vssystem - - - Source Files\libretro - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - Source Files\core\api - - - diff -Nru nestopia-1.48/libretro/msvc/msvc-2010-360.bat nestopia-1.49/libretro/msvc/msvc-2010-360.bat --- nestopia-1.48/libretro/msvc/msvc-2010-360.bat 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2010-360.bat 1970-01-01 00:00:00.000000000 +0000 @@ -1,124 +0,0 @@ -@echo off - -@echo Setting environment for using Microsoft Visual Studio 2010 x86 tools. - -@call :GetVSCommonToolsDir -@if "%VS100COMNTOOLS%"=="" goto error_no_VS100COMNTOOLSDIR - -@call "%VS100COMNTOOLS%VCVarsQueryRegistry.bat" 32bit No64bit - -@if "%VSINSTALLDIR%"=="" goto error_no_VSINSTALLDIR -@if "%FrameworkDir32%"=="" goto error_no_FrameworkDIR32 -@if "%FrameworkVersion32%"=="" goto error_no_FrameworkVer32 -@if "%Framework35Version%"=="" goto error_no_Framework35Version - -@set FrameworkDir=%FrameworkDir32% -@set FrameworkVersion=%FrameworkVersion32% - -@if not "%WindowsSdkDir%" == "" ( - @set "PATH=%WindowsSdkDir%bin\NETFX 4.0 Tools;%WindowsSdkDir%bin;%PATH%" - @set "INCLUDE=%WindowsSdkDir%include;%INCLUDE%" - @set "LIB=%WindowsSdkDir%lib;%LIB%" -) - -@rem -@rem Root of Visual Studio IDE installed files. -@rem -@set DevEnvDir=%VSINSTALLDIR%Common7\IDE\ - -@rem PATH -@rem ---- -@if exist "%VSINSTALLDIR%Team Tools\Performance Tools" ( - @set "PATH=%VSINSTALLDIR%Team Tools\Performance Tools;%PATH%" -) -@if exist "%ProgramFiles%\HTML Help Workshop" set PATH=%ProgramFiles%\HTML Help Workshop;%PATH% -@if exist "%ProgramFiles(x86)%\HTML Help Workshop" set PATH=%ProgramFiles(x86)%\HTML Help Workshop;%PATH% -@if exist "%VCINSTALLDIR%VCPackages" set PATH=%VCINSTALLDIR%VCPackages;%PATH% -@set PATH=%FrameworkDir%%Framework35Version%;%PATH% -@set PATH=%FrameworkDir%%FrameworkVersion%;%PATH% -@set PATH=%VSINSTALLDIR%Common7\Tools;%PATH% -@if exist "%VCINSTALLDIR%BIN" set PATH=%VCINSTALLDIR%BIN;%PATH% -@set PATH=%DevEnvDir%;%PATH% - -@if exist "%VSINSTALLDIR%VSTSDB\Deploy" ( - @set "PATH=%VSINSTALLDIR%VSTSDB\Deploy;%PATH%" -) - -@if not "%FSHARPINSTALLDIR%" == "" ( - @set "PATH=%FSHARPINSTALLDIR%;%PATH%" -) - -@rem INCLUDE -@rem ------- -@if exist "%VCINSTALLDIR%ATLMFC\INCLUDE" set INCLUDE=%VCINSTALLDIR%ATLMFC\INCLUDE;%INCLUDE% -@if exist "%VCINSTALLDIR%INCLUDE" set INCLUDE=%VCINSTALLDIR%INCLUDE;%INCLUDE% - -@rem LIB -@rem --- -@if exist "%VCINSTALLDIR%ATLMFC\LIB" set LIB=%VCINSTALLDIR%ATLMFC\LIB;%LIB% -@if exist "%VCINSTALLDIR%LIB" set LIB=%VCINSTALLDIR%LIB;%LIB% - -@rem LIBPATH -@rem ------- -@if exist "%VCINSTALLDIR%ATLMFC\LIB" set LIBPATH=%VCINSTALLDIR%ATLMFC\LIB;%LIBPATH% -@if exist "%VCINSTALLDIR%LIB" set LIBPATH=%VCINSTALLDIR%LIB;%LIBPATH% -@set LIBPATH=%FrameworkDir%%Framework35Version%;%LIBPATH% -@set LIBPATH=%FrameworkDir%%FrameworkVersion%;%LIBPATH% - -@goto end - -@REM ----------------------------------------------------------------------- -:GetVSCommonToolsDir -@set VS100COMNTOOLS= -@call :GetVSCommonToolsDirHelper32 HKLM > nul 2>&1 -@if errorlevel 1 call :GetVSCommonToolsDirHelper32 HKCU > nul 2>&1 -@if errorlevel 1 call :GetVSCommonToolsDirHelper64 HKLM > nul 2>&1 -@if errorlevel 1 call :GetVSCommonToolsDirHelper64 HKCU > nul 2>&1 -@exit /B 0 - -:GetVSCommonToolsDirHelper32 -@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO ( - @if "%%i"=="10.0" ( - @SET "VS100COMNTOOLS=%%k" - ) -) -@if "%VS100COMNTOOLS%"=="" exit /B 1 -@SET "VS100COMNTOOLS=%VS100COMNTOOLS%Common7\Tools\" -@exit /B 0 - -:GetVSCommonToolsDirHelper64 -@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO ( - @if "%%i"=="10.0" ( - @SET "VS100COMNTOOLS=%%k" - ) -) -@if "%VS100COMNTOOLS%"=="" exit /B 1 -@SET "VS100COMNTOOLS=%VS100COMNTOOLS%Common7\Tools\" -@exit /B 0 - -@REM ----------------------------------------------------------------------- -:error_no_VS100COMNTOOLSDIR -@echo ERROR: Cannot determine the location of the VS Common Tools folder. -@goto end - -:error_no_VSINSTALLDIR -@echo ERROR: Cannot determine the location of the VS installation. -@goto end - -:error_no_FrameworkDIR32 -@echo ERROR: Cannot determine the location of the .NET Framework 32bit installation. -@goto end - -:error_no_FrameworkVer32 -@echo ERROR: Cannot determine the version of the .NET Framework 32bit installation. -@goto end - -:error_no_Framework35Version -@echo ERROR: Cannot determine the .NET Framework 3.5 version. -@goto end - -:end - -msbuild msvc-2010-360.sln /p:Configuration=Release_LTCG /target:clean -msbuild msvc-2010-360.sln /p:Configuration=Release_LTCG -exit diff -Nru nestopia-1.48/libretro/msvc/msvc-2010-360.sln nestopia-1.49/libretro/msvc/msvc-2010-360.sln --- nestopia-1.48/libretro/msvc/msvc-2010-360.sln 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2010-360.sln 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "msvc-2010-360", "msvc-2010-360\msvc-2010-360.vcxproj", "{C4D4209C-05D5-404F-8925-BD7ABA58D686}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - CodeAnalysis|Xbox 360 = CodeAnalysis|Xbox 360 - Debug|Xbox 360 = Debug|Xbox 360 - Profile_FastCap|Xbox 360 = Profile_FastCap|Xbox 360 - Profile|Xbox 360 = Profile|Xbox 360 - Release_LTCG|Xbox 360 = Release_LTCG|Xbox 360 - Release|Xbox 360 = Release|Xbox 360 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.CodeAnalysis|Xbox 360.ActiveCfg = CodeAnalysis|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.CodeAnalysis|Xbox 360.Build.0 = CodeAnalysis|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Debug|Xbox 360.ActiveCfg = Debug|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Debug|Xbox 360.Build.0 = Debug|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Profile_FastCap|Xbox 360.ActiveCfg = Profile_FastCap|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Profile_FastCap|Xbox 360.Build.0 = Profile_FastCap|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Profile|Xbox 360.ActiveCfg = Profile|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Profile|Xbox 360.Build.0 = Profile|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Release_LTCG|Xbox 360.ActiveCfg = Release_LTCG|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Release_LTCG|Xbox 360.Build.0 = Release_LTCG|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Release|Xbox 360.ActiveCfg = Release|Xbox 360 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Release|Xbox 360.Build.0 = Release|Xbox 360 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff -Nru nestopia-1.48/libretro/msvc/msvc-2010.bat nestopia-1.49/libretro/msvc/msvc-2010.bat --- nestopia-1.48/libretro/msvc/msvc-2010.bat 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2010.bat 1970-01-01 00:00:00.000000000 +0000 @@ -1,124 +0,0 @@ -@echo off - -@echo Setting environment for using Microsoft Visual Studio 2010 x86 tools. - -@call :GetVSCommonToolsDir -@if "%VS100COMNTOOLS%"=="" goto error_no_VS100COMNTOOLSDIR - -@call "%VS100COMNTOOLS%VCVarsQueryRegistry.bat" 32bit No64bit - -@if "%VSINSTALLDIR%"=="" goto error_no_VSINSTALLDIR -@if "%FrameworkDir32%"=="" goto error_no_FrameworkDIR32 -@if "%FrameworkVersion32%"=="" goto error_no_FrameworkVer32 -@if "%Framework35Version%"=="" goto error_no_Framework35Version - -@set FrameworkDir=%FrameworkDir32% -@set FrameworkVersion=%FrameworkVersion32% - -@if not "%WindowsSdkDir%" == "" ( - @set "PATH=%WindowsSdkDir%bin\NETFX 4.0 Tools;%WindowsSdkDir%bin;%PATH%" - @set "INCLUDE=%WindowsSdkDir%include;%INCLUDE%" - @set "LIB=%WindowsSdkDir%lib;%LIB%" -) - -@rem -@rem Root of Visual Studio IDE installed files. -@rem -@set DevEnvDir=%VSINSTALLDIR%Common7\IDE\ - -@rem PATH -@rem ---- -@if exist "%VSINSTALLDIR%Team Tools\Performance Tools" ( - @set "PATH=%VSINSTALLDIR%Team Tools\Performance Tools;%PATH%" -) -@if exist "%ProgramFiles%\HTML Help Workshop" set PATH=%ProgramFiles%\HTML Help Workshop;%PATH% -@if exist "%ProgramFiles(x86)%\HTML Help Workshop" set PATH=%ProgramFiles(x86)%\HTML Help Workshop;%PATH% -@if exist "%VCINSTALLDIR%VCPackages" set PATH=%VCINSTALLDIR%VCPackages;%PATH% -@set PATH=%FrameworkDir%%Framework35Version%;%PATH% -@set PATH=%FrameworkDir%%FrameworkVersion%;%PATH% -@set PATH=%VSINSTALLDIR%Common7\Tools;%PATH% -@if exist "%VCINSTALLDIR%BIN" set PATH=%VCINSTALLDIR%BIN;%PATH% -@set PATH=%DevEnvDir%;%PATH% - -@if exist "%VSINSTALLDIR%VSTSDB\Deploy" ( - @set "PATH=%VSINSTALLDIR%VSTSDB\Deploy;%PATH%" -) - -@if not "%FSHARPINSTALLDIR%" == "" ( - @set "PATH=%FSHARPINSTALLDIR%;%PATH%" -) - -@rem INCLUDE -@rem ------- -@if exist "%VCINSTALLDIR%ATLMFC\INCLUDE" set INCLUDE=%VCINSTALLDIR%ATLMFC\INCLUDE;%INCLUDE% -@if exist "%VCINSTALLDIR%INCLUDE" set INCLUDE=%VCINSTALLDIR%INCLUDE;%INCLUDE% - -@rem LIB -@rem --- -@if exist "%VCINSTALLDIR%ATLMFC\LIB" set LIB=%VCINSTALLDIR%ATLMFC\LIB;%LIB% -@if exist "%VCINSTALLDIR%LIB" set LIB=%VCINSTALLDIR%LIB;%LIB% - -@rem LIBPATH -@rem ------- -@if exist "%VCINSTALLDIR%ATLMFC\LIB" set LIBPATH=%VCINSTALLDIR%ATLMFC\LIB;%LIBPATH% -@if exist "%VCINSTALLDIR%LIB" set LIBPATH=%VCINSTALLDIR%LIB;%LIBPATH% -@set LIBPATH=%FrameworkDir%%Framework35Version%;%LIBPATH% -@set LIBPATH=%FrameworkDir%%FrameworkVersion%;%LIBPATH% - -@goto end - -@REM ----------------------------------------------------------------------- -:GetVSCommonToolsDir -@set VS100COMNTOOLS= -@call :GetVSCommonToolsDirHelper32 HKLM > nul 2>&1 -@if errorlevel 1 call :GetVSCommonToolsDirHelper32 HKCU > nul 2>&1 -@if errorlevel 1 call :GetVSCommonToolsDirHelper64 HKLM > nul 2>&1 -@if errorlevel 1 call :GetVSCommonToolsDirHelper64 HKCU > nul 2>&1 -@exit /B 0 - -:GetVSCommonToolsDirHelper32 -@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO ( - @if "%%i"=="10.0" ( - @SET "VS100COMNTOOLS=%%k" - ) -) -@if "%VS100COMNTOOLS%"=="" exit /B 1 -@SET "VS100COMNTOOLS=%VS100COMNTOOLS%Common7\Tools\" -@exit /B 0 - -:GetVSCommonToolsDirHelper64 -@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO ( - @if "%%i"=="10.0" ( - @SET "VS100COMNTOOLS=%%k" - ) -) -@if "%VS100COMNTOOLS%"=="" exit /B 1 -@SET "VS100COMNTOOLS=%VS100COMNTOOLS%Common7\Tools\" -@exit /B 0 - -@REM ----------------------------------------------------------------------- -:error_no_VS100COMNTOOLSDIR -@echo ERROR: Cannot determine the location of the VS Common Tools folder. -@goto end - -:error_no_VSINSTALLDIR -@echo ERROR: Cannot determine the location of the VS installation. -@goto end - -:error_no_FrameworkDIR32 -@echo ERROR: Cannot determine the location of the .NET Framework 32bit installation. -@goto end - -:error_no_FrameworkVer32 -@echo ERROR: Cannot determine the version of the .NET Framework 32bit installation. -@goto end - -:error_no_Framework35Version -@echo ERROR: Cannot determine the .NET Framework 3.5 version. -@goto end - -:end - -msbuild msvc-2010.sln /p:Configuration=Release /target:clean -msbuild msvc-2010.sln /p:Configuration=Release -exit diff -Nru nestopia-1.48/libretro/msvc/msvc-2010.sln nestopia-1.49/libretro/msvc/msvc-2010.sln --- nestopia-1.48/libretro/msvc/msvc-2010.sln 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/libretro/msvc/msvc-2010.sln 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "msvc-2010", "msvc-2010\msvc-2010.vcxproj", "{C4D4209C-05D5-404F-8925-BD7ABA58D686}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Debug|Win32.ActiveCfg = Debug|Win32 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Debug|Win32.Build.0 = Debug|Win32 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Release|Win32.ActiveCfg = Release|Win32 - {C4D4209C-05D5-404F-8925-BD7ABA58D686}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff -Nru nestopia-1.48/Makefile.am nestopia-1.49/Makefile.am --- nestopia-1.48/Makefile.am 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/Makefile.am 2018-06-24 23:26:58.000000000 +0000 @@ -2,12 +2,14 @@ # Definitions # ############### bin_PROGRAMS = nestopia -nestopia_SOURCES = source/unix/main.cpp EXTRA_DIST = doc nestopia_CPPFLAGS = \ -I$(top_srcdir)/source \ + -I$(top_srcdir)/source/common \ + -I$(top_srcdir)/source/gtkui \ + -I$(top_srcdir)/source/sdl \ -DDATADIR=\"$(datadir)/nestopia\" \ -DDATAROOTDIR=\"$(datarootdir)\" \ -DNST_PRAGMA_ONCE \ @@ -19,7 +21,6 @@ nestopia_LDADD = \ $(ZLIB_LIBS) \ $(LIBARCHIVE_LIBS) \ - $(LIBAO_LIBS) \ $(SDL2_LIBS) \ $(LIBEPOXY_LIBS) @@ -28,6 +29,16 @@ nestopia_LDADD += $(GTK3_LIBS) endif +if ENABLE_LIBAO +nestopia_CPPFLAGS += -D_LIBAO $(LIBAO_CFLAGS) +nestopia_LDADD += $(LIBAO_LIBS) +endif + +if ENABLE_JACK +nestopia_CPPFLAGS += -D_JACK $(JACK_CFLAGS) +nestopia_LDADD += $(JACK_LIBS) +endif + ################ # Installation # ################ @@ -37,28 +48,28 @@ # freedesktop.org-specific files desktopdir = $(datarootdir)/applications -dist_desktop_DATA = source/unix/icons/nestopia.desktop +dist_desktop_DATA = icons/nestopia.desktop icon32dir = $(datarootdir)/icons/hicolor/32x32/apps -dist_icon32_DATA = source/unix/icons/32/nestopia.png +dist_icon32_DATA = icons/32/nestopia.png icon48dir = $(datarootdir)/icons/hicolor/48x48/apps -dist_icon48_DATA = source/unix/icons/48/nestopia.png +dist_icon48_DATA = icons/48/nestopia.png icon64dir = $(datarootdir)/icons/hicolor/64x64/apps -dist_icon64_DATA = source/unix/icons/64/nestopia.png +dist_icon64_DATA = icons/64/nestopia.png icon96dir = $(datarootdir)/icons/hicolor/96x96/apps -dist_icon96_DATA = source/unix/icons/96/nestopia.png +dist_icon96_DATA = icons/96/nestopia.png icon128dir = $(datarootdir)/icons/hicolor/128x128/apps -dist_icon128_DATA = source/unix/icons/128/nestopia.png +dist_icon128_DATA = icons/128/nestopia.png iconsvgdir = $(datarootdir)/icons/hicolor/scalable/apps -dist_iconsvg_DATA = source/unix/icons/svg/nestopia.svg source/unix/icons/svg/nespad.svg +dist_iconsvg_DATA = icons/svg/nestopia.svg icons/svg/nespad.svg # documentation -dist_doc_DATA = AUTHORS ChangeLog README.md README.unix +dist_doc_DATA = AUTHORS ChangeLog README.md dist_html_DATA = readme.html ##################### @@ -71,7 +82,7 @@ source/core/NstSoundRenderer.inl \ source/nes_ntsc/nes_ntsc.inl -nestopia_SOURCES += \ +nestopia_SOURCES = \ source/core/NstTrackerMovie.hpp \ source/core/NstFile.hpp \ source/core/NstAssert.cpp \ @@ -536,6 +547,7 @@ source/core/board/NstBoardBmcFamily4646B.cpp \ source/core/board/NstBoardBtlT230.cpp \ source/core/board/NstBoardBmc1200in1.hpp \ + source/core/board/NstBoardMagicKidGoogoo.cpp \ source/core/board/NstBoardMagicSeries.cpp \ source/core/board/NstBoardSunsoft2.hpp \ source/core/board/NstBoardBmcGoldenCard6in1.hpp \ @@ -684,42 +696,59 @@ source/nes_ntsc/nes_ntsc_impl.h \ source/nes_ntsc/nes_ntsc_config.h \ source/nes_ntsc/nes_ntsc.h \ - source/nes_ntsc/demo_impl.h \ - source/unix/input.cpp \ - source/unix/ini.cpp \ - source/unix/config.h \ - source/unix/png.cpp \ - source/unix/png.h \ - source/unix/config.cpp \ - source/unix/cheats.h \ - source/unix/cursor.h \ - source/unix/audio.cpp \ - source/unix/cli.h \ - source/unix/audio.h \ - source/unix/video.h \ - source/unix/cli.cpp \ - source/unix/cursor.cpp \ - source/unix/ini.h \ - source/unix/font.h \ - source/unix/video.cpp \ - source/unix/main.h \ - source/unix/input.h \ - source/unix/cheats.cpp + source/nes_ntsc/demo_impl.h + +nestopia_SOURCES += \ + source/common/nstcommon.cpp \ + source/common/nstcommon.h \ + source/common/cheats.cpp \ + source/common/cheats.h \ + source/common/cli.cpp \ + source/common/cli.h \ + source/common/config.cpp \ + source/common/config.h \ + source/common/video.cpp \ + source/common/video.h \ + source/common/input.cpp \ + source/common/input.h \ + source/common/samples.cpp \ + source/common/samples.h \ + source/common/font.h \ + source/common/ini.cpp \ + source/common/ini.h \ + source/common/png.cpp \ + source/common/png.h + +nestopia_SOURCES += \ + source/sdl/audio.cpp \ + source/sdl/audio.h \ + source/sdl/sdlinput.cpp \ + source/sdl/sdlinput.h \ + source/sdl/cursor.cpp \ + source/sdl/cursor.h \ + source/sdl/sdlvideo.cpp \ + source/sdl/sdlvideo.h if ENABLE_GUI nestopia_SOURCES += \ - source/unix/gtkui/gtkui_config.h \ - source/unix/gtkui/gtkui_archive.h \ - source/unix/gtkui/gtkui_cheats.cpp \ - source/unix/gtkui/gtkui_callbacks.h \ - source/unix/gtkui/gtkui_callbacks.cpp \ - source/unix/gtkui/gtkui_dialogs.cpp \ - source/unix/gtkui/gtkui_cheats.h \ - source/unix/gtkui/gtkui_dialogs.h \ - source/unix/gtkui/gtkui_archive.cpp \ - source/unix/gtkui/gtkui.cpp \ - source/unix/gtkui/gtkui.h \ - source/unix/gtkui/gtkui_config.cpp + source/gtkui/gtkui_config.h \ + source/gtkui/gtkui_archive.h \ + source/gtkui/gtkui_cheats.cpp \ + source/gtkui/gtkui_callbacks.h \ + source/gtkui/gtkui_callbacks.cpp \ + source/gtkui/gtkui_dialogs.cpp \ + source/gtkui/gtkui_cheats.h \ + source/gtkui/gtkui_dialogs.h \ + source/gtkui/gtkui_archive.cpp \ + source/gtkui/gtkui.cpp \ + source/gtkui/gtkui.h \ + source/gtkui/gtkui_input.cpp \ + source/gtkui/gtkui_input.h \ + source/gtkui/gtkui_config.cpp +else +nestopia_SOURCES += \ + source/sdl/sdlmain.cpp \ + source/sdl/sdlmain.h endif # install full HTML suite diff -Nru nestopia-1.48/README.md nestopia-1.49/README.md --- nestopia-1.48/README.md 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/README.md 2018-06-24 23:26:58.000000000 +0000 @@ -1,3 +1,6 @@ +[![Build Status](https://travis-ci.org/libretro/nestopia.svg?branch=master)](https://travis-ci.org/libretro/nestopia) +[![Build status](https://ci.appveyor.com/api/projects/status/wcs7u48485ma8mm3/branch/master?svg=true)](https://ci.appveyor.com/project/bparker06/nestopia/branch/master) + This project is a fork of the original Nestopia source code, plus the Linux port. The purpose of the project is to enhance the original, and ensure it continues to work on modern operating systems. @@ -27,21 +30,6 @@ export PKG_CONFIG_PATH=/usr/local/opt/libarchive/lib/pkgconfig/ ./configure --disable-gui ``` - -## Building with CMake -In order to build with CMake: -``` -mkdir BUILD -cd BUILD -cmake -DCMAKE_INSTALL_PREFIX= .. -make -j -``` -optionally: -``` -make install -``` -The CMake build system can also be used with Ninja by adding `-GNinja` to the `cmake` line. - In order to bootstrap the Autotools you will need: 1. **Autoconf**; latest 2.69 release (http://www.gnu.org/software/autoconf/) diff -Nru nestopia-1.48/README.unix nestopia-1.49/README.unix --- nestopia-1.48/README.unix 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/README.unix 1970-01-01 00:00:00.000000000 +0000 @@ -1,95 +0,0 @@ -Nestopia is a portable open source NES/Famicom emulator written in C++. -It is designed to be as accurate as possible and supports a large number -of peripherals. - -Nestopia UE (Undead Edition) is a fork of the original source code, with -enhancements from members of the emulation community. - -Compiling -========= - -Linux: - -* Make sure you have the proper development libraries installed. - In Debian: - apt-get install libglew-dev libsdl2-dev libgtk-3-dev libarchive-dev libao-dev - -* cd to the nestopia source directory: - mkdir build && cd build && cmake .. && make - -* Install globally and add menu entries: - sudo make install - -Free/Open/NetBSD: - -* Make sure you have GNU make and all dependencies installed from ports, - pkgsrc or binary packages. Also make sure to have xdg-utils installed. - -* cd to the nestopia source directory: - gmake - -* Install globally and add menu entries: - sudo gmake install - -Modes -===== -* CLI mode has a command line interface only. - -* GUI mode has a GTK+ GUI, and is *nix only. - -* CLI mode should work on any platform, and GUI builds can be disabled - by modifying the Makefile accordingly. Comment lines 32-42 to build - a CLI-only binary. Binaries with support for a GUI can still be run - in CLI mode. - -Post-Installation -================= - -* Copy the Famicom Disk System rom (not included) to ~/.nestopia: - cp disksys.rom ~/.nestopia/disksys.rom - -Configuration -============= -* CLI mode can only be configured by editing the config files or passing - command line arguments. - -* GUI mode can be configured by editing config files, passing arguments, - or from the Configuration window. - -* Config files: ~/.nestopia/nestopia.conf and ~/.nestopia/input.conf - -Patching -======== - -* For soft-patching to work, the patch must be in the same directory as - the rom, and the filename must be exactly the same as the rom - filename, but with the .ips extension. - -Hardcoded Keys -============== - -Esc = Exit (CLI mode) - -` = Alternate Speed (Fast-forward) - -F1, F2 = Insert Coins -F3 = Flip FDS Disk -F4 = Switch FDS Disk -F5 = Quick Save (slot 1) -F6 = Quick Save (slot 2) -F7 = Quick Load (slot 1) -F8 = Quick Load (slot 2) -F9 = Screenshot -F12 = Reset - -Backspace = Rewind -\ = Stop Rewinding - -F = Toggle Fullscreen -T = Toggle Filters -G = Toggle Scale factor - -Copyright -========= - -This program is licensed under the GNU GPLv2. For details, read COPYING. diff -Nru nestopia-1.48/source/common/cheats.cpp nestopia-1.49/source/common/cheats.cpp --- nestopia-1.48/source/common/cheats.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/cheats.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,187 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2018 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include + +#include "cheats.h" + +extern Emulator emulator; + +void nst_cheats_init(const char *cheatpath) { + // Initialize cheat engine + Cheats cheats(emulator); + Xml xml; + + cheats.ClearCodes(); + + std::ifstream cheatfile(cheatpath, std::ifstream::in|std::ifstream::binary); + + if (cheatfile.is_open()) { + xml.Read(cheatfile); + + if (xml.GetRoot().IsType(L"cheats")) { + + Xml::Node root(xml.GetRoot()); + Xml::Node node(root.GetFirstChild()); + + for (int i = 0; i < root.NumChildren(L"cheat"); i++) { + + if (node.GetAttribute(L"enabled").IsValue(L"1")) { + + if (node.GetChild(L"genie")) { // Game Genie + nst_cheats_code_gg_add(node.GetChild(L"genie").GetValue()); + } + + else if (node.GetChild(L"rocky")) { // Pro Action Rocky + nst_cheats_code_par_add(node.GetChild(L"rocky").GetValue()); + } + + else if (node.GetChild(L"address")) { // Raw + nst_cheats_code_raw_add(node); + } + + //fprintf(stderr, "Cheat: %ls\n", node.GetChild(L"description").GetValue()); + } + node = node.GetNextSibling(); + } + } + cheatfile.close(); + } +} + +/*void nst_cheats_list() { + // List the active cheats + Cheats cheats(emulator); + Cheats::Code code; + + char gg[9]; + + for (int i = 0; i < cheats.NumCodes(); i++) { + cheats.GetCode(i, code); + cheats.GameGenieEncode(code, gg); + + fprintf(stderr, "Cheat: %s\n", gg); + } +}*/ + +void nst_cheats_code_gg_add(const wchar_t *data) { + // Add a Game Genie code + Cheats cheats(emulator); + Cheats::Code code; + + char gg[9]; + wcstombs(gg, data, sizeof(gg)); + + cheats.GameGenieDecode(gg, code); + cheats.SetCode(code); +} + +void nst_cheats_code_par_add(const wchar_t *data) { + // Add a Pro Action Rocky code + Cheats cheats(emulator); + Cheats::Code code; + + char par[9]; + wcstombs(par, data, sizeof(par)); + + cheats.ProActionRockyDecode(par, code); + cheats.SetCode(code); +} + +void nst_cheats_code_raw_add(Xml::Node node) { + // Add a Raw code + Cheats cheats(emulator); + Cheats::Code code; + + code.useCompare = false; + + code.address = node.GetChild(L"address").GetUnsignedValue(); + if (node.GetChild(L"value")) { + code.value = node.GetChild(L"value").GetUnsignedValue(); + } + if (node.GetChild(L"compare")) { + code.compare = node.GetChild(L"compare").GetUnsignedValue(); + code.useCompare = true; + } + cheats.SetCode(code); +} + +// DIP Switches +void nst_dip_handle(const char *dippath) { + // Handle the DIP switch file + DipSwitches dipswitches(emulator); + Xml xml; + + std::ifstream dipfile(dippath, std::ifstream::in|std::ifstream::binary); + + if (dipfile.is_open()) { + xml.Read(dipfile); + + if (xml.GetRoot().IsType(L"dipswitches")) { + Xml::Node root(xml.GetRoot()); + Xml::Node node(root.GetFirstChild()); + + for (int i = 0; i < root.NumChildren(L"dip"); i++) { + + if (node.GetChild(L"value")) { + dipswitches.SetValue(i, node.GetChild(L"value").GetUnsignedValue()); + } + node = node.GetNextSibling(); + } + } + dipfile.close(); + } + else { + Xml::Node root(xml.GetRoot()); + + root = xml.Create(L"dipswitches"); + root.AddAttribute(L"version", L"1.0"); + + wchar_t wbuf[32]; + char buf[2]; + + int numdips = dipswitches.NumDips(); + + if (numdips > 0) { + for (int i = 0; i < numdips; i++) { + Xml::Node node(root.AddChild(L"dip")); + + mbstowcs(wbuf, dipswitches.GetDipName(i), sizeof(wbuf)); + node.AddChild(L"description", wbuf); + + snprintf(buf, sizeof(buf), "%d", dipswitches.GetValue(i)); + mbstowcs(wbuf, buf, sizeof(buf)); + node.AddChild(L"value", wbuf); + } + } + + std::ofstream dipout(dippath, std::ifstream::out|std::ifstream::binary); + + if (dipout.is_open()) { + xml.Write(root, dipout); + } + + dipout.close(); + } +} diff -Nru nestopia-1.48/source/common/cheats.h nestopia-1.49/source/common/cheats.h --- nestopia-1.48/source/common/cheats.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/cheats.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,22 @@ +#ifndef _CHEATS_H_ +#define _CHEATS_H_ + +#include "core/api/NstApiEmulator.hpp" +#include "core/api/NstApiCheats.hpp" +#include "core/api/NstApiDipSwitches.hpp" +#include "core/NstStream.hpp" +#include "core/NstXml.hpp" + +using namespace Nes::Api; + +typedef Nes::Core::Xml Xml; + +void nst_cheats_init(const char *cheatpath); +void nst_cheats_code_gg_add(const wchar_t *data); +void nst_cheats_code_par_add(const wchar_t *data); +void nst_cheats_code_raw_add(Xml::Node node); + +// DIP Switches +void nst_dip_handle(const char *dippath); + +#endif diff -Nru nestopia-1.48/source/common/cli.cpp nestopia-1.49/source/common/cli.cpp --- nestopia-1.48/source/common/cli.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/cli.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,179 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2016 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include + +#include "cli.h" +#include "config.h" + +void cli_error(const char *message) { + cli_show_usage(); + fprintf(stderr, "%s\n", message); + exit(1); +} + +void cli_show_usage() { + printf("Usage: nestopia [options] [FILE]\n"); + printf("\nOptions:\n"); + //printf(" -d, --disablegui Disable GTK+ GUI\n"); + //printf(" -e, --enablegui Enable GTK+ GUI\n\n"); + printf(" -f, --fullscreen Fullscreen mode\n"); + printf(" -w, --window Window mode\n\n"); + printf(" -l, --filter Video Filter\n"); + printf(" (0=None, 1=NTSC, 2=xBR, 3=HqX, 4=2xSaI, 5=ScaleX)\n\n"); + printf(" -m, --maskoverscan Mask overscan areas\n"); + printf(" -n, --no-maskoverscan Disable overscan masking\n\n"); + printf(" -o, --stretchfs Stretch to native resolution in fullscreen mode\n"); + printf(" -p, --preserveaspect Preserve aspect ratio in fullscreen mode\n\n"); + printf(" -s, --scalefactor Video scale factor (1-4)\n\n"); + printf(" -t, --tvaspect TV aspect ratio\n"); + printf(" -r, --no-tvaspect Regular aspect ratio\n\n"); + printf(" -u, --unlimitedsprites Remove sprite limit\n"); + printf(" -q, --spritelimit Enable sprite limit\n\n"); + printf(" -v, --version Show version information\n\n"); + printf("More options can be set in the configuration file.\n"); + printf("Options are saved, and do not need to be set on future invocations.\n\n"); +} + +void cli_show_version() { + printf("Nestopia UE %s\n", VERSION); +} + +void cli_handle_command(int argc, char *argv[]) { + int c; + int optint; + + while (1) { + static struct option long_options[] = { + {"disablegui", no_argument, 0, 'd'}, + {"enablegui", no_argument, 0, 'e'}, + {"fullscreen", no_argument, 0, 'f'}, + {"window", no_argument, 0, 'w'}, + {"help", no_argument, 0, 'h'}, + {"filter", required_argument, 0, 'l'}, + {"maskoverscan", no_argument, 0, 'm'}, + {"no-maskoverscan", no_argument, 0, 'n'}, + {"stretchfs", no_argument, 0, 'o'}, + {"preserveaspect", no_argument, 0, 'p'}, + {"scalefactor", required_argument, 0, 's'}, + {"tvaspect", no_argument, 0, 't'}, + {"no-tvaspect", no_argument, 0, 'r'}, + {"unlimitedsprites", no_argument, 0, 'u'}, + {"spritelimit", no_argument, 0, 'q'}, + {"version", no_argument, 0, 'v'}, + {0, 0, 0, 0} + }; + + int option_index = 0; + + c = getopt_long(argc, argv, "defhl:mnopqrs:tuvw", + long_options, &option_index); + + if (c == -1) { break; } + + switch(c) { + /*case 'd': + conf.misc_disable_gui = true; + break; + + case 'e': + conf.misc_disable_gui = false; + break;*/ + + case 'f': + conf.video_fullscreen = true; + break; + + case 'w': + conf.video_fullscreen = false; + break; + + case 'h': + cli_show_usage(); + exit(0); + break; + + case 'l': + optint = atoi(optarg); + if (optint < 6) { + conf.video_filter = optint; + } + else { + cli_error("Error: Invalid filter"); + } + break; + + case 'm': + conf.video_unmask_overscan = false; + break; + + case 'n': + conf.video_unmask_overscan = true; + break; + + case 'o': + conf.video_stretch_aspect = true; + break; + + case 'p': + conf.video_stretch_aspect = false; + break; + + case 's': + optint = atoi(optarg); + if (optint < 5 && optint != 0) { + conf.video_scale_factor = optint; + } + else { + cli_error("Error: Invalid scale factor"); + } + break; + + case 't': + conf.video_tv_aspect = true; + break; + + case 'r': + conf.video_tv_aspect = false; + break; + + case 'u': + conf.video_unlimited_sprites = true; + break; + + case 'q': + conf.video_unlimited_sprites = false; + break; + + case 'v': + cli_show_version(); + exit(0); + break; + + default: + cli_error("Error: Invalid option"); + break; + } + } +} diff -Nru nestopia-1.48/source/common/cli.h nestopia-1.49/source/common/cli.h --- nestopia-1.48/source/common/cli.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/cli.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,4 @@ +void cli_error(const char *message); +void cli_show_usage(); +void cli_show_version(); +void cli_handle_command(int argc, char *argv[]); diff -Nru nestopia-1.48/source/common/config.cpp nestopia-1.49/source/common/config.cpp --- nestopia-1.48/source/common/config.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/config.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,279 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2016 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include + +#include "config.h" +#include "ini.h" + +settings_t conf; + +void config_file_read(const char *nstdir) { + // Read the config file + + char confpath[256]; + snprintf(confpath, sizeof(confpath), "%snestopia.conf", nstdir); + + if (ini_parse(confpath, config_match, &conf) < 0) { + fprintf(stderr, "Failed to read config file %s: Using defaults.\n", confpath); + } +} + +void config_file_write(const char *nstdir) { + // Write the config file + + char confpath[256]; + snprintf(confpath, sizeof(confpath), "%snestopia.conf", nstdir); + + FILE *fp = fopen(confpath, "w"); + if (fp != NULL) { + // Video + fprintf(fp, "; Nestopia UE Configuration File\n\n"); + fprintf(fp, "[video]\n"); + fprintf(fp, "; 0=None, 1=NTSC, 2=xBR, 3=HqX, 4=2xSaI, 5=ScaleX\n"); + fprintf(fp, "filter=%d\n\n", conf.video_filter); + fprintf(fp, "; Valid values are 1 to 8.\n"); + fprintf(fp, "scale_factor=%d\n\n", conf.video_scale_factor); + fprintf(fp, "; 0=YUV, 1=RGB, 2=Custom\n"); + fprintf(fp, "palette_mode=%d\n\n", conf.video_palette_mode); + fprintf(fp, "; 0=Consumer, 1=Canonical, 2=Alternative\n"); + fprintf(fp, "decoder=%d\n\n", conf.video_decoder); + fprintf(fp, "; Valid values are -100 to 100.\n"); + fprintf(fp, "brightness=%d\n", conf.video_brightness); + fprintf(fp, "saturation=%d\n", conf.video_saturation); + fprintf(fp, "contrast=%d\n\n", conf.video_contrast); + fprintf(fp, "; Valid values are -45 to 45.\n"); + fprintf(fp, "hue=%d\n\n", conf.video_hue); + fprintf(fp, "; 0=Composite, 1=S-Video, 2=RGB, 3=Monochrome, 4=Custom\n"); + fprintf(fp, "ntsc_mode=%d\n\n", conf.video_ntsc_mode); + fprintf(fp, "; Valid values are -100 to 100.\n"); + fprintf(fp, "ntsc_sharpness=%d\n", conf.video_ntsc_sharpness); + fprintf(fp, "ntsc_resolution=%d\n", conf.video_ntsc_resolution); + fprintf(fp, "ntsc_bleed=%d\n", conf.video_ntsc_bleed); + fprintf(fp, "ntsc_artifacts=%d\n", conf.video_ntsc_artifacts); + fprintf(fp, "ntsc_fringing=%d\n\n", conf.video_ntsc_fringing); + fprintf(fp, "; 0=None, 1=Some, 2=All\n"); + fprintf(fp, "xbr_corner_rounding=%d\n\n", conf.video_xbr_corner_rounding); + fprintf(fp, "; Valid values are 1 and 0.\n"); + fprintf(fp, "linear_filter=%d\n", conf.video_linear_filter); + fprintf(fp, "tv_aspect=%d\n", conf.video_tv_aspect); + fprintf(fp, "unmask_overscan=%d\n", conf.video_unmask_overscan); + fprintf(fp, "fullscreen=%d\n", conf.video_fullscreen); + fprintf(fp, "stretch_aspect=%d\n", conf.video_stretch_aspect); + fprintf(fp, "unlimited_sprites=%d\n", conf.video_unlimited_sprites); + fprintf(fp, "xbr_pixel_blending=%d\n", conf.video_xbr_pixel_blending); + fprintf(fp, "\n"); // End of Section + + // Audio + fprintf(fp, "[audio]\n"); + fprintf(fp, "; 0=SDL, 1=libao, 2=jack\n"); + fprintf(fp, "api=%d\n\n", conf.audio_api); + fprintf(fp, "; Valid values are 1 and 0.\n"); + fprintf(fp, "stereo=%d\n\n", conf.audio_stereo); + fprintf(fp, "; Valid values are 11025, 22050, 44100, 48000, and 96000.\n"); + fprintf(fp, "sample_rate=%d\n\n", conf.audio_sample_rate); + fprintf(fp, "; Valid values are 0 to 100.\n"); + fprintf(fp, "volume=%d\n", conf.audio_volume); + fprintf(fp, "vol_sq1=%d\n", conf.audio_vol_sq1); + fprintf(fp, "vol_sq2=%d\n", conf.audio_vol_sq2); + fprintf(fp, "vol_tri=%d\n", conf.audio_vol_tri); + fprintf(fp, "vol_noise=%d\n", conf.audio_vol_noise); + fprintf(fp, "vol_dpcm=%d\n", conf.audio_vol_dpcm); + fprintf(fp, "vol_fds=%d\n", conf.audio_vol_fds); + fprintf(fp, "vol_mmc5=%d\n", conf.audio_vol_mmc5); + fprintf(fp, "vol_vrc6=%d\n", conf.audio_vol_vrc6); + fprintf(fp, "vol_vrc7=%d\n", conf.audio_vol_vrc7); + fprintf(fp, "vol_n163=%d\n", conf.audio_vol_n163); + fprintf(fp, "vol_s5b=%d\n", conf.audio_vol_s5b); + fprintf(fp, "\n"); // End of Section + + // Timing + fprintf(fp, "[timing]\n"); + fprintf(fp, "; Base speed for NTSC in Frames per Second.\n"); + fprintf(fp, "speed=%d\n\n", conf.timing_speed); + fprintf(fp, "; Fast-Forward Speed\n"); + fprintf(fp, "ffspeed=%d\n\n", conf.timing_ffspeed); + fprintf(fp, "; Pulse turbo buttons every n frames. Minimum value is 2.\n"); + fprintf(fp, "turbopulse=%d\n\n", conf.timing_turbopulse); + fprintf(fp, "; Valid values are 1 and 0.\n"); + fprintf(fp, "vsync=%d\n", conf.timing_vsync); + fprintf(fp, "limiter=%d\n", conf.timing_limiter); + fprintf(fp, "\n"); // End of Section + + // Misc + fprintf(fp, "[misc]\n"); + fprintf(fp, "; 0=Auto, 1=NTSC, 2=PAL, 3=Famicom, 4=Dendy\n"); + fprintf(fp, "default_system=%d\n\n", conf.misc_default_system); + fprintf(fp, "; Valid values are 1 and 0.\n"); + fprintf(fp, "soft_patching=%d\n", conf.misc_soft_patching); + //fprintf(fp, "suppress_screensaver=%d\n", conf.misc_suppress_screensaver); + fprintf(fp, "genie_distortion=%d\n", conf.misc_genie_distortion); + //fprintf(fp, "disable_gui=%d\n", conf.misc_disable_gui); + fprintf(fp, "disable_cursor=%d\n", conf.misc_disable_cursor); + fprintf(fp, "disable_cursor_special=%d\n", conf.misc_disable_cursor_special); + fprintf(fp, "config_pause=%d\n", conf.misc_config_pause); + fprintf(fp, "last_folder=%s\n", conf.misc_last_folder); + fprintf(fp, "; 0=0x00, 1=0xFF, 2=Random\n"); + fprintf(fp, "power_state=%d\n", conf.misc_power_state); + fprintf(fp, "overclock=%d\n", conf.misc_overclock); + + fclose(fp); + } + else { + fprintf(stderr, "Failed to write config file %s.\n", confpath); + } +} + +void config_set_default() { + + // Video + conf.video_filter = 0; + conf.video_scale_factor = 2; + conf.video_palette_mode = 0; + conf.video_decoder = 0; + conf.video_brightness = 0; // -100 to 100 + conf.video_saturation = 0; // -100 to 100 + conf.video_contrast = 0; // -100 to 100 + conf.video_hue = 0; // -45 to 45 + conf.video_ntsc_mode = 0; + conf.video_ntsc_sharpness = 0; // -100 to 100 + conf.video_ntsc_resolution = 0; // -100 to 100 + conf.video_ntsc_bleed = 0; // -100 to 100 + conf.video_ntsc_artifacts = 0; // -100 to 100 + conf.video_ntsc_fringing = 0; // -100 to 100 + conf.video_xbr_corner_rounding = 0; + conf.video_linear_filter = false; + conf.video_tv_aspect = false; + conf.video_unmask_overscan = false; + conf.video_fullscreen = false; + conf.video_stretch_aspect = false; + conf.video_unlimited_sprites = false; + conf.video_xbr_pixel_blending = false; + + // Audio + conf.audio_api = 0; + conf.audio_stereo = false; + conf.audio_sample_rate = 48000; + conf.audio_volume = 85; + conf.audio_vol_sq1 = 85; + conf.audio_vol_sq2 = 85; + conf.audio_vol_tri = 85; + conf.audio_vol_noise = 85; + conf.audio_vol_dpcm = 85; + conf.audio_vol_fds = 85; + conf.audio_vol_mmc5 = 85; + conf.audio_vol_vrc6 = 85; + conf.audio_vol_vrc7 = 85; + conf.audio_vol_n163 = 85; + conf.audio_vol_s5b = 85; + + // Timing + conf.timing_speed = 60; + conf.timing_ffspeed = 3; + conf.timing_turbopulse = 3; + conf.timing_vsync = true; + conf.timing_limiter = true; + + // Misc + conf.misc_default_system = 0; + conf.misc_soft_patching = true; + //conf.misc_suppress_screensaver = true; + conf.misc_genie_distortion = false; + //conf.misc_disable_gui = false; + conf.misc_disable_cursor = false; + conf.misc_disable_cursor_special = false; + conf.misc_config_pause = false; + conf.misc_last_folder = NULL; + conf.misc_power_state = 0; + conf.misc_overclock = false; +} + +static int config_match(void* user, const char* section, const char* name, const char* value) { + // Match values from config file and populate live config + settings_t* pconfig = (settings_t*)user; + + // Video + if (MATCH("video", "filter")) { pconfig->video_filter = atoi(value); } + else if (MATCH("video", "scale_factor")) { pconfig->video_scale_factor = atoi(value); } + else if (MATCH("video", "palette_mode")) { pconfig->video_palette_mode = atoi(value); } + else if (MATCH("video", "decoder")) { pconfig->video_decoder = atoi(value); } + else if (MATCH("video", "brightness")) { pconfig->video_brightness = atoi(value); } + else if (MATCH("video", "saturation")) { pconfig->video_saturation = atoi(value); } + else if (MATCH("video", "contrast")) { pconfig->video_contrast = atoi(value); } + else if (MATCH("video", "hue")) { pconfig->video_hue = atoi(value); } + else if (MATCH("video", "ntsc_mode")) { pconfig->video_ntsc_mode = atoi(value); } + else if (MATCH("video", "ntsc_sharpness")) { pconfig->video_ntsc_sharpness = atoi(value); } + else if (MATCH("video", "ntsc_resolution")) { pconfig->video_ntsc_resolution = atoi(value); } + else if (MATCH("video", "ntsc_bleed")) { pconfig->video_ntsc_bleed = atoi(value); } + else if (MATCH("video", "ntsc_artifacts")) { pconfig->video_ntsc_artifacts = atoi(value); } + else if (MATCH("video", "ntsc_fringing")) { pconfig->video_ntsc_fringing = atoi(value); } + else if (MATCH("video", "xbr_corner_rounding")) { pconfig->video_xbr_corner_rounding = atoi(value); } + else if (MATCH("video", "linear_filter")) { pconfig->video_linear_filter = atoi(value); } + else if (MATCH("video", "tv_aspect")) { pconfig->video_tv_aspect = atoi(value); } + else if (MATCH("video", "unmask_overscan")) { pconfig->video_unmask_overscan = atoi(value); } + else if (MATCH("video", "fullscreen")) { pconfig->video_fullscreen = atoi(value); } + else if (MATCH("video", "stretch_aspect")) { pconfig->video_stretch_aspect = atoi(value); } + else if (MATCH("video", "unlimited_sprites")) { pconfig->video_unlimited_sprites = atoi(value); } + else if (MATCH("video", "xbr_pixel_blending")) { pconfig->video_xbr_pixel_blending = atoi(value); } + + // Audio + else if (MATCH("audio", "api")) { pconfig->audio_api = atoi(value); } + else if (MATCH("audio", "stereo")) { pconfig->audio_stereo = atoi(value); } + else if (MATCH("audio", "sample_rate")) { pconfig->audio_sample_rate = atoi(value); } + else if (MATCH("audio", "volume")) { pconfig->audio_volume = atoi(value); } + else if (MATCH("audio", "vol_sq1")) { pconfig->audio_vol_sq1 = atoi(value); } + else if (MATCH("audio", "vol_sq2")) { pconfig->audio_vol_sq2 = atoi(value); } + else if (MATCH("audio", "vol_tri")) { pconfig->audio_vol_tri = atoi(value); } + else if (MATCH("audio", "vol_noise")) { pconfig->audio_vol_noise = atoi(value); } + else if (MATCH("audio", "vol_dpcm")) { pconfig->audio_vol_dpcm = atoi(value); } + else if (MATCH("audio", "vol_fds")) { pconfig->audio_vol_fds = atoi(value); } + else if (MATCH("audio", "vol_mmc5")) { pconfig->audio_vol_mmc5 = atoi(value); } + else if (MATCH("audio", "vol_vrc6")) { pconfig->audio_vol_vrc6 = atoi(value); } + else if (MATCH("audio", "vol_vrc7")) { pconfig->audio_vol_vrc7 = atoi(value); } + else if (MATCH("audio", "vol_n163")) { pconfig->audio_vol_n163 = atoi(value); } + else if (MATCH("audio", "vol_s5b")) { pconfig->audio_vol_s5b = atoi(value); } + + // Timing + else if (MATCH("timing", "speed")) { pconfig->timing_speed = atoi(value); } + else if (MATCH("timing", "ffspeed")) { pconfig->timing_ffspeed = atoi(value); } + else if (MATCH("timing", "turbopulse")) { pconfig->timing_turbopulse = atoi(value); } + else if (MATCH("timing", "vsync")) { pconfig->timing_vsync = atoi(value); } + else if (MATCH("timing", "limiter")) { pconfig->timing_limiter = atoi(value); } + + // Misc + else if (MATCH("misc", "default_system")) { pconfig->misc_default_system = atoi(value); } + else if (MATCH("misc", "soft_patching")) { pconfig->misc_soft_patching = atoi(value); } + //else if (MATCH("misc", "suppress_screensaver")) { pconfig->misc_suppress_screensaver = atoi(value); } + else if (MATCH("misc", "genie_distortion")) { pconfig->misc_genie_distortion = atoi(value); } + //else if (MATCH("misc", "disable_gui")) { pconfig->misc_disable_gui = atoi(value); } + else if (MATCH("misc", "config_pause")) { pconfig->misc_config_pause = atoi(value); } + else if (MATCH("misc", "disable_cursor")) { pconfig->misc_disable_cursor = atoi(value); } + else if (MATCH("misc", "disable_cursor_special")) { pconfig->misc_disable_cursor_special = atoi(value); } + else if (MATCH("misc", "last_folder")) { pconfig->misc_last_folder = strdup(value); } + else if (MATCH("misc", "power_state")) { pconfig->misc_power_state = atoi(value); } + else if (MATCH("misc", "overclock")) { pconfig->misc_overclock = atoi(value); } + + else { return 0; } + return 1; +} diff -Nru nestopia-1.48/source/common/config.h nestopia-1.49/source/common/config.h --- nestopia-1.48/source/common/config.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/config.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,74 @@ +#ifndef _CONFIG_H_ +#define _CONFIG_H_ + +typedef struct { + + // Video + int video_filter; + int video_scale_factor; + int video_palette_mode; + int video_decoder; + int video_brightness; + int video_saturation; + int video_contrast; + int video_hue; + int video_ntsc_mode; + int video_ntsc_sharpness; + int video_ntsc_resolution; + int video_ntsc_bleed; + int video_ntsc_artifacts; + int video_ntsc_fringing; + int video_xbr_corner_rounding; + bool video_linear_filter; + bool video_tv_aspect; + bool video_unmask_overscan; + bool video_fullscreen; + bool video_stretch_aspect; + bool video_unlimited_sprites; + bool video_xbr_pixel_blending; + + // Audio + int audio_api; + bool audio_stereo; + int audio_sample_rate; + int audio_volume; + int audio_vol_sq1; + int audio_vol_sq2; + int audio_vol_tri; + int audio_vol_noise; + int audio_vol_dpcm; + int audio_vol_fds; + int audio_vol_mmc5; + int audio_vol_vrc6; + int audio_vol_vrc7; + int audio_vol_n163; + int audio_vol_s5b; + + // Timing + int timing_speed; + int timing_ffspeed; + int timing_turbopulse; + bool timing_vsync; + bool timing_limiter; + + // Misc + //int misc_video_region; + int misc_default_system; + bool misc_soft_patching; + //bool misc_suppress_screensaver; + bool misc_genie_distortion; + bool misc_disable_cursor; + bool misc_disable_cursor_special; + bool misc_config_pause; + char* misc_last_folder; + int misc_power_state; + bool misc_overclock; +} settings_t; + +void config_file_read(const char *nstdir); +void config_file_write(const char *nstdir); +void config_set_default(); +static int config_match(void* user, const char* section, const char* name, const char* value); + +extern settings_t conf; +#endif diff -Nru nestopia-1.48/source/common/font.h nestopia-1.49/source/common/font.h --- nestopia-1.48/source/common/font.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/font.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,99 @@ +const char *nesfont[] = { +" .. . . . . . ", // 0 +" ..+ .+ .+ . . . . . + . . +", +" ..+ .+ .+ ...... . +. + . .+ . + ", +" ..+ ++ ++ .++.++ +. + . .+. ..... ..... . + ", +" ..+ .+ .+ . +. +.+ + +.+++ +++++ . + ", +" ++ ...... . +. . . .+. .+ .. .. . + ", +" .. .++.++ . + . + +.+ + + ..+ ..+ . + ", +" ++ + + + + + .++ ++ + ", +" ..... .. ..... ..... ... ....... ..... ....... ..... ..... .... ", // 8 +"..+++.. ...+ ..+++.. ..+++.. ....+ ..++++++..+++.. ..+++..+..+++.. ..+++.. .. .. .. .. ..++.. ", +"..+ ..+ ..+ ..+ ..+ ++ ..+ ..+..+ ...... ..+ ++ ++ ..++..+ ..+..+ ..+ ..+ ..+ ..++ ..... .. ++ ..+ ", +"..+ ..+ ..+ ++ ..++ ....++..++..+ ..+++.. ...... ..++ .....++ ......+ ++ ++ .++ +++++ .+ ..++ ", +"..+ ..+ ..+ .. ++ ++.. ..+ ..+ ++ ..+..+++.. ..+ ..+++.. +++..+ .+ .+ ..++ ", +"..+ ..+ ..+ ..++ .. ..+....... .. ..+..+ ..+ ..++ ..+ ..+.. ..+ .. ..+ .. ..... ..+ ++ ", +" .....++ .... ....... .....++ +++..++ .....++ .....++ ..+ .....++ .....++ ..+ ..+ .. +++++ ..++ .. ", +" +++++ ++++ +++++++ +++++ ++ +++++ +++++ ++ +++++ +++++ ++ .++ ++ ++ ++ ", +" ... ...... .... ..... ....... ....... ..... .. .. .... ..... .. .. .. . . . .. ..... ", // 16 +" ..+.. ..+++.. ..++.. ..++.. ..++++++..++++++..+++.. ..+ ..+ ..++ +..++..+ ..++..+ .. ..+.. ..+..+++.. ", +" .++ .+ ..+ ..+..++ ++..+ .. ..+ ..+ ..+ ++..+ ..+ ..+ ..+ ..+..++ ..+ ... ...+... ..+..+ ..+", +" ..+ .. ......++..+ ..+ ..+...... ...... ..+.... .......+ ..+ ..+ ....++ ..+ .......+.... ..+..+ ..+", +" .......+..+++.. ..+ ..+ ..+..+++++ ..+++++ ..+ +..+..+++..+ ..+ ..+ ..+.. ..+ ..+.+..+..+....+..+ ..+", +" ..+++..+..+ ..+ .. .. ..+ ..++..+ ..+ ..+ ..+..+ ..+ ..+ .. ..+ ..+ .. ..+ ..+ +..+..+ ...+..+ ..+", +" ..+ ..+......++ ....++.....++ ....... ..+ .....++..+ ..+ .... ....++ ..+ .. ....... ..+ ..+..+ ..+ .....++", +" ++ ++ ++++++ ++++ +++++ +++++++ ++ +++++ ++ ++ ++++ ++++ ++ ++ +++++++ ++ ++ ++ ++ +++++ ", +"...... ..... ...... ..... ...... .. .. .. .. .. .. .. .. .. .. ...... ", // 24 +"..+++.. ..+++.. ..+++.. ..+++.. +..+++ ..+ ..+..+ ..+..+ ..+..+ ..+..+ ..+ +++..+ .. .. ", +"..+ ..+..+ ..+..+ ..+..+ ++ ..+ ..+ ..+..+ ..+..+. ..+ .. ..++..+ ..+ ..++ ..++ .. ", +"..+ ..+..+ ..+..+ ...+ ..... ..+ ..+ ..+..+ ..+..+.+..+ ...++ ....++ ..++ .++ .+ ", +"......++..+.. .+.....+++ +++.. ..+ ..+ ..+ .. ..++.......+ ..+.. ..++ ..++ .+ .+ ", +"..+++++ ..+ .. +..+... .. ..+ ..+ ..+ ..+ ..+..+ ...+...+..++ .. ..+ ..++ .. ..+ ", +"..+ ... .. ..+ ... .....++ ..+ .....++ ...++ .++ .++..+ ..+ ..+ ...... .. ..++ ....... ", +" ++ +++ ++ ++ +++ +++++ ++ +++++ +++ + + ++ ++ ++ ++++++ ++ ++ +++++++", +" .. .. .. ... .. .. ... ", // 32 +" ..+ ..+ ..+ ..+++ ..+ .. .. ..+ ..+ ", +" .++ .... ..... ..... .....+ .... ..+ ..... ..+ ++ ++ ..+ .. ..+ ... .. ..... .... ", +" + ..++.. ..++.. ..+++++ ..++..+ ..++.. ...... ..++..+ ..... .. .. ..+..++ ..+ ..+. .. ..++.. ..++.. ", +" ..+ ..+ ..+ ..+ ..+ ..+ ..+ ......+ +..+++ ..+ ..+ ..++.. ..+ ..+ ....++ ..+ ..+.+..+..+ ..+ ..+ ..+ ", +" ..+ ..+ ..+ ..+ ..+ ..+ ..+ ..+++++ ..+ .....+ ..+ ..+ ..+ ..+ ..+.. ..+ ..+.+..+..+ ..+ ..+ ..+ ", +" ... .. .....++ ..... .....+ ..... ..+ ++..+ ..+ ..+ ..+ .. ..+ ..+ .. ..+ ..+.+..+..+ ..+ ....++ ", +" +++ ++ +++++ +++++ +++++ +++++ ++ ....++ ++ ++ ++ ....++ ++ ++ ++ ++ + ++ ++ ++ ++++ ", +" .. ", // 40 +" ..+ .. .. ", +"..... ..... .. ... .... ...... .. .. .. .. .. .. .. .. .. .. ...... ..++ .. ", +"..++.. ..++..+ ... +++ ..++++ +..+++ ..+ ..+ ..+ ..+ ..+. ..+ .. ..++..+ ..+ ++..++ .++ .+ .. . ", +"..+ ..+ ..+ ..+ ..++ .... ..+ ..+ ..+ ..+ ..+ ..+.+..+ ...++ ....++ ..++ .+ .+ . +.. + ", +".....++ .....+ ..+ ++.. ..+ ..+ ..+ ....++ ..+.+..+ ..+.. ..++ ..++ .. ..+ + ++ ", +"..++++ ++..+ ..+ .....++ ... ....++ ..++ .. ..++..++ .. ..++ ...... .. ..++ ", +"..+ ... ++ +++++ +++ ++++ ++ ++ ++ ++ ++..++ ++++++ ++ ++ "}; + +const char *nesfont2[] = { +" .. .. .. .. .. .. ... .. .. .. .. ", // 0 +" .... .. .. .. .. ..... .. .. .. .. .. .. .. .. .. .. .. ", +" .... .. .. ....... .. .. .. ... .. .. .. .... .. .. ", +" .... .. .. .... .. ... .. .. .. .............. ...... .. ", +" .. ....... .. .. .. ... .. .. .... .. .. ", +" .. .. .. ..... .. .. .. .. .. .. .. .. .. .. .. .. ", +" .. .. .. .. .. ... .. .. .. .. .. . ", +" .. .. ", +" ... .. ..... ...... ... ...... .... ....... ..... ..... .. .. .... ", // 8 +" . .. ... .. .. .. .... .. .. .. .. .. .. .. .. .. .. .. .. .. .. ", +".. .. .. ... .. .. .. ...... .. .. .. .. .. .. .. .. .. ...... .. .. ", +".. .. .. .... .... .. .. .. ...... .. ..... ...... .. .. .. ", +".. .. .. .... .. ....... .. .. .. .. .. .. .. .. .. .. ", +" .. . .. ... .. .. .. .. .. .. .. .. .. .. .. .. .. .. ...... .. ", +" ... ...... ....... ..... .. ..... ..... .. ..... .... .. .. .. .. .. ", +" .. ", +" ..... ... ...... .... ..... ....... ....... ..... .. .. ...... .... .. .. .. .. .. .. .. ..... ", // 16 +".. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ... ... ... .. .. .. ", +".. .... .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ....... .... .. .. .. ", +".. .... .. .. ...... .. .. .. ...... ...... .. ... ....... .. .. .... .. ....... ....... .. .. ", +".. .... ....... .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..... .. .. . .. .. .... .. .. ", +".. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ... .. .. .. .. ... .. .. ", +" .... .. .. ...... .... ..... ....... .. ..... .. .. ...... ..... .. ... ...... .. .. .. .. ..... ", +" ", +"...... ..... ...... .... ...... .. .. .. .. .. .. .. .. .. .. ....... .... .. .... . ", // 24 +".. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ... ... .. .. ... .. .. .. ... ", +".. .. .. .. .. .. .. .. .. .. .. .. .. . .. ..... .. .. ... .. .. .. .. .. ", +".. .. .. .. .. ... ..... .. .. .. ... ... ....... ... .... ... .. .. .. .. .. ", +"...... .. .... ..... .. .. .. .. ..... ....... ..... .. ... .. .. .. ", +".. .. .. .. ... .. .. .. .. .. ... ... ... ... ... .. ... .. .. .. ", +".. .... . .. ... ..... .. ..... . .. .. .. .. .. ....... .... . .... ", +" ........", +" .. .. .. ... .. .. .. ", // 32 +" .. .. .. .. .. .. .. .. .. ", +" .. .... ..... ..... ..... .... .. ..... .. .. . .. ... .. ..... .... ", +" .. .. .. .. .. .. .. .. .. ...... .. .. ..... .. .. .. . .. .. . .. .. .. .. .. ", +" .. .. .. .. .. .. .. ...... .. .. .. .. .. .. .. .. . .. .. . .. .. .. .. .. ", +" .. .. .. .. .. .. .. .. .. ..... .. .. .. .. ..... .. .. . .. .. .. .. .. ", +" ... .. ..... ..... ..... ..... .. .. .. .. .. .. .. .. .. .. .. . .. .. .. .... ", +" .... .... ", +" .. ... .. ... ... .. ", // 40 +" .. .. .. .. .. ... . ", +" ..... ..... .. ... .... ...... .. .. .. .. .. .. .. .. .. .. ...... .. .. .. ... ", +" .. .. .. .. ... . .. .. .. .. .. .. . .. .. .. .. .. .. ... ... .. .. ", +" .. .. .. .. .. .... .. .. .. .. .. .. . .. ... . .. .. .. .. .. .. .. ", +" ..... ..... .. .. .. .. .. . . .. . .. .. .. .. .. .. .. .. .. .. ", +" .. .. .. ..... ... .... .. .. .. .. .. .. ...... ... .. ... ....... ", +" .. .. .. "}; diff -Nru nestopia-1.48/source/common/ini.cpp nestopia-1.49/source/common/ini.cpp --- nestopia-1.48/source/common/ini.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/ini.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,196 @@ +/* inih -- simple .INI file parser + +Copyright (c) 2009, Brush Technology +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Brush Technology nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY BRUSH TECHNOLOGY ''AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BRUSH TECHNOLOGY BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#include +#include +#include + +#include "ini.h" + +#if !INI_USE_STACK +#include +#endif + +#define MAX_SECTION 50 +#define MAX_NAME 50 + +/* Strip whitespace chars off end of given string, in place. Return s. */ +static char* rstrip(char* s) +{ + char* p = s + strlen(s); + while (p > s && isspace((unsigned char)(*--p))) + *p = '\0'; + return s; +} + +/* Return pointer to first non-whitespace char in given string. */ +static char* lskip(const char* s) +{ + while (*s && isspace((unsigned char)(*s))) + s++; + return (char*)s; +} + +/* Return pointer to first char c or ';' comment in given string, or pointer to + null at end of string if neither found. ';' must be prefixed by a whitespace + character to register as a comment. */ +static char* find_char_or_comment(const char* s, char c) +{ + int was_whitespace = 0; + while (*s && *s != c && !(was_whitespace && *s == ';')) { + was_whitespace = isspace((unsigned char)(*s)); + s++; + } + return (char*)s; +} + +/* Version of strncpy that ensures dest (size bytes) is null-terminated. */ +static char* strncpy0(char* dest, const char* src, size_t size) +{ + strncpy(dest, src, size); + dest[size - 1] = '\0'; + return dest; +} + +/* See documentation in header file. */ +int ini_parse_file(FILE* file, + int (*handler)(void*, const char*, const char*, + const char*), + void* user) +{ + /* Uses a fair bit of stack (use heap instead if you need to) */ +#if INI_USE_STACK + char line[INI_MAX_LINE]; +#else + char* line; +#endif + char section[MAX_SECTION] = ""; + char prev_name[MAX_NAME] = ""; + + char* start; + char* end; + char* name; + char* value; + int lineno = 0; + int error = 0; + +#if !INI_USE_STACK + line = (char*)malloc(INI_MAX_LINE); + if (!line) { + return -2; + } +#endif + + /* Scan through file line by line */ + while (fgets(line, INI_MAX_LINE, file) != NULL) { + lineno++; + + start = line; +#if INI_ALLOW_BOM + if (lineno == 1 && (unsigned char)start[0] == 0xEF && + (unsigned char)start[1] == 0xBB && + (unsigned char)start[2] == 0xBF) { + start += 3; + } +#endif + start = lskip(rstrip(start)); + + if (*start == ';' || *start == '#') { + /* Per Python ConfigParser, allow '#' comments at start of line */ + } +#if INI_ALLOW_MULTILINE + else if (*prev_name && *start && start > line) { + /* Non-black line with leading whitespace, treat as continuation + of previous name's value (as per Python ConfigParser). */ + if (!handler(user, section, prev_name, start) && !error) + error = lineno; + } +#endif + else if (*start == '[') { + /* A "[section]" line */ + end = find_char_or_comment(start + 1, ']'); + if (*end == ']') { + *end = '\0'; + strncpy0(section, start + 1, sizeof(section)); + *prev_name = '\0'; + } + else if (!error) { + /* No ']' found on section line */ + error = lineno; + } + } + else if (*start && *start != ';') { + /* Not a comment, must be a name[=:]value pair */ + end = find_char_or_comment(start, '='); + if (*end != '=') { + end = find_char_or_comment(start, ':'); + } + if (*end == '=' || *end == ':') { + *end = '\0'; + name = rstrip(start); + value = lskip(end + 1); + end = find_char_or_comment(value, '\0'); + if (*end == ';') + *end = '\0'; + rstrip(value); + + /* Valid name[=:]value pair found, call handler */ + strncpy0(prev_name, name, sizeof(prev_name)); + if (!handler(user, section, name, value) && !error) + error = lineno; + } + else if (!error) { + /* No '=' or ':' found on name[=:]value line */ + error = lineno; + } + } + } + +#if !INI_USE_STACK + free(line); +#endif + + return error; +} + +/* See documentation in header file. */ +int ini_parse(const char* filename, + int (*handler)(void*, const char*, const char*, const char*), + void* user) +{ + FILE* file; + int error; + + file = fopen(filename, "r"); + if (!file) + return -1; + error = ini_parse_file(file, handler, user); + fclose(file); + return error; +} diff -Nru nestopia-1.48/source/common/ini.h nestopia-1.49/source/common/ini.h --- nestopia-1.48/source/common/ini.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/ini.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,96 @@ +/* inih -- simple .INI file parser + +Copyright (c) 2009, Brush Technology +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Brush Technology nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY BRUSH TECHNOLOGY ''AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BRUSH TECHNOLOGY BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef __INI_H__ +#define __INI_H__ + +/* Make this header file easier to include in C++ code */ +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* Parse given INI-style file. May have [section]s, name=value pairs + (whitespace stripped), and comments starting with ';' (semicolon). Section + is "" if name=value pair parsed before any section heading. name:value + pairs are also supported as a concession to Python's ConfigParser. + + For each name=value pair parsed, call handler function with given user + pointer as well as section, name, and value (data only valid for duration + of handler call). Handler should return nonzero on success, zero on error. + + Returns 0 on success, line number of first error on parse error (doesn't + stop on first error), -1 on file open error, or -2 on memory allocation + error (only when INI_USE_STACK is zero). +*/ +int ini_parse(const char* filename, + int (*handler)(void* user, const char* section, + const char* name, const char* value), + void* user); + +/* Same as ini_parse(), but takes a FILE* instead of filename. This doesn't + close the file when it's finished -- the caller must do that. */ +int ini_parse_file(FILE* file, + int (*handler)(void* user, const char* section, + const char* name, const char* value), + void* user); + +/* Nonzero to allow multi-line value parsing, in the style of Python's + ConfigParser. If allowed, ini_parse() will call the handler with the same + name for each subsequent line parsed. */ +#ifndef INI_ALLOW_MULTILINE +#define INI_ALLOW_MULTILINE 1 +#endif + +/* Nonzero to allow a UTF-8 BOM sequence (0xEF 0xBB 0xBF) at the start of + the file. See http://code.google.com/p/inih/issues/detail?id=21 */ +#ifndef INI_ALLOW_BOM +#define INI_ALLOW_BOM 1 +#endif + +/* Nonzero to use stack, zero to use heap (malloc/free). */ +#ifndef INI_USE_STACK +#define INI_USE_STACK 1 +#endif + +/* Maximum line length for any line in INI file. */ +#ifndef INI_MAX_LINE +#define INI_MAX_LINE 200 +#endif + +#ifndef MATCH +#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0 +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* __INI_H__ */ diff -Nru nestopia-1.48/source/common/input.cpp nestopia-1.49/source/common/input.cpp --- nestopia-1.48/source/common/input.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/input.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,257 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2016 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include + +#include "nstcommon.h" +#include "config.h" +#include "input.h" +#include "video.h" + +static turbo_t turbostate; +static turbo_t turbotoggle; + +extern Emulator emulator; + +void nst_input_init() { + // Initialize input + char controller[32]; + + for (int i = 0; i < NUMGAMEPADS; i++) { + Input(emulator).AutoSelectController(i); + + switch(Input(emulator).GetConnectedController(i)) { + case Input::UNCONNECTED: + snprintf(controller, sizeof(controller), "%s", "Unconnected"); + break; + case Input::PAD1: + case Input::PAD2: + case Input::PAD3: + case Input::PAD4: + snprintf(controller, sizeof(controller), "%s", "Standard Pad"); + break; + case Input::ZAPPER: + snprintf(controller, sizeof(controller), "%s", "Zapper"); + break; + case Input::PADDLE: + snprintf(controller, sizeof(controller), "%s", "Arkanoid Paddle"); + break; + case Input::POWERPAD: + snprintf(controller, sizeof(controller), "%s", "Power Pad"); + break; + case Input::POWERGLOVE: + snprintf(controller, sizeof(controller), "%s", "Power Glove"); + break; + case Input::MOUSE: + snprintf(controller, sizeof(controller), "%s", "Mouse"); + break; + case Input::ROB: + snprintf(controller, sizeof(controller), "%s", "R.O.B."); + break; + case Input::FAMILYTRAINER: + snprintf(controller, sizeof(controller), "%s", "Family Trainer"); + break; + case Input::FAMILYKEYBOARD: + snprintf(controller, sizeof(controller), "%s", "Family Keyboard"); + break; + case Input::SUBORKEYBOARD: + snprintf(controller, sizeof(controller), "%s", "Subor Keyboard"); + break; + case Input::DOREMIKKOKEYBOARD: + snprintf(controller, sizeof(controller), "%s", "Doremikko Keyboard"); + break; + case Input::HORITRACK: + snprintf(controller, sizeof(controller), "%s", "Hori Track"); + break; + case Input::PACHINKO: + snprintf(controller, sizeof(controller), "%s", "Pachinko"); + break; + case Input::OEKAKIDSTABLET: + snprintf(controller, sizeof(controller), "%s", "Oeka Kids Tablet"); + break; + case Input::KONAMIHYPERSHOT: + snprintf(controller, sizeof(controller), "%s", "Konami Hypershot"); + break; + case Input::BANDAIHYPERSHOT: + snprintf(controller, sizeof(controller), "%s", "Bandai Hypershot"); + break; + case Input::CRAZYCLIMBER: + snprintf(controller, sizeof(controller), "%s", "Crazy Climber"); + break; + case Input::MAHJONG: + snprintf(controller, sizeof(controller), "%s", "Mahjong"); + break; + case Input::EXCITINGBOXING: + snprintf(controller, sizeof(controller), "%s", "Exciting Boxing"); + break; + case Input::TOPRIDER: + snprintf(controller, sizeof(controller), "%s", "Top Rider"); + break; + case Input::POKKUNMOGURAA: + snprintf(controller, sizeof(controller), "%s", "Pokkun Moguraa"); + break; + case Input::PARTYTAP: + snprintf(controller, sizeof(controller), "%s", "PartyTap"); + break; + case Input::TURBOFILE: + snprintf(controller, sizeof(controller), "%s", "Turbo File"); + break; + case Input::BARCODEWORLD: + snprintf(controller, sizeof(controller), "%s", "Barcode World"); + break; + default: + snprintf(controller, sizeof(controller), "%s", "Unknown"); + break; + } + + fprintf(stderr, "Port %d: %s\n", i + 1, controller); + } +} + +void nst_input_inject(Input::Controllers *controllers, nesinput_t input) { + // Insert the input signal into the NES + if(controllers == NULL) { return; } + + if (input.pressed) { + controllers->pad[input.player].buttons |= input.nescode; + + if (input.turboa) { input.player == 0 ? turbostate.p1a = true : turbostate.p2a = true; } + if (input.turbob) { input.player == 0 ? turbostate.p1b = true : turbostate.p2b = true; } + } + else { + controllers->pad[input.player].buttons &= ~input.nescode; + + if (input.turboa) { input.player == 0 ? turbostate.p1a = false : turbostate.p2a = false; } + if (input.turbob) { input.player == 0 ? turbostate.p1b = false : turbostate.p2b = false; } + } +} + +void nst_input_inject_mouse(Input::Controllers *controllers, int b, int s, int x, int y) { + // Insert input signal for Zappers + if(controllers == NULL) { return; } + + double xaspect; + double yaspect; + + if (s) { + // Get X coords + if (conf.video_filter == 1) { // NTSC + xaspect = (double)(Video::Output::WIDTH) / (double)(Video::Output::NTSC_WIDTH / 2); + } + else if (conf.video_tv_aspect) { + xaspect = (double)(Video::Output::WIDTH) / (double)(TV_WIDTH); + } + else { xaspect = 1.0; } + + dimensions_t rendersize = nst_video_get_dimensions_render(); + dimensions_t screensize = nst_video_get_dimensions_screen(); + + // Calculate fullscreen X coords + if (conf.video_fullscreen) { + if (conf.video_stretch_aspect) { + xaspect = (double)(conf.video_scale_factor * Video::Output::WIDTH) / (double)(screensize.w); + } + else { + // Remove the same amount of pixels as the black area to the left of the screen + x -= screensize.w / 2.0f - rendersize.w / 2.0f; + xaspect = (double)(conf.video_scale_factor * Video::Output::WIDTH) / (double)(rendersize.w); + } + } + controllers->zapper.x = (int)(x * xaspect) / conf.video_scale_factor; + + // Get Y coords + if (conf.video_unmask_overscan) { + controllers->zapper.y = y / conf.video_scale_factor; + } + else { + controllers->zapper.y = (y + OVERSCAN_TOP * conf.video_scale_factor) / conf.video_scale_factor; + } + + // Calculate fullscreen Y coords + if (conf.video_fullscreen) { + yaspect = (double)(conf.video_scale_factor * Video::Output::HEIGHT) / (double)(screensize.h); + controllers->zapper.y = (y * yaspect) / conf.video_scale_factor; + } + + // Offscreen + if (b != 1) { controllers->zapper.x = ~1U; } + + controllers->zapper.fire = true; + } + else { controllers->zapper.fire = false; } +} + +void nst_input_turbo_init() { + // Initialize the turbo button states + turbostate.p1a = turbotoggle.p1a = 0; + turbostate.p1b = turbotoggle.p1b = 0; + turbostate.p2a = turbotoggle.p2a = 0; + turbostate.p2b = turbotoggle.p2b = 0; +} + +void nst_input_turbo_pulse(Input::Controllers *controllers) { + // Pulse the turbo buttons if they're pressed + if (turbostate.p1a) { + turbotoggle.p1a++; + if (turbotoggle.p1a >= conf.timing_turbopulse) { + turbotoggle.p1a = 0; + controllers->pad[0].buttons &= ~Input::Controllers::Pad::A; + } + else { controllers->pad[0].buttons |= Input::Controllers::Pad::A; } + } + + if (turbostate.p1b) { + turbotoggle.p1b++; + if (turbotoggle.p1b >= conf.timing_turbopulse) { + turbotoggle.p1b = 0; + controllers->pad[0].buttons &= ~Input::Controllers::Pad::B; + } + else { controllers->pad[0].buttons |= Input::Controllers::Pad::B; } + } + + if (turbostate.p2a) { + turbotoggle.p2a++; + if (turbotoggle.p2a >= conf.timing_turbopulse) { + turbotoggle.p2a = 0; + controllers->pad[1].buttons &= ~Input::Controllers::Pad::A; + } + else { controllers->pad[1].buttons |= Input::Controllers::Pad::A; } + } + + if (turbostate.p2b) { + turbotoggle.p2b++; + if (turbotoggle.p2b >= conf.timing_turbopulse) { + turbotoggle.p2b = 0; + controllers->pad[1].buttons &= ~Input::Controllers::Pad::B; + } + else { controllers->pad[1].buttons |= Input::Controllers::Pad::B; } + } +} + +int nst_input_zapper_present() { + // Check if a Zapper is presently connected + if (Input(emulator).GetConnectedController(0) == Input::ZAPPER || + Input(emulator).GetConnectedController(1) == Input::ZAPPER) { + return 1; + } + else { return 0; } +} diff -Nru nestopia-1.48/source/common/input.h nestopia-1.49/source/common/input.h --- nestopia-1.48/source/common/input.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/input.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,37 @@ +#ifndef _INPUT_H_ +#define _INPUT_H_ + +#define NUMGAMEPADS 2 +#define NUMBUTTONS 10 + +#include "core/api/NstApiInput.hpp" + +using namespace Nes::Api; + +typedef struct { + unsigned char player; + unsigned char nescode; + unsigned char pressed; + unsigned char turboa; + unsigned char turbob; +} nesinput_t; + +typedef struct { + int p1a; + int p1b; + int p2a; + int p2b; +} turbo_t; + +void nst_input_init(); + +void nst_input_inject(Input::Controllers *controllers, nesinput_t input); +void nst_input_inject_mouse(Input::Controllers *controllers, int b, int s, int x, int y); + +void nst_input_turbo_init(); +void nst_input_turbo_pulse(Input::Controllers *controllers); + +int nst_input_zapper_present(); + +int input_configure_item(int pnum, int bnum, int type); +#endif diff -Nru nestopia-1.48/source/common/nstcommon.cpp nestopia-1.49/source/common/nstcommon.cpp --- nestopia-1.48/source/common/nstcommon.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/nstcommon.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,1021 @@ +/* + * Nestopia UE + * + * Copyright (C) 2007-2008 R. Belmont + * Copyright (C) 2012-2018 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#ifdef _MINGW +#include +#endif +#ifndef _MINGW +#include +#include +#endif + +// Nst Common +#include "nstcommon.h" +#include "config.h" +#include "cheats.h" +#include "input.h" +#include "audio.h" +#include "video.h" +#include "samples.h" + +Emulator emulator; +Video::Output *cNstVideo; +Sound::Output *cNstSound; +Input::Controllers *cNstPads; + +nstpaths_t nstpaths; + +static bool ffspeed = false; +static bool playing = false; + +static std::ifstream *nstdb; + +static std::ifstream *fdsbios; + +static std::ifstream *moviefile; +static std::fstream *movierecfile; + +void *custompalette = NULL; +static size_t custpalsize; + +bool (*nst_archive_select)(const char*, char*, size_t); + +static bool NST_CALLBACK nst_cb_videolock(void* userData, Video::Output& video) { + video.pitch = video_lock_screen(video.pixels); + return true; // true=lock success, false=lock failed (Nestopia will carry on but skip video) +} + +static void NST_CALLBACK nst_cb_videounlock(void* userData, Video::Output& video) { + video_unlock_screen(video.pixels); +} + +static bool NST_CALLBACK nst_cb_soundlock(void* userData, Sound::Output& sound) { + return true; +} + +static void NST_CALLBACK nst_cb_soundunlock(void* userData, Sound::Output& sound) { + // Do Nothing +} + +static void NST_CALLBACK nst_cb_event(void *userData, User::Event event, const void* data) { + // Handle special events + switch (event) { + case User::EVENT_CPU_JAM: + fprintf(stderr, "Cpu: Jammed\n"); + break; + case User::EVENT_CPU_UNOFFICIAL_OPCODE: + fprintf(stderr, "Cpu: Unofficial Opcode %s\n", (const char*)data); + break; + case User::EVENT_DISPLAY_TIMER: + fprintf(stderr, "\r%s", (const char*)data); + nst_video_print_time((const char*)data + strlen((char*)data) - 5, true); + break; + default: break; + } +} + +static void NST_CALLBACK nst_cb_log(void *userData, const char *string, unsigned long int length) { + // Print logging information to stderr + fprintf(stderr, "%s", string); +} + +static void NST_CALLBACK nst_cb_file(void *userData, User::File& file) { + unsigned char *compbuffer; + int compsize, compoffset; + char *filename; + + switch (file.GetAction()) { + case User::File::LOAD_ROM: + // Nothing here for now + break; + + case User::File::LOAD_SAMPLE: break; + case User::File::LOAD_SAMPLE_MOERO_PRO_YAKYUU: nst_sample_load_samples(file, "moepro"); break; + case User::File::LOAD_SAMPLE_MOERO_PRO_YAKYUU_88: nst_sample_load_samples(file, "moepro88"); break; + case User::File::LOAD_SAMPLE_MOERO_PRO_TENNIS: nst_sample_load_samples(file, "mptennis"); break; + case User::File::LOAD_SAMPLE_TERAO_NO_DOSUKOI_OOZUMOU: nst_sample_load_samples(file, "terao"); break; + case User::File::LOAD_SAMPLE_AEROBICS_STUDIO: nst_sample_load_samples(file, "ftaerobi"); break; + + case User::File::LOAD_BATTERY: // load in battery data from a file + case User::File::LOAD_EEPROM: // used by some Bandai games, can be treated the same as battery files + case User::File::LOAD_TAPE: // for loading Famicom cassette tapes + case User::File::LOAD_TURBOFILE: // for loading turbofile data + { + std::ifstream batteryFile(nstpaths.savename, std::ifstream::in|std::ifstream::binary); + + if (batteryFile.is_open()) { file.SetContent(batteryFile); } + break; + } + + case User::File::SAVE_BATTERY: // save battery data to a file + case User::File::SAVE_EEPROM: // can be treated the same as battery files + case User::File::SAVE_TAPE: // for saving Famicom cassette tapes + case User::File::SAVE_TURBOFILE: // for saving turbofile data + { + std::ofstream batteryFile(nstpaths.savename, std::ifstream::out|std::ifstream::binary); + const void* savedata; + unsigned long savedatasize; + + file.GetContent(savedata, savedatasize); + + if (batteryFile.is_open()) { batteryFile.write((const char*) savedata, savedatasize); } + + break; + } + + case User::File::LOAD_FDS: // for loading modified Famicom Disk System files + { + char fdsname[512]; + + snprintf(fdsname, sizeof(fdsname), "%s.ups", nstpaths.fdssave); + + std::ifstream batteryFile( fdsname, std::ifstream::in|std::ifstream::binary ); + + // no ups, look for ips + if (!batteryFile.is_open()) + { + snprintf(fdsname, sizeof(fdsname), "%s.ips", nstpaths.fdssave); + + std::ifstream batteryFile( fdsname, std::ifstream::in|std::ifstream::binary ); + + if (!batteryFile.is_open()) + { + return; + } + + file.SetPatchContent(batteryFile); + return; + } + + file.SetPatchContent(batteryFile); + break; + } + + case User::File::SAVE_FDS: // for saving modified Famicom Disk System files + { + char fdsname[512]; + + snprintf(fdsname, sizeof(fdsname), "%s.ups", nstpaths.fdssave); + + std::ofstream fdsFile( fdsname, std::ifstream::out|std::ifstream::binary ); + + if (fdsFile.is_open()) + file.GetPatchContent( User::File::PATCH_UPS, fdsFile ); + + break; + } + } +} + +static Machine::FavoredSystem nst_default_system() { + switch (conf.misc_default_system) { + case 2: return Machine::FAVORED_NES_PAL; break; + case 3: return Machine::FAVORED_FAMICOM; break; + case 4: return Machine::FAVORED_DENDY; break; + default: return Machine::FAVORED_NES_NTSC; break; + } +} + +void* nst_ptr_video() { return &cNstVideo; } +void* nst_ptr_sound() { return &cNstSound; } +void* nst_ptr_input() { return &cNstPads; } + +bool nst_archive_checkext(const char *filename) { + // Check if the file extension is valid + int len = strlen(filename); + + if ((!strcasecmp(&filename[len-4], ".nes")) || + (!strcasecmp(&filename[len-4], ".fds")) || + (!strcasecmp(&filename[len-4], ".nsf")) || + (!strcasecmp(&filename[len-4], ".unf")) || + (!strcasecmp(&filename[len-5], ".unif"))|| + (!strcasecmp(&filename[len-4], ".xml"))) { + return true; + } + return false; +} + +bool nst_archive_select_file(const char *filename, char *reqfile, size_t reqsize) { + // Select a filename to pull out of the archive +#ifndef _MINGW + struct archive *a; + struct archive_entry *entry; + int r, numarchives = 0; + + a = archive_read_new(); + archive_read_support_filter_all(a); + archive_read_support_format_all(a); + r = archive_read_open_filename(a, filename, 10240); + + // Test if it's actually an archive + if (r != ARCHIVE_OK) { + r = archive_read_free(a); + return false; + } + // If it is an archive, handle it + else { + // Find files with valid extensions within the archive + while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { + const char *currentfile = archive_entry_pathname(entry); + if (nst_archive_checkext(currentfile)) { + numarchives++; + snprintf(reqfile, reqsize, "%s", currentfile); + } + archive_read_data_skip(a); + break; // Load the first one found + } + // Free the archive + r = archive_read_free(a); + + // If there are no valid files in the archive, return + if (numarchives == 0) { return false; } + else { return true; } + } +#endif + return false; +} + +bool nst_archive_open(const char *filename, char **rom, int *romsize, const char *reqfile) { + // Opens archives +#ifndef _MINGW + struct archive *a; + struct archive_entry *entry; + int r; + int64_t entrysize; + + a = archive_read_new(); + archive_read_support_filter_all(a); + archive_read_support_format_all(a); + r = archive_read_open_filename(a, filename, 10240); + + // Test if it's actually an archive + if (r != ARCHIVE_OK) { + r = archive_read_free(a); + return false; + } + + // Scan through the archive for files + while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { + char *rombuf; + const char *currentfile = archive_entry_pathname(entry); + if (nst_archive_checkext(currentfile)) { + nst_set_paths(currentfile); + // If there's a specific file we want, load it + if (reqfile != NULL) { + if (!strcmp(currentfile, reqfile)) { + entrysize = archive_entry_size(entry); + rombuf = (char*)malloc(entrysize); + archive_read_data(a, rombuf, entrysize); + archive_read_data_skip(a); + r = archive_read_free(a); + *romsize = entrysize; + *rom = rombuf; + return true; + } + } + // Otherwise just take the first file in the archive + else { + entrysize = archive_entry_size(entry); + rombuf = (char*)malloc(entrysize); + archive_read_data(a, rombuf, entrysize); + archive_read_data_skip(a); + r = archive_read_free(a); + *romsize = entrysize; + *rom = rombuf; + return true; + } + } + } +#endif + return false; +} + +void nst_db_load() { + Nes::Api::Cartridge::Database database(emulator); + char dbpath[512]; + + if (nstdb) { return; } + + // Try to open the database file + snprintf(dbpath, sizeof(dbpath), "%sNstDatabase.xml", nstpaths.nstdir); + nstdb = new std::ifstream(dbpath, std::ifstream::in|std::ifstream::binary); + + if (nstdb->is_open()) { + database.Load(*nstdb); + database.Enable(true); + return; + } +#ifndef _MINGW + // If it fails, try looking in the data directory + snprintf(dbpath, sizeof(dbpath), "%s/NstDatabase.xml", DATADIR); + nstdb = new std::ifstream(dbpath, std::ifstream::in|std::ifstream::binary); + + if (nstdb->is_open()) { + database.Load(*nstdb); + database.Enable(true); + return; + } + + // If that fails, try looking in the working directory + char *pwd = getenv("PWD"); + snprintf(dbpath, sizeof(dbpath), "%s/NstDatabase.xml", pwd); + nstdb = new std::ifstream(dbpath, std::ifstream::in|std::ifstream::binary); + + if (nstdb->is_open()) { + database.Load(*nstdb); + database.Enable(true); + return; + } +#endif + else { + fprintf(stderr, "NstDatabase.xml not found!\n"); + delete nstdb; + nstdb = NULL; + } +} + +void nst_db_unload() { + if (nstdb) { delete nstdb; nstdb = NULL; } +} + +void nst_dipswitch() { + // Print DIP switch information and call handler + DipSwitches dipswitches(emulator); + + int numdips = dipswitches.NumDips(); + + if (numdips > 0) { + for (int i = 0; i < numdips; i++) { + fprintf(stderr, "%d: %s\n", i, dipswitches.GetDipName(i)); + int numvalues = dipswitches.NumValues(i); + + for (int j = 0; j < numvalues; j++) { + fprintf(stderr, " %d: %s\n", j, dipswitches.GetValueName(i, j)); + } + } + + char dippath[512]; + snprintf(dippath, sizeof(dippath), "%s%s.dip", nstpaths.savedir, nstpaths.gamename); + nst_dip_handle(dippath); + } +} + +void nst_fds_bios_load() { + // Load the Famicom Disk System BIOS + Nes::Api::Fds fds(emulator); + char biospath[512]; + + if (fdsbios) { return; } + + snprintf(biospath, sizeof(biospath), "%sdisksys.rom", nstpaths.nstdir); + + fdsbios = new std::ifstream(biospath, std::ifstream::in|std::ifstream::binary); + + if (fdsbios->is_open()) { + fds.SetBIOS(fdsbios); + } + else { + fprintf(stderr, "Fds: BIOS not found: %s\n", biospath); + delete fdsbios; + fdsbios = NULL; + } +} + +void nst_fds_bios_unload() { + if (fdsbios) { delete fdsbios; fdsbios = NULL; } +} + +void nst_fds_info() { + Fds fds(emulator); + + const char* disk; + const char* side; + char textbuf[24]; + + fds.GetCurrentDisk() == 0 ? disk = "1" : disk = "2"; + fds.GetCurrentDiskSide() == 0 ? side = "A" : side = "B"; + + fprintf(stderr, "Fds: Disk %s Side %s\n", disk, side); + snprintf(textbuf, sizeof(textbuf), "Disk %s Side %s", disk, side); + nst_video_print((const char*)textbuf, 8, 16, 2, true); +} + +void nst_fds_flip() { + // Flips the FDS disk + Fds fds(emulator); + + if (fds.CanChangeDiskSide()) { + fds.ChangeSide(); + nst_fds_info(); + } +} + +void nst_fds_switch() { + // Switches the FDS disk in multi-disk games + Fds fds(emulator); + + int currentdisk = fds.GetCurrentDisk(); + + // If it's a multi-disk game, eject and insert the other disk + if (fds.GetNumDisks() > 1) { + fds.EjectDisk(); + fds.InsertDisk(!currentdisk, 0); + nst_fds_info(); + } +} + +void nst_movie_save(char *filename) { + // Save/Record a movie + Movie movie(emulator); + + movierecfile = new std::fstream(filename, std::ifstream::out|std::ifstream::binary); + + if (movierecfile->is_open()) { + movie.Record((std::iostream&)*movierecfile, Nes::Api::Movie::CLEAN); + } + else { + delete movierecfile; + movierecfile = NULL; + } +} + +void nst_movie_load(char *filename) { + // Load and play a movie + Movie movie(emulator); + + moviefile = new std::ifstream(filename, std::ifstream::in|std::ifstream::binary); + + if (moviefile->is_open()) { + movie.Play(*moviefile); + } + else { + delete moviefile; + moviefile = NULL; + } +} + +void nst_movie_stop() { + // Stop any movie that is playing or recording + Movie movie(emulator); + + if (movie.IsPlaying() || movie.IsRecording()) { + movie.Stop(); + movierecfile = NULL; + delete movierecfile; + moviefile = NULL; + delete moviefile; + } +} + +bool nst_nsf() { + Machine machine(emulator); + return machine.Is(Machine::SOUND); +} + +void nst_nsf_play() { + Nsf nsf(emulator); + nsf.PlaySong(); + video_clear_buffer(); + video_disp_nsf(); +} + +void nst_nsf_stop() { + Nsf nsf(emulator); + nsf.StopSong(); +} + +void nst_nsf_prev() { + Nsf nsf(emulator); + nsf.SelectPrevSong(); + video_clear_buffer(); + video_disp_nsf(); +} + +void nst_nsf_next() { + Nsf nsf(emulator); + nsf.SelectNextSong(); + video_clear_buffer(); + video_disp_nsf(); +} + +bool nst_pal() { + Machine machine(emulator); + return machine.GetMode() == Machine::PAL; +} + +bool nst_playing() { return playing; } + +void nst_palette_load(const char *filename) { + // Load a custom palette + + FILE *file; + long filesize; // File size in bytes + size_t result; + + char custgamepalpath[512]; + snprintf(custgamepalpath, sizeof(custgamepalpath), "%s%s%s", nstpaths.nstdir, nstpaths.gamename, ".pal"); + + // Try the game-specific palette first + file = fopen(custgamepalpath, "rb"); + if (!file) { file = fopen(filename, "rb"); } + + // Then try the global custom palette + if (!file) { + if (conf.video_palette_mode == 2) { + fprintf(stderr, "Custom palette: not found: %s\n", filename); + conf.video_palette_mode = 0; + } + return; + } + + fseek(file, 0, SEEK_END); + filesize = ftell(file); + fseek(file, 0, SEEK_SET); + + if (custompalette) { free(custompalette); } + custompalette = malloc(filesize * sizeof(uint8_t)); + custpalsize = filesize * sizeof(uint8_t); + + result = fread(custompalette, sizeof(uint8_t), filesize, file); + + fclose(file); +} + +void nst_palette_save() { + // Save a custom palette + FILE *file; + void *custpalout; + + file = fopen(nstpaths.palettepath, "wb"); + if (!file) { return; } + + custpalout = malloc(custpalsize); + + memcpy(custpalout, custompalette, custpalsize); + + fwrite(custpalout, custpalsize, sizeof(uint8_t), file); + fclose(file); + free(custpalout); +} + +void nst_palette_unload() { + if (custompalette) { free(custompalette); } +} + +bool nst_find_patch(char *patchname, unsigned int patchname_length, const char *filename) { + // Check for a patch in the same directory as the game + FILE *file; + char filedir[512]; + + // Copy filename (will be used by dirname) + // dirname needs a copy because it can modify its argument + strncpy(filedir, filename, sizeof(filedir)); + filedir[sizeof(filedir) - 1] = '\0'; + // Use memmove because dirname can return the same pointer as its argument, + // since copying into same string as the argument we don't want any overlap + memmove(filedir, dirname(filedir), sizeof(filedir)); + filedir[sizeof(filedir) - 1] = '\0'; + + if (!conf.misc_soft_patching) { return 0; } + + snprintf(patchname, patchname_length, "%s/%s.ips", filedir, nstpaths.gamename); + + if ((file = fopen(patchname, "rb")) != NULL) { fclose(file); return 1; } + else { + snprintf(patchname, patchname_length, "%s/%s.ups", filedir, nstpaths.gamename); + if ((file = fopen(patchname, "rb")) != NULL) { fclose(file); return 1; } + } + + return 0; +} + +void nst_set_callbacks() { + // Set up the callbacks + void *userData = (void*)0xDEADC0DE; + + Video::Output::lockCallback.Set(nst_cb_videolock, userData); + Video::Output::unlockCallback.Set(nst_cb_videounlock, userData); + + Sound::Output::lockCallback.Set(nst_cb_soundlock, userData); + Sound::Output::unlockCallback.Set(nst_cb_soundunlock, userData); + + User::fileIoCallback.Set(nst_cb_file, userData); + User::logCallback.Set(nst_cb_log, userData); + User::eventCallback.Set(nst_cb_event, userData); +} + +void nst_set_dirs() { + // Set up system directories +#ifdef _MINGW + snprintf(nstpaths.nstdir, sizeof(nstpaths.nstdir), ""); +#else + // create system directory if it doesn't exist + snprintf(nstpaths.nstdir, sizeof(nstpaths.nstdir), "%s/.nestopia/", getenv("HOME")); + if (mkdir(nstpaths.nstdir, 0755) && errno != EEXIST) { + fprintf(stderr, "Failed to create %s: %d\n", nstpaths.nstdir, errno); + } +#endif + // create save and state directories if they don't exist + char dirstr[256]; + snprintf(dirstr, sizeof(dirstr), "%ssave", nstpaths.nstdir); +#ifdef _MINGW + if (mkdir(dirstr) && errno != EEXIST) { +#else + if (mkdir(dirstr, 0755) && errno != EEXIST) { +#endif + fprintf(stderr, "Failed to create %s: %d\n", dirstr, errno); + } + + snprintf(dirstr, sizeof(dirstr), "%sstate", nstpaths.nstdir); +#ifdef _MINGW + if (mkdir(dirstr) && errno != EEXIST) { +#else + if (mkdir(dirstr, 0755) && errno != EEXIST) { +#endif + fprintf(stderr, "Failed to create %s: %d\n", dirstr, errno); + } + + // create cheats directory if it doesn't exist + snprintf(dirstr, sizeof(dirstr), "%scheats", nstpaths.nstdir); +#ifdef _MINGW + if (mkdir(dirstr) && errno != EEXIST) { +#else + if (mkdir(dirstr, 0755) && errno != EEXIST) { +#endif + fprintf(stderr, "Failed to create %s: %d\n", dirstr, errno); + } + + // create screenshots directory if it doesn't exist + snprintf(dirstr, sizeof(dirstr), "%sscreenshots", nstpaths.nstdir); +#ifdef _MINGW + if (mkdir(dirstr) && errno != EEXIST) { +#else + if (mkdir(dirstr, 0755) && errno != EEXIST) { +#endif + fprintf(stderr, "Failed to create %s: %d\n", dirstr, errno); + } + + // Construct the custom palette path + snprintf(nstpaths.palettepath, sizeof(nstpaths.palettepath), "%s%s", nstpaths.nstdir, "custom.pal"); + + // Construct samples directory if it doesn't exist + snprintf(dirstr, sizeof(dirstr), "%ssamples", nstpaths.nstdir); +#ifdef _MINGW + if (mkdir(dirstr) && errno != EEXIST) { +#else + if (mkdir(dirstr, 0755) && errno != EEXIST) { +#endif + fprintf(stderr, "Failed to create %s: %d\n", dirstr, errno); + } +} + +void nst_set_paths(const char *filename) { + + // Set up the save directory + snprintf(nstpaths.savedir, sizeof(nstpaths.savedir), "%ssave/", nstpaths.nstdir); + + // Copy the full file path to the savename variable + snprintf(nstpaths.savename, sizeof(nstpaths.savename), "%s", filename); + + // strip the . and extention off the filename for saving + for (int i = strlen(nstpaths.savename)-1; i > 0; i--) { + if (nstpaths.savename[i] == '.') { + nstpaths.savename[i] = '\0'; + break; + } + } + + // Set up the sample directory + snprintf(nstpaths.sampdir, sizeof(nstpaths.sampdir), "%ssamples/", nstpaths.nstdir); + + // Get the name of the game minus file path and extension + snprintf(nstpaths.gamename, sizeof(nstpaths.gamename), "%s", basename(nstpaths.savename)); + + // Construct save path + snprintf(nstpaths.savename, sizeof(nstpaths.savename), "%s%s%s", nstpaths.savedir, nstpaths.gamename, ".sav"); + + // Construct path for FDS save patches + snprintf(nstpaths.fdssave, sizeof(nstpaths.fdssave), "%s%s", nstpaths.savedir, nstpaths.gamename); + + // Construct the save state path + snprintf(nstpaths.statepath, sizeof(nstpaths.statepath), "%sstate/%s", nstpaths.nstdir, nstpaths.gamename); + + // Construct the cheat path + snprintf(nstpaths.cheatpath, sizeof(nstpaths.cheatpath), "%scheats/%s.xml", nstpaths.nstdir, nstpaths.gamename); +} + +void nst_set_region() { + // Set the region + Machine machine(emulator); + Cartridge::Database database(emulator); + + /*if (database.IsLoaded()) { + std::ifstream dbfile(filename, std::ios::in|std::ios::binary); + Cartridge::Profile profile; + Cartridge::ReadInes(dbfile, nst_default_system(), profile); + dbentry = database.FindEntry(profile.hash, nst_default_system()); + printf("Mapper: %d\n", dbentry.GetMapper()); + }*/ + + switch (conf.misc_default_system) { + case 0: machine.SetMode(machine.GetDesiredMode()); break; // Auto + case 1: machine.SetMode(Machine::NTSC); break; // NTSC + case 2: machine.SetMode(Machine::PAL); break; // PAL + case 3: machine.SetMode(Machine::NTSC); break; // Famicom + case 4: machine.SetMode(Machine::PAL); break; // Dendy + } +} + +void nst_set_rewind(int direction) { + // Set the rewinder backward or forward + switch (direction) { + case 0: Rewinder(emulator).SetDirection(Rewinder::BACKWARD); break; + case 1: Rewinder(emulator).SetDirection(Rewinder::FORWARD); break; + default: break; + } +} + +void nst_state_save(char *filename) { + // Save a state by filename + Machine machine(emulator); + + std::ofstream statefile(filename, std::ifstream::out|std::ifstream::binary); + + if (statefile.is_open()) { machine.SaveState(statefile, Nes::Api::Machine::NO_COMPRESSION); } + fprintf(stderr, "State Saved: %s\n", filename); + nst_video_print("State Saved", 8, 212, 2, true); +} + +void nst_state_load(char *filename) { + // Load a state by filename + Machine machine(emulator); + + std::ifstream statefile(filename, std::ifstream::in|std::ifstream::binary); + + if (statefile.is_open()) { machine.LoadState(statefile); } + fprintf(stderr, "State Loaded: %s\n", filename); + nst_video_print("State Loaded", 8, 212, 2, true); +} + +void nst_state_quicksave(int slot) { + // Quick Save State + char slotpath[520]; + snprintf(slotpath, sizeof(slotpath), "%s_%d.nst", nstpaths.statepath, slot); + nst_state_save(slotpath); +} + + +void nst_state_quickload(int slot) { + // Quick Load State + char slotpath[520]; + snprintf(slotpath, sizeof(slotpath), "%s_%d.nst", nstpaths.statepath, slot); + + struct stat qloadstat; + if (stat(slotpath, &qloadstat) == -1) { + fprintf(stderr, "No State to Load\n"); + nst_video_print("No State to Load", 8, 212, 2, true); + return; + } + + nst_state_load(slotpath); +} + +int nst_timing_runframes() { + // Calculate how many emulation frames to run + if (ffspeed) { return conf.timing_ffspeed; } + return 1; +} + +void nst_timing_set_ffspeed() { + // Set the framerate to the fast-forward speed + ffspeed = true; +} + +void nst_timing_set_default() { + // Set the framerate to the default + ffspeed = false; +} + +void nst_reset(bool hardreset) { + // Reset the machine (soft or hard) + Machine machine(emulator); + Fds fds(emulator); + machine.SetRamPowerState(conf.misc_power_state); + machine.Reset(hardreset); + + // Set the FDS disk to defaults + fds.EjectDisk(); + fds.InsertDisk(0, 0); +} + +void nst_emuloop() { + // Main Emulation Loop + if (NES_SUCCEEDED(Rewinder(emulator).Enable(true))) { + Rewinder(emulator).EnableSound(true); + } + + if (playing) { + audio_play(); + + // Pulse the turbo buttons + nst_input_turbo_pulse(cNstPads); + + // Execute frames + for (int i = 0; i < nst_timing_runframes(); i++) { + emulator.Execute(cNstVideo, cNstSound, cNstPads); + } + } +} + +void nst_unload() { + // Remove the cartridge and shut down the NES + Machine machine(emulator); + + // Power down the NES + machine.Power(false); + + // Remove the cartridge + machine.Unload(); +} + +void nst_pause() { + // Pauses the game + if (playing) { + audio_pause(); + audio_deinit(); + } + + playing = false; + //nstsdl_video_set_cursor(); +} + +void nst_play() { + // Play the game + if (playing) { return; } + + video_init(); + audio_init(); + nst_input_init(); + nst_cheats_init(nstpaths.cheatpath); + + cNstVideo = new Video::Output; + cNstSound = new Sound::Output; + cNstPads = new Input::Controllers; + + audio_set_params(cNstSound); + audio_unpause(); + + if (nst_nsf()) { + Nsf nsf(emulator); + nsf.PlaySong(); + video_disp_nsf(); + } + + playing = true; +} + +int nst_load(const char *filename) { + // Load a Game ROM + Machine machine(emulator); + Nsf nsf(emulator); + Sound sound(emulator); + Nes::Result result; + char *rom; + int romsize; + char patchname[512]; + + // Pause play before pulling out a cartridge + if (playing) { nst_pause(); } + + // Pull out any inserted cartridges + static int loaded = 0; + if (loaded) { nst_unload(); } + nst_video_print_time("", false); + + // Check if the file is an archive and select the file within + char reqfile[256]; // Requested file inside the archive + if (nst_archive_select(filename, reqfile, sizeof(reqfile))) { + // Extract the contents + nst_archive_open(filename, &rom, &romsize, reqfile); + + // Convert the malloc'd char* to an istream + std::string rombuf(rom, romsize); + std::istringstream file(rombuf); + free(rom); + + result = machine.Load(file, nst_default_system()); + } + else { // Otherwise just load the file + std::ifstream file(filename, std::ios::in|std::ios::binary); + + // Set the file paths + nst_set_paths(filename); + + if (nst_find_patch(patchname, sizeof(patchname), filename)) { // Load with a patch if there is one + std::ifstream pfile(patchname, std::ios::in|std::ios::binary); + Machine::Patch patch(pfile, false); + result = machine.Load(file, nst_default_system(), patch); + } + else { result = machine.Load(file, nst_default_system()); } + } + + if (NES_FAILED(result)) { + char errorstring[32]; + switch (result) { + case Nes::RESULT_ERR_INVALID_FILE: + snprintf(errorstring, sizeof(errorstring), "Error: Invalid file"); + break; + + case Nes::RESULT_ERR_OUT_OF_MEMORY: + snprintf(errorstring, sizeof(errorstring), "Error: Out of Memory"); + break; + + case Nes::RESULT_ERR_CORRUPT_FILE: + snprintf(errorstring, sizeof(errorstring), "Error: Corrupt or Missing File"); + break; + + case Nes::RESULT_ERR_UNSUPPORTED_MAPPER: + snprintf(errorstring, sizeof(errorstring), "Error: Unsupported Mapper"); + break; + + case Nes::RESULT_ERR_MISSING_BIOS: + snprintf(errorstring, sizeof(errorstring), "Error: Missing Fds BIOS"); + break; + + default: + snprintf(errorstring, sizeof(errorstring), "Error: %d", result); + break; + } + + fprintf(stderr, "%s\n", errorstring); + + return 0; + } + + // Deal with any DIP Switches + nst_dipswitch(); + + // Set the region + nst_set_region(); + + if (machine.Is(Machine::DISK)) { + Fds fds(emulator); + fds.InsertDisk(0, 0); + nst_fds_info(); + } + + // Check if this is an NSF + if (nst_nsf()) { nsf.StopSong(); } + + // Check if sound distortion should be enabled + sound.SetGenie(conf.misc_genie_distortion); + + // Load the custom palette + nst_palette_load(nstpaths.palettepath); + + // Set video overclocking + Video video(emulator); + video.EnableOverclocking(conf.misc_overclock); + + // Set the RAM's power state + machine.SetRamPowerState(conf.misc_power_state); + + // Power on + machine.Power(true); + + loaded = 1; + return loaded; +} diff -Nru nestopia-1.48/source/common/nstcommon.h nestopia-1.49/source/common/nstcommon.h --- nestopia-1.48/source/common/nstcommon.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/nstcommon.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,108 @@ +#ifndef _NSTCOMMON_H_ +#define _NSTCOMMON_H_ + +// Nst Core +#include "core/api/NstApiEmulator.hpp" +#include "core/api/NstApiVideo.hpp" +#include "core/api/NstApiSound.hpp" +#include "core/api/NstApiMachine.hpp" +#include "core/api/NstApiCartridge.hpp" +#include "core/api/NstApiFds.hpp" +#include "core/api/NstApiNsf.hpp" +#include "core/api/NstApiUser.hpp" +#include "core/api/NstApiRewinder.hpp" +#include "core/api/NstApiMovie.hpp" + +using namespace Nes::Api; + +typedef struct { + char nstdir[256]; + char savedir[256]; + char gamename[256]; + char savename[512]; + char fdssave[512]; + char statepath[512]; + char cheatpath[512]; + char palettepath[512]; + char sampdir[512]; +} nstpaths_t; + +// Pointers +void* nst_ptr_video(); +void* nst_ptr_sound(); +void* nst_ptr_input(); + +// Archives +bool nst_archive_checkext(const char *filename); +bool nst_archive_select_file(const char *filename, char *reqfile, size_t reqsize); +bool nst_archive_open(const char *filename, char **rom, int *romsize, const char *reqfile); + +// DIP Switches +void nst_dipswitch(); + +// Database +void nst_db_load(); +void nst_db_unload(); + +// FDS +void nst_fds_bios_load(); +void nst_fds_bios_unload(); +void nst_fds_info(); +void nst_fds_flip(); +void nst_fds_switch(); + +// Movies +void nst_movie_save(char *filename); +void nst_movie_load(char *filename); +void nst_movie_stop(); + +// NSF +bool nst_nsf(); +void nst_nsf_play(); +void nst_nsf_stop(); +void nst_nsf_prev(); +void nst_nsf_next(); + +// PAL +bool nst_pal(); + +// Play check +bool nst_playing(); + +// Palette +void nst_palette_load(const char *filename); +void nst_palette_save(); +void nst_palette_unload(); + +// Patch +bool nst_find_patch(char *patchname, unsigned int patchname_length, const char *filename); + +// Setters +void nst_set_callbacks(); +void nst_set_dirs(); +void nst_set_paths(const char *filename); +void nst_set_region(); +void nst_set_rewind(int direction); + +// States +void nst_state_save(char *filename); +void nst_state_load(char *filename); +void nst_state_quicksave(int isvst); +void nst_state_quickload(int isvst); + +// Timing +int nst_timing_runframes(); +void nst_timing_set_ffspeed(); +void nst_timing_set_default(); + +// Main Emulation +void nst_reset(bool hardreset); +void nst_emuloop(); + +// Unsorted +int nst_load(const char *filename); +void nst_unload(); +void nst_play(); +void nst_pause(); + +#endif diff -Nru nestopia-1.48/source/common/png.cpp nestopia-1.49/source/common/png.cpp --- nestopia-1.48/source/common/png.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/png.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,6136 @@ +/* +LodePNG version 20141130 + +Copyright (c) 2005-2014 Lode Vandevenne + +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 "png.h" + +#include +#include + +#ifdef LODEPNG_COMPILE_CPP +#include +#endif /*LODEPNG_COMPILE_CPP*/ + +#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/ +#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/ +#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/ +#endif /*_MSC_VER */ + +/* +This source file is built up in the following large parts. The code sections +with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way. +-Tools for C and common code for PNG and Zlib +-C Code for Zlib (huffman, deflate, ...) +-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...) +-The C++ wrapper around all of the above +*/ + +/*The malloc, realloc and free functions defined here with "lodepng_" in front +of the name, so that you can easily change them to others related to your +platform if needed. Everything else in the code calls these. Pass +-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out +#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and +define them in your own project's source files without needing to change +lodepng source code. Don't forget to remove "static" if you copypaste them +from here.*/ + +#ifdef LODEPNG_COMPILE_ALLOCATORS +static void* lodepng_malloc(size_t size) +{ + return malloc(size); +} + +static void* lodepng_realloc(void* ptr, size_t new_size) +{ + return realloc(ptr, new_size); +} + +static void lodepng_free(void* ptr) +{ + free(ptr); +} +#else /*LODEPNG_COMPILE_ALLOCATORS*/ +void* lodepng_malloc(size_t size); +void* lodepng_realloc(void* ptr, size_t new_size); +void lodepng_free(void* ptr); +#endif /*LODEPNG_COMPILE_ALLOCATORS*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // Tools for C, and common code for PNG and Zlib. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/* +Often in case of an error a value is assigned to a variable and then it breaks +out of a loop (to go to the cleanup phase of a function). This macro does that. +It makes the error handling code shorter and more readable. + +Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83); +*/ +#define CERROR_BREAK(errorvar, code)\ +{\ + errorvar = code;\ + break;\ +} + +/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/ +#define ERROR_BREAK(code) CERROR_BREAK(error, code) + +/*Set error var to the error code, and return it.*/ +#define CERROR_RETURN_ERROR(errorvar, code)\ +{\ + errorvar = code;\ + return code;\ +} + +/*Try the code, if it returns error, also return the error.*/ +#define CERROR_TRY_RETURN(call)\ +{\ + unsigned error = call;\ + if(error) return error;\ +} + +/*Set error var to the error code, and return from the void function.*/ +#define CERROR_RETURN(errorvar, code)\ +{\ + errorvar = code;\ + return;\ +} + +/* +About uivector, ucvector and string: +-All of them wrap dynamic arrays or text strings in a similar way. +-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version. +-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated. +-They're not used in the interface, only internally in this file as static functions. +-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor. +*/ + +#ifdef LODEPNG_COMPILE_ZLIB +/*dynamic vector of unsigned ints*/ +typedef struct uivector +{ + unsigned* data; + size_t size; /*size in number of unsigned longs*/ + size_t allocsize; /*allocated size in bytes*/ +} uivector; + +static void uivector_cleanup(void* p) +{ + ((uivector*)p)->size = ((uivector*)p)->allocsize = 0; + lodepng_free(((uivector*)p)->data); + ((uivector*)p)->data = NULL; +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_reserve(uivector* p, size_t allocsize) +{ + if(allocsize > p->allocsize) + { + size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); + void* data = lodepng_realloc(p->data, newsize); + if(data) + { + p->allocsize = newsize; + p->data = (unsigned*)data; + } + else return 0; /*error: not enough memory*/ + } + return 1; +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_resize(uivector* p, size_t size) +{ + if(!uivector_reserve(p, size * sizeof(unsigned))) return 0; + p->size = size; + return 1; /*success*/ +} + +/*resize and give all new elements the value*/ +static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) +{ + size_t oldsize = p->size, i; + if(!uivector_resize(p, size)) return 0; + for(i = oldsize; i < size; ++i) p->data[i] = value; + return 1; +} + +static void uivector_init(uivector* p) +{ + p->data = NULL; + p->size = p->allocsize = 0; +} + +#ifdef LODEPNG_COMPILE_ENCODER +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_push_back(uivector* p, unsigned c) +{ + if(!uivector_resize(p, p->size + 1)) return 0; + p->data[p->size - 1] = c; + return 1; +} + +/*copy q to p, returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned uivector_copy(uivector* p, const uivector* q) +{ + size_t i; + if(!uivector_resize(p, q->size)) return 0; + for(i = 0; i != q->size; ++i) p->data[i] = q->data[i]; + return 1; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_ZLIB*/ + +/* /////////////////////////////////////////////////////////////////////////// */ + +/*dynamic vector of unsigned chars*/ +typedef struct ucvector +{ + unsigned char* data; + size_t size; /*used size*/ + size_t allocsize; /*allocated size*/ +} ucvector; + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned ucvector_reserve(ucvector* p, size_t allocsize) +{ + if(allocsize > p->allocsize) + { + size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); + void* data = lodepng_realloc(p->data, newsize); + if(data) + { + p->allocsize = newsize; + p->data = (unsigned char*)data; + } + else return 0; /*error: not enough memory*/ + } + return 1; +} + +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned ucvector_resize(ucvector* p, size_t size) +{ + if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0; + p->size = size; + return 1; /*success*/ +} + +#ifdef LODEPNG_COMPILE_PNG + +static void ucvector_cleanup(void* p) +{ + ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0; + lodepng_free(((ucvector*)p)->data); + ((ucvector*)p)->data = NULL; +} + +static void ucvector_init(ucvector* p) +{ + p->data = NULL; + p->size = p->allocsize = 0; +} + +#ifdef LODEPNG_COMPILE_DECODER +/*resize and give all new elements the value*/ +static unsigned ucvector_resizev(ucvector* p, size_t size, unsigned char value) +{ + size_t oldsize = p->size, i; + if(!ucvector_resize(p, size)) return 0; + for(i = oldsize; i < size; ++i) p->data[i] = value; + return 1; +} +#endif /*LODEPNG_COMPILE_DECODER*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ZLIB +/*you can both convert from vector to buffer&size and vica versa. If you use +init_buffer to take over a buffer and size, it is not needed to use cleanup*/ +static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) +{ + p->data = buffer; + p->allocsize = p->size = size; +} +#endif /*LODEPNG_COMPILE_ZLIB*/ + +#if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER) +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned ucvector_push_back(ucvector* p, unsigned char c) +{ + if(!ucvector_resize(p, p->size + 1)) return 0; + p->data[p->size - 1] = c; + return 1; +} +#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ + + +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_PNG +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*returns 1 if success, 0 if failure ==> nothing done*/ +static unsigned string_resize(char** out, size_t size) +{ + char* data = (char*)lodepng_realloc(*out, size + 1); + if(data) + { + data[size] = 0; /*null termination char*/ + *out = data; + } + return data != 0; +} + +/*init a {char*, size_t} pair for use as string*/ +static void string_init(char** out) +{ + *out = NULL; + string_resize(out, 0); +} + +/*free the above pair again*/ +static void string_cleanup(char** out) +{ + lodepng_free(*out); + *out = NULL; +} + +static void string_set(char** out, const char* in) +{ + size_t insize = strlen(in), i; + if(string_resize(out, insize)) + { + for(i = 0; i != insize; ++i) + { + (*out)[i] = in[i]; + } + } +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +/* ////////////////////////////////////////////////////////////////////////// */ + +unsigned lodepng_read32bitInt(const unsigned char* buffer) +{ + return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); +} + +#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER) +/*buffer must have at least 4 allocated bytes available*/ +static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) +{ + buffer[0] = (unsigned char)((value >> 24) & 0xff); + buffer[1] = (unsigned char)((value >> 16) & 0xff); + buffer[2] = (unsigned char)((value >> 8) & 0xff); + buffer[3] = (unsigned char)((value ) & 0xff); +} +#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ + +#ifdef LODEPNG_COMPILE_ENCODER +static void lodepng_add32bitInt(ucvector* buffer, unsigned value) +{ + ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/ + lodepng_set32bitInt(&buffer->data[buffer->size - 4], value); +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / File IO / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_DISK + +unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) +{ + FILE* file; + long size; + + /*provide some proper output values if error will happen*/ + *out = 0; + *outsize = 0; + + file = fopen(filename, "rb"); + if(!file) return 78; + + /*get filesize:*/ + fseek(file , 0 , SEEK_END); + size = ftell(file); + rewind(file); + + /*read contents of the file into the vector*/ + *outsize = 0; + *out = (unsigned char*)lodepng_malloc((size_t)size); + if(size && (*out)) (*outsize) = fread(*out, 1, (size_t)size, file); + + fclose(file); + if(!(*out) && size) return 83; /*the above malloc failed*/ + return 0; +} + +/*write given buffer to the file, overwriting the file, it doesn't append to it.*/ +unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) +{ + FILE* file; + file = fopen(filename, "wb" ); + if(!file) return 79; + fwrite((char*)buffer , 1 , buffersize, file); + fclose(file); + return 0; +} + +#endif /*LODEPNG_COMPILE_DISK*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // End of common code and tools. Begin of Zlib related code. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_ENCODER +/*TODO: this ignores potential out of memory errors*/ +#define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit)\ +{\ + /*add a new byte at the end*/\ + if(((*bitpointer) & 7) == 0) ucvector_push_back(bitstream, (unsigned char)0);\ + /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/\ + (bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));\ + ++(*bitpointer);\ +} + +static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) +{ + size_t i; + for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1)); +} + +static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) +{ + size_t i; + for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1)); +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +#define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1) + +static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream) +{ + unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream)); + ++(*bitpointer); + return result; +} + +static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) +{ + unsigned result = 0, i; + for(i = 0; i != nbits; ++i) + { + result += ((unsigned)READBIT(*bitpointer, bitstream)) << i; + ++(*bitpointer); + } + return result; +} +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Deflate - Huffman / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#define FIRST_LENGTH_CODE_INDEX 257 +#define LAST_LENGTH_CODE_INDEX 285 +/*256 literals, the end code, some length codes, and 2 unused codes*/ +#define NUM_DEFLATE_CODE_SYMBOLS 288 +/*the distance codes have their own symbols, 30 used, 2 unused*/ +#define NUM_DISTANCE_SYMBOLS 32 +/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/ +#define NUM_CODE_LENGTH_CODES 19 + +/*the base lengths represented by codes 257-285*/ +static const unsigned LENGTHBASE[29] + = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, + 67, 83, 99, 115, 131, 163, 195, 227, 258}; + +/*the extra bits used by codes 257-285 (added to base length)*/ +static const unsigned LENGTHEXTRA[29] + = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, + 4, 4, 4, 4, 5, 5, 5, 5, 0}; + +/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/ +static const unsigned DISTANCEBASE[30] + = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, + 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; + +/*the extra bits of backwards distances (added to base)*/ +static const unsigned DISTANCEEXTRA[30] + = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, + 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + +/*the order in which "code length alphabet code lengths" are stored, out of this +the huffman tree of the dynamic huffman tree lengths is generated*/ +static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES] + = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + +/* ////////////////////////////////////////////////////////////////////////// */ + +/* +Huffman tree struct, containing multiple representations of the tree +*/ +typedef struct HuffmanTree +{ + unsigned* tree2d; + unsigned* tree1d; + unsigned* lengths; /*the lengths of the codes of the 1d-tree*/ + unsigned maxbitlen; /*maximum number of bits a single code can get*/ + unsigned numcodes; /*number of symbols in the alphabet = number of codes*/ +} HuffmanTree; + +/*function used for debug purposes to draw the tree in ascii art with C++*/ +/* +static void HuffmanTree_draw(HuffmanTree* tree) +{ + std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl; + for(size_t i = 0; i != tree->tree1d.size; ++i) + { + if(tree->lengths.data[i]) + std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl; + } + std::cout << std::endl; +}*/ + +static void HuffmanTree_init(HuffmanTree* tree) +{ + tree->tree2d = 0; + tree->tree1d = 0; + tree->lengths = 0; +} + +static void HuffmanTree_cleanup(HuffmanTree* tree) +{ + lodepng_free(tree->tree2d); + lodepng_free(tree->tree1d); + lodepng_free(tree->lengths); +} + +/*the tree representation used by the decoder. return value is error*/ +static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) +{ + unsigned nodefilled = 0; /*up to which node it is filled*/ + unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/ + unsigned n, i; + + tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned)); + if(!tree->tree2d) return 83; /*alloc fail*/ + + /* + convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means + uninited, a value >= numcodes is an address to another bit, a value < numcodes + is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as + many columns as codes - 1. + A good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. + Here, the internal nodes are stored (what their 0 and 1 option point to). + There is only memory for such good tree currently, if there are more nodes + (due to too long length codes), error 55 will happen + */ + for(n = 0; n < tree->numcodes * 2; ++n) + { + tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/ + } + + for(n = 0; n < tree->numcodes; ++n) /*the codes*/ + { + for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/ + { + unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1); + /*oversubscribed, see comment in lodepng_error_text*/ + if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55; + if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ + { + if(i + 1 == tree->lengths[n]) /*last bit*/ + { + tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/ + treepos = 0; + } + else + { + /*put address of the next step in here, first that address has to be found of course + (it's just nodefilled + 1)...*/ + ++nodefilled; + /*addresses encoded with numcodes added to it*/ + tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes; + treepos = nodefilled; + } + } + else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes; + } + } + + for(n = 0; n < tree->numcodes * 2; ++n) + { + if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/ + } + + return 0; +} + +/* +Second step for the ...makeFromLengths and ...makeFromFrequencies functions. +numcodes, lengths and maxbitlen must already be filled in correctly. return +value is error. +*/ +static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) +{ + uivector blcount; + uivector nextcode; + unsigned error = 0; + unsigned bits, n; + + uivector_init(&blcount); + uivector_init(&nextcode); + + tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned)); + if(!tree->tree1d) error = 83; /*alloc fail*/ + + if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0) + || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0)) + error = 83; /*alloc fail*/ + + if(!error) + { + /*step 1: count number of instances of each code length*/ + for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]]; + /*step 2: generate the nextcode values*/ + for(bits = 1; bits <= tree->maxbitlen; ++bits) + { + nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1; + } + /*step 3: generate all the codes*/ + for(n = 0; n != tree->numcodes; ++n) + { + if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++; + } + } + + uivector_cleanup(&blcount); + uivector_cleanup(&nextcode); + + if(!error) return HuffmanTree_make2DTree(tree); + else return error; +} + +/* +given the code lengths (as stored in the PNG file), generate the tree as defined +by Deflate. maxbitlen is the maximum bits that a code in the tree can have. +return value is error. +*/ +static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen, + size_t numcodes, unsigned maxbitlen) +{ + unsigned i; + tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); + if(!tree->lengths) return 83; /*alloc fail*/ + for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i]; + tree->numcodes = (unsigned)numcodes; /*number of symbols*/ + tree->maxbitlen = maxbitlen; + return HuffmanTree_makeFromLengths2(tree); +} + +#ifdef LODEPNG_COMPILE_ENCODER + +/* +A coin, this is the terminology used for the package-merge algorithm and the +coin collector's problem. This is used to generate the huffman tree. +A coin can be multiple coins (when they're merged) +*/ +typedef struct Coin +{ + uivector symbols; + float weight; /*the sum of all weights in this coin*/ +} Coin; + +static void coin_init(Coin* c) +{ + uivector_init(&c->symbols); +} + +/*argument c is void* so that this dtor can be given as function pointer to the vector resize function*/ +static void coin_cleanup(void* c) +{ + uivector_cleanup(&((Coin*)c)->symbols); +} + +static void coin_copy(Coin* c1, const Coin* c2) +{ + c1->weight = c2->weight; + uivector_copy(&c1->symbols, &c2->symbols); +} + +static void add_coins(Coin* c1, const Coin* c2) +{ + size_t i; + for(i = 0; i != c2->symbols.size; ++i) uivector_push_back(&c1->symbols, c2->symbols.data[i]); + c1->weight += c2->weight; +} + +static void init_coins(Coin* coins, size_t num) +{ + size_t i; + for(i = 0; i != num; ++i) coin_init(&coins[i]); +} + +static void cleanup_coins(Coin* coins, size_t num) +{ + size_t i; + for(i = 0; i != num; ++i) coin_cleanup(&coins[i]); +} + +static int coin_compare(const void* a, const void* b) { + float wa = ((const Coin*)a)->weight; + float wb = ((const Coin*)b)->weight; + return wa > wb ? 1 : wa < wb ? -1 : 0; +} + +static unsigned append_symbol_coins(Coin* coins, const unsigned* frequencies, unsigned numcodes, size_t sum) +{ + unsigned i; + unsigned j = 0; /*index of present symbols*/ + for(i = 0; i != numcodes; ++i) + { + if(frequencies[i] != 0) /*only include symbols that are present*/ + { + coins[j].weight = frequencies[i] / (float)sum; + uivector_push_back(&coins[j].symbols, i); + ++j; + } + } + return 0; +} + +unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, + size_t numcodes, unsigned maxbitlen) +{ + unsigned i, j; + size_t sum = 0, numpresent = 0; + unsigned error = 0; + Coin* coins; /*the coins of the currently calculated row*/ + Coin* prev_row; /*the previous row of coins*/ + size_t numcoins; + size_t coinmem; + + if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ + + for(i = 0; i != numcodes; ++i) + { + if(frequencies[i] > 0) + { + ++numpresent; + sum += frequencies[i]; + } + } + + for(i = 0; i != numcodes; ++i) lengths[i] = 0; + + /*ensure at least two present symbols. There should be at least one symbol + according to RFC 1951 section 3.2.7. To decoders incorrectly require two. To + make these work as well ensure there are at least two symbols. The + Package-Merge code below also doesn't work correctly if there's only one + symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/ + if(numpresent == 0) + { + lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/ + } + else if(numpresent == 1) + { + for(i = 0; i != numcodes; ++i) + { + if(frequencies[i]) + { + lengths[i] = 1; + lengths[i == 0 ? 1 : 0] = 1; + break; + } + } + } + else + { + /*Package-Merge algorithm represented by coin collector's problem + For every symbol, maxbitlen coins will be created*/ + + coinmem = numpresent * 2; /*max amount of coins needed with the current algo*/ + coins = (Coin*)lodepng_malloc(sizeof(Coin) * coinmem); + prev_row = (Coin*)lodepng_malloc(sizeof(Coin) * coinmem); + if(!coins || !prev_row) + { + lodepng_free(coins); + lodepng_free(prev_row); + return 83; /*alloc fail*/ + } + init_coins(coins, coinmem); + init_coins(prev_row, coinmem); + + /*first row, lowest denominator*/ + error = append_symbol_coins(coins, frequencies, numcodes, sum); + numcoins = numpresent; + qsort(coins, numcoins, sizeof(Coin), coin_compare); + if(!error) + { + unsigned numprev = 0; + for(j = 1; j <= maxbitlen && !error; ++j) /*each of the remaining rows*/ + { + unsigned tempnum; + Coin* tempcoins; + /*swap prev_row and coins, and their amounts*/ + tempcoins = prev_row; prev_row = coins; coins = tempcoins; + tempnum = numprev; numprev = numcoins; numcoins = tempnum; + + cleanup_coins(coins, numcoins); + init_coins(coins, numcoins); + + numcoins = 0; + + /*fill in the merged coins of the previous row*/ + for(i = 0; i + 1 < numprev; i += 2) + { + /*merge prev_row[i] and prev_row[i + 1] into new coin*/ + Coin* coin = &coins[numcoins++]; + coin_copy(coin, &prev_row[i]); + add_coins(coin, &prev_row[i + 1]); + } + /*fill in all the original symbols again*/ + if(j < maxbitlen) + { + error = append_symbol_coins(coins + numcoins, frequencies, numcodes, sum); + numcoins += numpresent; + } + qsort(coins, numcoins, sizeof(Coin), coin_compare); + } + } + + if(!error) + { + /*calculate the lengths of each symbol, as the amount of times a coin of each symbol is used*/ + for(i = 0; i + 1 < numpresent; ++i) + { + Coin* coin = &coins[i]; + for(j = 0; j < coin->symbols.size; ++j) ++lengths[coin->symbols.data[j]]; + } + } + + cleanup_coins(coins, coinmem); + lodepng_free(coins); + cleanup_coins(prev_row, coinmem); + lodepng_free(prev_row); + } + + return error; +} + +/*Create the Huffman tree given the symbol frequencies*/ +static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, + size_t mincodes, size_t numcodes, unsigned maxbitlen) +{ + unsigned error = 0; + while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/ + tree->maxbitlen = maxbitlen; + tree->numcodes = (unsigned)numcodes; /*number of symbols*/ + tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned)); + if(!tree->lengths) return 83; /*alloc fail*/ + /*initialize all lengths to 0*/ + memset(tree->lengths, 0, numcodes * sizeof(unsigned)); + + error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); + if(!error) error = HuffmanTree_makeFromLengths2(tree); + return error; +} + +static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) +{ + return tree->tree1d[index]; +} + +static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) +{ + return tree->lengths[index]; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/ +static unsigned generateFixedLitLenTree(HuffmanTree* tree) +{ + unsigned i, error = 0; + unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); + if(!bitlen) return 83; /*alloc fail*/ + + /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/ + for(i = 0; i <= 143; ++i) bitlen[i] = 8; + for(i = 144; i <= 255; ++i) bitlen[i] = 9; + for(i = 256; i <= 279; ++i) bitlen[i] = 7; + for(i = 280; i <= 287; ++i) bitlen[i] = 8; + + error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15); + + lodepng_free(bitlen); + return error; +} + +/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/ +static unsigned generateFixedDistanceTree(HuffmanTree* tree) +{ + unsigned i, error = 0; + unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); + if(!bitlen) return 83; /*alloc fail*/ + + /*there are 32 distance codes, but 30-31 are unused*/ + for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5; + error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15); + + lodepng_free(bitlen); + return error; +} + +#ifdef LODEPNG_COMPILE_DECODER + +/* +returns the code, or (unsigned)(-1) if error happened +inbitlength is the length of the complete buffer, in bits (so its byte length times 8) +*/ +static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp, + const HuffmanTree* codetree, size_t inbitlength) +{ + unsigned treepos = 0, ct; + for(;;) + { + if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/ + /* + decode the symbol from the tree. The "readBitFromStream" code is inlined in + the expression below because this is the biggest bottleneck while decoding + */ + ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)]; + ++(*bp); + if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/ + else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/ + + if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/ + } +} +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Inflator (Decompressor) / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/ +static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) +{ + /*TODO: check for out of memory errors*/ + generateFixedLitLenTree(tree_ll); + generateFixedDistanceTree(tree_d); +} + +/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/ +static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, + const unsigned char* in, size_t* bp, size_t inlength) +{ + /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/ + unsigned error = 0; + unsigned n, HLIT, HDIST, HCLEN, i; + size_t inbitlength = inlength * 8; + + /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/ + unsigned* bitlen_ll = 0; /*lit,len code lengths*/ + unsigned* bitlen_d = 0; /*dist code lengths*/ + /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/ + unsigned* bitlen_cl = 0; + HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/ + + if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/ + + /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/ + HLIT = readBitsFromStream(bp, in, 5) + 257; + /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/ + HDIST = readBitsFromStream(bp, in, 5) + 1; + /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/ + HCLEN = readBitsFromStream(bp, in, 4) + 4; + + if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/ + + HuffmanTree_init(&tree_cl); + + while(!error) + { + /*read the code length codes out of 3 * (amount of code length codes) bits*/ + + bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); + if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/); + + for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i) + { + if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3); + else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/ + } + + error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7); + if(error) break; + + /*now we can use this tree to read the lengths for the tree that this function will return*/ + bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); + bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); + if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/); + for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0; + for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0; + + /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/ + i = 0; + while(i < HLIT + HDIST) + { + unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength); + if(code <= 15) /*a length code*/ + { + if(i < HLIT) bitlen_ll[i] = code; + else bitlen_d[i - HLIT] = code; + ++i; + } + else if(code == 16) /*repeat previous*/ + { + unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/ + unsigned value; /*set value to the previous code*/ + + if (i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/ + + if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + replength += readBitsFromStream(bp, in, 2); + + if(i < HLIT + 1) value = bitlen_ll[i - 1]; + else value = bitlen_d[i - HLIT - 1]; + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) + { + if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/ + if(i < HLIT) bitlen_ll[i] = value; + else bitlen_d[i - HLIT] = value; + ++i; + } + } + else if(code == 17) /*repeat "0" 3-10 times*/ + { + unsigned replength = 3; /*read in the bits that indicate repeat length*/ + if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + replength += readBitsFromStream(bp, in, 3); + + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) + { + if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/ + + if(i < HLIT) bitlen_ll[i] = 0; + else bitlen_d[i - HLIT] = 0; + ++i; + } + } + else if(code == 18) /*repeat "0" 11-138 times*/ + { + unsigned replength = 11; /*read in the bits that indicate repeat length*/ + if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ + replength += readBitsFromStream(bp, in, 7); + + /*repeat this value in the next lengths*/ + for(n = 0; n < replength; ++n) + { + if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/ + + if(i < HLIT) bitlen_ll[i] = 0; + else bitlen_d[i - HLIT] = 0; + ++i; + } + } + else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ + { + if(code == (unsigned)(-1)) + { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + error = (*bp) > inbitlength ? 10 : 11; + } + else error = 16; /*unexisting code, this can never happen*/ + break; + } + } + if(error) break; + + if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/ + + /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/ + error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15); + if(error) break; + error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15); + + break; /*end of error-while*/ + } + + lodepng_free(bitlen_cl); + lodepng_free(bitlen_ll); + lodepng_free(bitlen_d); + HuffmanTree_cleanup(&tree_cl); + + return error; +} + +/*inflate a block with dynamic of fixed Huffman tree*/ +static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp, + size_t* pos, size_t inlength, unsigned btype) +{ + unsigned error = 0; + HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ + HuffmanTree tree_d; /*the huffman tree for distance codes*/ + size_t inbitlength = inlength * 8; + + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + + if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d); + else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength); + + while(!error) /*decode all symbols until end reached, breaks at end code*/ + { + /*code_ll is literal, length or end code*/ + unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength); + if(code_ll <= 255) /*literal symbol*/ + { + /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/ + if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/); + out->data[*pos] = (unsigned char)code_ll; + ++(*pos); + } + else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ + { + unsigned code_d, distance; + unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/ + size_t start, forward, backward, length; + + /*part 1: get length base*/ + length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX]; + + /*part 2: get extra bits and add the value of that to length*/ + numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX]; + if((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ + length += readBitsFromStream(bp, in, numextrabits_l); + + /*part 3: get distance code*/ + code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength); + if(code_d > 29) + { + if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ + { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + error = (*bp) > inlength * 8 ? 10 : 11; + } + else error = 18; /*error: invalid distance code (30-31 are never used)*/ + break; + } + distance = DISTANCEBASE[code_d]; + + /*part 4: get extra bits from distance*/ + numextrabits_d = DISTANCEEXTRA[code_d]; + if((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ + distance += readBitsFromStream(bp, in, numextrabits_d); + + /*part 5: fill in all the out[n] values based on the length and dist*/ + start = (*pos); + if(distance > start) ERROR_BREAK(52); /*too long backward distance*/ + backward = start - distance; + + if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/); + for(forward = 0; forward < length; ++forward) + { + out->data[(*pos)] = out->data[backward]; + ++(*pos); + ++backward; + if(backward >= start) backward = start - distance; + } + } + else if(code_ll == 256) + { + break; /*end code, break the loop*/ + } + else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ + { + /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol + (10=no endcode, 11=wrong jump outside of tree)*/ + error = ((*bp) > inlength * 8) ? 10 : 11; + break; + } + } + + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + + return error; +} + +static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength) +{ + size_t p; + unsigned LEN, NLEN, n, error = 0; + + /*go to first boundary of byte*/ + while(((*bp) & 0x7) != 0) ++(*bp); + p = (*bp) / 8; /*byte position*/ + + /*read LEN (2 bytes) and NLEN (2 bytes)*/ + if(p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/ + LEN = in[p] + 256u * in[p + 1]; p += 2; + NLEN = in[p] + 256u * in[p + 1]; p += 2; + + /*check if 16-bit NLEN is really the one's complement of LEN*/ + if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/ + + if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/ + + /*read the literal data: LEN bytes are now stored in the out buffer*/ + if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/ + for(n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++]; + + (*bp) = p * 8; + + return error; +} + +static unsigned lodepng_inflatev(ucvector* out, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) +{ + /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/ + size_t bp = 0; + unsigned BFINAL = 0; + size_t pos = 0; /*byte position in the out buffer*/ + unsigned error = 0; + + (void)settings; + + while(!BFINAL) + { + unsigned BTYPE; + if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/ + BFINAL = readBitFromStream(&bp, in); + BTYPE = 1u * readBitFromStream(&bp, in); + BTYPE += 2u * readBitFromStream(&bp, in); + + if(BTYPE == 3) return 20; /*error: invalid BTYPE*/ + else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/ + else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/ + + if(error) return error; + } + + return error; +} + +unsigned lodepng_inflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) +{ + unsigned error; + ucvector v; + ucvector_init_buffer(&v, *out, *outsize); + error = lodepng_inflatev(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; +} + +static unsigned inflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings) +{ + if(settings->custom_inflate) + { + return settings->custom_inflate(out, outsize, in, insize, settings); + } + else + { + return lodepng_inflate(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Deflator (Compressor) / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258; + +/*bitlen is the size in bits of the code*/ +static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen) +{ + addBitsToStreamReversed(bp, compressed, code, bitlen); +} + +/*search the index in the array, that has the largest value smaller than or equal to the given value, +given array must be sorted (if no value is smaller, it returns the size of the given array)*/ +static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) +{ + /*linear search implementation*/ + /*for(size_t i = 1; i < array_size; ++i) if(array[i] > value) return i - 1; + return array_size - 1;*/ + + /*binary search implementation (not that much faster) (precondition: array_size > 0)*/ + size_t left = 1; + size_t right = array_size - 1; + while(left <= right) + { + size_t mid = (left + right) / 2; + if(array[mid] <= value) left = mid + 1; /*the value to find is more to the right*/ + else if(array[mid - 1] > value) right = mid - 1; /*the value to find is more to the left*/ + else return mid - 1; + } + return array_size - 1; +} + +static void addLengthDistance(uivector* values, size_t length, size_t distance) +{ + /*values in encoded vector are those used by deflate: + 0-255: literal bytes + 256: end + 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits) + 286-287: invalid*/ + + unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length); + unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]); + unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance); + unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]); + + uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX); + uivector_push_back(values, extra_length); + uivector_push_back(values, dist_code); + uivector_push_back(values, extra_distance); +} + +/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3 +bytes as input because 3 is the minimum match length for deflate*/ +static const unsigned HASH_NUM_VALUES = 65536; +static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/ + +typedef struct Hash +{ + int* head; /*hash value to head circular pos - can be outdated if went around window*/ + /*circular pos to prev circular pos*/ + unsigned short* chain; + int* val; /*circular pos to hash value*/ + + /*TODO: do this not only for zeros but for any repeated byte. However for PNG + it's always going to be the zeros that dominate, so not important for PNG*/ + int* headz; /*similar to head, but for chainz*/ + unsigned short* chainz; /*those with same amount of zeros*/ + unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/ +} Hash; + +static unsigned hash_init(Hash* hash, unsigned windowsize) +{ + unsigned i; + hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES); + hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize); + hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + + hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1)); + hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); + + if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) + { + return 83; /*alloc fail*/ + } + + /*initialize hash table*/ + for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1; + for(i = 0; i != windowsize; ++i) hash->val[i] = -1; + for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/ + + for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1; + for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/ + + return 0; +} + +static void hash_cleanup(Hash* hash) +{ + lodepng_free(hash->head); + lodepng_free(hash->val); + lodepng_free(hash->chain); + + lodepng_free(hash->zeros); + lodepng_free(hash->headz); + lodepng_free(hash->chainz); +} + + + +static unsigned getHash(const unsigned char* data, size_t size, size_t pos) +{ + unsigned result = 0; + if (pos + 2 < size) + { + /*A simple shift and xor hash is used. Since the data of PNGs is dominated + by zeroes due to the filters, a better hash does not have a significant + effect on speed in traversing the chain, and causes more time spend on + calculating the hash.*/ + result ^= (unsigned)(data[pos + 0] << 0u); + result ^= (unsigned)(data[pos + 1] << 4u); + result ^= (unsigned)(data[pos + 2] << 8u); + } else { + size_t amount, i; + if(pos >= size) return 0; + amount = size - pos; + for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u)); + } + return result & HASH_BIT_MASK; +} + +static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) +{ + const unsigned char* start = data + pos; + const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH; + if(end > data + size) end = data + size; + data = start; + while (data != end && *data == 0) ++data; + /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/ + return (unsigned)(data - start); +} + +/*wpos = pos & (windowsize - 1)*/ +static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) +{ + hash->val[wpos] = (int)hashval; + if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; + hash->head[hashval] = wpos; + + hash->zeros[wpos] = numzeros; + if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; + hash->headz[numzeros] = wpos; +} + +/* +LZ77-encode the data. Return value is error code. The input are raw bytes, the output +is in the form of unsigned integers with codes representing for example literal bytes, or +length/distance pairs. +It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a +sliding window (of windowsize) is used, and all past bytes in that window can be used as +the "dictionary". A brute force search through all possible distances would be slow, and +this hash technique is one out of several ways to speed this up. +*/ +static unsigned encodeLZ77(uivector* out, Hash* hash, + const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize, + unsigned minmatch, unsigned nicematch, unsigned lazymatching) +{ + size_t pos; + unsigned i, error = 0; + /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/ + unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8; + unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64; + + unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/ + unsigned numzeros = 0; + + unsigned offset; /*the offset represents the distance in LZ77 terminology*/ + unsigned length; + unsigned lazy = 0; + unsigned lazylength = 0, lazyoffset = 0; + unsigned hashval; + unsigned current_offset, current_length; + unsigned prev_offset; + const unsigned char *lastptr, *foreptr, *backptr; + unsigned hashpos; + + if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/ + if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/ + + if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH; + + for(pos = inpos; pos < insize; ++pos) + { + size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/ + unsigned chainlength = 0; + + hashval = getHash(in, insize, pos); + + if(usezeros && hashval == 0) + { + if (numzeros == 0) numzeros = countZeros(in, insize, pos); + else if (pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; + } + else + { + numzeros = 0; + } + + updateHashChain(hash, wpos, hashval, numzeros); + + /*the length and offset found for the current position*/ + length = 0; + offset = 0; + + hashpos = hash->chain[wpos]; + + lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH]; + + /*search for the longest string*/ + prev_offset = 0; + for(;;) + { + if(chainlength++ >= maxchainlength) break; + current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize; + + if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ + prev_offset = current_offset; + if(current_offset > 0) + { + /*test the next characters*/ + foreptr = &in[pos]; + backptr = &in[pos - current_offset]; + + /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/ + if(numzeros >= 3) + { + unsigned skip = hash->zeros[hashpos]; + if(skip > numzeros) skip = numzeros; + backptr += skip; + foreptr += skip; + } + + while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ + { + ++backptr; + ++foreptr; + } + current_length = (unsigned)(foreptr - &in[pos]); + + if(current_length > length) + { + length = current_length; /*the longest length*/ + offset = current_offset; /*the offset that is related to this longest length*/ + /*jump out once a length of max length is found (speed gain). This also jumps + out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/ + if(current_length >= nicematch) break; + } + } + + if(hashpos == hash->chain[hashpos]) break; + + if(numzeros >= 3 && length > numzeros) { + hashpos = hash->chainz[hashpos]; + if(hash->zeros[hashpos] != numzeros) break; + } else { + hashpos = hash->chain[hashpos]; + /*outdated hash value, happens if particular value was not encountered in whole last window*/ + if(hash->val[hashpos] != (int)hashval) break; + } + } + + if(lazymatching) + { + if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) + { + lazy = 1; + lazylength = length; + lazyoffset = offset; + continue; /*try the next byte*/ + } + if(lazy) + { + lazy = 0; + if(pos == 0) ERROR_BREAK(81); + if(length > lazylength + 1) + { + /*push the previous character as literal*/ + if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/); + } + else + { + length = lazylength; + offset = lazyoffset; + hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/ + hash->headz[numzeros] = -1; /*idem*/ + --pos; + } + } + } + if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/); + + /*encode it as length/distance pair or literal value*/ + if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ + { + if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); + } + else if(length < minmatch || (length == 3 && offset > 4096)) + { + /*compensate for the fact that longer offsets have more extra bits, a + length of only 3 may be not worth it then*/ + if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); + } + else + { + addLengthDistance(out, length, offset); + for(i = 1; i < length; ++i) + { + ++pos; + wpos = pos & (windowsize - 1); + hashval = getHash(in, insize, pos); + if(usezeros && hashval == 0) + { + if (numzeros == 0) numzeros = countZeros(in, insize, pos); + else if (pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; + } + else + { + numzeros = 0; + } + updateHashChain(hash, wpos, hashval, numzeros); + } + } + } /*end of the loop through each character of input*/ + + return error; +} + +/* /////////////////////////////////////////////////////////////////////////// */ + +static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) +{ + /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte, + 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/ + + size_t i, j, numdeflateblocks = (datasize + 65534) / 65535; + unsigned datapos = 0; + for(i = 0; i != numdeflateblocks; ++i) + { + unsigned BFINAL, BTYPE, LEN, NLEN; + unsigned char firstbyte; + + BFINAL = (i == numdeflateblocks - 1); + BTYPE = 0; + + firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1)); + ucvector_push_back(out, firstbyte); + + LEN = 65535; + if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos; + NLEN = 65535 - LEN; + + ucvector_push_back(out, (unsigned char)(LEN % 256)); + ucvector_push_back(out, (unsigned char)(LEN / 256)); + ucvector_push_back(out, (unsigned char)(NLEN % 256)); + ucvector_push_back(out, (unsigned char)(NLEN / 256)); + + /*Decompressed data*/ + for(j = 0; j < 65535 && datapos < datasize; ++j) + { + ucvector_push_back(out, data[datapos++]); + } + } + + return 0; +} + +/* +write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees. +tree_ll: the tree for lit and len codes. +tree_d: the tree for distance codes. +*/ +static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded, + const HuffmanTree* tree_ll, const HuffmanTree* tree_d) +{ + size_t i = 0; + for(i = 0; i != lz77_encoded->size; ++i) + { + unsigned val = lz77_encoded->data[i]; + addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val)); + if(val > 256) /*for a length code, 3 more things have to be added*/ + { + unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; + unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; + unsigned length_extra_bits = lz77_encoded->data[++i]; + + unsigned distance_code = lz77_encoded->data[++i]; + + unsigned distance_index = distance_code; + unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; + unsigned distance_extra_bits = lz77_encoded->data[++i]; + + addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits); + addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code), + HuffmanTree_getLength(tree_d, distance_code)); + addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits); + } + } +} + +/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/ +static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, + const unsigned char* data, size_t datapos, size_t dataend, + const LodePNGCompressSettings* settings, unsigned final) +{ + unsigned error = 0; + + /* + A block is compressed as follows: The PNG data is lz77 encoded, resulting in + literal bytes and length/distance pairs. This is then huffman compressed with + two huffman trees. One huffman tree is used for the lit and len values ("ll"), + another huffman tree is used for the dist values ("d"). These two trees are + stored using their code lengths, and to compress even more these code lengths + are also run-length encoded and huffman compressed. This gives a huffman tree + of code lengths "cl". The code lenghts used to describe this third tree are + the code length code lengths ("clcl"). + */ + + /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/ + uivector lz77_encoded; + HuffmanTree tree_ll; /*tree for lit,len values*/ + HuffmanTree tree_d; /*tree for distance codes*/ + HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/ + uivector frequencies_ll; /*frequency of lit,len codes*/ + uivector frequencies_d; /*frequency of dist codes*/ + uivector frequencies_cl; /*frequency of code length codes*/ + uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/ + uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/ + /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl + (these are written as is in the file, it would be crazy to compress these using yet another huffman + tree that needs to be represented by yet another set of code lengths)*/ + uivector bitlen_cl; + size_t datasize = dataend - datapos; + + /* + Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies: + bitlen_lld is to tree_cl what data is to tree_ll and tree_d. + bitlen_lld_e is to bitlen_lld what lz77_encoded is to data. + bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded. + */ + + unsigned BFINAL = final; + size_t numcodes_ll, numcodes_d, i; + unsigned HLIT, HDIST, HCLEN; + + uivector_init(&lz77_encoded); + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + HuffmanTree_init(&tree_cl); + uivector_init(&frequencies_ll); + uivector_init(&frequencies_d); + uivector_init(&frequencies_cl); + uivector_init(&bitlen_lld); + uivector_init(&bitlen_lld_e); + uivector_init(&bitlen_cl); + + /*This while loop never loops due to a break at the end, it is here to + allow breaking out of it to the cleanup phase on error conditions.*/ + while(!error) + { + if(settings->use_lz77) + { + error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, + settings->minmatch, settings->nicematch, settings->lazymatching); + if(error) break; + } + else + { + if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/); + for(i = datapos; i < dataend; ++i) lz77_encoded.data[i] = data[i]; /*no LZ77, but still will be Huffman compressed*/ + } + + if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/); + if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/); + + /*Count the frequencies of lit, len and dist codes*/ + for(i = 0; i != lz77_encoded.size; ++i) + { + unsigned symbol = lz77_encoded.data[i]; + ++frequencies_ll.data[symbol]; + if(symbol > 256) + { + unsigned dist = lz77_encoded.data[i + 2]; + ++frequencies_d.data[dist]; + i += 3; + } + } + frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/ + + /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/ + error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15); + if(error) break; + /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/ + error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15); + if(error) break; + + numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286; + numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30; + /*store the code lengths of both generated trees in bitlen_lld*/ + for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i)); + for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i)); + + /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times), + 17 (3-10 zeroes), 18 (11-138 zeroes)*/ + for(i = 0; i != (unsigned)bitlen_lld.size; ++i) + { + unsigned j = 0; /*amount of repititions*/ + while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j; + + if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ + { + ++j; /*include the first zero*/ + if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ + { + uivector_push_back(&bitlen_lld_e, 17); + uivector_push_back(&bitlen_lld_e, j - 3); + } + else /*repeat code 18 supports max 138 zeroes*/ + { + if(j > 138) j = 138; + uivector_push_back(&bitlen_lld_e, 18); + uivector_push_back(&bitlen_lld_e, j - 11); + } + i += (j - 1); + } + else if(j >= 3) /*repeat code for value other than zero*/ + { + size_t k; + unsigned num = j / 6, rest = j % 6; + uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); + for(k = 0; k < num; ++k) + { + uivector_push_back(&bitlen_lld_e, 16); + uivector_push_back(&bitlen_lld_e, 6 - 3); + } + if(rest >= 3) + { + uivector_push_back(&bitlen_lld_e, 16); + uivector_push_back(&bitlen_lld_e, rest - 3); + } + else j -= rest; + i += j; + } + else /*too short to benefit from repeat code*/ + { + uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); + } + } + + /*generate tree_cl, the huffmantree of huffmantrees*/ + + if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/); + for(i = 0; i != bitlen_lld_e.size; ++i) + { + ++frequencies_cl.data[bitlen_lld_e.data[i]]; + /*after a repeat code come the bits that specify the number of repetitions, + those don't need to be in the frequencies_cl calculation*/ + if(bitlen_lld_e.data[i] >= 16) ++i; + } + + error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data, + frequencies_cl.size, frequencies_cl.size, 7); + if(error) break; + + if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/); + for(i = 0; i != tree_cl.numcodes; ++i) + { + /*lenghts of code length tree is in the order as specified by deflate*/ + bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]); + } + while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) + { + /*remove zeros at the end, but minimum size must be 4*/ + if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/); + } + if(error) break; + + /* + Write everything into the output + + After the BFINAL and BTYPE, the dynamic block consists out of the following: + - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN + - (HCLEN+4)*3 bits code lengths of code length alphabet + - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length + alphabet, + possible repetition codes 16, 17, 18) + - HDIST + 1 code lengths of distance alphabet (encoded using the code length + alphabet, + possible repetition codes 16, 17, 18) + - compressed data + - 256 (end code) + */ + + /*Write block type*/ + addBitToStream(bp, out, BFINAL); + addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/ + addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/ + + /*write the HLIT, HDIST and HCLEN values*/ + HLIT = (unsigned)(numcodes_ll - 257); + HDIST = (unsigned)(numcodes_d - 1); + HCLEN = (unsigned)bitlen_cl.size - 4; + /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/ + while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN; + addBitsToStream(bp, out, HLIT, 5); + addBitsToStream(bp, out, HDIST, 5); + addBitsToStream(bp, out, HCLEN, 4); + + /*write the code lenghts of the code length alphabet*/ + for(i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3); + + /*write the lenghts of the lit/len AND the dist alphabet*/ + for(i = 0; i != bitlen_lld_e.size; ++i) + { + addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]), + HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i])); + /*extra bits of repeat codes*/ + if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2); + else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3); + else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7); + } + + /*write the compressed data symbols*/ + writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); + /*error: the length of the end code 256 must be larger than 0*/ + if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64); + + /*write the end code*/ + addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); + + break; /*end of error-while*/ + } + + /*cleanup*/ + uivector_cleanup(&lz77_encoded); + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + HuffmanTree_cleanup(&tree_cl); + uivector_cleanup(&frequencies_ll); + uivector_cleanup(&frequencies_d); + uivector_cleanup(&frequencies_cl); + uivector_cleanup(&bitlen_lld_e); + uivector_cleanup(&bitlen_lld); + uivector_cleanup(&bitlen_cl); + + return error; +} + +static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash, + const unsigned char* data, + size_t datapos, size_t dataend, + const LodePNGCompressSettings* settings, unsigned final) +{ + HuffmanTree tree_ll; /*tree for literal values and length codes*/ + HuffmanTree tree_d; /*tree for distance codes*/ + + unsigned BFINAL = final; + unsigned error = 0; + size_t i; + + HuffmanTree_init(&tree_ll); + HuffmanTree_init(&tree_d); + + generateFixedLitLenTree(&tree_ll); + generateFixedDistanceTree(&tree_d); + + addBitToStream(bp, out, BFINAL); + addBitToStream(bp, out, 1); /*first bit of BTYPE*/ + addBitToStream(bp, out, 0); /*second bit of BTYPE*/ + + if(settings->use_lz77) /*LZ77 encoded*/ + { + uivector lz77_encoded; + uivector_init(&lz77_encoded); + error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, + settings->minmatch, settings->nicematch, settings->lazymatching); + if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); + uivector_cleanup(&lz77_encoded); + } + else /*no LZ77, but still will be Huffman compressed*/ + { + for(i = datapos; i < dataend; ++i) + { + addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i])); + } + } + /*add END code*/ + if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); + + /*cleanup*/ + HuffmanTree_cleanup(&tree_ll); + HuffmanTree_cleanup(&tree_d); + + return error; +} + +static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) +{ + unsigned error = 0; + size_t i, blocksize, numdeflateblocks; + size_t bp = 0; /*the bit pointer*/ + Hash hash; + + if(settings->btype > 2) return 61; + else if(settings->btype == 0) return deflateNoCompression(out, in, insize); + else if(settings->btype == 1) blocksize = insize; + else /*if(settings->btype == 2)*/ + { + blocksize = insize / 8 + 8; + if(blocksize < 65535) blocksize = 65535; + } + + numdeflateblocks = (insize + blocksize - 1) / blocksize; + if(numdeflateblocks == 0) numdeflateblocks = 1; + + error = hash_init(&hash, settings->windowsize); + if(error) return error; + + for(i = 0; i != numdeflateblocks && !error; ++i) + { + unsigned final = (i == numdeflateblocks - 1); + size_t start = i * blocksize; + size_t end = start + blocksize; + if(end > insize) end = insize; + + if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final); + else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final); + } + + hash_cleanup(&hash); + + return error; +} + +unsigned lodepng_deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) +{ + unsigned error; + ucvector v; + ucvector_init_buffer(&v, *out, *outsize); + error = lodepng_deflatev(&v, in, insize, settings); + *out = v.data; + *outsize = v.size; + return error; +} + +static unsigned deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings) +{ + if(settings->custom_deflate) + { + return settings->custom_deflate(out, outsize, in, insize, settings); + } + else + { + return lodepng_deflate(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Adler32 */ +/* ////////////////////////////////////////////////////////////////////////// */ + +static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) +{ + unsigned s1 = adler & 0xffff; + unsigned s2 = (adler >> 16) & 0xffff; + + while(len > 0) + { + /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/ + unsigned amount = len > 5550 ? 5550 : len; + len -= amount; + while(amount > 0) + { + s1 += (*data++); + s2 += s1; + --amount; + } + s1 %= 65521; + s2 %= 65521; + } + + return (s2 << 16) | s1; +} + +/*Return the adler32 of the bytes data[0..len-1]*/ +static unsigned adler32(const unsigned char* data, unsigned len) +{ + return update_adler32(1L, data, len); +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Zlib / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_DECODER + +unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGDecompressSettings* settings) +{ + unsigned error = 0; + unsigned CM, CINFO, FDICT; + + if(insize < 2) return 53; /*error, size of zlib data too small*/ + /*read information from zlib header*/ + if((in[0] * 256 + in[1]) % 31 != 0) + { + /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/ + return 24; + } + + CM = in[0] & 15; + CINFO = (in[0] >> 4) & 15; + /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/ + FDICT = (in[1] >> 5) & 1; + /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/ + + if(CM != 8 || CINFO > 7) + { + /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/ + return 25; + } + if(FDICT != 0) + { + /*error: the specification of PNG says about the zlib stream: + "The additional flags shall not specify a preset dictionary."*/ + return 26; + } + + error = inflate(out, outsize, in + 2, insize - 2, settings); + if(error) return error; + + if(!settings->ignore_adler32) + { + unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); + unsigned checksum = adler32(*out, (unsigned)(*outsize)); + if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ + } + + return 0; /*no error*/ +} + +static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGDecompressSettings* settings) +{ + if(settings->custom_zlib) + { + return settings->custom_zlib(out, outsize, in, insize, settings); + } + else + { + return lodepng_zlib_decompress(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER + +unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) +{ + /*initially, *out must be NULL and outsize 0, if you just give some random *out + that's pointing to a non allocated buffer, this'll crash*/ + ucvector outv; + size_t i; + unsigned error; + unsigned char* deflatedata = 0; + size_t deflatesize = 0; + + /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/ + unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/ + unsigned FLEVEL = 0; + unsigned FDICT = 0; + unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64; + unsigned FCHECK = 31 - CMFFLG % 31; + CMFFLG += FCHECK; + + /*ucvector-controlled version of the output buffer, for dynamic array*/ + ucvector_init_buffer(&outv, *out, *outsize); + + ucvector_push_back(&outv, (unsigned char)(CMFFLG / 256)); + ucvector_push_back(&outv, (unsigned char)(CMFFLG % 256)); + + error = deflate(&deflatedata, &deflatesize, in, insize, settings); + + if(!error) + { + unsigned ADLER32 = adler32(in, (unsigned)insize); + for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]); + lodepng_free(deflatedata); + lodepng_add32bitInt(&outv, ADLER32); + } + + *out = outv.data; + *outsize = outv.size; + + return error; +} + +/* compress using the default or custom zlib function */ +static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) +{ + if(settings->custom_zlib) + { + return settings->custom_zlib(out, outsize, in, insize, settings); + } + else + { + return lodepng_zlib_compress(out, outsize, in, insize, settings); + } +} + +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#else /*no LODEPNG_COMPILE_ZLIB*/ + +#ifdef LODEPNG_COMPILE_DECODER +static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGDecompressSettings* settings) +{ + if (!settings->custom_zlib) return 87; /*no custom zlib function provided */ + return settings->custom_zlib(out, outsize, in, insize, settings); +} +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER +static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, + size_t insize, const LodePNGCompressSettings* settings) +{ + if (!settings->custom_zlib) return 87; /*no custom zlib function provided */ + return settings->custom_zlib(out, outsize, in, insize, settings); +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#endif /*LODEPNG_COMPILE_ZLIB*/ + +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_ENCODER + +/*this is a good tradeoff between speed and compression ratio*/ +#define DEFAULT_WINDOWSIZE 2048 + +void lodepng_compress_settings_init(LodePNGCompressSettings* settings) +{ + /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/ + settings->btype = 2; + settings->use_lz77 = 1; + settings->windowsize = DEFAULT_WINDOWSIZE; + settings->minmatch = 3; + settings->nicematch = 128; + settings->lazymatching = 1; + + settings->custom_zlib = 0; + settings->custom_deflate = 0; + settings->custom_context = 0; +} + +const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0}; + + +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DECODER + +void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) +{ + settings->ignore_adler32 = 0; + + settings->custom_zlib = 0; + settings->custom_inflate = 0; + settings->custom_context = 0; +} + +const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0}; + +#endif /*LODEPNG_COMPILE_DECODER*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // End of Zlib related code. Begin of PNG related code. // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_PNG + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / CRC32 / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/* CRC polynomial: 0xedb88320 */ +static unsigned lodepng_crc32_table[256] = { + 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, + 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, + 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u, + 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u, + 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u, + 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, + 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, + 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u, + 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u, + 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u, + 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, + 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, + 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u, + 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u, + 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u, + 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, + 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, + 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u, + 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u, + 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u, + 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, + 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, + 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u, + 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u, + 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u, + 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, + 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, + 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u, + 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u, + 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u, + 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, + 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u +}; + +/*Return the CRC of the bytes buf[0..len-1].*/ +unsigned lodepng_crc32(const unsigned char* buf, size_t len) +{ + unsigned c = 0xffffffffL; + size_t n; + + for(n = 0; n < len; ++n) + { + c = lodepng_crc32_table[(c ^ buf[n]) & 0xff] ^ (c >> 8); + } + return c ^ 0xffffffffL; +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Reading and writing single bits and bytes from/to stream for LodePNG / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) +{ + unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1); + ++(*bitpointer); + return result; +} + +static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) +{ + unsigned result = 0; + size_t i; + for(i = nbits - 1; i < nbits; --i) + { + result += (unsigned)readBitFromReversedStream(bitpointer, bitstream) << i; + } + return result; +} + +#ifdef LODEPNG_COMPILE_DECODER +static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) +{ + /*the current bit in bitstream must be 0 for this to work*/ + if(bit) + { + /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/ + bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7))); + } + ++(*bitpointer); +} +#endif /*LODEPNG_COMPILE_DECODER*/ + +static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) +{ + /*the current bit in bitstream may be 0 or 1 for this to work*/ + if(bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7)))); + else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7))); + ++(*bitpointer); +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG chunks / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +unsigned lodepng_chunk_length(const unsigned char* chunk) +{ + return lodepng_read32bitInt(&chunk[0]); +} + +void lodepng_chunk_type(char type[5], const unsigned char* chunk) +{ + unsigned i; + for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i]; + type[4] = 0; /*null termination char*/ +} + +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) +{ + if(strlen(type) != 4) return 0; + return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]); +} + +unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) +{ + return((chunk[4] & 32) != 0); +} + +unsigned char lodepng_chunk_private(const unsigned char* chunk) +{ + return((chunk[6] & 32) != 0); +} + +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) +{ + return((chunk[7] & 32) != 0); +} + +unsigned char* lodepng_chunk_data(unsigned char* chunk) +{ + return &chunk[8]; +} + +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) +{ + return &chunk[8]; +} + +unsigned lodepng_chunk_check_crc(const unsigned char* chunk) +{ + unsigned length = lodepng_chunk_length(chunk); + unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]); + /*the CRC is taken of the data and the 4 chunk type letters, not the length*/ + unsigned checksum = lodepng_crc32(&chunk[4], length + 4); + if(CRC != checksum) return 1; + else return 0; +} + +void lodepng_chunk_generate_crc(unsigned char* chunk) +{ + unsigned length = lodepng_chunk_length(chunk); + unsigned CRC = lodepng_crc32(&chunk[4], length + 4); + lodepng_set32bitInt(chunk + 8 + length, CRC); +} + +unsigned char* lodepng_chunk_next(unsigned char* chunk) +{ + unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; + return &chunk[total_chunk_length]; +} + +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) +{ + unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; + return &chunk[total_chunk_length]; +} + +unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) +{ + unsigned i; + unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; + unsigned char *chunk_start, *new_buffer; + size_t new_length = (*outlength) + total_chunk_length; + if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/ + + new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); + if(!new_buffer) return 83; /*alloc fail*/ + (*out) = new_buffer; + (*outlength) = new_length; + chunk_start = &(*out)[new_length - total_chunk_length]; + + for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i]; + + return 0; +} + +unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, + const char* type, const unsigned char* data) +{ + unsigned i; + unsigned char *chunk, *new_buffer; + size_t new_length = (*outlength) + length + 12; + if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/ + new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); + if(!new_buffer) return 83; /*alloc fail*/ + (*out) = new_buffer; + (*outlength) = new_length; + chunk = &(*out)[(*outlength) - length - 12]; + + /*1: length*/ + lodepng_set32bitInt(chunk, (unsigned)length); + + /*2: chunk name (4 letters)*/ + chunk[4] = (unsigned char)type[0]; + chunk[5] = (unsigned char)type[1]; + chunk[6] = (unsigned char)type[2]; + chunk[7] = (unsigned char)type[3]; + + /*3: the data*/ + for(i = 0; i != length; ++i) chunk[8 + i] = data[i]; + + /*4: CRC (of the chunkname characters and the data)*/ + lodepng_chunk_generate_crc(chunk); + + return 0; +} + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / Color types and such / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*return type is a LodePNG error code*/ +static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/ +{ + switch(colortype) + { + case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/ + case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/ + case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/ + case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/ + case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/ + default: return 31; + } + return 0; /*allowed color type / bits combination*/ +} + +static unsigned getNumColorChannels(LodePNGColorType colortype) +{ + switch(colortype) + { + case 0: return 1; /*grey*/ + case 2: return 3; /*RGB*/ + case 3: return 1; /*palette*/ + case 4: return 2; /*grey + alpha*/ + case 6: return 4; /*RGBA*/ + } + return 0; /*unexisting color type*/ +} + +static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) +{ + /*bits per pixel is amount of channels * bits per channel*/ + return getNumColorChannels(colortype) * bitdepth; +} + +/* ////////////////////////////////////////////////////////////////////////// */ + +void lodepng_color_mode_init(LodePNGColorMode* info) +{ + info->key_defined = 0; + info->key_r = info->key_g = info->key_b = 0; + info->colortype = LCT_RGBA; + info->bitdepth = 8; + info->palette = 0; + info->palettesize = 0; +} + +void lodepng_color_mode_cleanup(LodePNGColorMode* info) +{ + lodepng_palette_clear(info); +} + +unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) +{ + size_t i; + lodepng_color_mode_cleanup(dest); + *dest = *source; + if(source->palette) + { + dest->palette = (unsigned char*)lodepng_malloc(1024); + if(!dest->palette && source->palettesize) return 83; /*alloc fail*/ + for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i]; + } + return 0; +} + +static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) +{ + size_t i; + if(a->colortype != b->colortype) return 0; + if(a->bitdepth != b->bitdepth) return 0; + if(a->key_defined != b->key_defined) return 0; + if(a->key_defined) + { + if(a->key_r != b->key_r) return 0; + if(a->key_g != b->key_g) return 0; + if(a->key_b != b->key_b) return 0; + } + if(a->palettesize != b->palettesize) return 0; + for(i = 0; i != a->palettesize * 4; ++i) + { + if(a->palette[i] != b->palette[i]) return 0; + } + return 1; +} + +void lodepng_palette_clear(LodePNGColorMode* info) +{ + if(info->palette) lodepng_free(info->palette); + info->palette = 0; + info->palettesize = 0; +} + +unsigned lodepng_palette_add(LodePNGColorMode* info, + unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + unsigned char* data; + /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with + the max of 256 colors, it'll have the exact alloc size*/ + if(!info->palette) /*allocate palette if empty*/ + { + /*room for 256 colors with 4 bytes each*/ + data = (unsigned char*)lodepng_realloc(info->palette, 1024); + if(!data) return 83; /*alloc fail*/ + else info->palette = data; + } + info->palette[4 * info->palettesize + 0] = r; + info->palette[4 * info->palettesize + 1] = g; + info->palette[4 * info->palettesize + 2] = b; + info->palette[4 * info->palettesize + 3] = a; + ++info->palettesize; + return 0; +} + +unsigned lodepng_get_bpp(const LodePNGColorMode* info) +{ + /*calculate bits per pixel out of colortype and bitdepth*/ + return lodepng_get_bpp_lct(info->colortype, info->bitdepth); +} + +unsigned lodepng_get_channels(const LodePNGColorMode* info) +{ + return getNumColorChannels(info->colortype); +} + +unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) +{ + return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA; +} + +unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) +{ + return (info->colortype & 4) != 0; /*4 or 6*/ +} + +unsigned lodepng_is_palette_type(const LodePNGColorMode* info) +{ + return info->colortype == LCT_PALETTE; +} + +unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) +{ + size_t i; + for(i = 0; i != info->palettesize; ++i) + { + if(info->palette[i * 4 + 3] < 255) return 1; + } + return 0; +} + +unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) +{ + return info->key_defined + || lodepng_is_alpha_type(info) + || lodepng_has_palette_alpha(info); +} + +size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) +{ + return (w * h * lodepng_get_bpp(color) + 7) / 8; +} + +size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) +{ + return (w * h * lodepng_get_bpp_lct(colortype, bitdepth) + 7) / 8; +} + + +#ifdef LODEPNG_COMPILE_PNG +#ifdef LODEPNG_COMPILE_DECODER +/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/ +static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) +{ + return h * ((w * lodepng_get_bpp(color) + 7) / 8); +} +#endif /*LODEPNG_COMPILE_DECODER*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +static void LodePNGUnknownChunks_init(LodePNGInfo* info) +{ + unsigned i; + for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0; + for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0; +} + +static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) +{ + unsigned i; + for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]); +} + +static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) +{ + unsigned i; + + LodePNGUnknownChunks_cleanup(dest); + + for(i = 0; i != 3; ++i) + { + size_t j; + dest->unknown_chunks_size[i] = src->unknown_chunks_size[i]; + dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]); + if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/ + for(j = 0; j < src->unknown_chunks_size[i]; ++j) + { + dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j]; + } + } + + return 0; +} + +/******************************************************************************/ + +static void LodePNGText_init(LodePNGInfo* info) +{ + info->text_num = 0; + info->text_keys = NULL; + info->text_strings = NULL; +} + +static void LodePNGText_cleanup(LodePNGInfo* info) +{ + size_t i; + for(i = 0; i != info->text_num; ++i) + { + string_cleanup(&info->text_keys[i]); + string_cleanup(&info->text_strings[i]); + } + lodepng_free(info->text_keys); + lodepng_free(info->text_strings); +} + +static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) +{ + size_t i = 0; + dest->text_keys = 0; + dest->text_strings = 0; + dest->text_num = 0; + for(i = 0; i != source->text_num; ++i) + { + CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i])); + } + return 0; +} + +void lodepng_clear_text(LodePNGInfo* info) +{ + LodePNGText_cleanup(info); +} + +unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) +{ + char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1))); + char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1))); + if(!new_keys || !new_strings) + { + lodepng_free(new_keys); + lodepng_free(new_strings); + return 83; /*alloc fail*/ + } + + ++info->text_num; + info->text_keys = new_keys; + info->text_strings = new_strings; + + string_init(&info->text_keys[info->text_num - 1]); + string_set(&info->text_keys[info->text_num - 1], key); + + string_init(&info->text_strings[info->text_num - 1]); + string_set(&info->text_strings[info->text_num - 1], str); + + return 0; +} + +/******************************************************************************/ + +static void LodePNGIText_init(LodePNGInfo* info) +{ + info->itext_num = 0; + info->itext_keys = NULL; + info->itext_langtags = NULL; + info->itext_transkeys = NULL; + info->itext_strings = NULL; +} + +static void LodePNGIText_cleanup(LodePNGInfo* info) +{ + size_t i; + for(i = 0; i != info->itext_num; ++i) + { + string_cleanup(&info->itext_keys[i]); + string_cleanup(&info->itext_langtags[i]); + string_cleanup(&info->itext_transkeys[i]); + string_cleanup(&info->itext_strings[i]); + } + lodepng_free(info->itext_keys); + lodepng_free(info->itext_langtags); + lodepng_free(info->itext_transkeys); + lodepng_free(info->itext_strings); +} + +static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) +{ + size_t i = 0; + dest->itext_keys = 0; + dest->itext_langtags = 0; + dest->itext_transkeys = 0; + dest->itext_strings = 0; + dest->itext_num = 0; + for(i = 0; i != source->itext_num; ++i) + { + CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i], + source->itext_transkeys[i], source->itext_strings[i])); + } + return 0; +} + +void lodepng_clear_itext(LodePNGInfo* info) +{ + LodePNGIText_cleanup(info); +} + +unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, + const char* transkey, const char* str) +{ + char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1))); + char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1))); + char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1))); + char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1))); + if(!new_keys || !new_langtags || !new_transkeys || !new_strings) + { + lodepng_free(new_keys); + lodepng_free(new_langtags); + lodepng_free(new_transkeys); + lodepng_free(new_strings); + return 83; /*alloc fail*/ + } + + ++info->itext_num; + info->itext_keys = new_keys; + info->itext_langtags = new_langtags; + info->itext_transkeys = new_transkeys; + info->itext_strings = new_strings; + + string_init(&info->itext_keys[info->itext_num - 1]); + string_set(&info->itext_keys[info->itext_num - 1], key); + + string_init(&info->itext_langtags[info->itext_num - 1]); + string_set(&info->itext_langtags[info->itext_num - 1], langtag); + + string_init(&info->itext_transkeys[info->itext_num - 1]); + string_set(&info->itext_transkeys[info->itext_num - 1], transkey); + + string_init(&info->itext_strings[info->itext_num - 1]); + string_set(&info->itext_strings[info->itext_num - 1], str); + + return 0; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +void lodepng_info_init(LodePNGInfo* info) +{ + lodepng_color_mode_init(&info->color); + info->interlace_method = 0; + info->compression_method = 0; + info->filter_method = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + info->background_defined = 0; + info->background_r = info->background_g = info->background_b = 0; + + LodePNGText_init(info); + LodePNGIText_init(info); + + info->time_defined = 0; + info->phys_defined = 0; + + LodePNGUnknownChunks_init(info); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +void lodepng_info_cleanup(LodePNGInfo* info) +{ + lodepng_color_mode_cleanup(&info->color); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + LodePNGText_cleanup(info); + LodePNGIText_cleanup(info); + + LodePNGUnknownChunks_cleanup(info); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) +{ + lodepng_info_cleanup(dest); + *dest = *source; + lodepng_color_mode_init(&dest->color); + CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color)); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + CERROR_TRY_RETURN(LodePNGText_copy(dest, source)); + CERROR_TRY_RETURN(LodePNGIText_copy(dest, source)); + + LodePNGUnknownChunks_init(dest); + CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source)); +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + return 0; +} + +void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b) +{ + LodePNGInfo temp = *a; + *a = *b; + *b = temp; +} + +/* ////////////////////////////////////////////////////////////////////////// */ + +/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/ +static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) +{ + unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/ + /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/ + unsigned p = index & m; + in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/ + in = in << (bits * (m - p)); + if(p == 0) out[index * bits / 8] = in; + else out[index * bits / 8] |= in; +} + +typedef struct ColorTree ColorTree; + +/* +One node of a color tree +This is the data structure used to count the number of unique colors and to get a palette +index for a color. It's like an octree, but because the alpha channel is used too, each +node has 16 instead of 8 children. +*/ +struct ColorTree +{ + ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/ + int index; /*the payload. Only has a meaningful value if this is in the last level*/ +}; + +static void color_tree_init(ColorTree* tree) +{ + int i; + for(i = 0; i != 16; ++i) tree->children[i] = 0; + tree->index = -1; +} + +static void color_tree_cleanup(ColorTree* tree) +{ + int i; + for(i = 0; i != 16; ++i) + { + if(tree->children[i]) + { + color_tree_cleanup(tree->children[i]); + lodepng_free(tree->children[i]); + } + } +} + +/*returns -1 if color not present, its index otherwise*/ +static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + int bit = 0; + for(bit = 0; bit < 8; ++bit) + { + int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); + if(!tree->children[i]) return -1; + else tree = tree->children[i]; + } + return tree ? tree->index : -1; +} + +#ifdef LODEPNG_COMPILE_ENCODER +static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + return color_tree_get(tree, r, g, b, a) >= 0; +} +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/*color is not allowed to already exist. +Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/ +static void color_tree_add(ColorTree* tree, + unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) +{ + int bit; + for(bit = 0; bit < 8; ++bit) + { + int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); + if(!tree->children[i]) + { + tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree)); + color_tree_init(tree->children[i]); + } + tree = tree->children[i]; + } + tree->index = (int)index; +} + +/*put a pixel, given its RGBA color, into image of any color type*/ +static unsigned rgba8ToPixel(unsigned char* out, size_t i, + const LodePNGColorMode* mode, ColorTree* tree /*for palette*/, + unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + if(mode->colortype == LCT_GREY) + { + unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; + if(mode->bitdepth == 8) out[i] = grey; + else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey; + else + { + /*take the most significant bits of grey*/ + grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1); + addColorBits(out, i, mode->bitdepth, grey); + } + } + else if(mode->colortype == LCT_RGB) + { + if(mode->bitdepth == 8) + { + out[i * 3 + 0] = r; + out[i * 3 + 1] = g; + out[i * 3 + 2] = b; + } + else + { + out[i * 6 + 0] = out[i * 6 + 1] = r; + out[i * 6 + 2] = out[i * 6 + 3] = g; + out[i * 6 + 4] = out[i * 6 + 5] = b; + } + } + else if(mode->colortype == LCT_PALETTE) + { + int index = color_tree_get(tree, r, g, b, a); + if(index < 0) return 82; /*color not in palette*/ + if(mode->bitdepth == 8) out[i] = index; + else addColorBits(out, i, mode->bitdepth, (unsigned)index); + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; + if(mode->bitdepth == 8) + { + out[i * 2 + 0] = grey; + out[i * 2 + 1] = a; + } + else if(mode->bitdepth == 16) + { + out[i * 4 + 0] = out[i * 4 + 1] = grey; + out[i * 4 + 2] = out[i * 4 + 3] = a; + } + } + else if(mode->colortype == LCT_RGBA) + { + if(mode->bitdepth == 8) + { + out[i * 4 + 0] = r; + out[i * 4 + 1] = g; + out[i * 4 + 2] = b; + out[i * 4 + 3] = a; + } + else + { + out[i * 8 + 0] = out[i * 8 + 1] = r; + out[i * 8 + 2] = out[i * 8 + 3] = g; + out[i * 8 + 4] = out[i * 8 + 5] = b; + out[i * 8 + 6] = out[i * 8 + 7] = a; + } + } + + return 0; /*no error*/ +} + +/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/ +static void rgba16ToPixel(unsigned char* out, size_t i, + const LodePNGColorMode* mode, + unsigned short r, unsigned short g, unsigned short b, unsigned short a) +{ + if(mode->colortype == LCT_GREY) + { + unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; + out[i * 2 + 0] = (grey >> 8) & 255; + out[i * 2 + 1] = grey & 255; + } + else if(mode->colortype == LCT_RGB) + { + out[i * 6 + 0] = (r >> 8) & 255; + out[i * 6 + 1] = r & 255; + out[i * 6 + 2] = (g >> 8) & 255; + out[i * 6 + 3] = g & 255; + out[i * 6 + 4] = (b >> 8) & 255; + out[i * 6 + 5] = b & 255; + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; + out[i * 4 + 0] = (grey >> 8) & 255; + out[i * 4 + 1] = grey & 255; + out[i * 4 + 2] = (a >> 8) & 255; + out[i * 4 + 3] = a & 255; + } + else if(mode->colortype == LCT_RGBA) + { + out[i * 8 + 0] = (r >> 8) & 255; + out[i * 8 + 1] = r & 255; + out[i * 8 + 2] = (g >> 8) & 255; + out[i * 8 + 3] = g & 255; + out[i * 8 + 4] = (b >> 8) & 255; + out[i * 8 + 5] = b & 255; + out[i * 8 + 6] = (a >> 8) & 255; + out[i * 8 + 7] = a & 255; + } +} + +/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/ +static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, + unsigned char* b, unsigned char* a, + const unsigned char* in, size_t i, + const LodePNGColorMode* mode) +{ + if(mode->colortype == LCT_GREY) + { + if(mode->bitdepth == 8) + { + *r = *g = *b = in[i]; + if(mode->key_defined && *r == mode->key_r) *a = 0; + else *a = 255; + } + else if(mode->bitdepth == 16) + { + *r = *g = *b = in[i * 2 + 0]; + if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; + else *a = 255; + } + else + { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = i * mode->bitdepth; + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + *r = *g = *b = (value * 255) / highest; + if(mode->key_defined && value == mode->key_r) *a = 0; + else *a = 255; + } + } + else if(mode->colortype == LCT_RGB) + { + if(mode->bitdepth == 8) + { + *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2]; + if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0; + else *a = 255; + } + else + { + *r = in[i * 6 + 0]; + *g = in[i * 6 + 2]; + *b = in[i * 6 + 4]; + if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; + else *a = 255; + } + } + else if(mode->colortype == LCT_PALETTE) + { + unsigned index; + if(mode->bitdepth == 8) index = in[i]; + else + { + size_t j = i * mode->bitdepth; + index = readBitsFromReversedStream(&j, in, mode->bitdepth); + } + + if(index >= mode->palettesize) + { + /*This is an error according to the PNG spec, but common PNG decoders make it black instead. + Done here too, slightly faster due to no error handling needed.*/ + *r = *g = *b = 0; + *a = 255; + } + else + { + *r = mode->palette[index * 4 + 0]; + *g = mode->palette[index * 4 + 1]; + *b = mode->palette[index * 4 + 2]; + *a = mode->palette[index * 4 + 3]; + } + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + if(mode->bitdepth == 8) + { + *r = *g = *b = in[i * 2 + 0]; + *a = in[i * 2 + 1]; + } + else + { + *r = *g = *b = in[i * 4 + 0]; + *a = in[i * 4 + 2]; + } + } + else if(mode->colortype == LCT_RGBA) + { + if(mode->bitdepth == 8) + { + *r = in[i * 4 + 0]; + *g = in[i * 4 + 1]; + *b = in[i * 4 + 2]; + *a = in[i * 4 + 3]; + } + else + { + *r = in[i * 8 + 0]; + *g = in[i * 8 + 2]; + *b = in[i * 8 + 4]; + *a = in[i * 8 + 6]; + } + } +} + +/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color +mode test cases, optimized to convert the colors much faster, when converting +to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with +enough memory, if has_alpha is true the output is RGBA. mode has the color mode +of the input buffer.*/ +static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels, + unsigned has_alpha, const unsigned char* in, + const LodePNGColorMode* mode) +{ + unsigned num_channels = has_alpha ? 4 : 3; + size_t i; + if(mode->colortype == LCT_GREY) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i]; + if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255; + } + } + else if(mode->bitdepth == 16) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i * 2]; + if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255; + } + } + else + { + unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); + buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; + if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255; + } + } + } + else if(mode->colortype == LCT_RGB) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 3 + 0]; + buffer[1] = in[i * 3 + 1]; + buffer[2] = in[i * 3 + 2]; + if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r + && buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255; + } + } + else + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 6 + 0]; + buffer[1] = in[i * 6 + 2]; + buffer[2] = in[i * 6 + 4]; + if(has_alpha) buffer[3] = mode->key_defined + && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255; + } + } + } + else if(mode->colortype == LCT_PALETTE) + { + unsigned index; + size_t j = 0; + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + if(mode->bitdepth == 8) index = in[i]; + else index = readBitsFromReversedStream(&j, in, mode->bitdepth); + + if(index >= mode->palettesize) + { + /*This is an error according to the PNG spec, but most PNG decoders make it black instead. + Done here too, slightly faster due to no error handling needed.*/ + buffer[0] = buffer[1] = buffer[2] = 0; + if(has_alpha) buffer[3] = 255; + } + else + { + buffer[0] = mode->palette[index * 4 + 0]; + buffer[1] = mode->palette[index * 4 + 1]; + buffer[2] = mode->palette[index * 4 + 2]; + if(has_alpha) buffer[3] = mode->palette[index * 4 + 3]; + } + } + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; + if(has_alpha) buffer[3] = in[i * 2 + 1]; + } + } + else + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; + if(has_alpha) buffer[3] = in[i * 4 + 2]; + } + } + } + else if(mode->colortype == LCT_RGBA) + { + if(mode->bitdepth == 8) + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 4 + 0]; + buffer[1] = in[i * 4 + 1]; + buffer[2] = in[i * 4 + 2]; + if(has_alpha) buffer[3] = in[i * 4 + 3]; + } + } + else + { + for(i = 0; i != numpixels; ++i, buffer += num_channels) + { + buffer[0] = in[i * 8 + 0]; + buffer[1] = in[i * 8 + 2]; + buffer[2] = in[i * 8 + 4]; + if(has_alpha) buffer[3] = in[i * 8 + 6]; + } + } + } +} + +/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with +given color type, but the given color type must be 16-bit itself.*/ +static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a, + const unsigned char* in, size_t i, const LodePNGColorMode* mode) +{ + if(mode->colortype == LCT_GREY) + { + *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1]; + if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; + else *a = 65535; + } + else if(mode->colortype == LCT_RGB) + { + *r = 256 * in[i * 6 + 0] + in[i * 6 + 1]; + *g = 256 * in[i * 6 + 2] + in[i * 6 + 3]; + *b = 256 * in[i * 6 + 4] + in[i * 6 + 5]; + if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r + && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g + && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; + else *a = 65535; + } + else if(mode->colortype == LCT_GREY_ALPHA) + { + *r = *g = *b = 256 * in[i * 4 + 0] + in[i * 4 + 1]; + *a = 256 * in[i * 4 + 2] + in[i * 4 + 3]; + } + else if(mode->colortype == LCT_RGBA) + { + *r = 256 * in[i * 8 + 0] + in[i * 8 + 1]; + *g = 256 * in[i * 8 + 2] + in[i * 8 + 3]; + *b = 256 * in[i * 8 + 4] + in[i * 8 + 5]; + *a = 256 * in[i * 8 + 6] + in[i * 8 + 7]; + } +} + +unsigned lodepng_convert(unsigned char* out, const unsigned char* in, + LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, + unsigned w, unsigned h) +{ + size_t i; + ColorTree tree; + size_t numpixels = w * h; + + if(lodepng_color_mode_equal(mode_out, mode_in)) + { + size_t numbytes = lodepng_get_raw_size(w, h, mode_in); + for(i = 0; i != numbytes; ++i) out[i] = in[i]; + return 0; + } + + if(mode_out->colortype == LCT_PALETTE) + { + size_t palsize = 1u << mode_out->bitdepth; + if(mode_out->palettesize < palsize) palsize = mode_out->palettesize; + color_tree_init(&tree); + for(i = 0; i != palsize; ++i) + { + unsigned char* p = &mode_out->palette[i * 4]; + color_tree_add(&tree, p[0], p[1], p[2], p[3], i); + } + } + + if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) + { + for(i = 0; i != numpixels; ++i) + { + unsigned short r = 0, g = 0, b = 0, a = 0; + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); + rgba16ToPixel(out, i, mode_out, r, g, b, a); + } + } + else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) + { + getPixelColorsRGBA8(out, numpixels, 1, in, mode_in); + } + else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) + { + getPixelColorsRGBA8(out, numpixels, 0, in, mode_in); + } + else + { + unsigned char r = 0, g = 0, b = 0, a = 0; + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); + rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); + } + } + + if(mode_out->colortype == LCT_PALETTE) + { + color_tree_cleanup(&tree); + } + + return 0; /*no error (this function currently never has one, but maybe OOM detection added later.)*/ +} + +#ifdef LODEPNG_COMPILE_ENCODER + +void lodepng_color_profile_init(LodePNGColorProfile* profile) +{ + profile->colored = 0; + profile->key = 0; + profile->alpha = 0; + profile->key_r = profile->key_g = profile->key_b = 0; + profile->numcolors = 0; + profile->bits = 1; +} + +/*function used for debug purposes with C++*/ +/*void printColorProfile(LodePNGColorProfile* p) +{ + std::cout << "colored: " << (int)p->colored << ", "; + std::cout << "key: " << (int)p->key << ", "; + std::cout << "key_r: " << (int)p->key_r << ", "; + std::cout << "key_g: " << (int)p->key_g << ", "; + std::cout << "key_b: " << (int)p->key_b << ", "; + std::cout << "alpha: " << (int)p->alpha << ", "; + std::cout << "numcolors: " << (int)p->numcolors << ", "; + std::cout << "bits: " << (int)p->bits << std::endl; +}*/ + +/*Returns how many bits needed to represent given value (max 8 bit)*/ +static unsigned getValueRequiredBits(unsigned char value) +{ + if(value == 0 || value == 255) return 1; + /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/ + if(value % 17 == 0) return value % 85 == 0 ? 2 : 4; + return 8; +} + +/*profile must already have been inited with mode. +It's ok to set some parameters of profile to done already.*/ +unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, + const unsigned char* in, unsigned w, unsigned h, + const LodePNGColorMode* mode) +{ + unsigned error = 0; + size_t i; + ColorTree tree; + size_t numpixels = w * h; + + unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0; + unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1; + unsigned numcolors_done = 0; + unsigned bpp = lodepng_get_bpp(mode); + unsigned bits_done = bpp == 1 ? 1 : 0; + unsigned maxnumcolors = 257; + unsigned sixteen = 0; + if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256)); + + color_tree_init(&tree); + + /*Check if the 16-bit input is truly 16-bit*/ + if(mode->bitdepth == 16) + { + unsigned short r, g, b, a; + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); + if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) || + (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ + { + sixteen = 1; + break; + } + } + } + + if(sixteen) + { + unsigned short r = 0, g = 0, b = 0, a = 0; + profile->bits = 16; + bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/ + + for(i = 0; i != numpixels; ++i) + { + getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); + + if(!colored_done && (r != g || r != b)) + { + profile->colored = 1; + colored_done = 1; + } + + if(!alpha_done) + { + unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); + if(a != 65535 && (a != 0 || (profile->key && !matchkey))) + { + profile->alpha = 1; + alpha_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + else if(a == 0 && !profile->alpha && !profile->key) + { + profile->key = 1; + profile->key_r = r; + profile->key_g = g; + profile->key_b = b; + } + else if(a == 65535 && profile->key && matchkey) + { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + profile->alpha = 1; + alpha_done = 1; + } + } + + if(alpha_done && numcolors_done && colored_done && bits_done) break; + } + } + else /* < 16-bit */ + { + for(i = 0; i != numpixels; ++i) + { + unsigned char r = 0, g = 0, b = 0, a = 0; + getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode); + + if(!bits_done && profile->bits < 8) + { + /*only r is checked, < 8 bits is only relevant for greyscale*/ + unsigned bits = getValueRequiredBits(r); + if(bits > profile->bits) profile->bits = bits; + } + bits_done = (profile->bits >= bpp); + + if(!colored_done && (r != g || r != b)) + { + profile->colored = 1; + colored_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ + } + + if(!alpha_done) + { + unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); + if(a != 255 && (a != 0 || (profile->key && !matchkey))) + { + profile->alpha = 1; + alpha_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + else if(a == 0 && !profile->alpha && !profile->key) + { + profile->key = 1; + profile->key_r = r; + profile->key_g = g; + profile->key_b = b; + } + else if(a == 255 && profile->key && matchkey) + { + /* Color key cannot be used if an opaque pixel also has that RGB color. */ + profile->alpha = 1; + alpha_done = 1; + if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + } + + if(!numcolors_done) + { + if(!color_tree_has(&tree, r, g, b, a)) + { + color_tree_add(&tree, r, g, b, a, profile->numcolors); + if(profile->numcolors < 256) + { + unsigned char* p = profile->palette; + unsigned n = profile->numcolors; + p[n * 4 + 0] = r; + p[n * 4 + 1] = g; + p[n * 4 + 2] = b; + p[n * 4 + 3] = a; + } + ++profile->numcolors; + numcolors_done = profile->numcolors >= maxnumcolors; + } + } + + if(alpha_done && numcolors_done && colored_done && bits_done) break; + } + + /*make the profile's key always 16-bit for consistency - repeat each byte twice*/ + profile->key_r += (profile->key_r << 8); + profile->key_g += (profile->key_g << 8); + profile->key_b += (profile->key_b << 8); + } + + color_tree_cleanup(&tree); + return error; +} + +/*Automatically chooses color type that gives smallest amount of bits in the +output image, e.g. grey if there are only greyscale pixels, palette if there +are less than 256 colors, ... +Updates values of mode with a potentially smaller color model. mode_out should +contain the user chosen color model, but will be overwritten with the new chosen one.*/ +unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, + const unsigned char* image, unsigned w, unsigned h, + const LodePNGColorMode* mode_in) +{ + LodePNGColorProfile prof; + unsigned error = 0; + unsigned i, n, palettebits, grey_ok, palette_ok; + + lodepng_color_profile_init(&prof); + error = lodepng_get_color_profile(&prof, image, w, h, mode_in); + if(error) return error; + mode_out->key_defined = 0; + + if(prof.key && w * h <= 16) { + prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ + if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ + } + grey_ok = !prof.colored && !prof.alpha; /*grey without alpha, with potentially low bits*/ + n = prof.numcolors; + palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); + palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8; + if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ + if(grey_ok && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/ + + if(palette_ok) + { + unsigned char* p = prof.palette; + lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ + for(i = 0; i != prof.numcolors; ++i) + { + error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]); + if(error) break; + } + + mode_out->colortype = LCT_PALETTE; + mode_out->bitdepth = palettebits; + + if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize + && mode_in->bitdepth == mode_out->bitdepth) + { + /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/ + lodepng_color_mode_cleanup(mode_out); + lodepng_color_mode_copy(mode_out, mode_in); + } + } + else /*8-bit or 16-bit per channel*/ + { + mode_out->bitdepth = prof.bits; + mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA) + : (prof.colored ? LCT_RGB : LCT_GREY); + + if(prof.key && !prof.alpha) + { + unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/ + mode_out->key_r = prof.key_r & mask; + mode_out->key_g = prof.key_g & mask; + mode_out->key_b = prof.key_b & mask; + mode_out->key_defined = 1; + } + } + + return error; +} + +#endif /* #ifdef LODEPNG_COMPILE_ENCODER */ + +/* +Paeth predicter, used by PNG filter type 4 +The parameters are of type short, but should come from unsigned chars, the shorts +are only needed to make the paeth calculation correct. +*/ +static unsigned char paethPredictor(short a, short b, short c) +{ + short pa = abs(b - c); + short pb = abs(a - c); + short pc = abs(a + b - c - c); + + if(pc < pa && pc < pb) return (unsigned char)c; + else if(pb < pa) return (unsigned char)b; + else return (unsigned char)a; +} + +/*shared values used by multiple Adam7 related functions*/ + +static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/ +static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/ +static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/ +static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/ + +/* +Outputs various dimensions and positions in the image related to the Adam7 reduced images. +passw: output containing the width of the 7 passes +passh: output containing the height of the 7 passes +filter_passstart: output containing the index of the start and end of each + reduced image with filter bytes +padded_passstart output containing the index of the start and end of each + reduced image when without filter bytes but with padded scanlines +passstart: output containing the index of the start and end of each reduced + image without padding between scanlines, but still padding between the images +w, h: width and height of non-interlaced image +bpp: bits per pixel +"padded" is only relevant if bpp is less than 8 and a scanline or image does not + end at a full byte +*/ +static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8], + size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) +{ + /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/ + unsigned i; + + /*calculate width and height in pixels of each pass*/ + for(i = 0; i != 7; ++i) + { + passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i]; + passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i]; + if(passw[i] == 0) passh[i] = 0; + if(passh[i] == 0) passw[i] = 0; + } + + filter_passstart[0] = padded_passstart[0] = passstart[0] = 0; + for(i = 0; i != 7; ++i) + { + /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/ + filter_passstart[i + 1] = filter_passstart[i] + + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0); + /*bits padded if needed to fill full byte at end of each scanline*/ + padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8); + /*only padded at end of reduced image*/ + passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8; + } +} + +#ifdef LODEPNG_COMPILE_DECODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG Decoder / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*read the information from the header and store it in the LodePNGInfo. return value is error*/ +unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, + const unsigned char* in, size_t insize) +{ + LodePNGInfo* info = &state->info_png; + if(insize == 0 || in == 0) + { + CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/ + } + if(insize < 33) + { + CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/ + } + + /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/ + lodepng_info_cleanup(info); + lodepng_info_init(info); + + if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 + || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) + { + CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/ + } + if(in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R') + { + CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ + } + + /*read the values given in the header*/ + *w = lodepng_read32bitInt(&in[16]); + *h = lodepng_read32bitInt(&in[20]); + info->color.bitdepth = in[24]; + info->color.colortype = (LodePNGColorType)in[25]; + info->compression_method = in[26]; + info->filter_method = in[27]; + info->interlace_method = in[28]; + + if(*w == 0 || *h == 0) + { + CERROR_RETURN_ERROR(state->error, 93); + } + + if(!state->decoder.ignore_crc) + { + unsigned CRC = lodepng_read32bitInt(&in[29]); + unsigned checksum = lodepng_crc32(&in[12], 17); + if(CRC != checksum) + { + CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/ + } + } + + /*error: only compression method 0 is allowed in the specification*/ + if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32); + /*error: only filter method 0 is allowed in the specification*/ + if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33); + /*error: only interlace methods 0 and 1 exist in the specification*/ + if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34); + + state->error = checkColorValidity(info->color.colortype, info->color.bitdepth); + return state->error; +} + +static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, + size_t bytewidth, unsigned char filterType, size_t length) +{ + /* + For PNG filter method 0 + unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, + the filter works byte per byte (bytewidth = 1) + precon is the previous unfiltered scanline, recon the result, scanline the current one + the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead + recon and scanline MAY be the same memory address! precon must be disjoint. + */ + + size_t i; + switch(filterType) + { + case 0: + for(i = 0; i != length; ++i) recon[i] = scanline[i]; + break; + case 1: + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth]; + break; + case 2: + if(precon) + { + for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i]; + } + else + { + for(i = 0; i != length; ++i) recon[i] = scanline[i]; + } + break; + case 3: + if(precon) + { + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + precon[i] / 2; + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2); + } + else + { + for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth] / 2; + } + break; + case 4: + if(precon) + { + for(i = 0; i != bytewidth; ++i) + { + recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ + } + for(i = bytewidth; i < length; ++i) + { + recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); + } + } + else + { + for(i = 0; i != bytewidth; ++i) + { + recon[i] = scanline[i]; + } + for(i = bytewidth; i < length; ++i) + { + /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ + recon[i] = (scanline[i] + recon[i - bytewidth]); + } + } + break; + default: return 36; /*error: unexisting filter type given*/ + } + return 0; +} + +static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) +{ + /* + For PNG filter method 0 + this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times) + out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline + w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel + in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes) + */ + + unsigned y; + unsigned char* prevline = 0; + + /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ + size_t bytewidth = (bpp + 7) / 8; + size_t linebytes = (w * bpp + 7) / 8; + + for(y = 0; y < h; ++y) + { + size_t outindex = linebytes * y; + size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + unsigned char filterType = in[inindex]; + + CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes)); + + prevline = &out[outindex]; + } + + return 0; +} + +/* +in: Adam7 interlaced image, with no padding bits between scanlines, but between + reduced images so that each reduced image starts at a byte. +out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h +bpp: bits per pixel +out has the following size in bits: w * h * bpp. +in is possibly bigger due to padding bits between reduced images. +out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation +(because that's likely a little bit faster) +NOTE: comments about padding bits are only relevant if bpp < 8 +*/ +static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) +{ + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + if(bpp >= 8) + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + size_t bytewidth = bpp / 8; + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth; + size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; + for(b = 0; b < bytewidth; ++b) + { + out[pixeloutstart + b] = in[pixelinstart + b]; + } + } + } + } + else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + unsigned ilinebits = bpp * passw[i]; + unsigned olinebits = bpp * w; + size_t obp, ibp; /*bit pointers (for out and in buffer)*/ + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp); + obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; + for(b = 0; b < bpp; ++b) + { + unsigned char bit = readBitFromReversedStream(&ibp, in); + /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/ + setBitOfReversedStream0(&obp, out, bit); + } + } + } + } +} + +static void removePaddingBits(unsigned char* out, const unsigned char* in, + size_t olinebits, size_t ilinebits, unsigned h) +{ + /* + After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need + to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers + for the Adam7 code, the color convert code and the output to the user. + in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must + have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits + also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7 + only useful if (ilinebits - olinebits) is a value in the range 1..7 + */ + unsigned y; + size_t diff = ilinebits - olinebits; + size_t ibp = 0, obp = 0; /*input and output bit pointers*/ + for(y = 0; y < h; ++y) + { + size_t x; + for(x = 0; x < olinebits; ++x) + { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + ibp += diff; + } +} + +/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from +the IDAT chunks (with filter index bytes and possible padding bits) +return value is error*/ +static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, + unsigned w, unsigned h, const LodePNGInfo* info_png) +{ + /* + This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype. + Steps: + *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8) + *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace + NOTE: the in buffer will be overwritten with intermediate data! + */ + unsigned bpp = lodepng_get_bpp(&info_png->color); + if(bpp == 0) return 31; /*error: invalid colortype*/ + + if(info_png->interlace_method == 0) + { + if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) + { + CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); + removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h); + } + /*we can immediatly filter into the out buffer, no other steps needed*/ + else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp)); + } + else /*interlace_method is 1 (Adam7)*/ + { + unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + for(i = 0; i != 7; ++i) + { + CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp)); + /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline, + move bytes instead of bits or move not at all*/ + if(bpp < 8) + { + /*remove padding bits in scanlines; after this there still may be padding + bits between the different reduced images: each reduced image still starts nicely at a byte*/ + removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, + ((passw[i] * bpp + 7) / 8) * 8, passh[i]); + } + } + + Adam7_deinterlace(out, in, w, h, bpp); + } + + return 0; +} + +static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) +{ + unsigned pos = 0, i; + if(color->palette) lodepng_free(color->palette); + color->palettesize = chunkLength / 3; + color->palette = (unsigned char*)lodepng_malloc(4 * color->palettesize); + if(!color->palette && color->palettesize) + { + color->palettesize = 0; + return 83; /*alloc fail*/ + } + if(color->palettesize > 256) return 38; /*error: palette too big*/ + + for(i = 0; i != color->palettesize; ++i) + { + color->palette[4 * i + 0] = data[pos++]; /*R*/ + color->palette[4 * i + 1] = data[pos++]; /*G*/ + color->palette[4 * i + 2] = data[pos++]; /*B*/ + color->palette[4 * i + 3] = 255; /*alpha*/ + } + + return 0; /* OK */ +} + +static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) +{ + unsigned i; + if(color->colortype == LCT_PALETTE) + { + /*error: more alpha values given than there are palette entries*/ + if(chunkLength > color->palettesize) return 38; + + for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i]; + } + else if(color->colortype == LCT_GREY) + { + /*error: this chunk must be 2 bytes for greyscale image*/ + if(chunkLength != 2) return 30; + + color->key_defined = 1; + color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1]; + } + else if(color->colortype == LCT_RGB) + { + /*error: this chunk must be 6 bytes for RGB image*/ + if(chunkLength != 6) return 41; + + color->key_defined = 1; + color->key_r = 256u * data[0] + data[1]; + color->key_g = 256u * data[2] + data[3]; + color->key_b = 256u * data[4] + data[5]; + } + else return 42; /*error: tRNS chunk not allowed for other color models*/ + + return 0; /* OK */ +} + + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*background color chunk (bKGD)*/ +static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) +{ + if(info->color.colortype == LCT_PALETTE) + { + /*error: this chunk must be 1 byte for indexed color image*/ + if(chunkLength != 1) return 43; + + info->background_defined = 1; + info->background_r = info->background_g = info->background_b = data[0]; + } + else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) + { + /*error: this chunk must be 2 bytes for greyscale image*/ + if(chunkLength != 2) return 44; + + info->background_defined = 1; + info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1]; + } + else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) + { + /*error: this chunk must be 6 bytes for greyscale image*/ + if(chunkLength != 6) return 45; + + info->background_defined = 1; + info->background_r = 256u * data[0] + data[1]; + info->background_g = 256u * data[2] + data[3]; + info->background_b = 256u * data[4] + data[5]; + } + + return 0; /* OK */ +} + +/*text chunk (tEXt)*/ +static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) +{ + unsigned error = 0; + char *key = 0, *str = 0; + unsigned i; + + while(!error) /*not really a while loop, only used to break on error*/ + { + unsigned length, string2_begin; + + length = 0; + while(length < chunkLength && data[length] != 0) ++length; + /*even though it's not allowed by the standard, no error is thrown if + there's no null termination char, if the text is empty*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + key[length] = 0; + for(i = 0; i != length; ++i) key[i] = (char)data[i]; + + string2_begin = length + 1; /*skip keyword null terminator*/ + + length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin; + str = (char*)lodepng_malloc(length + 1); + if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ + + str[length] = 0; + for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i]; + + error = lodepng_add_text(info, key, str); + + break; + } + + lodepng_free(key); + lodepng_free(str); + + return error; +} + +/*compressed text chunk (zTXt)*/ +static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, + const unsigned char* data, size_t chunkLength) +{ + unsigned error = 0; + unsigned i; + + unsigned length, string2_begin; + char *key = 0; + ucvector decoded; + + ucvector_init(&decoded); + + while(!error) /*not really a while loop, only used to break on error*/ + { + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + key[length] = 0; + for(i = 0; i != length; ++i) key[i] = (char)data[i]; + + if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ + + string2_begin = length + 2; + if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ + + length = chunkLength - string2_begin; + /*will fail if zlib error, e.g. if length is too small*/ + error = zlib_decompress(&decoded.data, &decoded.size, + (unsigned char*)(&data[string2_begin]), + length, zlibsettings); + if(error) break; + ucvector_push_back(&decoded, 0); + + error = lodepng_add_text(info, key, (char*)decoded.data); + + break; + } + + lodepng_free(key); + ucvector_cleanup(&decoded); + + return error; +} + +/*international text chunk (iTXt)*/ +static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, + const unsigned char* data, size_t chunkLength) +{ + unsigned error = 0; + unsigned i; + + unsigned length, begin, compressed; + char *key = 0, *langtag = 0, *transkey = 0; + ucvector decoded; + ucvector_init(&decoded); + + while(!error) /*not really a while loop, only used to break on error*/ + { + /*Quick check if the chunk length isn't too small. Even without check + it'd still fail with other error checks below if it's too short. This just gives a different error code.*/ + if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/ + + /*read the key*/ + for(length = 0; length < chunkLength && data[length] != 0; ++length) ; + if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/ + if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ + + key = (char*)lodepng_malloc(length + 1); + if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ + + key[length] = 0; + for(i = 0; i != length; ++i) key[i] = (char)data[i]; + + /*read the compression method*/ + compressed = data[length + 1]; + if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ + + /*even though it's not allowed by the standard, no error is thrown if + there's no null termination char, if the text is empty for the next 3 texts*/ + + /*read the langtag*/ + begin = length + 3; + length = 0; + for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; + + langtag = (char*)lodepng_malloc(length + 1); + if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/ + + langtag[length] = 0; + for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i]; + + /*read the transkey*/ + begin += length + 1; + length = 0; + for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; + + transkey = (char*)lodepng_malloc(length + 1); + if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/ + + transkey[length] = 0; + for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i]; + + /*read the actual text*/ + begin += length + 1; + + length = chunkLength < begin ? 0 : chunkLength - begin; + + if(compressed) + { + /*will fail if zlib error, e.g. if length is too small*/ + error = zlib_decompress(&decoded.data, &decoded.size, + (unsigned char*)(&data[begin]), + length, zlibsettings); + if(error) break; + if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size; + ucvector_push_back(&decoded, 0); + } + else + { + if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/); + + decoded.data[length] = 0; + for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i]; + } + + error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data); + + break; + } + + lodepng_free(key); + lodepng_free(langtag); + lodepng_free(transkey); + ucvector_cleanup(&decoded); + + return error; +} + +static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) +{ + if(chunkLength != 7) return 73; /*invalid tIME chunk size*/ + + info->time_defined = 1; + info->time.year = 256u * data[0] + data[1]; + info->time.month = data[2]; + info->time.day = data[3]; + info->time.hour = data[4]; + info->time.minute = data[5]; + info->time.second = data[6]; + + return 0; /* OK */ +} + +static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) +{ + if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/ + + info->phys_defined = 1; + info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; + info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; + info->phys_unit = data[8]; + + return 0; /* OK */ +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/ +static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize) +{ + unsigned char IEND = 0; + const unsigned char* chunk; + size_t i; + ucvector idat; /*the data from idat chunks*/ + ucvector scanlines; + size_t predict; + size_t numpixels; + + /*for unknown chunk order*/ + unsigned unknown = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + + /*provide some proper output values if error will happen*/ + *out = 0; + + state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ + if(state->error) return; + + numpixels = *w * *h; + + /*multiplication overflow*/ + if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92); + /*multiplication overflow possible further below. Allows up to 2^31-1 pixel + bytes with 16-bit RGBA, the rest is room for filter bytes.*/ + if(numpixels > 268435455) CERROR_RETURN(state->error, 92); + + ucvector_init(&idat); + chunk = &in[33]; /*first byte of the first chunk after the header*/ + + /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. + IDAT data is put at the start of the in buffer*/ + while(!IEND && !state->error) + { + unsigned chunkLength; + const unsigned char* data; /*the data in the chunk*/ + + /*error: size of the in buffer too small to contain next chunk*/ + if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30); + + /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/ + chunkLength = lodepng_chunk_length(chunk); + /*error: chunk length larger than the max PNG chunk size*/ + if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63); + + if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) + { + CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/ + } + + data = lodepng_chunk_data_const(chunk); + + /*IDAT chunk, containing compressed image data*/ + if(lodepng_chunk_type_equals(chunk, "IDAT")) + { + size_t oldsize = idat.size; + if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/); + for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i]; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + critical_pos = 3; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } + /*IEND chunk*/ + else if(lodepng_chunk_type_equals(chunk, "IEND")) + { + IEND = 1; + } + /*palette chunk (PLTE)*/ + else if(lodepng_chunk_type_equals(chunk, "PLTE")) + { + state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength); + if(state->error) break; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + critical_pos = 2; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } + /*palette transparency chunk (tRNS)*/ + else if(lodepng_chunk_type_equals(chunk, "tRNS")) + { + state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength); + if(state->error) break; + } +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*background color chunk (bKGD)*/ + else if(lodepng_chunk_type_equals(chunk, "bKGD")) + { + state->error = readChunk_bKGD(&state->info_png, data, chunkLength); + if(state->error) break; + } + /*text chunk (tEXt)*/ + else if(lodepng_chunk_type_equals(chunk, "tEXt")) + { + if(state->decoder.read_text_chunks) + { + state->error = readChunk_tEXt(&state->info_png, data, chunkLength); + if(state->error) break; + } + } + /*compressed text chunk (zTXt)*/ + else if(lodepng_chunk_type_equals(chunk, "zTXt")) + { + if(state->decoder.read_text_chunks) + { + state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + if(state->error) break; + } + } + /*international text chunk (iTXt)*/ + else if(lodepng_chunk_type_equals(chunk, "iTXt")) + { + if(state->decoder.read_text_chunks) + { + state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); + if(state->error) break; + } + } + else if(lodepng_chunk_type_equals(chunk, "tIME")) + { + state->error = readChunk_tIME(&state->info_png, data, chunkLength); + if(state->error) break; + } + else if(lodepng_chunk_type_equals(chunk, "pHYs")) + { + state->error = readChunk_pHYs(&state->info_png, data, chunkLength); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + else /*it's not an implemented chunk type, so ignore it: skip over the data*/ + { + /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ + if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69); + + unknown = 1; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + if(state->decoder.remember_unknown_chunks) + { + state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1], + &state->info_png.unknown_chunks_size[critical_pos - 1], chunk); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + } + + if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ + { + if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/ + } + + if(!IEND) chunk = lodepng_chunk_next_const(chunk); + } + + ucvector_init(&scanlines); + /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation. + If the decompressed size does not match the prediction, the image must be corrupt.*/ + if(state->info_png.interlace_method == 0) + { + /*The extra *h is added because this are the filter bytes every scanline starts with*/ + predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h; + } + else + { + /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/ + const LodePNGColorMode* color = &state->info_png.color; + predict = 0; + predict += lodepng_get_raw_size_idat((*w + 7) / 8, (*h + 7) / 8, color) + (*h + 7) / 8; + if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) / 8, (*h + 7) / 8, color) + (*h + 7) / 8; + predict += lodepng_get_raw_size_idat((*w + 3) / 4, (*h + 3) / 8, color) + (*h + 3) / 8; + if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) / 4, (*h + 3) / 4, color) + (*h + 3) / 4; + predict += lodepng_get_raw_size_idat((*w + 1) / 2, (*h + 1) / 4, color) + (*h + 1) / 4; + if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) / 2, (*h + 1) / 2, color) + (*h + 1) / 2; + predict += lodepng_get_raw_size_idat((*w + 0) / 1, (*h + 0) / 2, color) + (*h + 0) / 2; + } + if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/ + if(!state->error) + { + state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data, + idat.size, &state->decoder.zlibsettings); + if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/ + } + ucvector_cleanup(&idat); + + if(!state->error) + { + size_t outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color); + ucvector outv; + ucvector_init(&outv); + if(!ucvector_resizev(&outv, outsize, 0)) state->error = 83; /*alloc fail*/ + if(!state->error) state->error = postProcessScanlines(outv.data, scanlines.data, *w, *h, &state->info_png); + *out = outv.data; + } + ucvector_cleanup(&scanlines); +} + +unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize) +{ + *out = 0; + decodeGeneric(out, w, h, state, in, insize); + if(state->error) return state->error; + if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) + { + /*same color type, no copying or converting of data needed*/ + /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype + the raw image has to the end user*/ + if(!state->decoder.color_convert) + { + state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color); + if(state->error) return state->error; + } + } + else + { + /*color conversion needed; sort of copy of the data*/ + unsigned char* data = *out; + size_t outsize; + + /*TODO: check if this works according to the statement in the documentation: "The converter can convert + from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/ + if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) + && !(state->info_raw.bitdepth == 8)) + { + return 56; /*unsupported color mode conversion*/ + } + + outsize = lodepng_get_raw_size(*w, *h, &state->info_raw); + *out = (unsigned char*)lodepng_malloc(outsize); + if(!(*out)) + { + state->error = 83; /*alloc fail*/ + } + else state->error = lodepng_convert(*out, data, &state->info_raw, + &state->info_png.color, *w, *h); + lodepng_free(data); + } + return state->error; +} + +unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, + size_t insize, LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned error; + LodePNGState state; + lodepng_state_init(&state); + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + error = lodepng_decode(out, w, h, &state, in, insize); + lodepng_state_cleanup(&state); + return error; +} + +unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) +{ + return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8); +} + +unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) +{ + return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, + LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned char* buffer; + size_t buffersize; + unsigned error; + error = lodepng_load_file(&buffer, &buffersize, filename); + if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth); + lodepng_free(buffer); + return error; +} + +unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) +{ + return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8); +} + +unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) +{ + return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8); +} +#endif /*LODEPNG_COMPILE_DISK*/ + +void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) +{ + settings->color_convert = 1; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + settings->read_text_chunks = 1; + settings->remember_unknown_chunks = 0; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + settings->ignore_crc = 0; + lodepng_decompress_settings_init(&settings->zlibsettings); +} + +#endif /*LODEPNG_COMPILE_DECODER*/ + +#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) + +void lodepng_state_init(LodePNGState* state) +{ +#ifdef LODEPNG_COMPILE_DECODER + lodepng_decoder_settings_init(&state->decoder); +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER + lodepng_encoder_settings_init(&state->encoder); +#endif /*LODEPNG_COMPILE_ENCODER*/ + lodepng_color_mode_init(&state->info_raw); + lodepng_info_init(&state->info_png); + state->error = 1; +} + +void lodepng_state_cleanup(LodePNGState* state) +{ + lodepng_color_mode_cleanup(&state->info_raw); + lodepng_info_cleanup(&state->info_png); +} + +void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) +{ + lodepng_state_cleanup(dest); + *dest = *source; + lodepng_color_mode_init(&dest->info_raw); + lodepng_info_init(&dest->info_png); + dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return; + dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return; +} + +#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ + +#ifdef LODEPNG_COMPILE_ENCODER + +/* ////////////////////////////////////////////////////////////////////////// */ +/* / PNG Encoder / */ +/* ////////////////////////////////////////////////////////////////////////// */ + +/*chunkName must be string of 4 characters*/ +static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length) +{ + CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data)); + out->allocsize = out->size; /*fix the allocsize again*/ + return 0; +} + +static void writeSignature(ucvector* out) +{ + /*8 bytes PNG signature, aka the magic bytes*/ + ucvector_push_back(out, 137); + ucvector_push_back(out, 80); + ucvector_push_back(out, 78); + ucvector_push_back(out, 71); + ucvector_push_back(out, 13); + ucvector_push_back(out, 10); + ucvector_push_back(out, 26); + ucvector_push_back(out, 10); +} + +static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) +{ + unsigned error = 0; + ucvector header; + ucvector_init(&header); + + lodepng_add32bitInt(&header, w); /*width*/ + lodepng_add32bitInt(&header, h); /*height*/ + ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/ + ucvector_push_back(&header, (unsigned char)colortype); /*color type*/ + ucvector_push_back(&header, 0); /*compression method*/ + ucvector_push_back(&header, 0); /*filter method*/ + ucvector_push_back(&header, interlace_method); /*interlace method*/ + + error = addChunk(out, "IHDR", header.data, header.size); + ucvector_cleanup(&header); + + return error; +} + +static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) +{ + unsigned error = 0; + size_t i; + ucvector PLTE; + ucvector_init(&PLTE); + for(i = 0; i != info->palettesize * 4; ++i) + { + /*add all channels except alpha channel*/ + if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]); + } + error = addChunk(out, "PLTE", PLTE.data, PLTE.size); + ucvector_cleanup(&PLTE); + + return error; +} + +static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) +{ + unsigned error = 0; + size_t i; + ucvector tRNS; + ucvector_init(&tRNS); + if(info->colortype == LCT_PALETTE) + { + size_t amount = info->palettesize; + /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/ + for(i = info->palettesize; i != 0; --i) + { + if(info->palette[4 * (i - 1) + 3] == 255) --amount; + else break; + } + /*add only alpha channel*/ + for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]); + } + else if(info->colortype == LCT_GREY) + { + if(info->key_defined) + { + ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256)); + } + } + else if(info->colortype == LCT_RGB) + { + if(info->key_defined) + { + ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_g / 256)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_g % 256)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_b / 256)); + ucvector_push_back(&tRNS, (unsigned char)(info->key_b % 256)); + } + } + + error = addChunk(out, "tRNS", tRNS.data, tRNS.size); + ucvector_cleanup(&tRNS); + + return error; +} + +static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize, + LodePNGCompressSettings* zlibsettings) +{ + ucvector zlibdata; + unsigned error = 0; + + /*compress with the Zlib compressor*/ + ucvector_init(&zlibdata); + error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings); + if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size); + ucvector_cleanup(&zlibdata); + + return error; +} + +static unsigned addChunk_IEND(ucvector* out) +{ + unsigned error = 0; + error = addChunk(out, "IEND", 0, 0); + return error; +} + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + +static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) +{ + unsigned error = 0; + size_t i; + ucvector text; + ucvector_init(&text); + for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]); + if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ + ucvector_push_back(&text, 0); /*0 termination char*/ + for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]); + error = addChunk(out, "tEXt", text.data, text.size); + ucvector_cleanup(&text); + + return error; +} + +static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring, + LodePNGCompressSettings* zlibsettings) +{ + unsigned error = 0; + ucvector data, compressed; + size_t i, textsize = strlen(textstring); + + ucvector_init(&data); + ucvector_init(&compressed); + for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]); + if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ + ucvector_push_back(&data, 0); /*0 termination char*/ + ucvector_push_back(&data, 0); /*compression method: 0*/ + + error = zlib_compress(&compressed.data, &compressed.size, + (unsigned char*)textstring, textsize, zlibsettings); + if(!error) + { + for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]); + error = addChunk(out, "zTXt", data.data, data.size); + } + + ucvector_cleanup(&compressed); + ucvector_cleanup(&data); + return error; +} + +static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag, + const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) +{ + unsigned error = 0; + ucvector data; + size_t i, textsize = strlen(textstring); + + ucvector_init(&data); + + for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]); + if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ + ucvector_push_back(&data, 0); /*null termination char*/ + ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/ + ucvector_push_back(&data, 0); /*compression method*/ + for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]); + ucvector_push_back(&data, 0); /*null termination char*/ + for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]); + ucvector_push_back(&data, 0); /*null termination char*/ + + if(compressed) + { + ucvector compressed_data; + ucvector_init(&compressed_data); + error = zlib_compress(&compressed_data.data, &compressed_data.size, + (unsigned char*)textstring, textsize, zlibsettings); + if(!error) + { + for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]); + } + ucvector_cleanup(&compressed_data); + } + else /*not compressed*/ + { + for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]); + } + + if(!error) error = addChunk(out, "iTXt", data.data, data.size); + ucvector_cleanup(&data); + return error; +} + +static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) +{ + unsigned error = 0; + ucvector bKGD; + ucvector_init(&bKGD); + if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) + { + ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); + } + else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) + { + ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_g / 256)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_g % 256)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_b / 256)); + ucvector_push_back(&bKGD, (unsigned char)(info->background_b % 256)); + } + else if(info->color.colortype == LCT_PALETTE) + { + ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); /*palette index*/ + } + + error = addChunk(out, "bKGD", bKGD.data, bKGD.size); + ucvector_cleanup(&bKGD); + + return error; +} + +static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) +{ + unsigned error = 0; + unsigned char* data = (unsigned char*)lodepng_malloc(7); + if(!data) return 83; /*alloc fail*/ + data[0] = (unsigned char)(time->year / 256); + data[1] = (unsigned char)(time->year % 256); + data[2] = (unsigned char)time->month; + data[3] = (unsigned char)time->day; + data[4] = (unsigned char)time->hour; + data[5] = (unsigned char)time->minute; + data[6] = (unsigned char)time->second; + error = addChunk(out, "tIME", data, 7); + lodepng_free(data); + return error; +} + +static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) +{ + unsigned error = 0; + ucvector data; + ucvector_init(&data); + + lodepng_add32bitInt(&data, info->phys_x); + lodepng_add32bitInt(&data, info->phys_y); + ucvector_push_back(&data, info->phys_unit); + + error = addChunk(out, "pHYs", data.data, data.size); + ucvector_cleanup(&data); + + return error; +} + +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline, + size_t length, size_t bytewidth, unsigned char filterType) +{ + size_t i; + switch(filterType) + { + case 0: /*None*/ + for(i = 0; i != length; ++i) out[i] = scanline[i]; + break; + case 1: /*Sub*/ + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth]; + break; + case 2: /*Up*/ + if(prevline) + { + for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i]; + } + else + { + for(i = 0; i != length; ++i) out[i] = scanline[i]; + } + break; + case 3: /*Average*/ + if(prevline) + { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - prevline[i] / 2; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) / 2); + } + else + { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth] / 2; + } + break; + case 4: /*Paeth*/ + if(prevline) + { + /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/ + for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]); + for(i = bytewidth; i < length; ++i) + { + out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth])); + } + } + else + { + for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; + /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/ + for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]); + } + break; + default: return; /*unexisting filter type given*/ + } +} + +/* log2 approximation. A slight bit faster than std::log. */ +static float flog2(float f) +{ + float result = 0; + while(f > 32) { result += 4; f /= 16; } + while(f > 2) { ++result; f /= 2; } + return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f); +} + +static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, + const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) +{ + /* + For PNG filter method 0 + out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are + the scanlines with 1 extra byte per scanline + */ + + unsigned bpp = lodepng_get_bpp(info); + /*the width of a scanline in bytes, not including the filter type*/ + size_t linebytes = (w * bpp + 7) / 8; + /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ + size_t bytewidth = (bpp + 7) / 8; + const unsigned char* prevline = 0; + unsigned x, y; + unsigned error = 0; + LodePNGFilterStrategy strategy = settings->filter_strategy; + + /* + There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard: + * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e. + use fixed filtering, with the filter None). + * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is + not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply + all five filters and select the filter that produces the smallest sum of absolute values per row. + This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true. + + If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed, + but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum + heuristic is used. + */ + if(settings->filter_palette_zero && + (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO; + + if(bpp == 0) return 31; /*error: invalid color type*/ + + if(strategy == LFS_ZERO) + { + for(y = 0; y != h; ++y) + { + size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + size_t inindex = linebytes * y; + out[outindex] = 0; /*filter type byte*/ + filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0); + prevline = &in[inindex]; + } + } + else if(strategy == LFS_MINSUM) + { + /*adaptive filtering*/ + size_t sum[5]; + ucvector attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t smallest = 0; + unsigned char type, bestType = 0; + + for(type = 0; type != 5; ++type) + { + ucvector_init(&attempt[type]); + if(!ucvector_resize(&attempt[type], linebytes)) return 83; /*alloc fail*/ + } + + if(!error) + { + for(y = 0; y != h; ++y) + { + /*try the 5 filter types*/ + for(type = 0; type != 5; ++type) + { + filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type); + + /*calculate the sum of the result*/ + sum[type] = 0; + if(type == 0) + { + for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type].data[x]); + } + else + { + for(x = 0; x != linebytes; ++x) + { + /*For differences, each byte should be treated as signed, values above 127 are negative + (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there. + This means filtertype 0 is almost never chosen, but that is justified.*/ + unsigned char s = attempt[type].data[x]; + sum[type] += s < 128 ? s : (255U - s); + } + } + + /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || sum[type] < smallest) + { + bestType = type; + smallest = sum[type]; + } + } + + prevline = &in[y * linebytes]; + + /*now fill the out values*/ + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x]; + } + } + + for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]); + } + else if(strategy == LFS_ENTROPY) + { + float sum[5]; + ucvector attempt[5]; /*five filtering attempts, one for each filter type*/ + float smallest = 0; + unsigned type, bestType = 0; + unsigned count[256]; + + for(type = 0; type != 5; ++type) + { + ucvector_init(&attempt[type]); + if(!ucvector_resize(&attempt[type], linebytes)) return 83; /*alloc fail*/ + } + + for(y = 0; y != h; ++y) + { + /*try the 5 filter types*/ + for(type = 0; type != 5; ++type) + { + filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type); + for(x = 0; x != 256; ++x) count[x] = 0; + for(x = 0; x != linebytes; ++x) ++count[attempt[type].data[x]]; + ++count[type]; /*the filter type itself is part of the scanline*/ + sum[type] = 0; + for(x = 0; x != 256; ++x) + { + float p = count[x] / (float)(linebytes + 1); + sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p; + } + /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || sum[type] < smallest) + { + bestType = type; + smallest = sum[type]; + } + } + + prevline = &in[y * linebytes]; + + /*now fill the out values*/ + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x]; + } + + for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]); + } + else if(strategy == LFS_PREDEFINED) + { + for(y = 0; y != h; ++y) + { + size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ + size_t inindex = linebytes * y; + unsigned char type = settings->predefined_filters[y]; + out[outindex] = type; /*filter type byte*/ + filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); + prevline = &in[inindex]; + } + } + else if(strategy == LFS_BRUTE_FORCE) + { + /*brute force filter chooser. + deflate the scanline after every filter attempt to see which one deflates best. + This is very slow and gives only slightly smaller, sometimes even larger, result*/ + size_t size[5]; + ucvector attempt[5]; /*five filtering attempts, one for each filter type*/ + size_t smallest = 0; + unsigned type = 0, bestType = 0; + unsigned char* dummy; + LodePNGCompressSettings zlibsettings = settings->zlibsettings; + /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose, + to simulate the true case where the tree is the same for the whole image. Sometimes it gives + better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare + cases better compression. It does make this a bit less slow, so it's worth doing this.*/ + zlibsettings.btype = 1; + /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG + images only, so disable it*/ + zlibsettings.custom_zlib = 0; + zlibsettings.custom_deflate = 0; + for(type = 0; type != 5; ++type) + { + ucvector_init(&attempt[type]); + ucvector_resize(&attempt[type], linebytes); /*todo: give error if resize failed*/ + } + for(y = 0; y != h; ++y) /*try the 5 filter types*/ + { + for(type = 0; type != 5; ++type) + { + unsigned testsize = attempt[type].size; + /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ + + filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type); + size[type] = 0; + dummy = 0; + zlib_compress(&dummy, &size[type], attempt[type].data, testsize, &zlibsettings); + lodepng_free(dummy); + /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/ + if(type == 0 || size[type] < smallest) + { + bestType = type; + smallest = size[type]; + } + } + prevline = &in[y * linebytes]; + out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ + for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x]; + } + for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]); + } + else return 88; /* unknown filter strategy */ + + return error; +} + +static void addPaddingBits(unsigned char* out, const unsigned char* in, + size_t olinebits, size_t ilinebits, unsigned h) +{ + /*The opposite of the removePaddingBits function + olinebits must be >= ilinebits*/ + unsigned y; + size_t diff = olinebits - ilinebits; + size_t obp = 0, ibp = 0; /*bit pointers*/ + for(y = 0; y != h; ++y) + { + size_t x; + for(x = 0; x < ilinebits; ++x) + { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + /*obp += diff; --> no, fill in some value in the padding bits too, to avoid + "Use of uninitialised value of size ###" warning from valgrind*/ + for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0); + } +} + +/* +in: non-interlaced image with size w*h +out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with + no padding bits between scanlines, but between reduced images so that each + reduced image starts at a byte. +bpp: bits per pixel +there are no padding bits, not between scanlines, not between reduced images +in has the following size in bits: w * h * bpp. +out is possibly bigger due to padding bits between reduced images +NOTE: comments about padding bits are only relevant if bpp < 8 +*/ +static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) +{ + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned i; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + if(bpp >= 8) + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + size_t bytewidth = bpp / 8; + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; + size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth; + for(b = 0; b < bytewidth; ++b) + { + out[pixeloutstart + b] = in[pixelinstart + b]; + } + } + } + } + else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ + { + for(i = 0; i != 7; ++i) + { + unsigned x, y, b; + unsigned ilinebits = bpp * passw[i]; + unsigned olinebits = bpp * w; + size_t obp, ibp; /*bit pointers (for out and in buffer)*/ + for(y = 0; y < passh[i]; ++y) + for(x = 0; x < passw[i]; ++x) + { + ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; + obp = (8 * passstart[i]) + (y * ilinebits + x * bpp); + for(b = 0; b < bpp; ++b) + { + unsigned char bit = readBitFromReversedStream(&ibp, in); + setBitOfReversedStream(&obp, out, bit); + } + } + } + } +} + +/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image. +return value is error**/ +static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in, + unsigned w, unsigned h, + const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) +{ + /* + This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps: + *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter + *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter + */ + unsigned bpp = lodepng_get_bpp(&info_png->color); + unsigned error = 0; + + if(info_png->interlace_method == 0) + { + *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/ + *out = (unsigned char*)lodepng_malloc(*outsize); + if(!(*out) && (*outsize)) error = 83; /*alloc fail*/ + + if(!error) + { + /*non multiple of 8 bits per scanline, padding bits needed per scanline*/ + if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) + { + unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7) / 8)); + if(!padded) error = 83; /*alloc fail*/ + if(!error) + { + addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h); + error = filter(*out, padded, w, h, &info_png->color, settings); + } + lodepng_free(padded); + } + else + { + /*we can immediatly filter into the out buffer, no other steps needed*/ + error = filter(*out, in, w, h, &info_png->color, settings); + } + } + } + else /*interlace_method is 1 (Adam7)*/ + { + unsigned passw[7], passh[7]; + size_t filter_passstart[8], padded_passstart[8], passstart[8]; + unsigned char* adam7; + + Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); + + *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/ + *out = (unsigned char*)lodepng_malloc(*outsize); + if(!(*out)) error = 83; /*alloc fail*/ + + adam7 = (unsigned char*)lodepng_malloc(passstart[7]); + if(!adam7 && passstart[7]) error = 83; /*alloc fail*/ + + if(!error) + { + unsigned i; + + Adam7_interlace(adam7, in, w, h, bpp); + for(i = 0; i != 7; ++i) + { + if(bpp < 8) + { + unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]); + if(!padded) ERROR_BREAK(83); /*alloc fail*/ + addPaddingBits(padded, &adam7[passstart[i]], + ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]); + error = filter(&(*out)[filter_passstart[i]], padded, + passw[i], passh[i], &info_png->color, settings); + lodepng_free(padded); + } + else + { + error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]], + passw[i], passh[i], &info_png->color, settings); + } + + if(error) break; + } + } + + lodepng_free(adam7); + } + + return error; +} + +/* +palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA... +returns 0 if the palette is opaque, +returns 1 if the palette has a single color with alpha 0 ==> color key +returns 2 if the palette is semi-translucent. +*/ +static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) +{ + size_t i; + unsigned key = 0; + unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/ + for(i = 0; i != palettesize; ++i) + { + if(!key && palette[4 * i + 3] == 0) + { + r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2]; + key = 1; + i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/ + } + else if(palette[4 * i + 3] != 255) return 2; + /*when key, no opaque RGB may have key's RGB*/ + else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2; + } + return key; +} + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) +{ + unsigned char* inchunk = data; + while((size_t)(inchunk - data) < datasize) + { + CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk)); + out->allocsize = out->size; /*fix the allocsize again*/ + inchunk = lodepng_chunk_next(inchunk); + } + return 0; +} +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +unsigned lodepng_encode(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGState* state) +{ + LodePNGInfo info; + ucvector outv; + unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/ + size_t datasize = 0; + + /*provide some proper output values if error will happen*/ + *out = 0; + *outsize = 0; + state->error = 0; + + lodepng_info_init(&info); + lodepng_info_copy(&info, &state->info_png); + + if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette) + && (info.color.palettesize == 0 || info.color.palettesize > 256)) + { + state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/ + return state->error; + } + + if(state->encoder.auto_convert) + { + state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw); + } + if(state->error) return state->error; + + if(state->encoder.zlibsettings.btype > 2) + { + CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/ + } + if(state->info_png.interlace_method > 1) + { + CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/ + } + + state->error = checkColorValidity(info.color.colortype, info.color.bitdepth); + if(state->error) return state->error; /*error: unexisting color type given*/ + state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); + if(state->error) return state->error; /*error: unexisting color type given*/ + + if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) + { + unsigned char* converted; + size_t size = (w * h * lodepng_get_bpp(&info.color) + 7) / 8; + + converted = (unsigned char*)lodepng_malloc(size); + if(!converted && size) state->error = 83; /*alloc fail*/ + if(!state->error) + { + state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); + } + if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); + lodepng_free(converted); + } + else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); + + ucvector_init(&outv); + while(!state->error) /*while only executed once, to break on error*/ + { +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + size_t i; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*write signature and chunks*/ + writeSignature(&outv); + /*IHDR*/ + addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*unknown chunks between IHDR and PLTE*/ + if(info.unknown_chunks_data[0]) + { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*PLTE*/ + if(info.color.colortype == LCT_PALETTE) + { + addChunk_PLTE(&outv, &info.color); + } + if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) + { + addChunk_PLTE(&outv, &info.color); + } + /*tRNS*/ + if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) + { + addChunk_tRNS(&outv, &info.color); + } + if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) + { + addChunk_tRNS(&outv, &info.color); + } +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*bKGD (must come between PLTE and the IDAt chunks*/ + if(info.background_defined) addChunk_bKGD(&outv, &info); + /*pHYs (must come before the IDAT chunks)*/ + if(info.phys_defined) addChunk_pHYs(&outv, &info); + + /*unknown chunks between PLTE and IDAT*/ + if(info.unknown_chunks_data[1]) + { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + /*IDAT (multiple IDAT chunks must be consecutive)*/ + state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings); + if(state->error) break; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*tIME*/ + if(info.time_defined) addChunk_tIME(&outv, &info.time); + /*tEXt and/or zTXt*/ + for(i = 0; i != info.text_num; ++i) + { + if(strlen(info.text_keys[i]) > 79) + { + state->error = 66; /*text chunk too large*/ + break; + } + if(strlen(info.text_keys[i]) < 1) + { + state->error = 67; /*text chunk too small*/ + break; + } + if(state->encoder.text_compression) + { + addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); + } + else + { + addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); + } + } + /*LodePNG version id in text chunk*/ + if(state->encoder.add_id) + { + unsigned alread_added_id_text = 0; + for(i = 0; i != info.text_num; ++i) + { + if(!strcmp(info.text_keys[i], "LodePNG")) + { + alread_added_id_text = 1; + break; + } + } + if(alread_added_id_text == 0) + { + addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ + } + } + /*iTXt*/ + for(i = 0; i != info.itext_num; ++i) + { + if(strlen(info.itext_keys[i]) > 79) + { + state->error = 66; /*text chunk too large*/ + break; + } + if(strlen(info.itext_keys[i]) < 1) + { + state->error = 67; /*text chunk too small*/ + break; + } + addChunk_iTXt(&outv, state->encoder.text_compression, + info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i], + &state->encoder.zlibsettings); + } + + /*unknown chunks between IDAT and IEND*/ + if(info.unknown_chunks_data[2]) + { + state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]); + if(state->error) break; + } +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + addChunk_IEND(&outv); + + break; /*this isn't really a while loop; no error happened so break out now!*/ + } + + lodepng_info_cleanup(&info); + lodepng_free(data); + /*instead of cleaning the vector up, give it to the output*/ + *out = outv.data; + *outsize = outv.size; + + return state->error; +} + +unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, + unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned error; + LodePNGState state; + lodepng_state_init(&state); + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + state.info_png.color.colortype = colortype; + state.info_png.color.bitdepth = bitdepth; + lodepng_encode(out, outsize, image, w, h, &state); + error = state.error; + lodepng_state_cleanup(&state); + return error; +} + +unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) +{ + return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8); +} + +unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) +{ + return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth); + if(!error) error = lodepng_save_file(buffer, buffersize, filename); + lodepng_free(buffer); + return error; +} + +unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) +{ + return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8); +} + +unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) +{ + return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8); +} +#endif /*LODEPNG_COMPILE_DISK*/ + +void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) +{ + lodepng_compress_settings_init(&settings->zlibsettings); + settings->filter_palette_zero = 1; + settings->filter_strategy = LFS_MINSUM; + settings->auto_convert = 1; + settings->force_palette = 0; + settings->predefined_filters = 0; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + settings->add_id = 0; + settings->text_compression = 1; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} + +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ERROR_TEXT +/* +This returns the description of a numerical error code in English. This is also +the documentation of all the error codes. +*/ +const char* lodepng_error_text(unsigned code) +{ + switch(code) + { + case 0: return "no error, everything went ok"; + case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/ + case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/ + case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/ + case 13: return "problem while processing dynamic deflate block"; + case 14: return "problem while processing dynamic deflate block"; + case 15: return "problem while processing dynamic deflate block"; + case 16: return "unexisting code while processing dynamic deflate block"; + case 17: return "end of out buffer memory reached while inflating"; + case 18: return "invalid distance code while inflating"; + case 19: return "end of out buffer memory reached while inflating"; + case 20: return "invalid deflate block BTYPE encountered while decoding"; + case 21: return "NLEN is not ones complement of LEN in a deflate block"; + /*end of out buffer memory reached while inflating: + This can happen if the inflated deflate data is longer than the amount of bytes required to fill up + all the pixels of the image, given the color depth and image dimensions. Something that doesn't + happen in a normal, well encoded, PNG image.*/ + case 22: return "end of out buffer memory reached while inflating"; + case 23: return "end of in buffer memory reached while inflating"; + case 24: return "invalid FCHECK in zlib header"; + case 25: return "invalid compression method in zlib header"; + case 26: return "FDICT encountered in zlib header while it's not used for PNG"; + case 27: return "PNG file is smaller than a PNG header"; + /*Checks the magic file header, the first 8 bytes of the PNG file*/ + case 28: return "incorrect PNG signature, it's no PNG or corrupted"; + case 29: return "first chunk is not the header chunk"; + case 30: return "chunk length too large, chunk broken off at end of file"; + case 31: return "illegal PNG color type or bpp"; + case 32: return "illegal PNG compression method"; + case 33: return "illegal PNG filter method"; + case 34: return "illegal PNG interlace method"; + case 35: return "chunk length of a chunk is too large or the chunk too small"; + case 36: return "illegal PNG filter type encountered"; + case 37: return "illegal bit depth for this color type given"; + case 38: return "the palette is too big"; /*more than 256 colors*/ + case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette"; + case 40: return "tRNS chunk has wrong size for greyscale image"; + case 41: return "tRNS chunk has wrong size for RGB image"; + case 42: return "tRNS chunk appeared while it was not allowed for this color type"; + case 43: return "bKGD chunk has wrong size for palette image"; + case 44: return "bKGD chunk has wrong size for greyscale image"; + case 45: return "bKGD chunk has wrong size for RGB image"; + /*the input data is empty, maybe a PNG file doesn't exist or is in the wrong path*/ + case 48: return "empty input or file doesn't exist"; + case 49: return "jumped past memory while generating dynamic huffman tree"; + case 50: return "jumped past memory while generating dynamic huffman tree"; + case 51: return "jumped past memory while inflating huffman block"; + case 52: return "jumped past memory while inflating"; + case 53: return "size of zlib data too small"; + case 54: return "repeat symbol in tree while there was no value symbol yet"; + /*jumped past tree while generating huffman tree, this could be when the + tree will have more leaves than symbols after generating it out of the + given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/ + case 55: return "jumped past tree while generating huffman tree"; + case 56: return "given output image colortype or bitdepth not supported for color conversion"; + case 57: return "invalid CRC encountered (checking CRC can be disabled)"; + case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)"; + case 59: return "requested color conversion not supported"; + case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)"; + case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)"; + /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/ + case 62: return "conversion from color to greyscale not supported"; + case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/ + /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/ + case 64: return "the length of the END symbol 256 in the Huffman tree is 0"; + case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes"; + case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte"; + case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors"; + case 69: return "unknown chunk type with 'critical' flag encountered by the decoder"; + case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)"; + case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)"; + case 73: return "invalid tIME chunk size"; + case 74: return "invalid pHYs chunk size"; + /*length could be wrong, or data chopped off*/ + case 75: return "no null termination char found while decoding text chunk"; + case 76: return "iTXt chunk too short to contain required bytes"; + case 77: return "integer overflow in buffer size"; + case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/ + case 79: return "failed to open file for writing"; + case 80: return "tried creating a tree of 0 symbols"; + case 81: return "lazy matching at pos 0 is impossible"; + case 82: return "color conversion to palette requested while a color isn't in palette"; + case 83: return "memory allocation failed"; + case 84: return "given image too small to contain all pixels to be encoded"; + case 86: return "impossible offset in lz77 encoding (internal bug)"; + case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined"; + case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy"; + case 89: return "text chunk keyword too short or long: must have size 1-79"; + /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ + case 90: return "windowsize must be a power of two"; + case 91: return "invalid decompressed idat size"; + case 92: return "too many pixels, not supported"; + case 93: return "zero width or height is invalid"; + } + return "unknown error code"; +} +#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ + +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* // C++ Wrapper // */ +/* ////////////////////////////////////////////////////////////////////////// */ +/* ////////////////////////////////////////////////////////////////////////// */ + +#ifdef LODEPNG_COMPILE_CPP +namespace lodepng +{ + +#ifdef LODEPNG_COMPILE_DISK +void load_file(std::vector& buffer, const std::string& filename) +{ + std::ifstream file(filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate); + + /*get filesize*/ + std::streamsize size = 0; + if(file.seekg(0, std::ios::end).good()) size = file.tellg(); + if(file.seekg(0, std::ios::beg).good()) size -= file.tellg(); + + /*read contents of the file into the vector*/ + buffer.resize(size_t(size)); + if(size > 0) file.read((char*)(&buffer[0]), size); +} + +/*write given buffer to the file, overwriting the file, it doesn't append to it.*/ +void save_file(const std::vector& buffer, const std::string& filename) +{ + std::ofstream file(filename.c_str(), std::ios::out|std::ios::binary); + file.write(buffer.empty() ? 0 : (char*)&buffer[0], std::streamsize(buffer.size())); +} +#endif //LODEPNG_COMPILE_DISK + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_DECODER +unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGDecompressSettings& settings) +{ + unsigned char* buffer = 0; + size_t buffersize = 0; + unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned decompress(std::vector& out, const std::vector& in, + const LodePNGDecompressSettings& settings) +{ + return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings); +} +#endif //LODEPNG_COMPILE_DECODER + +#ifdef LODEPNG_COMPILE_ENCODER +unsigned compress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings& settings) +{ + unsigned char* buffer = 0; + size_t buffersize = 0; + unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned compress(std::vector& out, const std::vector& in, + const LodePNGCompressSettings& settings) +{ + return compress(out, in.empty() ? 0 : &in[0], in.size(), settings); +} +#endif //LODEPNG_COMPILE_ENCODER +#endif //LODEPNG_COMPILE_ZLIB + + +#ifdef LODEPNG_COMPILE_PNG + +State::State() +{ + lodepng_state_init(this); +} + +State::State(const State& other) +{ + lodepng_state_init(this); + lodepng_state_copy(this, &other); +} + +State::~State() +{ + lodepng_state_cleanup(this); +} + +State& State::operator=(const State& other) +{ + lodepng_state_copy(this, &other); + return *this; +} + +#ifdef LODEPNG_COMPILE_DECODER + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, const unsigned char* in, + size_t insize, LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned char* buffer; + unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth); + if(buffer && !error) + { + State state; + state.info_raw.colortype = colortype; + state.info_raw.bitdepth = bitdepth; + size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::vector& in, LodePNGColorType colortype, unsigned bitdepth) +{ + return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth); +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const unsigned char* in, size_t insize) +{ + unsigned char* buffer = NULL; + unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize); + if(buffer && !error) + { + size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + } + lodepng_free(buffer); + return error; +} + +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const std::vector& in) +{ + return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size()); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::string& filename, + LodePNGColorType colortype, unsigned bitdepth) +{ + std::vector buffer; + load_file(buffer, filename); + return decode(out, w, h, buffer, colortype, bitdepth); +} +#endif //LODEPNG_COMPILE_DECODER +#endif //LODEPNG_COMPILE_DISK + +#ifdef LODEPNG_COMPILE_ENCODER +unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) +{ + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) +{ + if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; + return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); +} + +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + State& state) +{ + unsigned char* buffer; + size_t buffersize; + unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state); + if(buffer) + { + out.insert(out.end(), &buffer[0], &buffer[buffersize]); + lodepng_free(buffer); + } + return error; +} + +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + State& state) +{ + if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84; + return encode(out, in.empty() ? 0 : &in[0], w, h, state); +} + +#ifdef LODEPNG_COMPILE_DISK +unsigned encode(const std::string& filename, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) +{ + std::vector buffer; + unsigned error = encode(buffer, in, w, h, colortype, bitdepth); + if(!error) save_file(buffer, filename); + return error; +} + +unsigned encode(const std::string& filename, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth) +{ + if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; + return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); +} +#endif //LODEPNG_COMPILE_DISK +#endif //LODEPNG_COMPILE_ENCODER +#endif //LODEPNG_COMPILE_PNG +} //namespace lodepng +#endif /*LODEPNG_COMPILE_CPP*/ diff -Nru nestopia-1.48/source/common/png.h nestopia-1.49/source/common/png.h --- nestopia-1.48/source/common/png.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/png.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,1708 @@ +/* +LodePNG version 20141130 + +Copyright (c) 2005-2014 Lode Vandevenne + +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 LODEPNG_H +#define LODEPNG_H + +#include /*for size_t*/ + +#ifdef __cplusplus +#include +#include +#endif /*__cplusplus*/ + +#define LODEPNG_VERSION_STRING "20141130" + +/* +The following #defines are used to create code sections. They can be disabled +to disable code sections, which can give faster compile time and smaller binary. +The "NO_COMPILE" defines are designed to be used to pass as defines to the +compiler command to disable them without modifying this header, e.g. +-DLODEPNG_NO_COMPILE_ZLIB for gcc. +*/ +/*deflate & zlib. If disabled, you must specify alternative zlib functions in +the custom_zlib field of the compress and decompress settings*/ +#ifndef LODEPNG_NO_COMPILE_ZLIB +#define LODEPNG_COMPILE_ZLIB +#endif +/*png encoder and png decoder*/ +#ifndef LODEPNG_NO_COMPILE_PNG +#define LODEPNG_COMPILE_PNG +#endif +/*deflate&zlib decoder and png decoder*/ +#ifndef LODEPNG_NO_COMPILE_DECODER +#define LODEPNG_COMPILE_DECODER +#endif +/*deflate&zlib encoder and png encoder*/ +#ifndef LODEPNG_NO_COMPILE_ENCODER +#define LODEPNG_COMPILE_ENCODER +#endif +/*the optional built in harddisk file loading and saving functions*/ +#ifndef LODEPNG_NO_COMPILE_DISK +#define LODEPNG_COMPILE_DISK +#endif +/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/ +#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS +#define LODEPNG_COMPILE_ANCILLARY_CHUNKS +#endif +/*ability to convert error numerical codes to English text string*/ +#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT +#define LODEPNG_COMPILE_ERROR_TEXT +#endif +/*Compile the default allocators (C's free, malloc and realloc). If you disable this, +you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your +source files with custom allocators.*/ +#ifndef LODEPNG_NO_COMPILE_ALLOCATORS +#define LODEPNG_COMPILE_ALLOCATORS +#endif +/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/ +#ifdef __cplusplus +#ifndef LODEPNG_NO_COMPILE_CPP +#define LODEPNG_COMPILE_CPP +#endif +#endif + +#ifdef LODEPNG_COMPILE_PNG +/*The PNG color types (also used for raw).*/ +typedef enum LodePNGColorType +{ + LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/ + LCT_RGB = 2, /*RGB: 8,16 bit*/ + LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ + LCT_GREY_ALPHA = 4, /*greyscale with alpha: 8,16 bit*/ + LCT_RGBA = 6 /*RGB with alpha: 8,16 bit*/ +} LodePNGColorType; + +#ifdef LODEPNG_COMPILE_DECODER +/* +Converts PNG data in memory to raw pixel data. +out: Output parameter. Pointer to buffer that will contain the raw pixel data. + After decoding, its size is w * h * (bytes per pixel) bytes larger than + initially. Bytes per pixel depends on colortype and bitdepth. + Must be freed after usage with free(*out). + Note: for 16-bit per channel colors, uses big endian format like PNG does. +w: Output parameter. Pointer to width of pixel data. +h: Output parameter. Pointer to height of pixel data. +in: Memory buffer with the PNG file. +insize: size of the in buffer. +colortype: the desired color type for the raw output image. See explanation on PNG color types. +bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types. +Return value: LodePNG error code (0 means no error). +*/ +unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/ +unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize); + +/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/ +unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, + const unsigned char* in, size_t insize); + +#ifdef LODEPNG_COMPILE_DISK +/* +Load PNG from disk, from file with given name. +Same as the other decode functions, but instead takes a filename as input. +*/ +unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/ +unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename); + +/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/ +unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, + const char* filename); +#endif /*LODEPNG_COMPILE_DISK*/ +#endif /*LODEPNG_COMPILE_DECODER*/ + + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Converts raw pixel data into a PNG image in memory. The colortype and bitdepth + of the output PNG image cannot be chosen, they are automatically determined + by the colortype, bitdepth and content of the input pixel data. + Note: for 16-bit per channel colors, needs big endian format like PNG does. +out: Output parameter. Pointer to buffer that will contain the PNG image data. + Must be freed after usage with free(*out). +outsize: Output parameter. Pointer to the size in bytes of the out buffer. +image: The raw pixel data to encode. The size of this buffer should be + w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth. +w: width of the raw pixel data in pixels. +h: height of the raw pixel data in pixels. +colortype: the color type of the raw input image. See explanation on PNG color types. +bitdepth: the bit depth of the raw input image. See explanation on PNG color types. +Return value: LodePNG error code (0 means no error). +*/ +unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/ +unsigned lodepng_encode32(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h); + +/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/ +unsigned lodepng_encode24(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h); + +#ifdef LODEPNG_COMPILE_DISK +/* +Converts raw pixel data into a PNG file on disk. +Same as the other encode functions, but instead takes a filename as output. +NOTE: This overwrites existing files without warning! +*/ +unsigned lodepng_encode_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h, + LodePNGColorType colortype, unsigned bitdepth); + +/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/ +unsigned lodepng_encode32_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h); + +/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/ +unsigned lodepng_encode24_file(const char* filename, + const unsigned char* image, unsigned w, unsigned h); +#endif /*LODEPNG_COMPILE_DISK*/ +#endif /*LODEPNG_COMPILE_ENCODER*/ + + +#ifdef LODEPNG_COMPILE_CPP +namespace lodepng +{ +#ifdef LODEPNG_COMPILE_DECODER +/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype +is the format to output the pixels to. Default is RGBA 8-bit per channel.*/ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const unsigned char* in, size_t insize, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::vector& in, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#ifdef LODEPNG_COMPILE_DISK +/* +Converts PNG file from disk to raw pixel data in memory. +Same as the other decode functions, but instead takes a filename as input. +*/ +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + const std::string& filename, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#endif //LODEPNG_COMPILE_DISK +#endif //LODEPNG_COMPILE_DECODER + +#ifdef LODEPNG_COMPILE_ENCODER +/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype +is that of the raw input data. The output PNG color type will be auto chosen.*/ +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#ifdef LODEPNG_COMPILE_DISK +/* +Converts 32-bit RGBA raw pixel data into a PNG file on disk. +Same as the other encode functions, but instead takes a filename as output. +NOTE: This overwrites existing files without warning! +*/ +unsigned encode(const std::string& filename, + const unsigned char* in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +unsigned encode(const std::string& filename, + const std::vector& in, unsigned w, unsigned h, + LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); +#endif //LODEPNG_COMPILE_DISK +#endif //LODEPNG_COMPILE_ENCODER +} //namespace lodepng +#endif /*LODEPNG_COMPILE_CPP*/ +#endif /*LODEPNG_COMPILE_PNG*/ + +#ifdef LODEPNG_COMPILE_ERROR_TEXT +/*Returns an English description of the numerical error code.*/ +const char* lodepng_error_text(unsigned code); +#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ + +#ifdef LODEPNG_COMPILE_DECODER +/*Settings for zlib decompression*/ +typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; +struct LodePNGDecompressSettings +{ + unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ + + /*use custom zlib decoder instead of built in one (default: null)*/ + unsigned (*custom_zlib)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGDecompressSettings*); + /*use custom deflate decoder instead of built in one (default: null) + if custom_zlib is used, custom_deflate is ignored since only the built in + zlib function will call custom_deflate*/ + unsigned (*custom_inflate)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGDecompressSettings*); + + const void* custom_context; /*optional custom settings for custom functions*/ +}; + +extern const LodePNGDecompressSettings lodepng_default_decompress_settings; +void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Settings for zlib compression. Tweaking these settings tweaks the balance +between speed and compression ratio. +*/ +typedef struct LodePNGCompressSettings LodePNGCompressSettings; +struct LodePNGCompressSettings /*deflate = compress*/ +{ + /*LZ77 related settings*/ + unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ + unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ + unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/ + unsigned minmatch; /*mininum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/ + unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/ + unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ + + /*use custom zlib encoder instead of built in one (default: null)*/ + unsigned (*custom_zlib)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGCompressSettings*); + /*use custom deflate encoder instead of built in one (default: null) + if custom_zlib is used, custom_deflate is ignored since only the built in + zlib function will call custom_deflate*/ + unsigned (*custom_deflate)(unsigned char**, size_t*, + const unsigned char*, size_t, + const LodePNGCompressSettings*); + + const void* custom_context; /*optional custom settings for custom functions*/ +}; + +extern const LodePNGCompressSettings lodepng_default_compress_settings; +void lodepng_compress_settings_init(LodePNGCompressSettings* settings); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_PNG +/* +Color mode of an image. Contains all information required to decode the pixel +bits to RGBA colors. This information is the same as used in the PNG file +format, and is used both for PNG and raw image data in LodePNG. +*/ +typedef struct LodePNGColorMode +{ + /*header (IHDR)*/ + LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ + unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ + + /* + palette (PLTE and tRNS) + + Dynamically allocated with the colors of the palette, including alpha. + When encoding a PNG, to store your colors in the palette of the LodePNGColorMode, first use + lodepng_palette_clear, then for each color use lodepng_palette_add. + If you encode an image without alpha with palette, don't forget to put value 255 in each A byte of the palette. + + When decoding, by default you can ignore this palette, since LodePNG already + fills the palette colors in the pixels of the raw RGBA output. + + The palette is only supported for color type 3. + */ + unsigned char* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/ + size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/ + + /* + transparent color key (tRNS) + + This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit. + For greyscale PNGs, r, g and b will all 3 be set to the same. + + When decoding, by default you can ignore this information, since LodePNG sets + pixels with this key to transparent already in the raw RGBA output. + + The color key is only supported for color types 0 and 2. + */ + unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/ + unsigned key_r; /*red/greyscale component of color key*/ + unsigned key_g; /*green component of color key*/ + unsigned key_b; /*blue component of color key*/ +} LodePNGColorMode; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_color_mode_init(LodePNGColorMode* info); +void lodepng_color_mode_cleanup(LodePNGColorMode* info); +/*return value is error code (0 means no error)*/ +unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source); + +void lodepng_palette_clear(LodePNGColorMode* info); +/*add 1 color to the palette*/ +unsigned lodepng_palette_add(LodePNGColorMode* info, + unsigned char r, unsigned char g, unsigned char b, unsigned char a); + +/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/ +unsigned lodepng_get_bpp(const LodePNGColorMode* info); +/*get the amount of color channels used, based on colortype in the struct. +If a palette is used, it counts as 1 channel.*/ +unsigned lodepng_get_channels(const LodePNGColorMode* info); +/*is it a greyscale type? (only colortype 0 or 4)*/ +unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info); +/*has it got an alpha channel? (only colortype 2 or 6)*/ +unsigned lodepng_is_alpha_type(const LodePNGColorMode* info); +/*has it got a palette? (only colortype 3)*/ +unsigned lodepng_is_palette_type(const LodePNGColorMode* info); +/*only returns true if there is a palette and there is a value in the palette with alpha < 255. +Loops through the palette to check this.*/ +unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info); +/* +Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image. +Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels). +Returns false if the image can only have opaque pixels. +In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values, +or if "key_defined" is true. +*/ +unsigned lodepng_can_have_alpha(const LodePNGColorMode* info); +/*Returns the byte size of a raw image buffer with given width, height and color mode*/ +size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +/*The information of a Time chunk in PNG.*/ +typedef struct LodePNGTime +{ + unsigned year; /*2 bytes used (0-65535)*/ + unsigned month; /*1-12*/ + unsigned day; /*1-31*/ + unsigned hour; /*0-23*/ + unsigned minute; /*0-59*/ + unsigned second; /*0-60 (to allow for leap seconds)*/ +} LodePNGTime; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/*Information about the PNG image, except pixels, width and height.*/ +typedef struct LodePNGInfo +{ + /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ + unsigned compression_method;/*compression method of the original file. Always 0.*/ + unsigned filter_method; /*filter method of the original file*/ + unsigned interlace_method; /*interlace method of the original file*/ + LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /* + suggested background color chunk (bKGD) + This color uses the same color mode as the PNG (except alpha channel), which can be 1-bit to 16-bit. + + For greyscale PNGs, r, g and b will all 3 be set to the same. When encoding + the encoder writes the red one. For palette PNGs: When decoding, the RGB value + will be stored, not a palette index. But when encoding, specify the index of + the palette in background_r, the other two are then ignored. + + The decoder does not use this background color to edit the color of pixels. + */ + unsigned background_defined; /*is a suggested background color given?*/ + unsigned background_r; /*red component of suggested background color*/ + unsigned background_g; /*green component of suggested background color*/ + unsigned background_b; /*blue component of suggested background color*/ + + /* + non-international text chunks (tEXt and zTXt) + + The char** arrays each contain num strings. The actual messages are in + text_strings, while text_keys are keywords that give a short description what + the actual text represents, e.g. Title, Author, Description, or anything else. + + A keyword is minimum 1 character and maximum 79 characters long. It's + discouraged to use a single line length longer than 79 characters for texts. + + Don't allocate these text buffers yourself. Use the init/cleanup functions + correctly and use lodepng_add_text and lodepng_clear_text. + */ + size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ + char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ + char** text_strings; /*the actual text*/ + + /* + international text chunks (iTXt) + Similar to the non-international text chunks, but with additional strings + "langtags" and "transkeys". + */ + size_t itext_num; /*the amount of international texts in this PNG*/ + char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ + char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ + char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ + char** itext_strings; /*the actual international text - UTF-8 string*/ + + /*time chunk (tIME)*/ + unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ + LodePNGTime time; + + /*phys chunk (pHYs)*/ + unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/ + unsigned phys_x; /*pixels per unit in x direction*/ + unsigned phys_y; /*pixels per unit in y direction*/ + unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/ + + /* + unknown chunks + There are 3 buffers, one for each position in the PNG where unknown chunks can appear + each buffer contains all unknown chunks for that position consecutively + The 3 buffers are the unknown chunks between certain critical chunks: + 0: IHDR-PLTE, 1: PLTE-IDAT, 2: IDAT-IEND + Do not allocate or traverse this data yourself. Use the chunk traversing functions declared + later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. + */ + unsigned char* unknown_chunks_data[3]; + size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGInfo; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_info_init(LodePNGInfo* info); +void lodepng_info_cleanup(LodePNGInfo* info); +/*return value is error code (0 means no error)*/ +unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source); + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS +void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ +unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/ + +void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/ +unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, + const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/ +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ + +/* +Converts raw buffer from one color type to another color type, based on +LodePNGColorMode structs to describe the input and output color type. +See the reference manual at the end of this header file to see which color conversions are supported. +return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported) +The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel +of the output color type (lodepng_get_bpp). +For < 8 bpp images, there should not be padding bits at the end of scanlines. +For 16-bit per channel colors, uses big endian format like PNG does. +Return value is LodePNG error code +*/ +unsigned lodepng_convert(unsigned char* out, const unsigned char* in, + LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, + unsigned w, unsigned h); + +#ifdef LODEPNG_COMPILE_DECODER +/* +Settings for the decoder. This contains settings for the PNG and the Zlib +decoder, but not the Info settings from the Info structs. +*/ +typedef struct LodePNGDecoderSettings +{ + LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ + + unsigned ignore_crc; /*ignore CRC checksums*/ + + unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ + +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/ + /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/ + unsigned remember_unknown_chunks; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGDecoderSettings; + +void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/ +typedef enum LodePNGFilterStrategy +{ + /*every filter at zero*/ + LFS_ZERO, + /*Use filter that gives minumum sum, as described in the official PNG filter heuristic.*/ + LFS_MINSUM, + /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending + on the image, this is better or worse than minsum.*/ + LFS_ENTROPY, + /* + Brute-force-search PNG filters by compressing each filter for each scanline. + Experimental, very slow, and only rarely gives better compression than MINSUM. + */ + LFS_BRUTE_FORCE, + /*use predefined_filters buffer: you specify the filter type for each scanline*/ + LFS_PREDEFINED +} LodePNGFilterStrategy; + +/*Gives characteristics about the colors of the image, which helps decide which color model to use for encoding. +Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/ +typedef struct LodePNGColorProfile +{ + unsigned colored; /*not greyscale*/ + unsigned key; /*if true, image is not opaque. Only if true and alpha is false, color key is possible.*/ + unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/ + unsigned short key_g; + unsigned short key_b; + unsigned alpha; /*alpha channel or alpha palette required*/ + unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/ + unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/ + unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/ +} LodePNGColorProfile; + +void lodepng_color_profile_init(LodePNGColorProfile* profile); + +/*Get a LodePNGColorProfile of the image.*/ +unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, + const unsigned char* image, unsigned w, unsigned h, + const LodePNGColorMode* mode_in); +/*The function LodePNG uses internally to decide the PNG color with auto_convert. +Chooses an optimal color model, e.g. grey if only grey pixels, palette if < 256 colors, ...*/ +unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, + const unsigned char* image, unsigned w, unsigned h, + const LodePNGColorMode* mode_in); + +/*Settings for the encoder.*/ +typedef struct LodePNGEncoderSettings +{ + LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ + + unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ + + /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than + 8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to + completely follow the official PNG heuristic, filter_palette_zero must be true and + filter_strategy must be LFS_MINSUM*/ + unsigned filter_palette_zero; + /*Which filter strategy to use when not using zeroes due to filter_palette_zero. + Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/ + LodePNGFilterStrategy filter_strategy; + /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with + the same length as the amount of scanlines in the image, and each value must <= 5. You + have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero + must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ + const unsigned char* predefined_filters; + + /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). + If colortype is 3, PLTE is _always_ created.*/ + unsigned force_palette; +#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS + /*add LodePNG identifier and version as a text chunk, for debugging*/ + unsigned add_id; + /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/ + unsigned text_compression; +#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ +} LodePNGEncoderSettings; + +void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); +#endif /*LODEPNG_COMPILE_ENCODER*/ + + +#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) +/*The settings, state and information for extended encoding and decoding.*/ +typedef struct LodePNGState +{ +#ifdef LODEPNG_COMPILE_DECODER + LodePNGDecoderSettings decoder; /*the decoding settings*/ +#endif /*LODEPNG_COMPILE_DECODER*/ +#ifdef LODEPNG_COMPILE_ENCODER + LodePNGEncoderSettings encoder; /*the encoding settings*/ +#endif /*LODEPNG_COMPILE_ENCODER*/ + LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/ + LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/ + unsigned error; +#ifdef LODEPNG_COMPILE_CPP + //For the lodepng::State subclass. + virtual ~LodePNGState(){} +#endif +} LodePNGState; + +/*init, cleanup and copy functions to use with this struct*/ +void lodepng_state_init(LodePNGState* state); +void lodepng_state_cleanup(LodePNGState* state); +void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source); +#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ + +#ifdef LODEPNG_COMPILE_DECODER +/* +Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and +getting much more information about the PNG image and color mode. +*/ +unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize); + +/* +Read the PNG header, but not the actual data. This returns only the information +that is in the header chunk of the PNG, such as width, height and color type. The +information is placed in the info_png field of the LodePNGState. +*/ +unsigned lodepng_inspect(unsigned* w, unsigned* h, + LodePNGState* state, + const unsigned char* in, size_t insize); +#endif /*LODEPNG_COMPILE_DECODER*/ + + +#ifdef LODEPNG_COMPILE_ENCODER +/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/ +unsigned lodepng_encode(unsigned char** out, size_t* outsize, + const unsigned char* image, unsigned w, unsigned h, + LodePNGState* state); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +/* +The lodepng_chunk functions are normally not needed, except to traverse the +unknown chunks stored in the LodePNGInfo struct, or add new ones to it. +It also allows traversing the chunks of an encoded PNG file yourself. + +PNG standard chunk naming conventions: +First byte: uppercase = critical, lowercase = ancillary +Second byte: uppercase = public, lowercase = private +Third byte: must be uppercase +Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy +*/ + +/* +Gets the length of the data of the chunk. Total chunk length has 12 bytes more. +There must be at least 4 bytes to read from. If the result value is too large, +it may be corrupt data. +*/ +unsigned lodepng_chunk_length(const unsigned char* chunk); + +/*puts the 4-byte type in null terminated string*/ +void lodepng_chunk_type(char type[5], const unsigned char* chunk); + +/*check if the type is the given type*/ +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type); + +/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/ +unsigned char lodepng_chunk_ancillary(const unsigned char* chunk); + +/*0: public, 1: private (see PNG standard)*/ +unsigned char lodepng_chunk_private(const unsigned char* chunk); + +/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/ +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk); + +/*get pointer to the data of the chunk, where the input points to the header of the chunk*/ +unsigned char* lodepng_chunk_data(unsigned char* chunk); +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk); + +/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/ +unsigned lodepng_chunk_check_crc(const unsigned char* chunk); + +/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/ +void lodepng_chunk_generate_crc(unsigned char* chunk); + +/*iterate to next chunks. don't use on IEND chunk, as there is no next chunk then*/ +unsigned char* lodepng_chunk_next(unsigned char* chunk); +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk); + +/* +Appends chunk to the data in out. The given chunk should already have its chunk header. +The out variable and outlength are updated to reflect the new reallocated buffer. +Returns error code (0 if it went ok) +*/ +unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk); + +/* +Appends new chunk to out. The chunk to append is given by giving its length, type +and data separately. The type is a 4-letter string. +The out variable and outlength are updated to reflect the new reallocated buffer. +Returne error code (0 if it went ok) +*/ +unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, + const char* type, const unsigned char* data); + + +/*Calculate CRC32 of buffer*/ +unsigned lodepng_crc32(const unsigned char* buf, size_t len); +#endif /*LODEPNG_COMPILE_PNG*/ + + +#ifdef LODEPNG_COMPILE_ZLIB +/* +This zlib part can be used independently to zlib compress and decompress a +buffer. It cannot be used to create gzip files however, and it only supports the +part of zlib that is required for PNG, it does not support dictionaries. +*/ + +#ifdef LODEPNG_COMPILE_DECODER +/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/ +unsigned lodepng_inflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings); + +/* +Decompresses Zlib data. Reallocates the out buffer and appends the data. The +data must be according to the zlib specification. +Either, *out must be NULL and *outsize must be 0, or, *out must be a valid +buffer and *outsize its size in bytes. out must be freed by user after usage. +*/ +unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGDecompressSettings* settings); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +/* +Compresses data with Zlib. Reallocates the out buffer and appends the data. +Zlib adds a small header and trailer around the deflate data. +The data is output in the format of the zlib specification. +Either, *out must be NULL and *outsize must be 0, or, *out must be a valid +buffer and *outsize its size in bytes. out must be freed by user after usage. +*/ +unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings); + +/* +Find length-limited Huffman code for given frequencies. This function is in the +public interface only for tests, it's used internally by lodepng_deflate. +*/ +unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, + size_t numcodes, unsigned maxbitlen); + +/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/ +unsigned lodepng_deflate(unsigned char** out, size_t* outsize, + const unsigned char* in, size_t insize, + const LodePNGCompressSettings* settings); + +#endif /*LODEPNG_COMPILE_ENCODER*/ +#endif /*LODEPNG_COMPILE_ZLIB*/ + +#ifdef LODEPNG_COMPILE_DISK +/* +Load a file from disk into buffer. The function allocates the out buffer, and +after usage you should free it. +out: output parameter, contains pointer to loaded buffer. +outsize: output parameter, size of the allocated out buffer +filename: the path to the file to load +return value: error code (0 means ok) +*/ +unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename); + +/* +Save a file from buffer to disk. Warning, if it exists, this function overwrites +the file without warning! +buffer: the buffer to write +buffersize: size of the buffer to write +filename: the path to the file to save to +return value: error code (0 means ok) +*/ +unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename); +#endif /*LODEPNG_COMPILE_DISK*/ + +#ifdef LODEPNG_COMPILE_CPP +//The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. +namespace lodepng +{ +#ifdef LODEPNG_COMPILE_PNG +class State : public LodePNGState +{ + public: + State(); + State(const State& other); + virtual ~State(); + State& operator=(const State& other); +}; + +#ifdef LODEPNG_COMPILE_DECODER +//Same as other lodepng::decode, but using a State for more settings and information. +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const unsigned char* in, size_t insize); +unsigned decode(std::vector& out, unsigned& w, unsigned& h, + State& state, + const std::vector& in); +#endif /*LODEPNG_COMPILE_DECODER*/ + +#ifdef LODEPNG_COMPILE_ENCODER +//Same as other lodepng::encode, but using a State for more settings and information. +unsigned encode(std::vector& out, + const unsigned char* in, unsigned w, unsigned h, + State& state); +unsigned encode(std::vector& out, + const std::vector& in, unsigned w, unsigned h, + State& state); +#endif /*LODEPNG_COMPILE_ENCODER*/ + +#ifdef LODEPNG_COMPILE_DISK +/* +Load a file from disk into an std::vector. If the vector is empty, then either +the file doesn't exist or is an empty file. +*/ +void load_file(std::vector& buffer, const std::string& filename); + +/* +Save the binary data in an std::vector to a file on disk. The file is overwritten +without warning. +*/ +void save_file(const std::vector& buffer, const std::string& filename); +#endif //LODEPNG_COMPILE_DISK +#endif //LODEPNG_COMPILE_PNG + +#ifdef LODEPNG_COMPILE_ZLIB +#ifdef LODEPNG_COMPILE_DECODER +//Zlib-decompress an unsigned char buffer +unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); + +//Zlib-decompress an std::vector +unsigned decompress(std::vector& out, const std::vector& in, + const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); +#endif //LODEPNG_COMPILE_DECODER + +#ifdef LODEPNG_COMPILE_ENCODER +//Zlib-compress an unsigned char buffer +unsigned compress(std::vector& out, const unsigned char* in, size_t insize, + const LodePNGCompressSettings& settings = lodepng_default_compress_settings); + +//Zlib-compress an std::vector +unsigned compress(std::vector& out, const std::vector& in, + const LodePNGCompressSettings& settings = lodepng_default_compress_settings); +#endif //LODEPNG_COMPILE_ENCODER +#endif //LODEPNG_COMPILE_ZLIB +} //namespace lodepng +#endif /*LODEPNG_COMPILE_CPP*/ + +/* +TODO: +[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often +[.] check compatibility with vareous compilers - done but needs to be redone for every newer version +[X] converting color to 16-bit per channel types +[ ] read all public PNG chunk types (but never let the color profile and gamma ones touch RGB values) +[ ] make sure encoder generates no chunks with size > (2^31)-1 +[ ] partial decoding (stream processing) +[X] let the "isFullyOpaque" function check color keys and transparent palettes too +[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl" +[ ] don't stop decoding on errors like 69, 57, 58 (make warnings) +[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes +[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ... +*/ + +#endif /*LODEPNG_H inclusion guard*/ + +/* +LodePNG Documentation +--------------------- + +0. table of contents +-------------------- + + 1. about + 1.1. supported features + 1.2. features not supported + 2. C and C++ version + 3. security + 4. decoding + 5. encoding + 6. color conversions + 6.1. PNG color types + 6.2. color conversions + 6.3. padding bits + 6.4. A note about 16-bits per channel and endianness + 7. error values + 8. chunks and PNG editing + 9. compiler support + 10. examples + 10.1. decoder C++ example + 10.2. decoder C example + 11. changes + 12. contact information + + +1. about +-------- + +PNG is a file format to store raster images losslessly with good compression, +supporting different color types and alpha channel. + +LodePNG is a PNG codec according to the Portable Network Graphics (PNG) +Specification (Second Edition) - W3C Recommendation 10 November 2003. + +The specifications used are: + +*) Portable Network Graphics (PNG) Specification (Second Edition): + http://www.w3.org/TR/2003/REC-PNG-20031110 +*) RFC 1950 ZLIB Compressed Data Format version 3.3: + http://www.gzip.org/zlib/rfc-zlib.html +*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3: + http://www.gzip.org/zlib/rfc-deflate.html + +The most recent version of LodePNG can currently be found at +http://lodev.org/lodepng/ + +LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds +extra functionality. + +LodePNG exists out of two files: +-lodepng.h: the header file for both C and C++ +-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage + +If you want to start using LodePNG right away without reading this doc, get the +examples from the LodePNG website to see how to use it in code, or check the +smaller examples in chapter 13 here. + +LodePNG is simple but only supports the basic requirements. To achieve +simplicity, the following design choices were made: There are no dependencies +on any external library. There are functions to decode and encode a PNG with +a single function call, and extended versions of these functions taking a +LodePNGState struct allowing to specify or get more information. By default +the colors of the raw image are always RGB or RGBA, no matter what color type +the PNG file uses. To read and write files, there are simple functions to +convert the files to/from buffers in memory. + +This all makes LodePNG suitable for loading textures in games, demos and small +programs, ... It's less suitable for full fledged image editors, loading PNGs +over network (it requires all the image data to be available before decoding can +begin), life-critical systems, ... + +1.1. supported features +----------------------- + +The following features are supported by the decoder: + +*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image, + or the same color type as the PNG +*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image +*) Adam7 interlace and deinterlace for any color type +*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk +*) support for alpha channels, including RGBA color model, translucent palettes and color keying +*) zlib decompression (inflate) +*) zlib compression (deflate) +*) CRC32 and ADLER32 checksums +*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks. +*) the following chunks are supported (generated/interpreted) by both encoder and decoder: + IHDR: header information + PLTE: color palette + IDAT: pixel data + IEND: the final chunk + tRNS: transparency for palettized images + tEXt: textual information + zTXt: compressed textual information + iTXt: international textual information + bKGD: suggested background color + pHYs: physical dimensions + tIME: modification time + +1.2. features not supported +--------------------------- + +The following features are _not_ supported: + +*) some features needed to make a conformant PNG-Editor might be still missing. +*) partial loading/stream processing. All data must be available and is processed in one call. +*) The following public chunks are not supported but treated as unknown chunks by LodePNG + cHRM, gAMA, iCCP, sRGB, sBIT, hIST, sPLT + Some of these are not supported on purpose: LodePNG wants to provide the RGB values + stored in the pixels, not values modified by system dependent gamma or color models. + + +2. C and C++ version +-------------------- + +The C version uses buffers allocated with alloc that you need to free() +yourself. You need to use init and cleanup functions for each struct whenever +using a struct from the C version to avoid exploits and memory leaks. + +The C++ version has extra functions with std::vectors in the interface and the +lodepng::State class which is a LodePNGState with constructor and destructor. + +These files work without modification for both C and C++ compilers because all +the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers +ignore it, and the C code is made to compile both with strict ISO C90 and C++. + +To use the C++ version, you need to rename the source file to lodepng.cpp +(instead of lodepng.c), and compile it with a C++ compiler. + +To use the C version, you need to rename the source file to lodepng.c (instead +of lodepng.cpp), and compile it with a C compiler. + + +3. Security +----------- + +Even if carefully designed, it's always possible that LodePNG contains possible +exploits. If you discover one, please let me know, and it will be fixed. + +When using LodePNG, care has to be taken with the C version of LodePNG, as well +as the C-style structs when working with C++. The following conventions are used +for all C-style structs: + +-if a struct has a corresponding init function, always call the init function when making a new one +-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks +-if a struct has a corresponding copy function, use the copy function instead of "=". + The destination must also be inited already. + + +4. Decoding +----------- + +Decoding converts a PNG compressed image to a raw pixel buffer. + +Most documentation on using the decoder is at its declarations in the header +above. For C, simple decoding can be done with functions such as +lodepng_decode32, and more advanced decoding can be done with the struct +LodePNGState and lodepng_decode. For C++, all decoding can be done with the +various lodepng::decode functions, and lodepng::State can be used for advanced +features. + +When using the LodePNGState, it uses the following fields for decoding: +*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here +*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get +*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use + +LodePNGInfo info_png +-------------------- + +After decoding, this contains extra information of the PNG image, except the actual +pixels, width and height because these are already gotten directly from the decoder +functions. + +It contains for example the original color type of the PNG image, text comments, +suggested background color, etc... More details about the LodePNGInfo struct are +at its declaration documentation. + +LodePNGColorMode info_raw +------------------------- + +When decoding, here you can specify which color type you want +the resulting raw image to be. If this is different from the colortype of the +PNG, then the decoder will automatically convert the result. This conversion +always works, except if you want it to convert a color PNG to greyscale or to +a palette with missing colors. + +By default, 32-bit color is used for the result. + +LodePNGDecoderSettings decoder +------------------------------ + +The settings can be used to ignore the errors created by invalid CRC and Adler32 +chunks, and to disable the decoding of tEXt chunks. + +There's also a setting color_convert, true by default. If false, no conversion +is done, the resulting data will be as it was in the PNG (after decompression) +and you'll have to puzzle the colors of the pixels together yourself using the +color type information in the LodePNGInfo. + + +5. Encoding +----------- + +Encoding converts a raw pixel buffer to a PNG compressed image. + +Most documentation on using the encoder is at its declarations in the header +above. For C, simple encoding can be done with functions such as +lodepng_encode32, and more advanced decoding can be done with the struct +LodePNGState and lodepng_encode. For C++, all encoding can be done with the +various lodepng::encode functions, and lodepng::State can be used for advanced +features. + +Like the decoder, the encoder can also give errors. However it gives less errors +since the encoder input is trusted, the decoder input (a PNG image that could +be forged by anyone) is not trusted. + +When using the LodePNGState, it uses the following fields for encoding: +*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be. +*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has +*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use + +LodePNGInfo info_png +-------------------- + +When encoding, you use this the opposite way as when decoding: for encoding, +you fill in the values you want the PNG to have before encoding. By default it's +not needed to specify a color type for the PNG since it's automatically chosen, +but it's possible to choose it yourself given the right settings. + +The encoder will not always exactly match the LodePNGInfo struct you give, +it tries as close as possible. Some things are ignored by the encoder. The +encoder uses, for example, the following settings from it when applicable: +colortype and bitdepth, text chunks, time chunk, the color key, the palette, the +background color, the interlace method, unknown chunks, ... + +When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk. +If the palette contains any colors for which the alpha channel is not 255 (so +there are translucent colors in the palette), it'll add a tRNS chunk. + +LodePNGColorMode info_raw +------------------------- + +You specify the color type of the raw image that you give to the input here, +including a possible transparent color key and palette you happen to be using in +your raw image data. + +By default, 32-bit color is assumed, meaning your input has to be in RGBA +format with 4 bytes (unsigned chars) per pixel. + +LodePNGEncoderSettings encoder +------------------------------ + +The following settings are supported (some are in sub-structs): +*) auto_convert: when this option is enabled, the encoder will +automatically choose the smallest possible color mode (including color key) that +can encode the colors of all pixels without information loss. +*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree, + 2 = dynamic huffman tree (best compression). Should be 2 for proper + compression. +*) use_lz77: whether or not to use LZ77 for compressed block types. Should be + true for proper compression. +*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value + 2048 by default, but can be set to 32768 for better, but slow, compression. +*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE + chunk if force_palette is true. This can used as suggested palette to convert + to by viewers that don't support more than 256 colors (if those still exist) +*) add_id: add text chunk "Encoder: LodePNG " to the image. +*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks. + zTXt chunks use zlib compression on the text. This gives a smaller result on + large texts but a larger result on small texts (such as a single program name). + It's all tEXt or all zTXt though, there's no separate setting per text yet. + + +6. color conversions +-------------------- + +An important thing to note about LodePNG, is that the color type of the PNG, and +the color type of the raw image, are completely independent. By default, when +you decode a PNG, you get the result as a raw image in the color type you want, +no matter whether the PNG was encoded with a palette, greyscale or RGBA color. +And if you encode an image, by default LodePNG will automatically choose the PNG +color type that gives good compression based on the values of colors and amount +of colors in the image. It can be configured to let you control it instead as +well, though. + +To be able to do this, LodePNG does conversions from one color mode to another. +It can convert from almost any color type to any other color type, except the +following conversions: RGB to greyscale is not supported, and converting to a +palette when the palette doesn't have a required color is not supported. This is +not supported on purpose: this is information loss which requires a color +reduction algorithm that is beyong the scope of a PNG encoder (yes, RGB to grey +is easy, but there are multiple ways if you want to give some channels more +weight). + +By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB +color, no matter what color type the PNG has. And by default when encoding, +LodePNG automatically picks the best color model for the output PNG, and expects +the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control +the color format of the images yourself, you can skip this chapter. + +6.1. PNG color types +-------------------- + +A PNG image can have many color types, ranging from 1-bit color to 64-bit color, +as well as palettized color modes. After the zlib decompression and unfiltering +in the PNG image is done, the raw pixel data will have that color type and thus +a certain amount of bits per pixel. If you want the output raw image after +decoding to have another color type, a conversion is done by LodePNG. + +The PNG specification gives the following color types: + +0: greyscale, bit depths 1, 2, 4, 8, 16 +2: RGB, bit depths 8 and 16 +3: palette, bit depths 1, 2, 4 and 8 +4: greyscale with alpha, bit depths 8 and 16 +6: RGBA, bit depths 8 and 16 + +Bit depth is the amount of bits per pixel per color channel. So the total amount +of bits per pixel is: amount of channels * bitdepth. + +6.2. color conversions +---------------------- + +As explained in the sections about the encoder and decoder, you can specify +color types and bit depths in info_png and info_raw to change the default +behaviour. + +If, when decoding, you want the raw image to be something else than the default, +you need to set the color type and bit depth you want in the LodePNGColorMode, +or the parameters colortype and bitdepth of the simple decoding function. + +If, when encoding, you use another color type than the default in the raw input +image, you need to specify its color type and bit depth in the LodePNGColorMode +of the raw image, or use the parameters colortype and bitdepth of the simple +encoding function. + +If, when encoding, you don't want LodePNG to choose the output PNG color type +but control it yourself, you need to set auto_convert in the encoder settings +to false, and specify the color type you want in the LodePNGInfo of the +encoder (including palette: it can generate a palette if auto_convert is true, +otherwise not). + +If the input and output color type differ (whether user chosen or auto chosen), +LodePNG will do a color conversion, which follows the rules below, and may +sometimes result in an error. + +To avoid some confusion: +-the decoder converts from PNG to raw image +-the encoder converts from raw image to PNG +-the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image +-the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG +-when encoding, the color type in LodePNGInfo is ignored if auto_convert + is enabled, it is automatically generated instead +-when decoding, the color type in LodePNGInfo is set by the decoder to that of the original + PNG image, but it can be ignored since the raw image has the color type you requested instead +-if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion + between the color types is done if the color types are supported. If it is not + supported, an error is returned. If the types are the same, no conversion is done. +-even though some conversions aren't supported, LodePNG supports loading PNGs from any + colortype and saving PNGs to any colortype, sometimes it just requires preparing + the raw image correctly before encoding. +-both encoder and decoder use the same color converter. + +Non supported color conversions: +-color to greyscale: no error is thrown, but the result will look ugly because +only the red channel is taken +-anything to palette when that palette does not have that color in it: in this +case an error is thrown + +Supported color conversions: +-anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA +-any grey or grey+alpha, to grey or grey+alpha +-anything to a palette, as long as the palette has the requested colors in it +-removing alpha channel +-higher to smaller bitdepth, and vice versa + +If you want no color conversion to be done (e.g. for speed or control): +-In the encoder, you can make it save a PNG with any color type by giving the +raw color mode and LodePNGInfo the same color mode, and setting auto_convert to +false. +-In the decoder, you can make it store the pixel data in the same color type +as the PNG has, by setting the color_convert setting to false. Settings in +info_raw are then ignored. + +The function lodepng_convert does the color conversion. It is available in the +interface but normally isn't needed since the encoder and decoder already call +it. + +6.3. padding bits +----------------- + +In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines +have a bit amount that isn't a multiple of 8, then padding bits are used so that each +scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output. +The raw input image you give to the encoder, and the raw output image you get from the decoder +will NOT have these padding bits, e.g. in the case of a 1-bit image with a width +of 7 pixels, the first pixel of the second scanline will the the 8th bit of the first byte, +not the first bit of a new byte. + +6.4. A note about 16-bits per channel and endianness +---------------------------------------------------- + +LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like +for any other color format. The 16-bit values are stored in big endian (most +significant byte first) in these arrays. This is the opposite order of the +little endian used by x86 CPU's. + +LodePNG always uses big endian because the PNG file format does so internally. +Conversions to other formats than PNG uses internally are not supported by +LodePNG on purpose, there are myriads of formats, including endianness of 16-bit +colors, the order in which you store R, G, B and A, and so on. Supporting and +converting to/from all that is outside the scope of LodePNG. + +This may mean that, depending on your use case, you may want to convert the big +endian output of LodePNG to little endian with a for loop. This is certainly not +always needed, many applications and libraries support big endian 16-bit colors +anyway, but it means you cannot simply cast the unsigned char* buffer to an +unsigned short* buffer on x86 CPUs. + + +7. error values +--------------- + +All functions in LodePNG that return an error code, return 0 if everything went +OK, or a non-zero code if there was an error. + +The meaning of the LodePNG error values can be retrieved with the function +lodepng_error_text: given the numerical error code, it returns a description +of the error in English as a string. + +Check the implementation of lodepng_error_text to see the meaning of each code. + + +8. chunks and PNG editing +------------------------- + +If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG +editor that should follow the rules about handling of unknown chunks, or if your +program is able to read other types of chunks than the ones handled by LodePNG, +then that's possible with the chunk functions of LodePNG. + +A PNG chunk has the following layout: + +4 bytes length +4 bytes type name +length bytes data +4 bytes CRC + +8.1. iterating through chunks +----------------------------- + +If you have a buffer containing the PNG image data, then the first chunk (the +IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the +signature of the PNG and are not part of a chunk. But if you start at byte 8 +then you have a chunk, and can check the following things of it. + +NOTE: none of these functions check for memory buffer boundaries. To avoid +exploits, always make sure the buffer contains all the data of the chunks. +When using lodepng_chunk_next, make sure the returned value is within the +allocated memory. + +unsigned lodepng_chunk_length(const unsigned char* chunk): + +Get the length of the chunk's data. The total chunk length is this length + 12. + +void lodepng_chunk_type(char type[5], const unsigned char* chunk): +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type): + +Get the type of the chunk or compare if it's a certain type + +unsigned char lodepng_chunk_critical(const unsigned char* chunk): +unsigned char lodepng_chunk_private(const unsigned char* chunk): +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk): + +Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are). +Check if the chunk is private (public chunks are part of the standard, private ones not). +Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical +chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your +program doesn't handle that type of unknown chunk. + +unsigned char* lodepng_chunk_data(unsigned char* chunk): +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk): + +Get a pointer to the start of the data of the chunk. + +unsigned lodepng_chunk_check_crc(const unsigned char* chunk): +void lodepng_chunk_generate_crc(unsigned char* chunk): + +Check if the crc is correct or generate a correct one. + +unsigned char* lodepng_chunk_next(unsigned char* chunk): +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk): + +Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these +functions do no boundary checking of the allocated data whatsoever, so make sure there is enough +data available in the buffer to be able to go to the next chunk. + +unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk): +unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, + const char* type, const unsigned char* data): + +These functions are used to create new chunks that are appended to the data in *out that has +length *outlength. The append function appends an existing chunk to the new data. The create +function creates a new chunk with the given parameters and appends it. Type is the 4-letter +name of the chunk. + +8.2. chunks in info_png +----------------------- + +The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3 +buffers (each with size) to contain 3 types of unknown chunks: +the ones that come before the PLTE chunk, the ones that come between the PLTE +and the IDAT chunks, and the ones that come after the IDAT chunks. +It's necessary to make the distionction between these 3 cases because the PNG +standard forces to keep the ordering of unknown chunks compared to the critical +chunks, but does not force any other ordering rules. + +info_png.unknown_chunks_data[0] is the chunks before PLTE +info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT +info_png.unknown_chunks_data[2] is the chunks after IDAT + +The chunks in these 3 buffers can be iterated through and read by using the same +way described in the previous subchapter. + +When using the decoder to decode a PNG, you can make it store all unknown chunks +if you set the option settings.remember_unknown_chunks to 1. By default, this +option is off (0). + +The encoder will always encode unknown chunks that are stored in the info_png. +If you need it to add a particular chunk that isn't known by LodePNG, you can +use lodepng_chunk_append or lodepng_chunk_create to the chunk data in +info_png.unknown_chunks_data[x]. + +Chunks that are known by LodePNG should not be added in that way. E.g. to make +LodePNG add a bKGD chunk, set background_defined to true and add the correct +parameters there instead. + + +9. compiler support +------------------- + +No libraries other than the current standard C library are needed to compile +LodePNG. For the C++ version, only the standard C++ library is needed on top. +Add the files lodepng.c(pp) and lodepng.h to your project, include +lodepng.h where needed, and your program can read/write PNG files. + +It is compatible with C90 and up, and C++03 and up. + +If performance is important, use optimization when compiling! For both the +encoder and decoder, this makes a large difference. + +Make sure that LodePNG is compiled with the same compiler of the same version +and with the same settings as the rest of the program, or the interfaces with +std::vectors and std::strings in C++ can be incompatible. + +CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets. + +*) gcc and g++ + +LodePNG is developed in gcc so this compiler is natively supported. It gives no +warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++ +version 4.7.1 on Linux, 32-bit and 64-bit. + +*) Clang + +Fully supported and warning-free. + +*) Mingw + +The Mingw compiler (a port of gcc for Windows) should be fully supported by +LodePNG. + +*) Visual Studio and Visual C++ Express Edition + +LodePNG should be warning-free with warning level W4. Two warnings were disabled +with pragmas though: warning 4244 about implicit conversions, and warning 4996 +where it wants to use a non-standard function fopen_s instead of the standard C +fopen. + +Visual Studio may want "stdafx.h" files to be included in each source file and +give an error "unexpected end of file while looking for precompiled header". +This is not standard C++ and will not be added to the stock LodePNG. You can +disable it for lodepng.cpp only by right clicking it, Properties, C/C++, +Precompiled Headers, and set it to Not Using Precompiled Headers there. + +NOTE: Modern versions of VS should be fully supported, but old versions, e.g. +VS6, are not guaranteed to work. + +*) Compilers on Macintosh + +LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for +C and C++. + +*) Other Compilers + +If you encounter problems on any compilers, feel free to let me know and I may +try to fix it if the compiler is modern and standards complient. + + +10. examples +------------ + +This decoder example shows the most basic usage of LodePNG. More complex +examples can be found on the LodePNG website. + +10.1. decoder C++ example +------------------------- + +#include "lodepng.h" +#include + +int main(int argc, char *argv[]) +{ + const char* filename = argc > 1 ? argv[1] : "test.png"; + + //load and decode + std::vector image; + unsigned width, height; + unsigned error = lodepng::decode(image, width, height, filename); + + //if there's an error, display it + if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; + + //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... +} + +10.2. decoder C example +----------------------- + +#include "lodepng.h" + +int main(int argc, char *argv[]) +{ + unsigned error; + unsigned char* image; + size_t width, height; + const char* filename = argc > 1 ? argv[1] : "test.png"; + + error = lodepng_decode32_file(&image, &width, &height, filename); + + if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error)); + + / * use image here * / + + free(image); + return 0; +} + + +11. changes +----------- + +The version number of LodePNG is the date of the change given in the format +yyyymmdd. + +Some changes aren't backwards compatible. Those are indicated with a (!) +symbol. + +*) 23 aug 2014: Reduced needless memory usage of decoder. +*) 28 jun 2014: Removed fix_png setting, always support palette OOB for + simplicity. Made ColorProfile public. +*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization. +*) 22 dec 2013: Power of two windowsize required for optimization. +*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key. +*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png). +*) 11 mar 2013 (!): Bugfix with custom free. Changed from "my" to "lodepng_" + prefix for the custom allocators and made it possible with a new #define to + use custom ones in your project without needing to change lodepng's code. +*) 28 jan 2013: Bugfix with color key. +*) 27 okt 2012: Tweaks in text chunk keyword length error handling. +*) 8 okt 2012 (!): Added new filter strategy (entropy) and new auto color mode. + (no palette). Better deflate tree encoding. New compression tweak settings. + Faster color conversions while decoding. Some internal cleanups. +*) 23 sep 2012: Reduced warnings in Visual Studio a little bit. +*) 1 sep 2012 (!): Removed #define's for giving custom (de)compression functions + and made it work with function pointers instead. +*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc + and free functions and toggle #defines from compiler flags. Small fixes. +*) 6 may 2012 (!): Made plugging in custom zlib/deflate functions more flexible. +*) 22 apr 2012 (!): Made interface more consistent, renaming a lot. Removed + redundant C++ codec classes. Reduced amount of structs. Everything changed, + but it is cleaner now imho and functionality remains the same. Also fixed + several bugs and shrinked the implementation code. Made new samples. +*) 6 nov 2011 (!): By default, the encoder now automatically chooses the best + PNG color model and bit depth, based on the amount and type of colors of the + raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color. +*) 9 okt 2011: simpler hash chain implementation for the encoder. +*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching. +*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking. + A bug with the PNG filtertype heuristic was fixed, so that it chooses much + better ones (it's quite significant). A setting to do an experimental, slow, + brute force search for PNG filter types is added. +*) 17 aug 2011 (!): changed some C zlib related function names. +*) 16 aug 2011: made the code less wide (max 120 characters per line). +*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors. +*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled. +*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman + to optimize long sequences of zeros. +*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and + LodePNG_InfoColor_canHaveAlpha functions for convenience. +*) 7 nov 2010: added LodePNG_error_text function to get error code description. +*) 30 okt 2010: made decoding slightly faster +*) 26 okt 2010: (!) changed some C function and struct names (more consistent). + Reorganized the documentation and the declaration order in the header. +*) 08 aug 2010: only changed some comments and external samples. +*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version. +*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers. +*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could + read by ignoring the problem but windows apps couldn't. +*) 06 jun 2008: added more error checks for out of memory cases. +*) 26 apr 2008: added a few more checks here and there to ensure more safety. +*) 06 mar 2008: crash with encoding of strings fixed +*) 02 feb 2008: support for international text chunks added (iTXt) +*) 23 jan 2008: small cleanups, and #defines to divide code in sections +*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor. +*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder. +*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added + Also vareous fixes, such as in the deflate and the padding bits code. +*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved + filtering code of encoder. +*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A + C++ wrapper around this provides an interface almost identical to before. + Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code + are together in these files but it works both for C and C++ compilers. +*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks +*) 30 aug 2007: bug fixed which makes this Borland C++ compatible +*) 09 aug 2007: some VS2005 warnings removed again +*) 21 jul 2007: deflate code placed in new namespace separate from zlib code +*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images +*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing + invalid std::vector element [0] fixed, and level 3 and 4 warnings removed +*) 02 jun 2007: made the encoder add a tag with version by default +*) 27 may 2007: zlib and png code separated (but still in the same file), + simple encoder/decoder functions added for more simple usage cases +*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69), + moved some examples from here to lodepng_examples.cpp +*) 12 may 2007: palette decoding bug fixed +*) 24 apr 2007: changed the license from BSD to the zlib license +*) 11 mar 2007: very simple addition: ability to encode bKGD chunks. +*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding + palettized PNG images. Plus little interface change with palette and texts. +*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes. + Fixed a bug where the end code of a block had length 0 in the Huffman tree. +*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented + and supported by the encoder, resulting in smaller PNGs at the output. +*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone. +*) 24 jan 2007: gave encoder an error interface. Added color conversion from any + greyscale type to 8-bit greyscale with or without alpha. +*) 21 jan 2007: (!) Totally changed the interface. It allows more color types + to convert to and is more uniform. See the manual for how it works now. +*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days: + encode/decode custom tEXt chunks, separate classes for zlib & deflate, and + at last made the decoder give errors for incorrect Adler32 or Crc. +*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel. +*) 29 dec 2006: Added support for encoding images without alpha channel, and + cleaned out code as well as making certain parts faster. +*) 28 dec 2006: Added "Settings" to the encoder. +*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now. + Removed some code duplication in the decoder. Fixed little bug in an example. +*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter. + Fixed a bug of the decoder with 16-bit per color. +*) 15 okt 2006: Changed documentation structure +*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the + given image buffer, however for now it's not compressed. +*) 08 sep 2006: (!) Changed to interface with a Decoder class +*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different + way. Renamed decodePNG to decodePNGGeneric. +*) 29 jul 2006: (!) Changed the interface: image info is now returned as a + struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy. +*) 28 jul 2006: Cleaned the code and added new error checks. + Corrected terminology "deflate" into "inflate". +*) 23 jun 2006: Added SDL example in the documentation in the header, this + example allows easy debugging by displaying the PNG and its transparency. +*) 22 jun 2006: (!) Changed way to obtain error value. Added + loadFile function for convenience. Made decodePNG32 faster. +*) 21 jun 2006: (!) Changed type of info vector to unsigned. + Changed position of palette in info vector. Fixed an important bug that + happened on PNGs with an uncompressed block. +*) 16 jun 2006: Internally changed unsigned into unsigned where + needed, and performed some optimizations. +*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them + in LodePNG namespace. Changed the order of the parameters. Rewrote the + documentation in the header. Renamed files to lodepng.cpp and lodepng.h +*) 22 apr 2006: Optimized and improved some code +*) 07 sep 2005: (!) Changed to std::vector interface +*) 12 aug 2005: Initial release (C++, decoder only) + + +12. contact information +----------------------- + +Feel free to contact me with suggestions, problems, comments, ... concerning +LodePNG. If you encounter a PNG image that doesn't work properly with this +decoder, feel free to send it and I'll use it to find and fix the problem. + +My email address is (puzzle the account and domain together with an @ symbol): +Domain: gmail dot com. +Account: lode dot vandevenne. + + +Copyright (c) 2005-2014 Lode Vandevenne +*/ diff -Nru nestopia-1.48/source/common/samples.cpp nestopia-1.49/source/common/samples.cpp --- nestopia-1.48/source/common/samples.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/samples.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,151 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2018 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include +#include + +#ifndef _MINGW +#include +#include +#endif + +#include "nstcommon.h" +#include "samples.h" + +static uint8_t* wavfile; + +extern nstpaths_t nstpaths; + +int nst_sample_load_file(const char* filepath) { + // Load a sample file into memory + FILE *file; + long filesize; // File size in bytes + size_t result; + + file = fopen(filepath, "rb"); + + if (!file) { return 0; } + + fseek(file, 0, SEEK_END); + filesize = ftell(file); + fseek(file, 0, SEEK_SET); + + wavfile = (uint8_t*)malloc(filesize * sizeof(uint8_t)); + + if (wavfile == NULL) { return 0; } + + result = fread(wavfile, sizeof(uint8_t), filesize, file); + if (result != filesize) { return 0; } + + fclose(file); + return 1; +} + +int nst_sample_load_archive(const char* filename, const char* reqfile) { +#ifndef _MINGW + struct archive *a; + struct archive_entry *entry; + int r; + int64_t entrysize; + + a = archive_read_new(); + archive_read_support_filter_all(a); + archive_read_support_format_all(a); + r = archive_read_open_filename(a, filename, 10240); + + // Test if it's actually an archive + if (r != ARCHIVE_OK) { + r = archive_read_free(a); + return 0; + } + + // Scan through the archive for files + while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { + const char *currentfile = archive_entry_pathname(entry); + int len = strlen(currentfile); + if ((!strcasecmp(¤tfile[len-4], ".wav"))) { + // Load the specified file + if (!strcmp(currentfile, reqfile)) { + entrysize = archive_entry_size(entry); + wavfile = (uint8_t*)malloc(entrysize); + archive_read_data(a, wavfile, entrysize); + archive_read_data_skip(a); + r = archive_read_free(a); + return 1; + } + } + } +#endif + return 0; +} + +int nst_sample_unload_file() { + // Free the file + if (wavfile) { free(wavfile); } + return 1; +} + +void nst_sample_setcontent(User::File& file) { + // Parse the .WAV header and load the sample into the emulator + + // Check to see if it has a valid header + uint8_t fmt[4] = { 0x66, 0x6d, 0x74, 0x20}; + uint8_t subchunk2id[4] = { 0x64, 0x61, 0x74, 0x61}; + if (memcmp(&wavfile[0x00], "RIFF", 4) != 0) { return; } + if (memcmp(&wavfile[0x08], "WAVE", 4) != 0) { return; } + if (memcmp(&wavfile[0x0c], &fmt, 4) != 0) { return; } + if (memcmp(&wavfile[0x24], &subchunk2id, 4) != 0) { return; } + + // Load the sample into the emulator + uint8_t *dataptr = &wavfile[0x2c]; + uint32_t datasize = wavfile[0x2b] << 24 | wavfile[0x2a] << 16 | wavfile[0x29] << 8 | wavfile[0x28]; + uint16_t blockalign = wavfile[0x21] << 8 | wavfile[0x20]; + uint16_t numchannels = wavfile[0x17] << 8 | wavfile[0x16]; + uint16_t bitspersample = wavfile[0x23] << 8 | wavfile[0x22]; + uint32_t samplerate = wavfile[0x1b] << 24 | wavfile[0x1a] << 16 | wavfile[0x19] << 8 | wavfile[0x18]; + file.SetSampleContent(dataptr, datasize / blockalign, numchannels == 2, bitspersample, samplerate); +} + +void nst_sample_load_samples(User::File& file, const char* sampgame) { + // Load samples for the specific game + char reqfile[16]; + char samppath[576]; + + // Requested sample .wav file + snprintf(reqfile, sizeof(reqfile), "%02d.wav", file.GetId()); + + // Check if there's a MAME-style zip archive + snprintf(samppath, sizeof(samppath), "%s%s.zip", nstpaths.sampdir, sampgame); + if (nst_sample_load_archive(samppath, reqfile)) { + nst_sample_setcontent(file); + nst_sample_unload_file(); + } + else { // Otherwise load .wav files from an extracted directory + snprintf(samppath, sizeof(samppath), "%s%s/%s", nstpaths.sampdir, sampgame, reqfile); + if (nst_sample_load_file(samppath)) { + nst_sample_setcontent(file); + nst_sample_unload_file(); + } + } +} diff -Nru nestopia-1.48/source/common/samples.h nestopia-1.49/source/common/samples.h --- nestopia-1.48/source/common/samples.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/samples.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,14 @@ +#ifndef _SAMPLES_H_ +#define _SAMPLES_H_ + +#include "core/api/NstApiUser.hpp" + +using namespace Nes::Api; + +int nst_sample_load_file(const char* filepath); +int nst_sample_load_archive(const char* filename, const char* reqfile); +int nst_sample_unload_file(); +void nst_sample_setcontent(User::File& file); +void nst_sample_load_samples(User::File& file, const char* sampgame); + +#endif diff -Nru nestopia-1.48/source/common/video.cpp nestopia-1.49/source/common/video.cpp --- nestopia-1.48/source/common/video.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/video.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,781 @@ +/* + * Nestopia UE + * + * Copyright (C) 2007-2008 R. Belmont + * Copyright (C) 2012-2018 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include + +#include "core/api/NstApiEmulator.hpp" +#include "core/api/NstApiInput.hpp" +#include "core/api/NstApiVideo.hpp" +#include "core/api/NstApiNsf.hpp" + +#include "nstcommon.h" +#include "video.h" +#include "config.h" +#include "font.h" +#include "png.h" + +using namespace Nes::Api; + +static int overscan_offset, overscan_height; + +static uint32_t videobuf[VIDBUF_MAXSIZE]; // Maximum possible internal size + +static Video::RenderState::Filter filter; +static Video::RenderState renderstate; + +static dimensions_t basesize, rendersize, screensize; +static osdtext_t osdtext; + +extern void *custompalette; + +extern nstpaths_t nstpaths; +extern Emulator emulator; + +// Shader sources +const GLchar* vshader_src = + "#version 150 core\n" + "in vec2 position;" + "in vec2 texcoord;" + "out vec2 outcoord;" + "void main() {" + " outcoord = texcoord;" + " gl_Position = vec4(position, 0.0, 1.0);" + "}"; + +const GLchar* fshader_src = + "#version 150 core\n" + "in vec2 outcoord;" + "out vec4 fragcolor;" + "uniform sampler2D nestex;" + "void main() {" + " fragcolor = texture(nestex, outcoord);" + "}"; + +GLuint vao; +GLuint vbo; +GLuint vshader; +GLuint fshader; +GLuint gl_shader_prog = 0; +GLuint gl_texture_id = 0; + +void nst_ogl_init() { + // Initialize OpenGL + + float vertices[] = { + -1.0f, -1.0f, // Vertex 1 (X, Y) + -1.0f, 1.0f, // Vertex 2 (X, Y) + 1.0f, -1.0f, // Vertex 3 (X, Y) + 1.0f, 1.0f, // Vertex 4 (X, Y) + 0.0, 1.0, // Texture 1 (X, Y) + 0.0, 0.0, // Texture 2 (X, Y) + 1.0, 1.0, // Texture 3 (X, Y) + 1.0, 0.0 // Texture 4 (X, Y) + }; + + GLint status; + + glGenVertexArrays(1, &vao); + glBindVertexArray(vao); + + glGenBuffers(1, &vbo); + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); + + vshader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(vshader, 1, &vshader_src, NULL); + glCompileShader(vshader); + + glGetShaderiv(vshader, GL_COMPILE_STATUS, &status); + if (status == GL_FALSE) { fprintf(stderr, "Failed to compile vertex shader\n"); } + + fshader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fshader, 1, &fshader_src, NULL); + glCompileShader(fshader); + + glGetShaderiv(fshader, GL_COMPILE_STATUS, &status); + if (status == GL_FALSE) { fprintf(stderr, "Failed to compile fragment shader\n"); } + + GLuint gl_shader_prog = glCreateProgram(); + glAttachShader(gl_shader_prog, vshader); + glAttachShader(gl_shader_prog, fshader); + + glLinkProgram(gl_shader_prog); + + glValidateProgram(gl_shader_prog); + glGetProgramiv(gl_shader_prog, GL_LINK_STATUS, &status); + if (status == GL_FALSE) { fprintf(stderr, "Failed to link shader program\n"); } + + glUseProgram(gl_shader_prog); + + GLint posAttrib = glGetAttribLocation(gl_shader_prog, "position"); + glEnableVertexAttribArray(posAttrib); + glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0); + + GLint texAttrib = glGetAttribLocation(gl_shader_prog, "texcoord"); + glEnableVertexAttribArray(texAttrib); + glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 0, (void*)(8 * sizeof(GLfloat))); + + glGenTextures(1, &gl_texture_id); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, gl_texture_id); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, conf.video_linear_filter ? GL_LINEAR : GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + + conf.video_fullscreen ? + glViewport(screensize.w / 2.0f - rendersize.w / 2.0f, 0, rendersize.w, rendersize.h) : + glViewport(0, 0, rendersize.w, rendersize.h); + + glUniform1i(glGetUniformLocation(gl_shader_prog, "nestex"), 0); +} + +void nst_ogl_deinit() { + // Deinitialize OpenGL + if (gl_texture_id) { glDeleteTextures(1, &gl_texture_id); } + if (gl_shader_prog) { glDeleteProgram(gl_shader_prog); } + if (vshader) { glDeleteShader(vshader); } + if (fshader) { glDeleteShader(fshader); } + if (vao) { glDeleteVertexArrays(1, &vao); } + if (vbo) { glDeleteBuffers(1, &vbo); } +} + +void nst_ogl_render() { + // Render the scene + glTexImage2D(GL_TEXTURE_2D, + 0, + GL_RGBA, + basesize.w, + overscan_height, + 0, + GL_BGRA, + GL_UNSIGNED_BYTE, + videobuf + overscan_offset); + + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); +} + +void nst_video_refresh() { + // Refresh the video settings + + nst_ogl_deinit(); + + nst_ogl_init(); +} + +void video_init() { + // Initialize video + + nst_ogl_deinit(); + + video_set_dimensions(); + video_set_filter(); + + nst_ogl_init(); + + if (nst_nsf()) { video_clear_buffer(); video_disp_nsf(); } +} + +void video_toggle_fullscreen() { + // Toggle between fullscreen and window mode + if (!nst_playing()) { return; } + conf.video_fullscreen ^= 1; +} + +void video_toggle_filter() { + conf.video_filter++; + if (conf.video_filter > 5) { conf.video_filter = 0; } + //video_init(); + //nst_video_refresh(); +} + +void video_toggle_filterupdate() { + // Clear the filter update flag + Video video(emulator); + video.ClearFilterUpdateFlag(); +} + +void video_toggle_scalefactor() { + // Toggle video scale factor + conf.video_scale_factor++; + if (conf.video_scale_factor > 8) { conf.video_scale_factor = 1; } + //video_init(); +} + +void video_set_filter() { + // Set the filter + Video video(emulator); + int scalefactor = conf.video_scale_factor; + if (conf.video_scale_factor > 4) { scalefactor = 4; } + if ((conf.video_scale_factor > 3) && (conf.video_filter == 5)) { scalefactor = 3; } + + switch(conf.video_filter) { + case 0: // None + filter = Video::RenderState::FILTER_NONE; + break; + + case 1: // NTSC + filter = Video::RenderState::FILTER_NTSC; + break; + + case 2: // xBR + switch (scalefactor) { + case 2: + filter = Video::RenderState::FILTER_2XBR; + break; + case 3: + filter = Video::RenderState::FILTER_3XBR; + break; + case 4: + filter = Video::RenderState::FILTER_4XBR; + break; + default: + filter = Video::RenderState::FILTER_NONE; + break; + } + break; + + case 3: // scale HQx + switch (scalefactor) { + case 2: + filter = Video::RenderState::FILTER_HQ2X; + break; + case 3: + filter = Video::RenderState::FILTER_HQ3X; + break; + case 4: + filter = Video::RenderState::FILTER_HQ4X; + break; + default: + filter = Video::RenderState::FILTER_NONE; + break; + } + break; + + case 4: // 2xSaI + filter = Video::RenderState::FILTER_2XSAI; + break; + + case 5: // scale x + switch (scalefactor) { + case 2: + filter = Video::RenderState::FILTER_SCALE2X; + break; + case 3: + filter = Video::RenderState::FILTER_SCALE3X; + break; + default: + filter = Video::RenderState::FILTER_NONE; + break; + } + break; + break; + } + + // Set the sprite limit: false = enable sprite limit, true = disable sprite limit + video.EnableUnlimSprites(conf.video_unlimited_sprites ? true : false); + + // Set Palette options + switch (conf.video_palette_mode) { + case 0: // YUV + video.GetPalette().SetMode(Video::Palette::MODE_YUV); + break; + + case 1: // RGB + video.GetPalette().SetMode(Video::Palette::MODE_RGB); + break; + + case 2: // Custom + video.GetPalette().SetMode(Video::Palette::MODE_CUSTOM); + video.GetPalette().SetCustom((const unsigned char (*)[3])custompalette, Video::Palette::EXT_PALETTE); + break; + + default: break; + } + + // Set YUV Decoder/Picture options + if (video.GetPalette().GetMode() == Video::Palette::MODE_YUV) { + switch (conf.video_decoder) { + case 0: // Consumer + video.SetDecoder(Video::DECODER_CONSUMER); + break; + + case 1: // Canonical + video.SetDecoder(Video::DECODER_CANONICAL); + break; + + case 2: // Alternative (Canonical with yellow boost) + video.SetDecoder(Video::DECODER_ALTERNATIVE); + break; + + default: break; + } + } + + video.SetBrightness(conf.video_brightness); + video.SetSaturation(conf.video_saturation); + video.SetContrast(conf.video_contrast); + video.SetHue(conf.video_hue); + + // Set NTSC options + if (conf.video_filter == 1) { + switch (conf.video_ntsc_mode) { + case 0: // Composite + video.SetSaturation(Video::DEFAULT_SATURATION_COMP); + video.SetSharpness(Video::DEFAULT_SHARPNESS_COMP); + video.SetColorResolution(Video::DEFAULT_COLOR_RESOLUTION_COMP); + video.SetColorBleed(Video::DEFAULT_COLOR_BLEED_COMP); + video.SetColorArtifacts(Video::DEFAULT_COLOR_ARTIFACTS_COMP); + video.SetColorFringing(Video::DEFAULT_COLOR_FRINGING_COMP); + break; + + case 1: // S-Video + video.SetSaturation(Video::DEFAULT_SATURATION_SVIDEO); + video.SetSharpness(Video::DEFAULT_SHARPNESS_SVIDEO); + video.SetColorResolution(Video::DEFAULT_COLOR_RESOLUTION_SVIDEO); + video.SetColorBleed(Video::DEFAULT_COLOR_BLEED_SVIDEO); + video.SetColorArtifacts(Video::DEFAULT_COLOR_ARTIFACTS_SVIDEO); + video.SetColorFringing(Video::DEFAULT_COLOR_FRINGING_SVIDEO); + break; + + case 2: // RGB + video.SetSaturation(Video::DEFAULT_SATURATION_RGB); + video.SetSharpness(Video::DEFAULT_SHARPNESS_RGB); + video.SetColorResolution(Video::DEFAULT_COLOR_RESOLUTION_RGB); + video.SetColorBleed(Video::DEFAULT_COLOR_BLEED_RGB); + video.SetColorArtifacts(Video::DEFAULT_COLOR_ARTIFACTS_RGB); + video.SetColorFringing(Video::DEFAULT_COLOR_FRINGING_RGB); + break; + + case 3: // Monochrome + video.SetSaturation(Video::DEFAULT_SATURATION_MONO); + video.SetSharpness(Video::DEFAULT_SHARPNESS_MONO); + video.SetColorResolution(Video::DEFAULT_COLOR_RESOLUTION_MONO); + video.SetColorBleed(Video::DEFAULT_COLOR_BLEED_MONO); + video.SetColorArtifacts(Video::DEFAULT_COLOR_ARTIFACTS_MONO); + video.SetColorFringing(Video::DEFAULT_COLOR_FRINGING_MONO); + break; + + case 4: // Custom + video.SetSaturation(conf.video_saturation); + video.SetSharpness(conf.video_ntsc_sharpness); + video.SetColorResolution(conf.video_ntsc_resolution); + video.SetColorBleed(conf.video_ntsc_bleed); + video.SetColorArtifacts(conf.video_ntsc_artifacts); + video.SetColorFringing(conf.video_ntsc_fringing); + break; + + default: break; + } + } + + // Set xBR options + if (conf.video_filter == 2) { + video.SetCornerRounding(conf.video_xbr_corner_rounding); + video.SetBlend(conf.video_xbr_pixel_blending); + } + + // Set up the render state parameters + renderstate.filter = filter; + renderstate.width = basesize.w; + renderstate.height = basesize.h; + renderstate.bits.count = 32; + + int e = 1; // Check Endianness + if ((int)*((unsigned char *)&e) == 1) { // Little Endian + renderstate.bits.mask.r = 0x00ff0000; + renderstate.bits.mask.g = 0x0000ff00; + renderstate.bits.mask.b = 0x000000ff; + } + else { // Big Endian + renderstate.bits.mask.r = 0x000000ff; + renderstate.bits.mask.g = 0xff000000; + renderstate.bits.mask.b = 0x00ff0000; + } + + if (NES_FAILED(video.SetRenderState(renderstate))) { + fprintf(stderr, "Nestopia core rejected render state\n"); + exit(1); + } +} + +dimensions_t nst_video_get_dimensions_render() { + // Return the dimensions of the rendered video + return rendersize; +} + +dimensions_t nst_video_get_dimensions_screen() { + // Return the dimensions of the screen + return screensize; +} + +void nst_video_set_dimensions_screen(dimensions_t scrsize) { + screensize = scrsize; +} + +void video_set_dimensions() { + // Set up the video dimensions + int scalefactor = conf.video_scale_factor; + if (conf.video_scale_factor > 4) { scalefactor = 4; } + if ((conf.video_scale_factor > 3) && (conf.video_filter == 5)) { scalefactor = 3; } + int wscalefactor = conf.video_scale_factor; + int tvwidth = nst_pal() ? PAL_TV_WIDTH : TV_WIDTH; + + switch(conf.video_filter) { + case 0: // None + basesize.w = Video::Output::WIDTH; + basesize.h = Video::Output::HEIGHT; + conf.video_tv_aspect == true ? rendersize.w = tvwidth * wscalefactor : rendersize.w = basesize.w * wscalefactor; + rendersize.h = basesize.h * wscalefactor; + overscan_offset = basesize.w * OVERSCAN_TOP; + overscan_height = basesize.h - OVERSCAN_TOP - OVERSCAN_BOTTOM; + break; + + case 1: // NTSC + basesize.w = Video::Output::NTSC_WIDTH; + rendersize.w = (basesize.w / 2) * wscalefactor; + basesize.h = Video::Output::HEIGHT; + rendersize.h = basesize.h * wscalefactor; + overscan_offset = basesize.w * OVERSCAN_TOP; + overscan_height = basesize.h - OVERSCAN_TOP - OVERSCAN_BOTTOM; + break; + + case 2: // xBR + case 3: // HqX + case 5: // ScaleX + basesize.w = Video::Output::WIDTH * scalefactor; + basesize.h = Video::Output::HEIGHT * scalefactor; + conf.video_tv_aspect == true ? rendersize.w = tvwidth * wscalefactor : rendersize.w = Video::Output::WIDTH * wscalefactor;; + rendersize.h = Video::Output::HEIGHT * wscalefactor; + overscan_offset = basesize.w * OVERSCAN_TOP * scalefactor; + overscan_height = basesize.h - (OVERSCAN_TOP + OVERSCAN_BOTTOM) * scalefactor; + break; + + case 4: // 2xSaI + basesize.w = Video::Output::WIDTH * 2; + basesize.h = Video::Output::HEIGHT * 2; + conf.video_tv_aspect == true ? rendersize.w = tvwidth * wscalefactor : rendersize.w = Video::Output::WIDTH * wscalefactor; + rendersize.h = Video::Output::HEIGHT * wscalefactor; + overscan_offset = basesize.w * OVERSCAN_TOP * 2; + overscan_height = basesize.h - (OVERSCAN_TOP + OVERSCAN_BOTTOM) * 2; + break; + } + + if (!conf.video_unmask_overscan) { + rendersize.h -= (OVERSCAN_TOP + OVERSCAN_BOTTOM) * scalefactor; + } + else { overscan_offset = 0; overscan_height = basesize.h; } + + // Calculate the aspect from the height because it's smaller + float aspect = (float)screensize.h / (float)rendersize.h; + + if (!conf.video_stretch_aspect && conf.video_fullscreen) { + rendersize.h *= aspect; + rendersize.w *= aspect; + } + else if (conf.video_fullscreen) { + rendersize.h = screensize.h; + rendersize.w = screensize.w; + } +} + +long video_lock_screen(void*& ptr) { + ptr = videobuf; + return basesize.w * 4; +} + +void video_unlock_screen(void*) { + + int xscale = renderstate.width / Video::Output::WIDTH;; + int yscale = renderstate.height / Video::Output::HEIGHT; + + if (osdtext.drawtext) { + nst_video_text_draw(osdtext.textbuf, osdtext.xpos * xscale, osdtext.ypos * yscale, osdtext.bg); + osdtext.drawtext--; + } + + if (osdtext.drawtime) { + nst_video_text_draw(osdtext.timebuf, 208 * xscale, 218 * yscale, false); + } +} + +void video_screenshot_flip(unsigned char *pixels, int width, int height, int bytes) { + // Flip the pixels + int rowsize = width * bytes; + unsigned char *row = (unsigned char*)malloc(rowsize); + unsigned char *low = pixels; + unsigned char *high = &pixels[(height - 1) * rowsize]; + + for (; low < high; low += rowsize, high -= rowsize) { + memcpy(row, low, rowsize); + memcpy(low, high, rowsize); + memcpy(high, row, rowsize); + } + free(row); +} + +void video_screenshot(const char* filename) { + // Take a screenshot in .png format + unsigned char *pixels; + pixels = (unsigned char*)malloc(sizeof(unsigned char) * rendersize.w * rendersize.h * 4); + + // Read the pixels and flip them vertically + glReadPixels(0, 0, rendersize.w, rendersize.h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + video_screenshot_flip(pixels, rendersize.w, rendersize.h, 4); + + if (filename == NULL) { + // Set the filename + char sshotpath[512]; + snprintf(sshotpath, sizeof(sshotpath), "%sscreenshots/%s-%ld-%d.png", nstpaths.nstdir, nstpaths.gamename, time(NULL), rand() % 899 + 100); + + // Save the file + lodepng_encode32_file(sshotpath, (const unsigned char*)pixels, rendersize.w, rendersize.h); + fprintf(stderr, "Screenshot: %s\n", sshotpath); + } + else { + lodepng_encode32_file(filename, (const unsigned char*)pixels, rendersize.w, rendersize.h); + } + + free(pixels); +} + +void video_clear_buffer() { + // Write black to the video buffer + memset(videobuf, 0x00000000, VIDBUF_MAXSIZE); +} + +void video_disp_nsf() { + // Display NSF text + Nsf nsf(emulator); + + int xscale = renderstate.width / Video::Output::WIDTH;; + int yscale = renderstate.height / Video::Output::HEIGHT;; + + nst_video_text_draw(nsf.GetName(), 4 * xscale, 16 * yscale, false); + nst_video_text_draw(nsf.GetArtist(), 4 * xscale, 28 * yscale, false); + nst_video_text_draw(nsf.GetCopyright(), 4 * xscale, 40 * yscale, false); + + char currentsong[10]; + snprintf(currentsong, sizeof(currentsong), "%d / %d", nsf.GetCurrentSong() +1, nsf.GetNumSongs()); + nst_video_text_draw(currentsong, 4 * xscale, 52 * yscale, false); + + nst_ogl_render(); +} + +void nst_video_disp_inputconf(int type, int pnum, int bnum) { + + int xscale = renderstate.width / Video::Output::WIDTH;; + int yscale = renderstate.height / Video::Output::HEIGHT;; + + char textbuf[32]; + char buttontext[8]; + + if (type == 0) { snprintf(textbuf, sizeof(textbuf), "Player %d Keyboard Configuration", pnum + 1); } + else { snprintf(textbuf, sizeof(textbuf), "Player %d Joystick Configuration", pnum + 1); } + + switch (bnum) { + case 0: snprintf(buttontext, sizeof(buttontext), "Up"); break; + case 1: snprintf(buttontext, sizeof(buttontext), "Down"); break; + case 2: snprintf(buttontext, sizeof(buttontext), "Left"); break; + case 3: snprintf(buttontext, sizeof(buttontext), "Right"); break; + case 4: snprintf(buttontext, sizeof(buttontext), "Select"); break; + case 5: snprintf(buttontext, sizeof(buttontext), "Start"); break; + case 6: snprintf(buttontext, sizeof(buttontext), "A"); break; + case 7: snprintf(buttontext, sizeof(buttontext), "B"); break; + case 8: snprintf(buttontext, sizeof(buttontext), "Turbo A"); break; + case 9: snprintf(buttontext, sizeof(buttontext), "Turbo B"); break; + } + + video_clear_buffer(); + + nst_video_text_draw(textbuf, 4 * xscale, 64 * yscale, false); + nst_video_text_draw(buttontext, 112 * xscale, 128 * yscale, false); + + nst_ogl_render(); +} + +void nst_video_print(const char *text, int xpos, int ypos, int seconds, bool bg) { + snprintf(osdtext.textbuf, sizeof(osdtext.textbuf), "%s", text); + osdtext.xpos = xpos; + osdtext.ypos = ypos; + osdtext.drawtext = seconds * nst_pal() ? 50 : 60; + osdtext.bg = bg; +} + +void nst_video_print_time(const char *timebuf, bool drawtime) { + snprintf(osdtext.timebuf, sizeof(osdtext.timebuf), "%s", timebuf); + osdtext.drawtime = drawtime; +} + +void nst_video_text_draw(const char *text, int xpos, int ypos, bool bg) { + // Draw text on screen + uint32_t w = 0xc0c0c0c0; // "White", actually Grey + uint32_t b = 0x00000000; // Black + uint32_t g = 0x00358570; // Nestopia UE Green + uint32_t d = 0x00255f65; // Nestopia UE Dark Green + + int numchars = strlen(text); + + int letterypos; + int letterxpos; + int letternum = 0; + + if (bg) { // Draw background borders + for (int i = 0; i < numchars * 8; i++) { // Rows above and below + videobuf[(xpos + i) + ((ypos - 1) * renderstate.width)] = g; + videobuf[(xpos + i) + ((ypos + 8) * renderstate.width)] = g; + } + for (int i = 0; i < 8; i++) { // Columns on both sides + videobuf[(xpos - 1) + ((ypos + i) * renderstate.width)] = g; + videobuf[(xpos + (numchars * 8)) + ((ypos + i) * renderstate.width)] = g; + } + } + + for (int tpos = 0; tpos < (8 * numchars); tpos+=8) { + nst_video_text_match(text, &letterxpos, &letterypos, letternum); + for (int row = 0; row < 8; row++) { // Draw Rows + for (int col = 0; col < 8; col++) { // Draw Columns + switch (nesfont[row + letterypos][col + letterxpos]) { + case '.': + videobuf[xpos + ((ypos + row) * renderstate.width) + (col + tpos)] = w; + break; + + case '+': + videobuf[xpos + ((ypos + row) * renderstate.width) + (col + tpos)] = g; + break; + + default: + if (bg) { videobuf[xpos + ((ypos + row) * renderstate.width) + (col + tpos)] = d; } + break; + } + } + } + letternum++; + } +} + +void nst_video_text_match(const char *text, int *xpos, int *ypos, int strpos) { + // Match letters to draw on screen + switch (text[strpos]) { + case ' ': *xpos = 0; *ypos = 0; break; + case '!': *xpos = 8; *ypos = 0; break; + case '"': *xpos = 16; *ypos = 0; break; + case '#': *xpos = 24; *ypos = 0; break; + case '$': *xpos = 32; *ypos = 0; break; + case '%': *xpos = 40; *ypos = 0; break; + case '&': *xpos = 48; *ypos = 0; break; + case '\'': *xpos = 56; *ypos = 0; break; + case '(': *xpos = 64; *ypos = 0; break; + case ')': *xpos = 72; *ypos = 0; break; + case '*': *xpos = 80; *ypos = 0; break; + case '+': *xpos = 88; *ypos = 0; break; + case ',': *xpos = 96; *ypos = 0; break; + case '-': *xpos = 104; *ypos = 0; break; + case '.': *xpos = 112; *ypos = 0; break; + case '/': *xpos = 120; *ypos = 0; break; + case '0': *xpos = 0; *ypos = 8; break; + case '1': *xpos = 8; *ypos = 8; break; + case '2': *xpos = 16; *ypos = 8; break; + case '3': *xpos = 24; *ypos = 8; break; + case '4': *xpos = 32; *ypos = 8; break; + case '5': *xpos = 40; *ypos = 8; break; + case '6': *xpos = 48; *ypos = 8; break; + case '7': *xpos = 56; *ypos = 8; break; + case '8': *xpos = 64; *ypos = 8; break; + case '9': *xpos = 72; *ypos = 8; break; + case ':': *xpos = 80; *ypos = 8; break; + case ';': *xpos = 88; *ypos = 8; break; + case '<': *xpos = 96; *ypos = 8; break; + case '=': *xpos = 104; *ypos = 8; break; + case '>': *xpos = 112; *ypos = 8; break; + case '?': *xpos = 120; *ypos = 8; break; + case '@': *xpos = 0; *ypos = 16; break; + case 'A': *xpos = 8; *ypos = 16; break; + case 'B': *xpos = 16; *ypos = 16; break; + case 'C': *xpos = 24; *ypos = 16; break; + case 'D': *xpos = 32; *ypos = 16; break; + case 'E': *xpos = 40; *ypos = 16; break; + case 'F': *xpos = 48; *ypos = 16; break; + case 'G': *xpos = 56; *ypos = 16; break; + case 'H': *xpos = 64; *ypos = 16; break; + case 'I': *xpos = 72; *ypos = 16; break; + case 'J': *xpos = 80; *ypos = 16; break; + case 'K': *xpos = 88; *ypos = 16; break; + case 'L': *xpos = 96; *ypos = 16; break; + case 'M': *xpos = 104; *ypos = 16; break; + case 'N': *xpos = 112; *ypos = 16; break; + case 'O': *xpos = 120; *ypos = 16; break; + case 'P': *xpos = 0; *ypos = 24; break; + case 'Q': *xpos = 8; *ypos = 24; break; + case 'R': *xpos = 16; *ypos = 24; break; + case 'S': *xpos = 24; *ypos = 24; break; + case 'T': *xpos = 32; *ypos = 24; break; + case 'U': *xpos = 40; *ypos = 24; break; + case 'V': *xpos = 48; *ypos = 24; break; + case 'W': *xpos = 56; *ypos = 24; break; + case 'X': *xpos = 64; *ypos = 24; break; + case 'Y': *xpos = 72; *ypos = 24; break; + case 'Z': *xpos = 80; *ypos = 24; break; + case '[': *xpos = 88; *ypos = 24; break; + case '\\': *xpos = 96; *ypos = 24; break; + case ']': *xpos = 104; *ypos = 24; break; + case '^': *xpos = 112; *ypos = 24; break; + case '_': *xpos = 120; *ypos = 24; break; + case '`': *xpos = 0; *ypos = 32; break; + case 'a': *xpos = 8; *ypos = 32; break; + case 'b': *xpos = 16; *ypos = 32; break; + case 'c': *xpos = 24; *ypos = 32; break; + case 'd': *xpos = 32; *ypos = 32; break; + case 'e': *xpos = 40; *ypos = 32; break; + case 'f': *xpos = 48; *ypos = 32; break; + case 'g': *xpos = 56; *ypos = 32; break; + case 'h': *xpos = 64; *ypos = 32; break; + case 'i': *xpos = 72; *ypos = 32; break; + case 'j': *xpos = 80; *ypos = 32; break; + case 'k': *xpos = 88; *ypos = 32; break; + case 'l': *xpos = 96; *ypos = 32; break; + case 'm': *xpos = 104; *ypos = 32; break; + case 'n': *xpos = 112; *ypos = 32; break; + case 'o': *xpos = 120; *ypos = 32; break; + case 'p': *xpos = 0; *ypos = 40; break; + case 'q': *xpos = 8; *ypos = 40; break; + case 'r': *xpos = 16; *ypos = 40; break; + case 's': *xpos = 24; *ypos = 40; break; + case 't': *xpos = 32; *ypos = 40; break; + case 'u': *xpos = 40; *ypos = 40; break; + case 'v': *xpos = 48; *ypos = 40; break; + case 'w': *xpos = 56; *ypos = 40; break; + case 'x': *xpos = 64; *ypos = 40; break; + case 'y': *xpos = 72; *ypos = 40; break; + case 'z': *xpos = 80; *ypos = 40; break; + case '{': *xpos = 88; *ypos = 40; break; + case '|': *xpos = 96; *ypos = 40; break; + case '}': *xpos = 104; *ypos = 40; break; + case '~': *xpos = 112; *ypos = 40; break; + //case ' ': *xpos = 120; *ypos = 40; break; // Triangle + default: *xpos = 0; *ypos = 0; break; + } +} diff -Nru nestopia-1.48/source/common/video.h nestopia-1.49/source/common/video.h --- nestopia-1.48/source/common/video.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/common/video.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,60 @@ +#ifndef _VIDEO_H_ +#define _VIDEO_H_ + +#define TV_WIDTH 292 +#define PAL_TV_WIDTH 320 +#define OVERSCAN_LEFT 0 +#define OVERSCAN_RIGHT 0 +#define OVERSCAN_BOTTOM 8 +#define OVERSCAN_TOP 8 + +#define VIDBUF_MAXSIZE 31457280 + +#include +#ifdef _APPLE +#include +#endif + +typedef struct { + int w; + int h; +} dimensions_t; + +typedef struct { + int xpos; + int ypos; + char textbuf[32]; + char timebuf[6]; + int drawtext; + bool drawtime; + bool bg; +} osdtext_t; + +void nst_ogl_init(); +void nst_ogl_deinit(); +void nst_ogl_render(); + +void video_init(); +void video_toggle_fullscreen(); +void video_toggle_filter(); +void video_toggle_filterupdate(); +void video_toggle_scalefactor(); +void video_set_filter(); + +dimensions_t nst_video_get_dimensions_render(); +dimensions_t nst_video_get_dimensions_screen(); +void nst_video_set_dimensions_screen(dimensions_t scrsize); +void video_set_dimensions(); + +long video_lock_screen(void*& ptr); +void video_unlock_screen(void*); +void video_screenshot(const char* filename); +void video_clear_buffer(); +void video_disp_nsf(); +void nst_video_disp_inputconf(int type, int pnum, int bnum); +void nst_video_print(const char *text, int xpos, int ypos, int seconds, bool bg); +void nst_video_print_time(const char *timebuf, bool drawtime); +void nst_video_text_draw(const char *text, int xpos, int ypos, bool bg); +void nst_video_text_match(const char *text, int *xpos, int *ypos, int strpos); + +#endif diff -Nru nestopia-1.48/source/core/api/NstApiMachine.cpp nestopia-1.49/source/core/api/NstApiMachine.cpp --- nestopia-1.48/source/core/api/NstApiMachine.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/api/NstApiMachine.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -189,6 +189,7 @@ Result Machine::SetRamPowerState(const uint state) throw() { emulator.SetRamPowerState(state); + return RESULT_OK; } Machine::Mode Machine::GetMode() const throw() diff -Nru nestopia-1.48/source/core/api/NstApiVideo.cpp nestopia-1.49/source/core/api/NstApiVideo.cpp --- nestopia-1.48/source/core/api/NstApiVideo.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/api/NstApiVideo.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -58,6 +58,20 @@ return RESULT_NOP; } + Result Video::EnableOverclocking(bool state) throw() + { + if (emulator.tracker.IsLocked( true )) + return RESULT_ERR_NOT_READY; + + if (emulator.ppu.GetOverclockState() != state) + { + emulator.ppu.SetOverclockState( state ); + return RESULT_OK; + } + + return RESULT_NOP; + } + bool Video::AreUnlimSpritesEnabled() const throw() { return !emulator.ppu.HasSpriteLimit(); diff -Nru nestopia-1.48/source/core/api/NstApiVideo.hpp nestopia-1.49/source/core/api/NstApiVideo.hpp --- nestopia-1.48/source/core/api/NstApiVideo.hpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/api/NstApiVideo.hpp 2018-06-24 23:26:58.000000000 +0000 @@ -223,6 +223,11 @@ * @return result code */ Result EnableUnlimSprites(bool state) throw(); + + /** + * Adds extra scanlines to fix lag + */ + Result EnableOverclocking(bool state) throw(); /** * Checks if the PPU sprite software extension is enabled. diff -Nru nestopia-1.48/source/core/board/NstBoardAcclaimMcAcc.hpp nestopia-1.49/source/core/board/NstBoardAcclaimMcAcc.hpp --- nestopia-1.48/source/core/board/NstBoardAcclaimMcAcc.hpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/board/NstBoardAcclaimMcAcc.hpp 2018-06-24 23:26:58.000000000 +0000 @@ -40,7 +40,7 @@ { namespace Acclaim { - class NST_NO_VTABLE McAcc : public Board + class McAcc : public Board { public: diff -Nru nestopia-1.48/source/core/board/NstBoard.cpp nestopia-1.49/source/core/board/NstBoard.cpp --- nestopia-1.48/source/core/board/NstBoard.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/board/NstBoard.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -73,6 +73,7 @@ #include "NstBoardKasing.hpp" #include "NstBoardKay.hpp" #include "NstBoardKonami.hpp" +#include "NstBoardMagicKidGoogoo.hpp" #include "NstBoardMagicSeries.hpp" #include "NstBoardNanjing.hpp" #include "NstBoardNihon.hpp" @@ -1773,7 +1774,7 @@ case 21: - if (submapper == 9) + if (submapper == 1) { Chips::Type& chip = chips.Add(L"Konami VRC IV"); @@ -1785,7 +1786,7 @@ } case 25: - if (submapper == 15) + if (submapper == 2) { // The correct board is VRC2 but the functionality is implemented in the VRC4 code currently Chips::Type& chip = chips.Add(L"Konami VRC IV"); chip.Pin(3) = L"PRG A0"; @@ -1827,7 +1828,7 @@ case 23: - if (submapper == 10) + if (submapper == 2) { Chips::Type& chip = chips.Add(L"Konami VRC IV"); @@ -1837,7 +1838,7 @@ name = "KONAMI VRC4"; id = Type::KONAMI_VRC4_0; } - else if (submapper == 15) + else if (submapper == 3) { name = "KONAMI VRC2"; id = Type::KONAMI_VRC2; @@ -2880,6 +2881,12 @@ id = Type::TXC_TW; break; + case 190: + + name = "MAGICKIDGOOGOO"; + id = Type::MAGICKIDGOOGOO; + break; + case 191: name = "WAIXING (b)"; @@ -3579,6 +3586,7 @@ case Type::KONAMI_VRC7_0 : case Type::KONAMI_VRC7_1 : return new Konami::Vrc7(c); case Type::KONAMI_VSSYSTEM : return new Konami::VsSystem(c); + case Type::MAGICKIDGOOGOO : return new MagicKidGoogoo(c); case Type::MAGICSERIES_MAGICDRAGON : return new MagicSeries::MagicDragon(c); case Type::NAMCOT_3425 : return new Namcot::N3425(c); case Type::NAMCOT_3433 : return new Namcot::N3433(c); diff -Nru nestopia-1.48/source/core/board/NstBoard.hpp nestopia-1.49/source/core/board/NstBoard.hpp --- nestopia-1.48/source/core/board/NstBoard.hpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/board/NstBoard.hpp 2018-06-24 23:26:58.000000000 +0000 @@ -433,6 +433,8 @@ KONAMI_VRC7_0 = MakeId< 85, 512, 256, 0, 0, CRM_0, NMT_V, 0 >::ID, KONAMI_VRC7_1 = MakeId< 85, 512, 256, 8, 0, CRM_0, NMT_V, 0 >::ID, KONAMI_VSSYSTEM = MakeId< 151, 64, 64, 0, 0, CRM_0, NMT_4, 0 >::ID, + //Magic Kid Googoo + MAGICKIDGOOGOO = MakeId< 190, 256, 128, 8, 0, CRM_0, NMT_V, 0 >::ID, // Magic Series MAGICSERIES_MAGICDRAGON = MakeId< 107, 128, 64, 0, 0, CRM_0, NMT_X, 0 >::ID, // Namcot diff -Nru nestopia-1.48/source/core/board/NstBoardMagicKidGoogoo.cpp nestopia-1.49/source/core/board/NstBoardMagicKidGoogoo.cpp --- nestopia-1.48/source/core/board/NstBoardMagicKidGoogoo.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/core/board/NstBoardMagicKidGoogoo.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,65 @@ +//////////////////////////////////////////////////////////////////////////////////////// +// +// Nestopia - NES/Famicom emulator written in C++ +// +// Copyright (C) 2003-2008 Martin Freij +// +// This file is part of Nestopia. +// +// Nestopia is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// Nestopia is distributed in the hope that 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 Nestopia; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +//////////////////////////////////////////////////////////////////////////////////////// + +#include "NstBoard.hpp" +#include "NstBoardMagicKidGoogoo.hpp" + +namespace Nes +{ + namespace Core + { + namespace Boards + { + #ifdef NST_MSVC_OPTIMIZE + #pragma optimize("s", on) + #endif + + void MagicKidGoogoo::SubReset(const bool hard) + { + Map( 0x8000U, 0x9FFFU, &MagicKidGoogoo::Poke_8000 ); + Map( 0xC000U, 0xDFFFU, &MagicKidGoogoo::Poke_8000 ); + + for (uint i=0x0000; i < 0x2000; i += 0x04) + { + Map( 0xA000U + i, CHR_SWAP_2K_0 ); + Map( 0xA001U + i, CHR_SWAP_2K_1 ); + Map( 0xA002U + i, CHR_SWAP_2K_2 ); + Map( 0xA003U + i, CHR_SWAP_2K_3 ); + } + + if (hard) + prg.SwapBank(0); + } + + #ifdef NST_MSVC_OPTIMIZE + #pragma optimize("", on) + #endif + + NES_POKE_AD(MagicKidGoogoo, 8000) + { + prg.SwapBank( (address >> 11) | (data & 0x07) ); + } + } + } +} diff -Nru nestopia-1.48/source/core/board/NstBoardMagicKidGoogoo.hpp nestopia-1.49/source/core/board/NstBoardMagicKidGoogoo.hpp --- nestopia-1.48/source/core/board/NstBoardMagicKidGoogoo.hpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/core/board/NstBoardMagicKidGoogoo.hpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,55 @@ +//////////////////////////////////////////////////////////////////////////////////////// +// +// Nestopia - NES/Famicom emulator written in C++ +// +// Copyright (C) 2003-2008 Martin Freij +// +// This file is part of Nestopia. +// +// Nestopia is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// Nestopia is distributed in the hope that 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 Nestopia; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +//////////////////////////////////////////////////////////////////////////////////////// + +#ifndef NST_BOARD_MAGICKIDGOOGOO_H +#define NST_BOARD_MAGICKIDGOOGOO_H + +#ifdef NST_PRAGMA_ONCE +#pragma once +#endif + +namespace Nes +{ + namespace Core + { + namespace Boards + { + class MagicKidGoogoo : public Board + { + public: + + explicit MagicKidGoogoo(const Context& c) + : Board(c) {} + + private: + + void SubReset(bool); + + NES_DECL_POKE( 8000 ); + }; + } + } +} + +#endif diff -Nru nestopia-1.48/source/core/NstApu.cpp nestopia-1.49/source/core/NstApu.cpp --- nestopia-1.48/source/core/NstApu.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstApu.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -272,11 +272,7 @@ NES_DO_POKE(4015,0x4015,0x09); } - if (cpu.GetModel() == CPU_DENDY) - { - ctrl = STATUS_NO_FRAME_IRQ; - } - else if (hard) + if (hard) { ctrl = STATUS_FRAME_IRQ_ENABLE; } @@ -289,10 +285,7 @@ } else { - if (cpu.GetModel() == CPU_DENDY) - ctrl = STATUS_NO_FRAME_IRQ; - else - ctrl = STATUS_FRAME_IRQ_ENABLE; + ctrl = STATUS_FRAME_IRQ_ENABLE; } } @@ -1968,6 +1961,7 @@ dma.buffered = false; dma.address = 0xC000; dma.buffer = 0x00; + overclockingIsSafe = true; } Cycle Apu::Dmc::GetResetFrequency(CpuModel model) @@ -2181,16 +2175,31 @@ { out.dac = data & 0x7F; curSample = out.dac * outputVolume; + + if (out.dac != 0) + { + overclockingIsSafe = false; + } } NST_SINGLE_CALL void Apu::Dmc::WriteReg2(const uint data) { regs.address = 0xC000 | (data << 6); + + if (regs.address != 0) + { + overclockingIsSafe = true; + } } NST_SINGLE_CALL void Apu::Dmc::WriteReg3(const uint data) { regs.lengthCounter = (data << 4) + 1; + + if (regs.lengthCounter != 0) + { + overclockingIsSafe = true; + } } NST_SINGLE_CALL bool Apu::Dmc::ClockDAC() diff -Nru nestopia-1.48/source/core/NstApu.hpp nestopia-1.49/source/core/NstApu.hpp --- nestopia-1.48/source/core/NstApu.hpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstApu.hpp 2018-06-24 23:26:58.000000000 +0000 @@ -527,6 +527,8 @@ Dmc(); + bool overclockingIsSafe; + void Reset(CpuModel); void UpdateSettings(uint); void LoadState(State::Loader&,const Cpu&,CpuModel,Cycle&); @@ -624,6 +626,16 @@ public: + void SetOverclockSafety(bool safe) + { + dmc.overclockingIsSafe = safe; + } + + bool GetOverclockSafety() + { + return dmc.overclockingIsSafe; + } + dword GetSampleRate() const { return settings.rate; diff -Nru nestopia-1.48/source/core/NstCpu.cpp nestopia-1.49/source/core/NstCpu.cpp --- nestopia-1.48/source/core/NstCpu.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstCpu.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -204,6 +204,8 @@ ticks = 0; logged = 0; + cpuOverclocking = false; + pc = RESET_VECTOR; cycles.count = 0; @@ -1899,6 +1901,18 @@ if (interrupt.irqClock != CYCLE_MAX) interrupt.irqClock = (interrupt.irqClock > cycles.frame ? interrupt.irqClock - cycles.frame : 0); + + if (cpuOverclocking) + { + uint startCycle = cycles.count; + uint lastCycle = cycles.count + extraCycles; + do + { + ExecuteOp(); + } + while (cycles.count < extraCycles); + cycles.count = startCycle; + } } void Cpu::Clock() diff -Nru nestopia-1.48/source/core/NstCpu.hpp nestopia-1.49/source/core/NstCpu.hpp --- nestopia-1.48/source/core/NstCpu.hpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstCpu.hpp 2018-06-24 23:26:58.000000000 +0000 @@ -487,6 +487,8 @@ Ram ram; Apu apu; IoMap map; + bool cpuOverclocking; + uint extraCycles; static dword logged; static void (Cpu::*const opcodes[0x100])(); @@ -499,6 +501,12 @@ return apu; } + void SetOverclocking(bool overclocking,uint newCycles) + { + cpuOverclocking = overclocking; + extraCycles = newCycles; + } + Cycle Update(uint readAddress=0) { apu.ClockDMA( readAddress ); diff -Nru nestopia-1.48/source/core/NstFds.cpp nestopia-1.49/source/core/NstFds.cpp --- nestopia-1.48/source/core/NstFds.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstFds.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -162,12 +162,13 @@ Fds::Fds(Context& context) : - Image (DISK), - disks (context.stream), - adapter (context.cpu,disks.sides), - cpu (context.cpu), - ppu (context.ppu), - sound (context.apu) + Image (DISK), + disks (context.stream), + adapter (context.cpu,disks.sides), + cpu (context.cpu), + ppu (context.ppu), + sound (context.apu), + favoredSystem (context.favoredSystem) { if (!bios.Available()) throw RESULT_ERR_MISSING_BIOS; @@ -270,6 +271,16 @@ return SYSTEM_FAMICOM; } + else if ((region == REGION_PAL) && (favoredSystem == FAVORED_DENDY)) + { + if (cpu) + *cpu = CPU_DENDY; + + if (ppu) + *ppu = PPU_DENDY; + + return SYSTEM_DENDY; + } else { return Image::GetDesiredSystem( region, cpu, ppu ); diff -Nru nestopia-1.48/source/core/NstFds.hpp nestopia-1.49/source/core/NstFds.hpp --- nestopia-1.48/source/core/NstFds.hpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstFds.hpp 2018-06-24 23:26:58.000000000 +0000 @@ -473,6 +473,7 @@ Ppu& ppu; Ram ram; Sound sound; + FavoredSystem favoredSystem; mutable Checksum checksum; class Bios; diff -Nru nestopia-1.48/source/core/NstMachine.cpp nestopia-1.49/source/core/NstMachine.cpp --- nestopia-1.48/source/core/NstMachine.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstMachine.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -278,8 +278,13 @@ bool acknowledged = true; - if (image && ((image->GetDesiredSystem((state & Api::Machine::NTSC) ? REGION_NTSC : REGION_PAL))) == (SYSTEM_FAMICOM || SYSTEM_DENDY)) - acknowledged = false; + if (image) + { + System desiredSystem = image->GetDesiredSystem((state & Api::Machine::NTSC) ? REGION_NTSC : REGION_PAL); + + if (desiredSystem == SYSTEM_FAMICOM || desiredSystem == SYSTEM_DENDY) + acknowledged = false; + } ppu.Reset( hard, acknowledged ); diff -Nru nestopia-1.48/source/core/NstNsf.cpp nestopia-1.49/source/core/NstNsf.cpp --- nestopia-1.48/source/core/NstNsf.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstNsf.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -229,6 +229,7 @@ cpu (context.cpu), apu (context.apu), chips (NULL), + favoredSystem (context.favoredSystem), tuneMode (Api::Nsf::TUNE_MODE_NTSC) { if (context.patch && context.patchResult) @@ -381,6 +382,24 @@ return tuneMode == Api::Nsf::TUNE_MODE_PAL ? REGION_PAL : REGION_NTSC; } + System Nsf::GetDesiredSystem(Region region,CpuModel* cpu,PpuModel* ppu) const + { + if ((region == REGION_PAL) && (favoredSystem == FAVORED_DENDY)) + { + if (cpu) + *cpu = CPU_DENDY; + + if (ppu) + *ppu = PPU_DENDY; + + return SYSTEM_DENDY; + } + else + { + return Image::GetDesiredSystem( region, cpu, ppu ); + } + } + uint Nsf::GetChips() const { uint types = 0; @@ -536,7 +555,7 @@ routine.reset = Routine::RESET; routine.nmi = Routine::NMI; - cpu.SetFrameCycles( cpu.GetModel() == CPU_RP2A07 ? PPU_RP2C07_HVSYNC : PPU_RP2C02_HVSYNC ); + cpu.SetFrameCycles( cpu.GetModel() == CPU_RP2A03 ? PPU_RP2C02_HVSYNC : cpu.GetModel() == CPU_RP2A07 ? PPU_RP2C07_HVSYNC : PPU_DENDY_HVSYNC ); } bool Nsf::PowerOff() diff -Nru nestopia-1.48/source/core/NstNsf.hpp nestopia-1.49/source/core/NstNsf.hpp --- nestopia-1.48/source/core/NstNsf.hpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstNsf.hpp 2018-06-24 23:26:58.000000000 +0000 @@ -56,6 +56,7 @@ bool PowerOff(); void InitSong(); Region GetDesiredRegion() const; + System GetDesiredSystem(Region,CpuModel*,PpuModel*) const; inline uint FetchLast(uint) const; @@ -273,17 +274,18 @@ {} }; - Prg prg; - Routine routine; - Cpu& cpu; - Apu& apu; - Chips* chips; - Songs songs; - Addressing addressing; - Speed speed; - uint tuneMode; - byte banks[8]; - byte wrk[SIZE_8K]; + Prg prg; + Routine routine; + Cpu& cpu; + Apu& apu; + Chips* chips; + FavoredSystem favoredSystem; + Songs songs; + Addressing addressing; + Speed speed; + uint tuneMode; + byte banks[8]; + byte wrk[SIZE_8K]; public: diff -Nru nestopia-1.48/source/core/NstPpu.cpp nestopia-1.49/source/core/NstPpu.cpp --- nestopia-1.48/source/core/NstPpu.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstPpu.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -108,6 +108,7 @@ yuvMap (NULL) { cycles.one = PPU_RP2C02_CC; + overclocked = false; PowerOff(); } @@ -137,7 +138,7 @@ cpu.Map( i+7 ).Set( this, &Ppu::Peek_2007, &Ppu::Poke_2007 ); } - if (model == (PPU_RC2C05_01 || PPU_RC2C05_04)) + if (model == PPU_RC2C05_01 || model == PPU_RC2C05_04) { for (uint i=0x2002; i < 0x4000; i += 0x8) cpu.Map( i ).Set( &Ppu::Peek_2002_RC2C05_01_04 ); @@ -555,6 +556,38 @@ break; } + if (overclocked) + { + Apu& audioSafeOverclock = cpu.GetApu(); + if (audioSafeOverclock.GetOverclockSafety()) + { + switch (model) + { + case PPU_RP2C02: + default: + + cpu.SetOverclocking(true,PPU_RP2C02_HSYNC * PPU_RP2C02_VACTIVE); + break; + + case PPU_RP2C07: + + cpu.SetOverclocking(true,PPU_RP2C07_HSYNC * PPU_RP2C07_VACTIVE); + break; + + case PPU_DENDY: + + cpu.SetOverclocking(true,PPU_DENDY_HSYNC * PPU_DENDY_VACTIVE); + break; + } + } + else + { + cpu.SetOverclocking(false,0); + } + + audioSafeOverclock.SetOverclockSafety(true);//overclocking is only safe if direct pcm audio has not been written for one frame + } + cpu.SetFrameCycles( frame ); } diff -Nru nestopia-1.48/source/core/NstPpu.hpp nestopia-1.49/source/core/NstPpu.hpp --- nestopia-1.48/source/core/NstPpu.hpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/core/NstPpu.hpp 2018-06-24 23:26:58.000000000 +0000 @@ -416,6 +416,7 @@ int scanline; int scanline_sleep; int ssleep; + bool overclocked; PpuModel model; Hook hActiveHook; @@ -542,6 +543,16 @@ { return oam.spriteLimit; } + + bool GetOverclockState() const + { + return overclocked; + } + + void SetOverclockState(bool overclock2x) + { + overclocked = overclock2x; + } }; } } diff -Nru nestopia-1.48/source/gtkui/gtkui_archive.cpp nestopia-1.49/source/gtkui/gtkui_archive.cpp --- nestopia-1.48/source/gtkui/gtkui_archive.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_archive.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,182 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2016 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include + +#include "nstcommon.h" +#include "config.h" + +#include "gtkui.h" +#include "gtkui_archive.h" + +static bool windowopen, cancelled; + +static GtkWidget *archivewindow; + +bool gtkui_archive_select(const char *filename, char *reqfile, size_t reqsize) { + // Select a filename to pull out of the archive + struct archive *a; + struct archive_entry *entry; + int r, numarchives = 0; + + cancelled = false; + + a = archive_read_new(); + archive_read_support_filter_all(a); + archive_read_support_format_all(a); + r = archive_read_open_filename(a, filename, 10240); + + // Test if it's actually an archive + if (r != ARCHIVE_OK) { + r = archive_read_free(a); + return false; + } + // If it is an archive, handle it + else { + // Set up the archive window + GtkTreeIter iter; + GtkTreeModel *model; + GtkTreeSelection *selection; + + archivewindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(archivewindow), "Choose File from Archive"); + gtk_window_set_modal(GTK_WINDOW(archivewindow), TRUE); + + GtkWidget *archivebox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + gtk_container_add(GTK_CONTAINER(archivewindow), archivebox); + gtk_widget_show(archivebox); + + GtkWidget *scrolledwindow = gtk_scrolled_window_new(NULL, NULL); + gtk_box_pack_start(GTK_BOX(archivebox), scrolledwindow, TRUE, TRUE, 0); + gtk_widget_set_size_request(scrolledwindow, 340, 340); + gtk_widget_show(scrolledwindow); + + GtkWidget *buttonbox = gtk_widget_new(GTK_TYPE_BOX, "halign", GTK_ALIGN_END, NULL); + gtk_box_pack_start(GTK_BOX(archivebox), buttonbox, FALSE, TRUE, 0); + gtk_widget_show(buttonbox); + + GtkWidget *treeview = gtk_tree_view_new(); + gtk_container_add(GTK_CONTAINER(scrolledwindow), treeview); + gtk_tree_view_set_fixed_height_mode(GTK_TREE_VIEW (treeview), FALSE); + gtk_widget_show(treeview); + + GtkTreeStore *treestore = gtk_tree_store_new(1, G_TYPE_STRING); + + gtk_tree_view_set_model(GTK_TREE_VIEW(treeview), GTK_TREE_MODEL(treestore)); + + // Fill the treestore with the filenames + while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { + const char *currentfile = archive_entry_pathname(entry); + if (nst_archive_checkext(currentfile)) { + gtk_tree_store_append(treestore, &iter, NULL); + gtk_tree_store_set(treestore, &iter, 0, currentfile, -1); + numarchives++; + snprintf(reqfile, reqsize, "%s", currentfile); + } + archive_read_data_skip(a); + } + // Free the archive + r = archive_read_free(a); + + // If there are no valid files in the archive, return + if (numarchives == 0) { return false; } + // If there's only one file, don't bring up the selector + else if (numarchives == 1) { return true; } + + GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); + + GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes( + "NES file", + renderer, + "text", 0, + NULL); + + gtk_tree_view_append_column(GTK_TREE_VIEW (treeview), column); + + GtkWidget *cancelbutton = gtk_widget_new( + GTK_TYPE_BUTTON, + "label", "Cancel", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(buttonbox), cancelbutton, FALSE, FALSE, 0); + gtk_widget_show(cancelbutton); + + GtkWidget *okbutton = gtk_widget_new( + GTK_TYPE_BUTTON, + "label", "OK", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(buttonbox), okbutton, FALSE, FALSE, 0); + gtk_widget_show(okbutton); + + selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)); + + g_signal_connect(G_OBJECT(okbutton), "clicked", + G_CALLBACK(gtkui_archive_ok), NULL); + + g_signal_connect(G_OBJECT(cancelbutton), "clicked", + G_CALLBACK(gtkui_archive_cancel), NULL); + + g_signal_connect(G_OBJECT(treeview), "row-activated", + G_CALLBACK(gtkui_archive_ok), NULL); + + g_signal_connect(G_OBJECT(archivewindow), "destroy", + G_CALLBACK(gtkui_archive_cancel), NULL); + + gtk_widget_show(archivewindow); + + // Freeze the rest of the program until a selection is made + windowopen = true; + while (windowopen) { + gtk_main_iteration_do(TRUE); + if (cancelled) { return false; } + } + + gchar *reqbuf; + selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)); + gtk_tree_selection_get_selected(selection, &model, &iter); + gtk_tree_model_get(model, &iter, 0, &reqbuf, -1); + + gtk_widget_destroy(archivewindow); + + snprintf(reqfile, reqsize, "%s", reqbuf); + return true; + } + return false; +} + +void gtkui_archive_ok() { + windowopen = false; +} + +void gtkui_archive_cancel() { + cancelled = true; + gtk_widget_destroy(archivewindow); +} diff -Nru nestopia-1.48/source/gtkui/gtkui_archive.h nestopia-1.49/source/gtkui/gtkui_archive.h --- nestopia-1.48/source/gtkui/gtkui_archive.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_archive.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,8 @@ +#ifndef _GTKUI_ARCHIVE_H_ +#define _GTKUI_ARCHIVE_H_ + +bool gtkui_archive_select(const char *filename, char *reqfile, size_t reqsize); +void gtkui_archive_ok(); +void gtkui_archive_cancel(); + +#endif diff -Nru nestopia-1.48/source/gtkui/gtkui_callbacks.cpp nestopia-1.49/source/gtkui/gtkui_callbacks.cpp --- nestopia-1.48/source/gtkui/gtkui_callbacks.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_callbacks.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,291 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2017 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include + +#include "nstcommon.h" +#include "config.h" +#include "video.h" +#include "input.h" + +#include "gtkui.h" +#include "gtkui_callbacks.h" + +extern bool kbactivate, confrunning; +extern int nst_quit; + +//// Menu //// + +void gtkui_cb_reset(GtkWidget *reset, int hard) { + // Reset the NES from the GUI + nst_reset(hard); +} + +void gtkui_cb_nothing() { + // Do nothing +} + +void gtkui_cb_video_refresh() { + // Refresh the Video output after changes + if (nst_playing()) { video_init(); } + gtkui_resize(); +} + +// Video // + +void gtkui_cb_video_filter(GtkComboBox *combobox, gpointer userdata) { + // Change the video filter + conf.video_filter = gtk_combo_box_get_active(combobox); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_scale(GtkComboBox *combobox, gpointer userdata) { + // Change the scale factor + conf.video_scale_factor = gtk_combo_box_get_active(combobox) + 1; + + // The scalex filter only allows 3x scale and crashes otherwise + if (conf.video_filter == 5 && conf.video_scale_factor == 4) { + conf.video_scale_factor = 3; + } + + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_ntscmode(GtkComboBox *combobox, gpointer userdata) { + // Change the NTSC Mode + conf.video_ntsc_mode = gtk_combo_box_get_active(combobox); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_xbrrounding(GtkComboBox *combobox, gpointer userdata) { + // Set xBR corner rounding parameters + conf.video_xbr_corner_rounding = gtk_combo_box_get_active(combobox); + gtkui_cb_video_refresh(); + video_toggle_filterupdate(); +} + +void gtkui_cb_video_xbrpixblend(GtkToggleButton *togglebutton, gpointer userdata) { + // Set xBR pixel blending parameters + conf.video_xbr_pixel_blending = gtk_toggle_button_get_active(togglebutton); + gtkui_cb_video_refresh(); + video_toggle_filterupdate(); +} + +void gtkui_cb_video_linear_filter(GtkToggleButton *togglebutton, gpointer userdata) { + // Set linear filter + conf.video_linear_filter = gtk_toggle_button_get_active(togglebutton); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_tv_aspect(GtkToggleButton *togglebutton, gpointer userdata) { + // Set TV aspect ratio + conf.video_tv_aspect = gtk_toggle_button_get_active(togglebutton); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_unmask_overscan(GtkToggleButton *togglebutton, gpointer userdata) { + // Set overscan mask + conf.video_unmask_overscan = gtk_toggle_button_get_active(togglebutton); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_stretch_aspect(GtkToggleButton *togglebutton, gpointer userdata) { + // Set aspect ratio stretching/preservation + conf.video_stretch_aspect = gtk_toggle_button_get_active(togglebutton); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_unlimited_sprites(GtkToggleButton *togglebutton, gpointer userdata) { + // Set sprite limit + conf.video_unlimited_sprites = gtk_toggle_button_get_active(togglebutton); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_palette(GtkComboBox *combobox, gpointer userdata) { + // Change the video palette + conf.video_palette_mode = gtk_combo_box_get_active(combobox); + gtkui_cb_video_refresh(); + // this doesn't work unless there's a restart - fix +} + +void gtkui_cb_video_decoder(GtkComboBox *combobox, gpointer userdata) { + // Change the YUV Decoder + conf.video_decoder = gtk_combo_box_get_active(combobox); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_brightness(GtkRange *range, gpointer userdata) { + // Change video brightness + conf.video_brightness = (int)gtk_range_get_value(range); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_saturation(GtkRange *range, gpointer userdata) { + // Change video saturation + conf.video_saturation = (int)gtk_range_get_value(range); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_contrast(GtkRange *range, gpointer userdata) { + // Change video contrast + conf.video_contrast = (int)gtk_range_get_value(range); + gtkui_cb_video_refresh(); +} + +void gtkui_cb_video_hue(GtkRange *range, gpointer userdata) { + // Change video hue + conf.video_hue = (int)gtk_range_get_value(range); + gtkui_cb_video_refresh(); +} + +// Audio // + +void gtkui_cb_audio_api(GtkComboBox *combobox, gpointer userdata) { + // Change the Audio API + if (nst_playing()) { + nst_pause(); + conf.audio_api = gtk_combo_box_get_active(combobox); + nst_play(); + } + else { conf.audio_api = gtk_combo_box_get_active(combobox); } +} + +void gtkui_cb_audio_samplerate(GtkComboBox *combobox, gpointer userdata) { + // Change the Sample Rate + switch (gtk_combo_box_get_active(combobox)) { + case 0: + conf.audio_sample_rate = 11025; + break; + case 1: + conf.audio_sample_rate = 22050; + break; + case 2: + conf.audio_sample_rate = 44100; + break; + case 3: + conf.audio_sample_rate = 48000; + break; + case 4: + conf.audio_sample_rate = 96000; + break; + default: + conf.audio_sample_rate = 44100; + break; + } + + if (nst_playing()) { + nst_pause(); + nst_play(); + } +} + +void gtkui_cb_audio_stereo(GtkToggleButton *togglebutton, gpointer userdata) { + // Toggle Stereo + conf.audio_stereo = gtk_toggle_button_get_active(togglebutton); + + if (nst_playing()) { + nst_pause(); + nst_play(); + } +} + +//// Input //// + +void gtkui_cb_input_turbopulse(GtkRange *range, gpointer userdata) { + // Change turbo pulse + conf.timing_turbopulse = (int)gtk_range_get_value(range); +} + +//// Misc //// + +void gtkui_cb_misc_default_system(GtkComboBox *combobox, gpointer userdata) { + // Select the default system + conf.misc_default_system = gtk_combo_box_get_active(combobox); +} + +void gtkui_cb_misc_power_state(GtkComboBox *combobox, gpointer userdata) { + // Select the default system + conf.misc_power_state = gtk_combo_box_get_active(combobox); +} + +void gtkui_cb_timing_ffspeed(GtkRange *range, gpointer userdata) { + // Set Fast-Forward Speed + conf.timing_ffspeed = (int)gtk_range_get_value(range); +} + +void gtkui_cb_timing_vsync(GtkToggleButton *togglebutton, gpointer userdata) { + // Toggle vsync + conf.timing_vsync = gtk_toggle_button_get_active(togglebutton); +} + +void gtkui_cb_timing_limiter(GtkToggleButton *togglebutton, gpointer userdata) { + // Set the limiter on or off + conf.timing_limiter = gtk_toggle_button_get_active(togglebutton); +} + +void gtkui_cb_misc_soft_patching(GtkToggleButton *togglebutton, gpointer userdata) { + // Enable or Disable automatic soft patching + conf.misc_soft_patching = gtk_toggle_button_get_active(togglebutton); +} + +void gtkui_cb_misc_genie_distortion(GtkToggleButton *togglebutton, gpointer userdata) { + // Enable or Disable Game Genie Sound Distortion + conf.misc_genie_distortion = gtk_toggle_button_get_active(togglebutton); +} + +void gtkui_cb_misc_disable_cursor(GtkToggleButton *togglebutton, gpointer userdata) { + // Enable or Disable the Cursor + conf.misc_disable_cursor = gtk_toggle_button_get_active(togglebutton); + if (!nst_quit) { gtkui_play(); } +} + +void gtkui_cb_misc_disable_cursor_special(GtkToggleButton *togglebutton, gpointer userdata) { + // Enable or Disable Special Cursors + conf.misc_disable_cursor_special = gtk_toggle_button_get_active(togglebutton); + if (!nst_quit) { gtkui_play(); } +} + +void gtkui_cb_misc_config_pause(GtkToggleButton *togglebutton, gpointer userdata) { + // Pause GUI when configuration window is open + conf.misc_config_pause = gtk_toggle_button_get_active(togglebutton); +} + +void gtkui_cb_misc_overclock(GtkToggleButton *togglebutton, gpointer userdata) { + // Enable or Disable Core Overclocking + conf.misc_overclock = gtk_toggle_button_get_active(togglebutton); +} + +void gtkui_drag_data(GtkWidget *widget, GdkDragContext *dragcontext, gint x, gint y, GtkSelectionData *seldata, guint info, guint time, gpointer data) { + // Handle the Drag and Drop + if ((widget == NULL) || (dragcontext == NULL) || (seldata == NULL)) { return; } + + if (info == 0) { + gchar *fileuri = (gchar*)gtk_selection_data_get_data(seldata); + gchar *filename = g_filename_from_uri(fileuri, NULL, NULL); + + // Dirty hack. g_filename_from_uri adds a \r\n to the string + size_t ln = strlen(filename) - 2; + if (filename[ln] == '\r') { filename[ln] = '\0'; } + + nst_load(filename); + } +} diff -Nru nestopia-1.48/source/gtkui/gtkui_callbacks.h nestopia-1.49/source/gtkui/gtkui_callbacks.h --- nestopia-1.48/source/gtkui/gtkui_callbacks.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_callbacks.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,46 @@ +#ifndef _GTKUI_CALLBACKS_H_ +#define _GTKUI_CALLBACKS_H_ + +void gtkui_cb_reset(GtkWidget *reset, int hard); +void gtkui_cb_nothing(); +void gtkui_cb_video_refresh(); + +void gtkui_cb_video_filter(GtkComboBox *combobox, gpointer userdata); +void gtkui_cb_video_scale(GtkComboBox *combobox, gpointer userdata); +void gtkui_cb_video_ntscmode(GtkComboBox *combobox, gpointer userdata); +void gtkui_cb_video_xbrrounding(GtkComboBox *combobox, gpointer userdata); +void gtkui_cb_video_xbrpixblend(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_video_linear_filter(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_video_tv_aspect(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_video_unmask_overscan(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_video_stretch_aspect(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_video_unlimited_sprites(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_video_palette(GtkComboBox *combobox, gpointer userdata); +void gtkui_cb_video_decoder(GtkComboBox *combobox, gpointer userdata); +void gtkui_cb_video_brightness(GtkRange *range, gpointer userdata); +void gtkui_cb_video_saturation(GtkRange *range, gpointer userdata); +void gtkui_cb_video_contrast(GtkRange *range, gpointer userdata); +void gtkui_cb_video_hue(GtkRange *range, gpointer userdata); + +void gtkui_cb_audio_api(GtkComboBox *combobox, gpointer userdata); +void gtkui_cb_audio_samplerate(GtkComboBox *combobox, gpointer userdata); +void gtkui_cb_audio_stereo(GtkToggleButton *togglebutton, gpointer userdata); + +void gtkui_cb_input_turbopulse(GtkRange *range, gpointer userdata); + +void gtkui_cb_misc_default_system(GtkComboBox *combobox, gpointer userdata); +void gtkui_cb_misc_power_state(GtkComboBox *combobox, gpointer userdata); +void gtkui_cb_timing_ffspeed(GtkRange *range, gpointer userdata); +void gtkui_cb_timing_vsync(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_timing_limiter(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_misc_soft_patching(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_misc_genie_distortion(GtkToggleButton *togglebutton, gpointer userdata); +//void gtkui_cb_misc_disable_gui(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_misc_disable_cursor(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_misc_disable_cursor_special(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_misc_config_pause(GtkToggleButton *togglebutton, gpointer userdata); +void gtkui_cb_misc_overclock(GtkToggleButton *togglebutton, gpointer userdata); + +void gtkui_drag_data(GtkWidget *widget, GdkDragContext *dragcontext, gint x, gint y, GtkSelectionData *seldata, guint info, guint time, gpointer data); + +#endif diff -Nru nestopia-1.48/source/gtkui/gtkui_cheats.cpp nestopia-1.49/source/gtkui/gtkui_cheats.cpp --- nestopia-1.48/source/gtkui/gtkui_cheats.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_cheats.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,619 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2016 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include + +#include + +#include "nstcommon.h" +#include "config.h" +#include "cheats.h" + +#include "gtkui.h" +#include "gtkui_callbacks.h" +#include "gtkui_cheats.h" +#include "gtkui_dialogs.h" + +extern nstpaths_t nstpaths; +extern Emulator emulator; + +GtkWidget *cheatwindow; +GtkTreeStore *treestore; +GtkWidget *treeview; +GtkWidget *descedit, *ggedit, *paredit; +GtkWidget *infobar, *infolabel; + +Xml savexml; +Xml::Node saveroot; + +GtkWidget *gtkui_cheats() { + // Create the Cheats window + + if (cheatwindow) { return NULL; } + + cheatwindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW (cheatwindow), "Cheat Manager"); + + GtkWidget *cheatbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + gtk_container_add(GTK_CONTAINER(cheatwindow), cheatbox); + + GtkWidget *scrolledwindow = gtk_scrolled_window_new(NULL, NULL); + gtk_box_pack_start(GTK_BOX(cheatbox), scrolledwindow, TRUE, TRUE, 0); + gtk_widget_set_size_request(scrolledwindow, 512, 256); + + treeview = gtk_tree_view_new(); + gtk_container_add(GTK_CONTAINER (scrolledwindow), treeview); + + infobar = gtk_info_bar_new(); + infolabel = gtk_widget_new(GTK_TYPE_LABEL,"label", "", NULL); + gtk_box_pack_start(GTK_BOX(cheatbox), infobar, TRUE, TRUE, 0); + + GtkWidget *content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(infobar)); + gtk_box_pack_start(GTK_BOX(content_area), infolabel, TRUE, TRUE, 0); + + GtkWidget *opensavebox = gtk_widget_new(GTK_TYPE_BOX, "halign", GTK_ALIGN_END, NULL); + gtk_box_pack_start(GTK_BOX(cheatbox), opensavebox, FALSE, FALSE, 0); + + GtkWidget *cheatopen = gtk_widget_new( + GTK_TYPE_BUTTON, + "label", "Open", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(opensavebox), cheatopen, FALSE, FALSE, 0); + + GtkWidget *cheatclear = gtk_widget_new( + GTK_TYPE_BUTTON, + "label", "Clear", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(opensavebox), cheatclear, FALSE, FALSE, 0); + + GtkWidget *cheatremove = gtk_widget_new( + GTK_TYPE_BUTTON, + "label", "Remove", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(opensavebox), cheatremove, FALSE, FALSE, 0); + + GtkWidget *descbox = gtk_widget_new( + GTK_TYPE_BOX, + "halign", GTK_ALIGN_END, + NULL); + gtk_box_pack_start(GTK_BOX(cheatbox), descbox, FALSE, FALSE, 0); + + GtkWidget *desclabel = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "Description:", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-left", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(descbox), desclabel, FALSE, FALSE, 0); + + descedit = gtk_widget_new( + GTK_TYPE_ENTRY, + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(descbox), descedit, TRUE, TRUE, 0); + + GtkWidget *ggbox = gtk_widget_new( + GTK_TYPE_BOX, + "halign", GTK_ALIGN_END, + NULL); + gtk_box_pack_start(GTK_BOX(cheatbox), ggbox, FALSE, FALSE, 0); + + GtkWidget *gglabel = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "Game Genie:", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-left", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(ggbox), gglabel, FALSE, FALSE, 0); + + ggedit = gtk_widget_new( + GTK_TYPE_ENTRY, + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(ggbox), ggedit, TRUE, TRUE, 0); + + GtkWidget *genieadd = gtk_widget_new( + GTK_TYPE_BUTTON, + "label", "Add", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(ggbox), genieadd, FALSE, FALSE, 0); + + GtkWidget *parbox = gtk_widget_new( + GTK_TYPE_BOX, + "halign", GTK_ALIGN_END, + NULL); + gtk_box_pack_start(GTK_BOX(cheatbox), parbox, FALSE, FALSE, 0); + + GtkWidget *parlabel = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "Pro Action Rocky:", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-left", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(parbox), parlabel, FALSE, FALSE, 0); + + paredit = gtk_widget_new( + GTK_TYPE_ENTRY, + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(parbox), paredit, FALSE, FALSE, 0); + + GtkWidget *paradd = gtk_widget_new( + GTK_TYPE_BUTTON, + "label", "Add", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(parbox), paradd, FALSE, FALSE, 0); + + GtkWidget *cheatok = gtk_widget_new( + GTK_TYPE_BUTTON, + "label", "OK", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + gtk_box_pack_start(GTK_BOX(cheatbox), cheatok, FALSE, FALSE, 0); + + gtk_tree_view_set_fixed_height_mode(GTK_TREE_VIEW(treeview), FALSE); + + treestore = gtk_tree_store_new(5, G_TYPE_BOOLEAN, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); + gtk_tree_view_set_model(GTK_TREE_VIEW(treeview), GTK_TREE_MODEL(treestore)); + + GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); + GtkCellRenderer *checkbox = gtk_cell_renderer_toggle_new(); + + GtkTreeViewColumn *column[5]; + // create the display columns + column[0] = gtk_tree_view_column_new_with_attributes("Enable", checkbox, "active", 0, NULL); + column[1] = gtk_tree_view_column_new_with_attributes("Game Genie", renderer, "text", 1, NULL); + column[2] = gtk_tree_view_column_new_with_attributes("PAR", renderer, "text", 2, NULL); + column[3] = gtk_tree_view_column_new_with_attributes("Raw", renderer, "text", 3, NULL); + column[4] = gtk_tree_view_column_new_with_attributes("Description", renderer, "text", 4, NULL); + + // add the display column and renderer to the tree view + gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column[0]); + gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column[1]); + gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column[2]); + gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column[3]); + gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column[4]); + + gtkui_cheats_fill_tree(nstpaths.cheatpath); + + /*g_signal_connect(G_OBJECT(checkbox), "toggled", + G_CALLBACK(gtkui_cheats_check), NULL);*/ + + g_signal_connect(G_OBJECT(treeview), "row-activated", + G_CALLBACK(gtkui_cheats_toggle), NULL); + + g_signal_connect(G_OBJECT(cheatopen), "clicked", + G_CALLBACK(gtkui_cheats_load), NULL); + + g_signal_connect(G_OBJECT(cheatclear), "clicked", + G_CALLBACK(gtkui_cheats_clear), NULL); + + g_signal_connect(G_OBJECT(cheatremove), "clicked", + G_CALLBACK(gtkui_cheats_remove), NULL); + + g_signal_connect(G_OBJECT(genieadd), "clicked", + G_CALLBACK(gtkui_cheats_gg_add), NULL); + + g_signal_connect(G_OBJECT(paradd), "clicked", + G_CALLBACK(gtkui_cheats_par_add), NULL); + + g_signal_connect(G_OBJECT(cheatok), "clicked", + G_CALLBACK(gtkui_cheats_ok), NULL); + + g_signal_connect(G_OBJECT(cheatwindow), "destroy", + G_CALLBACK(gtkui_cheats_ok), NULL); + + gtk_widget_show_all(cheatwindow); + gtk_widget_hide(infobar); + + return cheatwindow; +} + +void gtkui_cheats_check(GtkWidget *widget, gchar *element, gpointer userdata) { + // This function doesn't work. Fix later. + GtkTreeIter iter; + + bool value; + + // Read the value of the checkbox + value = gtk_cell_renderer_toggle_get_active((GtkCellRendererToggle*)widget); + + // Flip the value and set it + value ^= 1; + gtk_cell_renderer_toggle_set_active((GtkCellRendererToggle*)widget, value); +} + +void gtkui_cheats_toggle(GtkWidget *widget, gpointer userdata) { + // Toggle a cheat on or off + GtkTreeIter iter; + GtkTreeModel *model; + GtkTreeSelection *selection; + + bool value; + + // Get the selected item + selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); + gtk_tree_selection_get_selected(selection, &model, &iter); + + // Read the value of the checkbox + gtk_tree_model_get(model, &iter, 0, &value, -1); + + // Flip the value and set it + value ^= 1; + gtk_tree_store_set(treestore, &iter, 0, value, -1); + + //Re-initialize the cheats + Cheats cheats(emulator); + cheats.ClearCodes(); + + gtk_tree_model_foreach(GTK_TREE_MODEL(model), gtkui_cheats_scan_list, NULL); +} + +void gtkui_cheats_fill_tree(char *filename) { + // Fill the cheat list + Xml xml; + + GtkTreeIter iter; + + bool enabled = false; + + char codebuf[9]; + char descbuf[512]; + + gtkui_cheats_clear(); + + std::ifstream cheatfile(filename, std::ifstream::in|std::ifstream::binary); + + if (cheatfile.is_open()) { + xml.Read(cheatfile); + + if (xml.GetRoot().IsType(L"cheats")) { + + Xml::Node root(xml.GetRoot()); + Xml::Node node(root.GetFirstChild()); + + for (int i = 0; i < root.NumChildren(L"cheat"); i++) { + + wcstombs(descbuf, node.GetChild(L"description").GetValue(), sizeof(descbuf)); + + // Check if the cheat is enabled + node.GetAttribute(L"enabled").IsValue(L"1") ? enabled = true : enabled = false; + + // Add the cheats to the list + if (node.GetChild(L"genie")) { // Game Genie + wcstombs(codebuf, node.GetChild(L"genie").GetValue(), sizeof(codebuf)); + gtk_tree_store_append(treestore, &iter, NULL); + gtk_tree_store_set(treestore, &iter, + 0, enabled, + 1, codebuf, + 4, descbuf, + -1); + if (enabled) { nst_cheats_code_gg_add(node.GetChild(L"genie").GetValue()); } + } + + else if (node.GetChild(L"rocky")) { // Pro Action Rocky + wcstombs(codebuf, node.GetChild(L"rocky").GetValue(), sizeof(codebuf)); + gtk_tree_store_append(treestore, &iter, NULL); + gtk_tree_store_set(treestore, &iter, + 0, enabled, + 2, codebuf, + 4, descbuf, + -1); + if (enabled) { nst_cheats_code_par_add(node.GetChild(L"rocky").GetValue()); } + } + + else if (node.GetChild(L"address")) { // Raw + char rawbuf[11]; + snprintf(rawbuf, sizeof(rawbuf), + "%04lu %02lu %02lu", + node.GetChild(L"address").GetUnsignedValue(), + node.GetChild(L"value").GetUnsignedValue(), + node.GetChild(L"compare").GetUnsignedValue()); + + gtk_tree_store_append(treestore, &iter, NULL); + gtk_tree_store_set(treestore, &iter, + 0, enabled, + 3, rawbuf, + 4, descbuf, + -1); + if (enabled) { nst_cheats_code_raw_add(node); } + } + + node = node.GetNextSibling(); + } + } + cheatfile.close(); + } +} + +void gtkui_cheats_save() { + // Save the cheat list + std::ofstream cheatfile(nstpaths.cheatpath, std::ifstream::out|std::ifstream::binary); + + if (cheatfile.is_open()) { + + GtkTreeModel *model; + model = gtk_tree_view_get_model(GTK_TREE_VIEW(treeview)); + + saveroot = (savexml.GetRoot()); + + saveroot = savexml.Create( L"cheats" ); + saveroot.AddAttribute( L"version", L"1.0" ); + + gtk_tree_model_foreach(GTK_TREE_MODEL(model), gtkui_cheats_write_list, NULL); + + savexml.Write(saveroot, cheatfile); + cheatfile.close(); + } + else { return; } +} + +void gtkui_cheats_gg_add(GtkWidget *widget, gpointer userdata) { + // Add a Game Genie code to the list + GtkTreeIter iter; + + Cheats cheats(emulator); + Cheats::Code code; + + char codebuf[9]; + char descbuf[512]; + + snprintf(codebuf, sizeof(codebuf), "%.8s", gtk_entry_get_text(GTK_ENTRY(ggedit))); + snprintf(descbuf, sizeof(descbuf), "%s", gtk_entry_get_text(GTK_ENTRY(descedit))); + + if (cheats.GameGenieDecode(codebuf, code) == Nes::RESULT_OK) { + gtk_tree_store_append(treestore, &iter, NULL); + gtk_tree_store_set(treestore, &iter, + 0, true, + 1, codebuf, + 4, descbuf, + -1); + gtk_entry_set_text(GTK_ENTRY(descedit), ""); + gtk_entry_set_text(GTK_ENTRY(ggedit), ""); + gtk_entry_set_text(GTK_ENTRY(paredit), ""); + gtk_widget_hide(infobar); + gtk_label_set_text(GTK_LABEL(infolabel), ""); + cheats.SetCode(code); + } + else { + gtk_info_bar_set_message_type(GTK_INFO_BAR(infobar), GTK_MESSAGE_ERROR); + gtk_label_set_text(GTK_LABEL(infolabel), "Error: Invalid Game Genie code"); + gtk_widget_show(infobar); + } +} + +void gtkui_cheats_par_add(GtkWidget *widget, gpointer userdata) { + // Add a Pro Action Rocky code to the list + GtkTreeIter iter; + + Cheats cheats(emulator); + Cheats::Code code; + + char codebuf[9]; + char descbuf[512]; + + snprintf(codebuf, sizeof(codebuf), "%.8s", gtk_entry_get_text(GTK_ENTRY(paredit))); + snprintf(descbuf, sizeof(descbuf), "%s", gtk_entry_get_text(GTK_ENTRY(descedit))); + + if (cheats.ProActionRockyDecode(codebuf, code) == Nes::RESULT_OK) { + gtk_tree_store_append(treestore, &iter, NULL); + gtk_tree_store_set(treestore, &iter, + 0, true, + 1, codebuf, + 4, descbuf, + -1); + gtk_entry_set_text(GTK_ENTRY(descedit), ""); + gtk_entry_set_text(GTK_ENTRY(ggedit), ""); + gtk_entry_set_text(GTK_ENTRY(paredit), ""); + gtk_widget_hide(infobar); + gtk_label_set_text(GTK_LABEL(infolabel), ""); + cheats.SetCode(code); + } + else { + gtk_info_bar_set_message_type(GTK_INFO_BAR(infobar), GTK_MESSAGE_ERROR); + gtk_label_set_text(GTK_LABEL(infolabel), "Error: Invalid PAR code"); + gtk_widget_show(infobar); + } +} + +void gtkui_cheats_remove(GtkWidget *widget, gpointer userdata) { + // Remove a cheat from the list + GtkTreeIter iter; + GtkTreeModel *model; + GtkTreeSelection *selection; + + // Get the selected item + selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)); + gtk_tree_selection_get_selected(selection, &model, &iter); + + // Remove the cheat + if (gtk_tree_store_iter_is_valid(treestore, &iter)) { + gtk_tree_store_remove(treestore, &iter); + } + + //Re-initialize the cheats + Cheats cheats(emulator); + cheats.ClearCodes(); + + gtk_tree_model_foreach(GTK_TREE_MODEL(model), gtkui_cheats_scan_list, NULL); +} + +void gtkui_cheats_ok() { + // Save the cheats and close the window + gtkui_cheats_save(); + gtk_widget_destroy(cheatwindow); + cheatwindow = NULL; +} + +void gtkui_cheats_clear() { + // Clear the list + gtk_tree_store_clear(treestore); + Cheats cheats(emulator); + cheats.ClearCodes(); +} + +gboolean gtkui_cheats_scan_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer userdata) { + // Scan through the list of cheats + Cheats cheats(emulator); + Cheats::Code code; + + bool enabled; + gchar *ggcode, *parcode, *rawcode, *description; + + gtk_tree_model_get(model, iter, 0, &enabled, 1, &ggcode, 2, &parcode, 3, &rawcode, 4, &description, -1); + + if (enabled) { + if (ggcode) { + cheats.GameGenieDecode(ggcode, code); + cheats.SetCode(code); + } + else if (parcode) { + cheats.ProActionRockyDecode(parcode, code); + cheats.SetCode(code); + } + else if (rawcode) { + code.useCompare = false; + + int addr, value, compare; + char buf[5]; + + snprintf(buf, sizeof(buf), "%c%c%c%c", rawcode[0], rawcode[1], rawcode[2], rawcode[3]); + sscanf(buf, "%x", &addr); + + snprintf(buf, sizeof(buf), "%c%c", rawcode[5], rawcode[6]); + sscanf(buf, "%x", &value); + + snprintf(buf, sizeof(buf), "%c%c", rawcode[8], rawcode[9]); + sscanf(buf, "%x", &compare); + + code.address = addr; + code.value = value; + code.compare = compare; + + if (compare) { code.useCompare = true; } + + cheats.SetCode(code); + } + } + + g_free(ggcode); + g_free(parcode); + g_free(rawcode); + g_free(description); + + return false; +} + +gboolean gtkui_cheats_write_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer userdata) { + // Write entries to the cheat file + bool enabled; + gchar *ggcode, *parcode, *rawcode, *description; + + char buf[9]; + wchar_t wbuf[9]; + + gtk_tree_model_get(model, iter, 0, &enabled, 1, &ggcode, 2, &parcode, 3, &rawcode, 4, &description, -1); + + Xml::Node node(saveroot.AddChild(L"cheat")); + node.AddAttribute(L"enabled", enabled ? L"1" : L"0"); + + if (ggcode) { + snprintf(buf, sizeof(buf), "%s", ggcode); + mbstowcs(wbuf, buf, 9); + node.AddChild(L"genie", wbuf); + } + if (parcode) { + snprintf(buf, sizeof(buf), "%s", parcode); + mbstowcs(wbuf, buf, 9); + node.AddChild(L"rocky", wbuf); + } + if (rawcode) { + snprintf(buf, sizeof(buf), "0x%c%c%c%c", rawcode[0], rawcode[1], rawcode[2], rawcode[3]); + mbstowcs(wbuf, buf, 9); + node.AddChild(L"address", wbuf); + + snprintf(buf, sizeof(buf), "0x%c%c", rawcode[5], rawcode[6]); + mbstowcs(wbuf, buf, 9); + node.AddChild(L"value", wbuf); + + snprintf(buf, sizeof(buf), "0x%c%c", rawcode[8], rawcode[9]); + mbstowcs(wbuf, buf, 9); + node.AddChild(L"compare", wbuf); + } + if (description) { + char descbuf[512]; + wchar_t wdescbuf[512]; + + snprintf(descbuf, sizeof(descbuf), "%s", description); + mbstowcs(wdescbuf, descbuf, 512); + node.AddChild(L"description", wdescbuf); + } + + g_free(ggcode); + g_free(parcode); + g_free(rawcode); + g_free(description); + + return false; +} diff -Nru nestopia-1.48/source/gtkui/gtkui_cheats.h nestopia-1.49/source/gtkui/gtkui_cheats.h --- nestopia-1.48/source/gtkui/gtkui_cheats.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_cheats.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,17 @@ +#ifndef _GTKUI_CHEATS_H_ +#define _GTKUI_CHEATS_H_ + +GtkWidget *gtkui_cheats(); +void gtkui_cheats_check(GtkWidget *widget, gchar *element, gpointer userdata); +void gtkui_cheats_toggle(GtkWidget *widget, gpointer userdata); +void gtkui_cheats_fill_tree(char *filename); +void gtkui_cheats_save(); +void gtkui_cheats_gg_add(GtkWidget *widget, gpointer userdata); +void gtkui_cheats_par_add(GtkWidget *widget, gpointer userdata); +void gtkui_cheats_remove(GtkWidget *widget, gpointer userdata); +void gtkui_cheats_ok(); +void gtkui_cheats_clear(); +gboolean gtkui_cheats_scan_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer userdata); +gboolean gtkui_cheats_write_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer userdata); + +#endif diff -Nru nestopia-1.48/source/gtkui/gtkui_config.cpp nestopia-1.49/source/gtkui/gtkui_config.cpp --- nestopia-1.48/source/gtkui/gtkui_config.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_config.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,1368 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2016 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include + +#include "nstcommon.h" +#include "config.h" +#include "audio.h" +#include "input.h" + +#include "sdlinput.h" + +#include "gtkui.h" +#include "gtkui_callbacks.h" +#include "gtkui_config.h" +#include "gtkui_input.h" + +extern gamepad_t player[NUMGAMEPADS]; +extern gpad_t pad[NUMGAMEPADS]; +extern char padpath[512]; +bool confrunning; + +GtkWidget *configwindow; +GtkWidget *notebook; +gint tabnum = 0; + +// Audio +GtkWidget *scale_audio_volume[NUMCHANNELS]; +GtkAdjustment *adj_audio_volume[NUMCHANNELS]; + +// Input +GtkWidget *combo_input_player; +GtkWidget *combo_input_type; +GtkWidget *inputconfbutton; +GtkWidget *entry_input[NUMBUTTONS]; + +GtkTreeStore *treestore_input; + +GtkWidget *gtkui_config() { + // Create the Configuration window + + if (configwindow) { return NULL; } + if (conf.misc_config_pause) { if (nst_playing()) { nst_pause(); } } + + configwindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(configwindow), "Configuration"); + + GtkWidget *box_upper = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + GtkWidget *box_lower = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + notebook = gtk_notebook_new(); + + gtk_container_add(GTK_CONTAINER(configwindow), box_upper); + + // Video // + GtkWidget *box_video = gtk_widget_new( + GTK_TYPE_BOX, + "orientation", GTK_ORIENTATION_HORIZONTAL, + "margin-top", MARGIN_TB, + "margin-bottom", MARGIN_TB, + NULL); + GtkWidget *box_video_l = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + GtkWidget *box_video_r = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + + // Filter + GtkWidget *box_video_filter = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_video_filter = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "Filter:", + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + GtkWidget *combo_video_filter = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "None"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "NTSC"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "xBR"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "HqX"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "2xSaI"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "ScaleX"); + + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_filter), conf.video_filter); + + gtk_box_pack_start(GTK_BOX(box_video_filter), label_video_filter, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_filter), combo_video_filter, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_l), box_video_filter, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_video_filter), "changed", + G_CALLBACK(gtkui_cb_video_filter), NULL); + + // Scale Factor + GtkWidget *box_video_scale = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_video_scale = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "Scale Factor:", + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + GtkWidget *combo_video_scale = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "1x"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "2x"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "3x"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "4x"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "5x"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "6x"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "7x"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "8x"); + + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_scale), conf.video_scale_factor - 1); + + gtk_box_pack_start(GTK_BOX(box_video_scale), label_video_scale, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_scale), combo_video_scale, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_l), box_video_scale, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_video_scale), "changed", + G_CALLBACK(gtkui_cb_video_scale), NULL); + + // NTSC Mode + GtkWidget *box_video_ntscmode = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_video_ntscmode = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "NTSC Mode:", + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + GtkWidget *combo_video_ntscmode = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_ntscmode), "Composite"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_ntscmode), "S-Video"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_ntscmode), "RGB"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_ntscmode), "Monochrome"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_ntscmode), "Custom"); + + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_ntscmode), conf.video_ntsc_mode); + + gtk_box_pack_start(GTK_BOX(box_video_ntscmode), label_video_ntscmode, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_ntscmode), combo_video_ntscmode, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_l), box_video_ntscmode, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_video_ntscmode), "changed", + G_CALLBACK(gtkui_cb_video_ntscmode), NULL); + + // xBR Corner Rounding + GtkWidget *box_video_xbrrounding = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_video_xbrrounding = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "xBR Corner Rounding:", + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + GtkWidget *combo_video_xbrrounding = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_xbrrounding), "None"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_xbrrounding), "Some"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_xbrrounding), "All"); + + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_xbrrounding), conf.video_xbr_corner_rounding); + + gtk_box_pack_start(GTK_BOX(box_video_xbrrounding), label_video_xbrrounding, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_xbrrounding), combo_video_xbrrounding, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_l), box_video_xbrrounding, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_video_xbrrounding), "changed", + G_CALLBACK(gtkui_cb_video_xbrrounding), NULL); + + // xBR Pixel Blending + GtkWidget *check_video_xbrpixblend = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "xBR Pixel Blending", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_xbrpixblend), conf.video_xbr_pixel_blending); + + gtk_box_pack_start(GTK_BOX(box_video_l), check_video_xbrpixblend, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_video_xbrpixblend), "toggled", + G_CALLBACK(gtkui_cb_video_xbrpixblend), NULL); + + // Linear Filter + GtkWidget *check_video_linear_filter = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Linear Filter", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_linear_filter), conf.video_linear_filter); + + gtk_box_pack_start(GTK_BOX(box_video_l), check_video_linear_filter, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_video_linear_filter), "toggled", + G_CALLBACK(gtkui_cb_video_linear_filter), NULL); + + // TV Aspect + GtkWidget *check_video_tv_aspect = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "TV Aspect Ratio", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_tv_aspect), conf.video_tv_aspect); + + gtk_box_pack_start(GTK_BOX(box_video_l), check_video_tv_aspect, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_video_tv_aspect), "toggled", + G_CALLBACK(gtkui_cb_video_tv_aspect), NULL); + + // Mask Overscan + GtkWidget *check_video_unmask_overscan = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Unmask Overscan", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_unmask_overscan), conf.video_unmask_overscan); + + gtk_box_pack_start(GTK_BOX(box_video_l), check_video_unmask_overscan, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_video_unmask_overscan), "toggled", + G_CALLBACK(gtkui_cb_video_unmask_overscan), NULL); + + // Stretch Aspect + /*GtkWidget *check_video_stretch_aspect = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Stretch Aspect Ratio", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_stretch_aspect), conf.video_stretch_aspect); + + gtk_box_pack_start(GTK_BOX(box_video_l), check_video_stretch_aspect, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_video_stretch_aspect), "toggled", + G_CALLBACK(gtkui_cb_video_stretch_aspect), NULL);*/ + + // Unlimited Sprites + GtkWidget *check_video_unlimited_sprites = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Unlimited Sprites", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_unlimited_sprites), conf.video_unlimited_sprites); + + gtk_box_pack_start(GTK_BOX(box_video_l), check_video_unlimited_sprites, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_video_unlimited_sprites), "toggled", + G_CALLBACK(gtkui_cb_video_unlimited_sprites), NULL); + + // Palette Mode + GtkWidget *box_video_palette = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_video_palette = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "Palette Mode:", + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + NULL); + GtkWidget *combo_video_palette = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_palette), "YUV"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_palette), "RGB"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_palette), "Custom"); + + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_palette), conf.video_palette_mode); + + gtk_box_pack_start(GTK_BOX(box_video_palette), label_video_palette, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_palette), combo_video_palette, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_r), box_video_palette, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_video_palette), "changed", + G_CALLBACK(gtkui_cb_video_palette), NULL); + + // YUV Decoder + GtkWidget *box_video_decoder = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_video_decoder = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "YUV Decoder:", + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + NULL); + GtkWidget *combo_video_decoder = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_decoder), "Consumer"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_decoder), "Canonical"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_decoder), "Alternative"); + + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_decoder), conf.video_decoder); + + gtk_box_pack_start(GTK_BOX(box_video_decoder), label_video_decoder, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_decoder), combo_video_decoder, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video_r), box_video_decoder, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_video_decoder), "changed", + G_CALLBACK(gtkui_cb_video_decoder), NULL); + + // Brightness + GtkAdjustment *adj_video_brightness = gtk_adjustment_new(conf.video_brightness, -100, 100, 1, 5, 0); + GtkWidget *frame_video_brightness = gtk_frame_new("Brightness"); + GtkWidget *scale_video_brightness = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + "margin-right", MARGIN_LR, + "orientation", GTK_ORIENTATION_HORIZONTAL, + "adjustment", adj_video_brightness, + "width-request", 201, + "height-request", 32, + "digits", 0, + NULL); + gtk_container_add(GTK_CONTAINER(frame_video_brightness), scale_video_brightness); + gtk_box_pack_start(GTK_BOX(box_video_r), frame_video_brightness, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(scale_video_brightness), "value-changed", + G_CALLBACK(gtkui_cb_video_brightness), NULL); + + // Saturation + GtkAdjustment *adj_video_saturation = gtk_adjustment_new(conf.video_saturation, -100, 100, 1, 5, 0); + GtkWidget *frame_video_saturation = gtk_frame_new("Saturation"); + GtkWidget *scale_video_saturation = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + "margin-right", MARGIN_LR, + "orientation", GTK_ORIENTATION_HORIZONTAL, + "adjustment", adj_video_saturation, + "width-request", 201, + "height-request", 32, + "digits", 0, + NULL); + gtk_container_add(GTK_CONTAINER(frame_video_saturation), scale_video_saturation); + gtk_box_pack_start(GTK_BOX(box_video_r), frame_video_saturation, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(scale_video_saturation), "value-changed", + G_CALLBACK(gtkui_cb_video_saturation), NULL); + + // Contrast + GtkAdjustment *adj_video_contrast = gtk_adjustment_new(conf.video_contrast, -100, 100, 1, 5, 0); + GtkWidget *frame_video_contrast = gtk_frame_new("Contrast"); + GtkWidget *scale_video_contrast = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + "margin-right", MARGIN_LR, + "orientation", GTK_ORIENTATION_HORIZONTAL, + "adjustment", adj_video_contrast, + "width-request", 201, + "height-request", 32, + "digits", 0, + NULL); + gtk_container_add(GTK_CONTAINER(frame_video_contrast), scale_video_contrast); + gtk_box_pack_start(GTK_BOX(box_video_r), frame_video_contrast, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(scale_video_contrast), "value-changed", + G_CALLBACK(gtkui_cb_video_contrast), NULL); + + // Hue + GtkAdjustment *adj_video_hue = gtk_adjustment_new(conf.video_hue, -45, 45, 1, 5, 0); + GtkWidget *frame_video_hue = gtk_frame_new("Hue"); + GtkWidget *scale_video_hue = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + "margin-right", MARGIN_LR, + "orientation", GTK_ORIENTATION_HORIZONTAL, + "adjustment", adj_video_hue, + "width-request", 91, + "height-request", 32, + "digits", 0, + NULL); + gtk_container_add(GTK_CONTAINER(frame_video_hue), scale_video_hue); + gtk_box_pack_start(GTK_BOX(box_video_r), frame_video_hue, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(scale_video_hue), "value-changed", + G_CALLBACK(gtkui_cb_video_hue), NULL); + + gtk_box_pack_start(GTK_BOX(box_video), box_video_l, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_video), box_video_r, FALSE, FALSE, MARGIN_LR); + + // Audio // + GtkWidget *box_audio = gtk_widget_new( + GTK_TYPE_BOX, + "orientation", GTK_ORIENTATION_VERTICAL, + "margin-top", MARGIN_TB, + "margin-bottom", MARGIN_TB, + NULL); + + // Audio API + GtkWidget *box_audio_api = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_audio_api = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "API:", + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + GtkWidget *combo_audio_api = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_api), "SDL"); + #ifdef _LIBAO + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_api), "libao"); + #endif + #ifdef _JACK + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_api), "jack"); + #endif + + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_api), conf.audio_api); + + gtk_box_pack_start(GTK_BOX(box_audio_api), label_audio_api, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_audio_api), combo_audio_api, FALSE, FALSE, 0); + #if SDL_VERSION_ATLEAST(2,0,4) + gtk_box_pack_start(GTK_BOX(box_audio), box_audio_api, FALSE, FALSE, 0); + #endif + + g_signal_connect(G_OBJECT(combo_audio_api), "changed", + G_CALLBACK(gtkui_cb_audio_api), NULL); + + // Sample Rate + GtkWidget *box_audio_samplerate = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_audio_samplerate = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "Sample Rate:", + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + GtkWidget *combo_audio_samplerate = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_samplerate), "11025Hz"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_samplerate), "22050Hz"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_samplerate), "44100Hz"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_samplerate), "48000Hz"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_samplerate), "96000Hz"); + + switch (conf.audio_sample_rate) { + case 11025: + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 0); + break; + case 22050: + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 1); + break; + case 44100: + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 2); + break; + case 48000: + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 3); + break; + case 96000: + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 4); + break; + default: + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 2); + break; + } + + gtk_box_pack_start(GTK_BOX(box_audio_samplerate), label_audio_samplerate, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_audio_samplerate), combo_audio_samplerate, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_audio), box_audio_samplerate, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_audio_samplerate), "changed", + G_CALLBACK(gtkui_cb_audio_samplerate), NULL); + + // Stereo + GtkWidget *check_audio_stereo = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Stereo", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_audio_stereo), conf.audio_stereo); + + gtk_box_pack_start(GTK_BOX(box_audio), check_audio_stereo, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_audio_stereo), "toggled", + G_CALLBACK(gtkui_cb_audio_stereo), NULL); + + // Volume + GtkWidget *label_audio_volume[NUMCHANNELS]; + + // The Grid + GtkWidget *grid_audio_volume = gtk_widget_new( + GTK_TYPE_GRID, + "column-homogeneous", TRUE, + "column-spacing", MARGIN_LR, + "row-spacing", MARGIN_TB, + "margin", MARGIN_TB, + NULL); + + // Master + label_audio_volume[0] = gtk_widget_new(GTK_TYPE_LABEL, "label", "Master", NULL); + adj_audio_volume[0] = gtk_adjustment_new(conf.audio_volume, 0, 100, 1, 5, 0); + scale_audio_volume[0] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[0], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[0], 0, 0, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[0], 0, 1, 1, 1); + + g_signal_connect(G_OBJECT(scale_audio_volume[0]), "value-changed", + G_CALLBACK(gtkui_audio_volume_master), NULL); + + // Square1 + label_audio_volume[1] = gtk_widget_new(GTK_TYPE_LABEL, "label", "Square1", NULL); + adj_audio_volume[1] = gtk_adjustment_new(conf.audio_vol_sq1, 0, 100, 1, 5, 0); + scale_audio_volume[1] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[1], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[1], 1, 0, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[1], 1, 1, 1, 1); + + // Square2 + label_audio_volume[2] = gtk_widget_new(GTK_TYPE_LABEL, "label", "Square2", NULL); + adj_audio_volume[2] = gtk_adjustment_new(conf.audio_vol_sq2, 0, 100, 1, 5, 0); + scale_audio_volume[2] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[2], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[2], 2, 0, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[2], 2, 1, 1, 1); + + // Triangle + label_audio_volume[3] = gtk_widget_new(GTK_TYPE_LABEL, "label", "Triangle", NULL); + adj_audio_volume[3] = gtk_adjustment_new(conf.audio_vol_tri, 0, 100, 1, 5, 0); + scale_audio_volume[3] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[3], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[3], 3, 0, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[3], 3, 1, 1, 1); + + // Noise + label_audio_volume[4] = gtk_widget_new(GTK_TYPE_LABEL, "label", "Noise", NULL); + adj_audio_volume[4] = gtk_adjustment_new(conf.audio_vol_noise, 0, 100, 1, 5, 0); + scale_audio_volume[4] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[4], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[4], 4, 0, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[4], 4, 1, 1, 1); + + // Noise + label_audio_volume[5] = gtk_widget_new(GTK_TYPE_LABEL, "label", "DPCM", NULL); + adj_audio_volume[5] = gtk_adjustment_new(conf.audio_vol_dpcm, 0, 100, 1, 5, 0); + scale_audio_volume[5] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[5], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[5], 5, 0, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[5], 5, 1, 1, 1); + + // FDS + label_audio_volume[6] = gtk_widget_new(GTK_TYPE_LABEL, "label", "FDS", NULL); + adj_audio_volume[6] = gtk_adjustment_new(conf.audio_vol_fds, 0, 100, 1, 5, 0); + scale_audio_volume[6] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[6], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[6], 0, 2, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[6], 0, 3, 1, 1); + + // MMC5 + label_audio_volume[7] = gtk_widget_new(GTK_TYPE_LABEL, "label", "MMC5", NULL); + adj_audio_volume[7] = gtk_adjustment_new(conf.audio_vol_mmc5, 0, 100, 1, 5, 0); + scale_audio_volume[7] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[7], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[7], 1, 2, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[7], 1, 3, 1, 1); + + // VRC6 + label_audio_volume[8] = gtk_widget_new(GTK_TYPE_LABEL, "label", "VRC6", NULL); + adj_audio_volume[8] = gtk_adjustment_new(conf.audio_vol_vrc6, 0, 100, 1, 5, 0); + scale_audio_volume[8] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[8], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[8], 2, 2, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[8], 2, 3, 1, 1); + + // VRC7 + label_audio_volume[9] = gtk_widget_new(GTK_TYPE_LABEL, "label", "VRC7", NULL); + adj_audio_volume[9] = gtk_adjustment_new(conf.audio_vol_vrc7, 0, 100, 1, 5, 0); + scale_audio_volume[9] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[9], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[9], 3, 2, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[9], 3, 3, 1, 1); + + // N163 + label_audio_volume[10] = gtk_widget_new(GTK_TYPE_LABEL, "label", "N163", NULL); + adj_audio_volume[10] = gtk_adjustment_new(conf.audio_vol_n163, 0, 100, 1, 5, 0); + scale_audio_volume[10] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[10], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[10], 4, 2, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[10], 4, 3, 1, 1); + + // S5B + label_audio_volume[11] = gtk_widget_new(GTK_TYPE_LABEL, "label", "S5B", NULL); + adj_audio_volume[11] = gtk_adjustment_new(conf.audio_vol_s5b, 0, 100, 1, 5, 0); + scale_audio_volume[11] = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_CENTER, + "orientation", GTK_ORIENTATION_VERTICAL, + "adjustment", adj_audio_volume[11], + "width-request", 32, + "height-request", 100, + "inverted", TRUE, + "digits", 0, + NULL); + + gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[11], 5, 2, 1, 1); + gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[11], 5, 3, 1, 1); + + // Set the callbacks for every control but master + for (int i = 1; i < NUMCHANNELS; i++) { + g_signal_connect(G_OBJECT(scale_audio_volume[i]), "value-changed", + G_CALLBACK(gtkui_audio_volume), NULL); + } + + // Pack the grid into the box + gtk_box_pack_start(GTK_BOX(box_audio), grid_audio_volume, FALSE, FALSE, 0); + + // Input // + GtkWidget *box_input = gtk_widget_new( + GTK_TYPE_BOX, + "orientation", GTK_ORIENTATION_HORIZONTAL, + "margin-top", MARGIN_TB, + "margin-bottom", MARGIN_TB, + NULL); + + // NES Controller + GtkWidget *box_input_l = gtk_widget_new(GTK_TYPE_BOX, "halign", GTK_ALIGN_START, "orientation", GTK_ORIENTATION_VERTICAL, NULL); + GtkWidget *nespad = gtk_widget_new( + GTK_TYPE_IMAGE, + "halign", GTK_ALIGN_CENTER, + "expand", FALSE, + "file", padpath, + "margin", MARGIN_TB, + NULL); + gtk_box_pack_start(GTK_BOX(box_input_l), nespad, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_input), box_input_l, FALSE, FALSE, 0); + + // Turbo Pulse + GtkAdjustment *adj_input_turbopulse = gtk_adjustment_new(conf.timing_turbopulse, 2, 9, 1, 5, 0); + GtkWidget *box_input_turbopulse = gtk_widget_new( + GTK_TYPE_BOX, + "halign", GTK_ALIGN_END, + "orientation", GTK_ORIENTATION_HORIZONTAL, + "margin-bottom", MARGIN_TB, + "margin-right", MARGIN_LR, + NULL); + GtkWidget *label_input_turbopulse = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "Turbo Pulse", + "halign", GTK_ALIGN_START, + "margin-top", MARGIN_TB, + "margin-right", MARGIN_LR, + NULL); + GtkWidget *scale_input_turbopulse = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_START, + "orientation", GTK_ORIENTATION_HORIZONTAL, + "adjustment", adj_input_turbopulse, + "width-request", 60, + "height-request", 32, + "digits", 0, + NULL); + gtk_box_pack_start(GTK_BOX(box_input_turbopulse), label_input_turbopulse, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_input_turbopulse), scale_input_turbopulse, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_input_l), box_input_turbopulse, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(scale_input_turbopulse), "value-changed", + G_CALLBACK(gtkui_cb_input_turbopulse), NULL); + + // Options Box + GtkWidget *box_input_r = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + gtk_box_pack_start(GTK_BOX(box_input), box_input_r, FALSE, FALSE, 0); + + // Player Select + combo_input_player = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_END, + "margin-top", MARGIN_TB, + "margin-bottom", MARGIN_TB, + "margin-right", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT (combo_input_player), "Player 1"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT (combo_input_player), "Player 2"); + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_input_player), 0); + gtk_box_pack_start(GTK_BOX(box_input_l), combo_input_player, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_input_player), "changed", + G_CALLBACK(gtkui_config_input_refresh), NULL); + + // Device Type Select + combo_input_type = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_END, + "margin-top", MARGIN_TB, + "margin-bottom", MARGIN_TB, + "margin-right", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT (combo_input_type), "Keyboard"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT (combo_input_type), "Joystick"); + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_input_type), 0); + gtk_box_pack_start(GTK_BOX(box_input_l), combo_input_type, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_input_type), "changed", + G_CALLBACK(gtkui_config_input_refresh), NULL); + + // The Treeview + GtkWidget *treeview = gtk_widget_new(GTK_TYPE_TREE_VIEW, + "margin-top", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_tree_view_set_fixed_height_mode(GTK_TREE_VIEW (treeview), FALSE); + gtk_tree_view_set_enable_search(GTK_TREE_VIEW(treeview), FALSE); + + treestore_input = gtk_tree_store_new(2, G_TYPE_STRING, G_TYPE_STRING); + + gtk_tree_view_set_model(GTK_TREE_VIEW(treeview), GTK_TREE_MODEL(treestore_input)); + + GtkTreeIter iter; + GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); + + GtkTreeViewColumn *columns[2]; + columns[0] = gtk_tree_view_column_new_with_attributes( + "Button", renderer, "text", 0, NULL); + + columns[1] = gtk_tree_view_column_new_with_attributes( + "Mapping", renderer, "text", 1, NULL); + gtk_tree_view_column_set_expand(columns[1], TRUE); + + gtk_tree_view_append_column(GTK_TREE_VIEW (treeview), columns[0]); + gtk_tree_view_append_column(GTK_TREE_VIEW (treeview), columns[1]); + + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Up", 1, gdk_keyval_name(pad[0].u), -1); + + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Down", 1, gdk_keyval_name(pad[0].d), -1); + + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Left", 1, gdk_keyval_name(pad[0].l), -1); + + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Right", 1, gdk_keyval_name(pad[0].r), -1); + + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Select", 1, gdk_keyval_name(pad[0].select), -1); + + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Start", 1, gdk_keyval_name(pad[0].start), -1); + + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "A", 1, gdk_keyval_name(pad[0].a), -1); + + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "B", 1, gdk_keyval_name(pad[0].b), -1); + + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Turbo A", 1, gdk_keyval_name(pad[0].ta), -1); + + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Turbo B", 1, gdk_keyval_name(pad[0].tb), -1); + + gtk_box_pack_start(GTK_BOX(box_input_r), treeview, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(treeview), "row-activated", + G_CALLBACK(gtkui_config_input_activate), NULL); + + // The Input Defaults button + GtkWidget *inputdefaults = gtk_widget_new( + GTK_TYPE_BUTTON, + "label", "Defaults", + "halign", GTK_ALIGN_START, + "margin-top", MARGIN_TB * 2, + "margin-left", MARGIN_LR, + NULL); + gtk_box_pack_start(GTK_BOX(box_input_r), inputdefaults, FALSE, FALSE, 0); + + // Connect the button to a callback + g_signal_connect(G_OBJECT(inputdefaults), "clicked", + G_CALLBACK(gtkui_config_input_defaults), NULL); + + // Misc // + GtkWidget *box_misc = gtk_widget_new( + GTK_TYPE_BOX, + "orientation", GTK_ORIENTATION_VERTICAL, + "margin-top", MARGIN_TB, + "margin-bottom", MARGIN_TB, + NULL); + + // Default System + GtkWidget *box_misc_default_system = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_misc_default_system = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "Default System:", + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + GtkWidget *combo_misc_default_system = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_default_system), "Auto"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_default_system), "NTSC"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_default_system), "PAL"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_default_system), "Famicom"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_default_system), "Dendy"); + + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_misc_default_system), conf.misc_default_system); + + gtk_box_pack_start(GTK_BOX(box_misc_default_system), label_misc_default_system, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_misc_default_system), combo_misc_default_system, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_misc), box_misc_default_system, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_misc_default_system), "changed", + G_CALLBACK(gtkui_cb_misc_default_system), NULL); + + // RAM Power-on State + GtkWidget *box_misc_power_state = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_misc_power_state = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "RAM Power-on State:", + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + GtkWidget *combo_misc_power_state = gtk_widget_new( + GTK_TYPE_COMBO_BOX_TEXT, + "halign", GTK_ALIGN_START, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + NULL); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_power_state), "0x00"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_power_state), "0xFF"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_power_state), "Random"); + + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_misc_power_state), conf.misc_power_state); + + gtk_box_pack_start(GTK_BOX(box_misc_power_state), label_misc_power_state, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_misc_power_state), combo_misc_power_state, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_misc), box_misc_power_state, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(combo_misc_power_state), "changed", + G_CALLBACK(gtkui_cb_misc_power_state), NULL); + + // Alternate Speed + GtkAdjustment *adj_timing_ffspeed = gtk_adjustment_new(conf.timing_ffspeed, 1, 8, 1, 5, 0); + GtkWidget *box_timing_ffspeed = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget *label_timing_ffspeed = gtk_widget_new( + GTK_TYPE_LABEL, + "label", "Fast-Forward Speed", + "halign", GTK_ALIGN_START, + "margin-top", MARGIN_TB, + "margin-bottom", MARGIN_TB, + "margin-left", MARGIN_LR, + "margin-right", MARGIN_LR, + NULL); + GtkWidget *scale_timing_ffspeed = gtk_widget_new( + GTK_TYPE_SCALE, + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + "orientation", GTK_ORIENTATION_HORIZONTAL, + "adjustment", adj_timing_ffspeed, + "width-request", 64, + "height-request", 32, + "digits", 0, + NULL); + gtk_box_pack_start(GTK_BOX(box_timing_ffspeed), label_timing_ffspeed, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_timing_ffspeed), scale_timing_ffspeed, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_misc), box_timing_ffspeed, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(scale_timing_ffspeed), "value-changed", + G_CALLBACK(gtkui_cb_timing_ffspeed), NULL); + + // Core Overclocking + GtkWidget *check_misc_overclock = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Core Overclocking (Requires Restart)", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_overclock), conf.misc_overclock); + + gtk_box_pack_start(GTK_BOX(box_misc), check_misc_overclock, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_misc_overclock), "toggled", + G_CALLBACK(gtkui_cb_misc_overclock), NULL); + + // Vsync + GtkWidget *check_timing_vsync = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Vsync", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_timing_vsync), conf.timing_vsync); + + gtk_box_pack_start(GTK_BOX(box_misc), check_timing_vsync, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_timing_vsync), "toggled", + G_CALLBACK(gtkui_cb_timing_vsync), NULL); + + // Limiter + GtkWidget *check_timing_limiter = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Speed Limiter", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_timing_limiter), conf.timing_limiter); + + gtk_box_pack_start(GTK_BOX(box_misc), check_timing_limiter, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_timing_limiter), "toggled", + G_CALLBACK(gtkui_cb_timing_limiter), NULL); + + // Soft Patching + GtkWidget *check_misc_soft_patching = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Automatic Soft Patching", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_soft_patching), conf.misc_soft_patching); + + gtk_box_pack_start(GTK_BOX(box_misc), check_misc_soft_patching, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_misc_soft_patching), "toggled", + G_CALLBACK(gtkui_cb_misc_soft_patching), NULL); + + // Game Genie Sound Distortion + GtkWidget *check_misc_genie_distortion = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Game Genie Sound Distortion", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_genie_distortion), conf.misc_genie_distortion); + + gtk_box_pack_start(GTK_BOX(box_misc), check_misc_genie_distortion, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_misc_genie_distortion), "toggled", + G_CALLBACK(gtkui_cb_misc_genie_distortion), NULL); + + // Disable Cursor + GtkWidget *check_misc_disable_cursor = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Disable Cursor", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_disable_cursor), conf.misc_disable_cursor); + + gtk_box_pack_start(GTK_BOX(box_misc), check_misc_disable_cursor, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_misc_disable_cursor), "toggled", + G_CALLBACK(gtkui_cb_misc_disable_cursor), NULL); + + // Disable Special Cursor + GtkWidget *check_misc_disable_cursor_special = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Disable Special Cursor", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_disable_cursor_special), conf.misc_disable_cursor_special); + + gtk_box_pack_start(GTK_BOX(box_misc), check_misc_disable_cursor_special, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_misc_disable_cursor_special), "toggled", + G_CALLBACK(gtkui_cb_misc_disable_cursor_special), NULL); + + // Pause While Configuration Open + GtkWidget *check_misc_config_pause = gtk_widget_new( + GTK_TYPE_CHECK_BUTTON, + "label", "Pause While Configuration Open", + "halign", GTK_ALIGN_START, + "margin-left", MARGIN_LR, + NULL); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_config_pause), conf.misc_config_pause); + + gtk_box_pack_start(GTK_BOX(box_misc), check_misc_config_pause, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(check_misc_config_pause), "toggled", + G_CALLBACK(gtkui_cb_misc_config_pause), NULL); + + // Structuring the notebook + GtkWidget *label_video = gtk_label_new("Video"); + GtkWidget *label_audio = gtk_label_new("Audio"); + GtkWidget *label_input = gtk_label_new("Input"); + GtkWidget *label_misc = gtk_label_new("Misc"); + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), box_video, label_video); + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), box_audio, label_audio); + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), box_input, label_input); + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), box_misc, label_misc); + + // The OK button + GtkWidget *okbutton = gtk_widget_new( + GTK_TYPE_BUTTON, + "label", "OK", + "halign", GTK_ALIGN_END, + "margin-top", 8, + "margin-bottom", 8, + "margin-right", 8, + NULL); + + // Connect the OK button to a callback + g_signal_connect(G_OBJECT(okbutton), "clicked", + G_CALLBACK(gtkui_config_ok), NULL); + + // Structuring the window + gtk_box_pack_start(GTK_BOX(box_upper), notebook, TRUE, TRUE, 0); + gtk_box_pack_start(GTK_BOX(box_upper), box_lower, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box_lower), okbutton, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(configwindow), "destroy", + G_CALLBACK(gtkui_config_ok), NULL); + + gtk_widget_show_all(configwindow); + + gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), tabnum); + + return configwindow; +} + +void gtkui_config_ok() { + if (confrunning) { confrunning = false; } + tabnum = gtk_notebook_get_current_page(GTK_NOTEBOOK(notebook)); + gtk_widget_destroy(configwindow); + configwindow = NULL; + nst_play(); +} + +void gtkui_audio_volume() { + // Set the audio volume on specific channels + conf.audio_vol_sq1 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[1]); + conf.audio_vol_sq2 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[2]); + conf.audio_vol_tri = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[3]); + conf.audio_vol_noise = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[4]); + conf.audio_vol_dpcm = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[5]); + conf.audio_vol_fds = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[6]); + conf.audio_vol_mmc5 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[7]); + conf.audio_vol_vrc6 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[8]); + conf.audio_vol_vrc7 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[9]); + conf.audio_vol_n163 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[10]); + conf.audio_vol_s5b = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[11]); + audio_adj_volume(); +} + +void gtkui_audio_volume_master() { + // Set the audio volume on all channels + conf.audio_volume = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[0]); + + for (int i = 1; i < NUMCHANNELS; i++) { + gtk_adjustment_set_value(adj_audio_volume[i], gtk_range_get_value((GtkRange*)scale_audio_volume[0])); + } + + gtkui_audio_volume(); +} + +void gtkui_config_input_activate(GtkWidget *widget, GtkTreePath *path, gpointer userdata) { + // React to a button configuration request + GtkTreeIter iter; + GtkTreeModel *model; + GtkTreeSelection *selection; + + int pnum = gtk_combo_box_get_active(GTK_COMBO_BOX(combo_input_player)); + int type = gtk_combo_box_get_active(GTK_COMBO_BOX(combo_input_type)); + + // Get the selected item + selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); + gtk_tree_selection_get_selected(selection, &model, &iter); + + path = gtk_tree_model_get_path(model, &iter); + int bnum = gtk_tree_path_get_indices(path)[0]; + + // Replace the text with the current key + gtk_tree_store_set(treestore_input, &iter, 1, "Set Key...", -1); + + // Set the key + if (type == 0) { // Keyboard + gtkui_input_config_key(pnum, bnum); + } + else { // Joystick + gtkui_input_config_js(pnum, bnum); + } + + // Replace the text with the new key + if (type == 0) { // Keyboard + switch (bnum) { + case 0: + gtk_tree_store_set(treestore_input, &iter, 1, gdk_keyval_name(pad[pnum].u), -1); + break; + case 1: + gtk_tree_store_set(treestore_input, &iter, 1, gdk_keyval_name(pad[pnum].d), -1); + break; + case 2: + gtk_tree_store_set(treestore_input, &iter, 1, gdk_keyval_name(pad[pnum].l), -1); + break; + case 3: + gtk_tree_store_set(treestore_input, &iter, 1, gdk_keyval_name(pad[pnum].r), -1); + break; + case 4: + gtk_tree_store_set(treestore_input, &iter, 1, gdk_keyval_name(pad[pnum].select), -1); + break; + case 5: + gtk_tree_store_set(treestore_input, &iter, 1, gdk_keyval_name(pad[pnum].start), -1); + break; + case 6: + gtk_tree_store_set(treestore_input, &iter, 1, gdk_keyval_name(pad[pnum].a), -1); + break; + case 7: + gtk_tree_store_set(treestore_input, &iter, 1, gdk_keyval_name(pad[pnum].b), -1); + break; + case 8: + gtk_tree_store_set(treestore_input, &iter, 1, gdk_keyval_name(pad[pnum].ta), -1); + break; + case 9: + gtk_tree_store_set(treestore_input, &iter, 1, gdk_keyval_name(pad[pnum].tb), -1); + break; + default: break; + } + } + else { // Joystick + switch (bnum) { + case 0: + gtk_tree_store_set(treestore_input, &iter, 1, nstsdl_input_translate_event(player[pnum].ju), -1); + break; + case 1: + gtk_tree_store_set(treestore_input, &iter, 1, nstsdl_input_translate_event(player[pnum].jd), -1); + break; + case 2: + gtk_tree_store_set(treestore_input, &iter, 1, nstsdl_input_translate_event(player[pnum].jl), -1); + break; + case 3: + gtk_tree_store_set(treestore_input, &iter, 1, nstsdl_input_translate_event(player[pnum].jr), -1); + break; + case 4: + gtk_tree_store_set(treestore_input, &iter, 1, nstsdl_input_translate_event(player[pnum].jselect), -1); + break; + case 5: + gtk_tree_store_set(treestore_input, &iter, 1, nstsdl_input_translate_event(player[pnum].jstart), -1); + break; + case 6: + gtk_tree_store_set(treestore_input, &iter, 1, nstsdl_input_translate_event(player[pnum].ja), -1); + break; + case 7: + gtk_tree_store_set(treestore_input, &iter, 1, nstsdl_input_translate_event(player[pnum].jb), -1); + break; + case 8: + gtk_tree_store_set(treestore_input, &iter, 1, nstsdl_input_translate_event(player[pnum].jta), -1); + break; + case 9: + gtk_tree_store_set(treestore_input, &iter, 1, nstsdl_input_translate_event(player[pnum].jtb), -1); + break; + default: break; + } + } +} + +void gtkui_config_input_refresh() { + // Refresh the input fields + int pnum = gtk_combo_box_get_active(GTK_COMBO_BOX(combo_input_player)); + int type = gtk_combo_box_get_active(GTK_COMBO_BOX(combo_input_type)); + gtkui_config_input_fields(type, pnum); +} + +void gtkui_config_input_fields(int type, int pnum) { + // Set the text in the input fields based on the current settings + GtkTreeIter iter; + + gtk_tree_store_clear(treestore_input); + + if (type == 0) { + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Up", 1, gdk_keyval_name(pad[pnum].u), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Down", 1, gdk_keyval_name(pad[pnum].d), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Left", 1, gdk_keyval_name(pad[pnum].l), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Right", 1, gdk_keyval_name(pad[pnum].r), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Select", 1, gdk_keyval_name(pad[pnum].select), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Start", 1, gdk_keyval_name(pad[pnum].start), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "A", 1, gdk_keyval_name(pad[pnum].a), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "B", 1, gdk_keyval_name(pad[pnum].b), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Turbo A", 1, gdk_keyval_name(pad[pnum].ta), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Turbo B", 1, gdk_keyval_name(pad[pnum].tb), -1); + } + if (type == 1) { + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Up", 1, nstsdl_input_translate_event(player[pnum].ju), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Down", 1, nstsdl_input_translate_event(player[pnum].jd), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Left", 1, nstsdl_input_translate_event(player[pnum].jl), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Right", 1, nstsdl_input_translate_event(player[pnum].jr), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Select", 1, nstsdl_input_translate_event(player[pnum].jselect), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Start", 1, nstsdl_input_translate_event(player[pnum].jstart), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "A", 1, nstsdl_input_translate_event(player[pnum].ja), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "B", 1, nstsdl_input_translate_event(player[pnum].jb), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Turbo A", 1, nstsdl_input_translate_event(player[pnum].jta), -1); + gtk_tree_store_append(treestore_input, &iter, NULL); + gtk_tree_store_set(treestore_input, &iter, 0, "Turbo B", 1, nstsdl_input_translate_event(player[pnum].jtb), -1); + } +} + +void gtkui_config_input_defaults() { + // Restore input defaults + gtkui_input_set_default(); + gtkui_config_input_refresh(); +} diff -Nru nestopia-1.48/source/gtkui/gtkui_config.h nestopia-1.49/source/gtkui/gtkui_config.h --- nestopia-1.48/source/gtkui/gtkui_config.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_config.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,18 @@ +#ifndef _GTKUI_CONFIG_H_ +#define _GTKUI_CONFIG_H_ + +#define MARGIN_TB 5 +#define MARGIN_LR 10 + +#define NUMCHANNELS 12 + +GtkWidget *gtkui_config(); +void gtkui_config_ok(); +void gtkui_audio_volume(); +void gtkui_audio_volume_master(); +void gtkui_config_input_activate(GtkWidget *widget, GtkTreePath *path, gpointer userdata); +void gtkui_config_input_refresh(); +void gtkui_config_input_fields(int type, int pnum); +void gtkui_config_input_defaults(); + +#endif diff -Nru nestopia-1.48/source/gtkui/gtkui.cpp nestopia-1.49/source/gtkui/gtkui.cpp --- nestopia-1.48/source/gtkui/gtkui.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,699 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2018 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include + +#include + +#include "nstcommon.h" +#include "cli.h" +#include "config.h" +#include "audio.h" +#include "video.h" +#include "input.h" + +#include "sdlinput.h" + +#include "gtkui.h" +#include "gtkui_archive.h" +#include "gtkui_callbacks.h" +#include "gtkui_config.h" +#include "gtkui_cheats.h" +#include "gtkui_dialogs.h" +#include "gtkui_input.h" + +GtkWidget *gtkwindow; +static GtkWidget *menubar; +static GtkWidget *drawingarea; + +static GThread *emuthread; + +char iconpath[512]; +char padpath[512]; + +extern bool (*nst_archive_select)(const char*, char*, size_t); + +extern Input::Controllers *cNstPads; +extern nstpaths_t nstpaths; +int nst_quit = 0; + +gpointer gtkui_emuloop(gpointer data) { + while(!nst_quit) { nst_emuloop(); } + g_thread_exit(emuthread); + return NULL; +} + +void gtkui_emuloop_start() { + nst_quit = 0; + emuthread = g_thread_new("emuloop", gtkui_emuloop, NULL); +} + +void gtkui_emuloop_stop() { + nst_quit = true; +} + +void gtkui_quit() { + gtkui_emuloop_stop(); + gtk_main_quit(); +} + +void gtkui_init(int argc, char *argv[]) { + // Initialize the GTK+ GUI + gtk_init(&argc, &argv); + gtkui_create(); +} + +static void gtkui_glarea_realize(GtkGLArea *glarea) { + gtk_gl_area_make_current(glarea); + gtk_gl_area_set_has_depth_buffer(glarea, FALSE); + nst_ogl_init(); +} + +static void gtkui_swapbuffers() { + gtk_widget_queue_draw(drawingarea); + gtk_widget_queue_draw(menubar); // Needed on some builds of GTK+3 + nst_ogl_render(); + nst_emuloop(); + + // Move this later FIXME + SDL_Event event; + while (SDL_PollEvent(&event)) { + switch (event.type) { + case SDL_JOYHATMOTION: + case SDL_JOYAXISMOTION: + case SDL_JOYBUTTONDOWN: + case SDL_JOYBUTTONUP: + nstsdl_input_process(cNstPads, event); + break; + default: break; + } + } +} + +void gtkui_state_quickload(GtkWidget *widget, gpointer userdata) { + // Wrapper function to quickload states + nst_state_quickload(GPOINTER_TO_INT(userdata)); +} + +void gtkui_state_quicksave(GtkWidget *widget, gpointer userdata) { + // Wrapper function to quicksave states + nst_state_quicksave(GPOINTER_TO_INT(userdata)); +} + +void gtkui_open_recent(GtkWidget *widget, gpointer userdata) { + // Open a recently used item + gchar *uri = gtk_recent_chooser_get_current_uri((GtkRecentChooser*)widget); + nst_load(g_filename_from_uri(uri, NULL, NULL)); + gtkui_set_title(nstpaths.gamename); + gtkui_play(); +} + +dimensions_t gtkui_video_get_dimensions() { + // Return the dimensions of the current screen + dimensions_t scrsize; + GdkDisplay *display = gdk_display_get_default(); + GdkWindow *gdkwindow = gtk_widget_get_window(GTK_WIDGET(gtkwindow)); + GdkMonitor *monitor = gdk_display_get_monitor_at_window(display, gdkwindow); + GdkRectangle geom; + gdk_monitor_get_geometry(monitor, &geom); + scrsize.w = geom.width; + scrsize.h = geom.height; + return scrsize; +} + +void gtkui_create() { + // Create the GTK+ Window + + gtkui_image_paths(); + GdkPixbuf *icon = gdk_pixbuf_new_from_file(iconpath, NULL); + + char title[24]; + snprintf(title, sizeof(title), "Nestopia UE %s", VERSION); + + gtkwindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_icon(GTK_WINDOW(gtkwindow), icon); + gtk_window_set_title(GTK_WINDOW(gtkwindow), title); + gtk_window_set_resizable(GTK_WINDOW(gtkwindow), FALSE); + + GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + gtk_container_add(GTK_CONTAINER(gtkwindow), box); + + // Define the menubar and menus + menubar = gtk_menu_bar_new(); + + // Define the File menu + GtkWidget *filemenu = gtk_menu_new(); + GtkWidget *file = gtk_menu_item_new_with_label("File"); + GtkWidget *open = gtk_menu_item_new_with_label("Open..."); + GtkWidget *recent = gtk_menu_item_new_with_label("Open Recent"); + GtkWidget *sep_open = gtk_separator_menu_item_new(); + GtkWidget *stateload = gtk_menu_item_new_with_label("Load State..."); + GtkWidget *statesave = gtk_menu_item_new_with_label("Save State..."); + + GtkWidget *quickload = gtk_menu_item_new_with_label("Quick Load"); + GtkWidget *qloadmenu = gtk_menu_new(); + GtkWidget *qload0 = gtk_menu_item_new_with_label("0"); + GtkWidget *qload1 = gtk_menu_item_new_with_label("1"); + GtkWidget *qload2 = gtk_menu_item_new_with_label("2"); + GtkWidget *qload3 = gtk_menu_item_new_with_label("3"); + GtkWidget *qload4 = gtk_menu_item_new_with_label("4"); + + GtkWidget *quicksave = gtk_menu_item_new_with_label("Quick Save"); + GtkWidget *qsavemenu = gtk_menu_new(); + GtkWidget *qsave0 = gtk_menu_item_new_with_label("0"); + GtkWidget *qsave1 = gtk_menu_item_new_with_label("1"); + GtkWidget *qsave2 = gtk_menu_item_new_with_label("2"); + GtkWidget *qsave3 = gtk_menu_item_new_with_label("3"); + GtkWidget *qsave4 = gtk_menu_item_new_with_label("4"); + + GtkWidget *sep_state = gtk_separator_menu_item_new(); + GtkWidget *palette = gtk_menu_item_new_with_label("Open Palette..."); + GtkWidget *sep_palette = gtk_separator_menu_item_new(); + GtkWidget *screenshot = gtk_menu_item_new_with_label("Screenshot..."); + GtkWidget *sep_screenshot = gtk_separator_menu_item_new(); + GtkWidget *movieload = gtk_menu_item_new_with_label("Load Movie..."); + GtkWidget *moviesave = gtk_menu_item_new_with_label("Record Movie..."); + GtkWidget *moviestop = gtk_menu_item_new_with_label("Stop Movie"); + GtkWidget *sep_movie = gtk_separator_menu_item_new(); + GtkWidget *quit = gtk_menu_item_new_with_label("Quit"); + + // Set up the recently used items + GtkWidget *recent_items = gtk_recent_chooser_menu_new(); + GtkRecentFilter *recent_filter = gtk_recent_filter_new(); + gtk_recent_filter_add_pattern(recent_filter, "*.nes"); + gtk_recent_filter_add_pattern(recent_filter, "*.fds"); + gtk_recent_filter_add_pattern(recent_filter, "*.unf"); + gtk_recent_filter_add_pattern(recent_filter, "*.unif"); + gtk_recent_filter_add_pattern(recent_filter, "*.nsf"); + gtk_recent_filter_add_pattern(recent_filter, "*.zip"); + gtk_recent_filter_add_pattern(recent_filter, "*.7z"); + gtk_recent_filter_add_pattern(recent_filter, "*.txz"); + gtk_recent_filter_add_pattern(recent_filter, "*.tar.xz"); + gtk_recent_filter_add_pattern(recent_filter, "*.xz"); + gtk_recent_filter_add_pattern(recent_filter, "*.tgz"); + gtk_recent_filter_add_pattern(recent_filter, "*.tar.gz"); + gtk_recent_filter_add_pattern(recent_filter, "*.gz"); + gtk_recent_filter_add_pattern(recent_filter, "*.tbz"); + gtk_recent_filter_add_pattern(recent_filter, "*.tar.bz2"); + gtk_recent_filter_add_pattern(recent_filter, "*.bz2"); + gtk_recent_chooser_add_filter(GTK_RECENT_CHOOSER(recent_items), recent_filter); + + // Populate the File menu + gtk_menu_item_set_submenu(GTK_MENU_ITEM(file), filemenu); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), open); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), recent); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(recent), recent_items); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), sep_open); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), stateload); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), statesave); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), quickload); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(quickload), qloadmenu); + gtk_menu_shell_append(GTK_MENU_SHELL(qloadmenu), qload0); + gtk_menu_shell_append(GTK_MENU_SHELL(qloadmenu), qload1); + gtk_menu_shell_append(GTK_MENU_SHELL(qloadmenu), qload2); + gtk_menu_shell_append(GTK_MENU_SHELL(qloadmenu), qload3); + gtk_menu_shell_append(GTK_MENU_SHELL(qloadmenu), qload4); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), quicksave); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(quicksave), qsavemenu); + gtk_menu_shell_append(GTK_MENU_SHELL(qsavemenu), qsave0); + gtk_menu_shell_append(GTK_MENU_SHELL(qsavemenu), qsave1); + gtk_menu_shell_append(GTK_MENU_SHELL(qsavemenu), qsave2); + gtk_menu_shell_append(GTK_MENU_SHELL(qsavemenu), qsave3); + gtk_menu_shell_append(GTK_MENU_SHELL(qsavemenu), qsave4); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), sep_state); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), palette); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), sep_palette); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), screenshot); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), sep_screenshot); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), movieload); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), moviesave); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), moviestop); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), sep_movie); + gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), quit); + + // Define the Emulator menu + GtkWidget *emulatormenu = gtk_menu_new(); + GtkWidget *emu = gtk_menu_item_new_with_label("Emulator"); + GtkWidget *cont = gtk_menu_item_new_with_label("Continue"); + GtkWidget *pause = gtk_menu_item_new_with_label("Pause"); + GtkWidget *sep_pause = gtk_separator_menu_item_new(); + GtkWidget *resetsoft = gtk_menu_item_new_with_label("Reset (Soft)"); + GtkWidget *resethard = gtk_menu_item_new_with_label("Reset (Hard)"); + GtkWidget *sep_reset = gtk_separator_menu_item_new(); + GtkWidget *fullscreen = gtk_menu_item_new_with_label("Fullscreen"); + GtkWidget *sep_fullscreen = gtk_separator_menu_item_new(); + GtkWidget *diskflip = gtk_menu_item_new_with_label("Flip FDS Disk"); + GtkWidget *diskswitch = gtk_menu_item_new_with_label("Switch FDS Disk"); + GtkWidget *sep_disk = gtk_separator_menu_item_new(); + GtkWidget *cheats = gtk_menu_item_new_with_label("Cheats..."); + GtkWidget *sep_cheats = gtk_separator_menu_item_new(); + GtkWidget *configuration = gtk_menu_item_new_with_label("Configuration..."); + + // Populate the Emulator menu + gtk_menu_item_set_submenu(GTK_MENU_ITEM(emu), emulatormenu); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), cont); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), pause); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), sep_pause); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), resetsoft); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), resethard); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), sep_reset); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), fullscreen); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), sep_fullscreen); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), diskflip); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), diskswitch); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), sep_disk); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), cheats); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), sep_cheats); + gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), configuration); + + // Define the Help menu + GtkWidget *helpmenu = gtk_menu_new(); + GtkWidget *help = gtk_menu_item_new_with_label("Help"); + GtkWidget *about = gtk_menu_item_new_with_label("About"); + + // Populate the Help menu + gtk_menu_item_set_submenu(GTK_MENU_ITEM(help), helpmenu); + gtk_menu_shell_append(GTK_MENU_SHELL(helpmenu), about); + + // Put the menus into the menubar + gtk_menu_shell_append(GTK_MENU_SHELL(menubar), file); + gtk_menu_shell_append(GTK_MENU_SHELL(menubar), emu); + gtk_menu_shell_append(GTK_MENU_SHELL(menubar), help); + + // Create the DrawingArea/OpenGL context + ///drawingarea = gtk_drawing_area_new(); + drawingarea = gtk_gl_area_new(); + g_signal_connect(G_OBJECT(drawingarea), "realize", G_CALLBACK(gtkui_glarea_realize), NULL); + g_signal_connect(G_OBJECT(drawingarea), "render", gtkui_swapbuffers, NULL); + //gtk_widget_add_tick_callback(drawingarea, gtkui_tick, drawingarea, NULL); + + g_object_set_data(G_OBJECT(gtkwindow), "area", drawingarea); + + // Set the Drawing Area to be the size of the game output + dimensions_t rendersize = nst_video_get_dimensions_render(); + gtk_widget_set_size_request(drawingarea, rendersize.w, rendersize.h); + + // Pack the box with the menubar, drawingarea, and statusbar + gtk_box_pack_start(GTK_BOX(box), menubar, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(box), drawingarea, TRUE, TRUE, 0); + + // Make it dark if there's a dark theme + GtkSettings *gtksettings = gtk_settings_get_default(); + g_object_set(G_OBJECT(gtksettings), "gtk-application-prefer-dark-theme", TRUE, NULL); + + // Set up the Drag and Drop target + GtkTargetEntry target_entry[1]; + + target_entry[0].target = (gchar*)"text/uri-list"; + target_entry[0].flags = 0; + target_entry[0].info = 0; + + gtk_drag_dest_set(drawingarea, (GtkDestDefaults)(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT | GTK_DEST_DEFAULT_DROP), + target_entry, sizeof(target_entry) / sizeof(GtkTargetEntry), (GdkDragAction)(GDK_ACTION_MOVE | GDK_ACTION_COPY)); + + // Connect the signals + g_signal_connect(G_OBJECT(drawingarea), "drag-data-received", + G_CALLBACK(gtkui_drag_data), NULL); + + g_signal_connect(G_OBJECT(gtkwindow), "delete_event", + G_CALLBACK(gtkui_quit), NULL); + + // File menu + g_signal_connect(G_OBJECT(open), "activate", + G_CALLBACK(gtkui_file_open), NULL); + + g_signal_connect(G_OBJECT(recent_items), "item-activated", + G_CALLBACK(gtkui_open_recent), NULL); + + g_signal_connect(G_OBJECT(stateload), "activate", + G_CALLBACK(gtkui_state_load), NULL); + + g_signal_connect(G_OBJECT(statesave), "activate", + G_CALLBACK(gtkui_state_save), NULL); + + g_signal_connect(G_OBJECT(qload0), "activate", + G_CALLBACK(gtkui_state_quickload), gpointer(0)); + + g_signal_connect(G_OBJECT(qload1), "activate", + G_CALLBACK(gtkui_state_quickload), gpointer(1)); + + g_signal_connect(G_OBJECT(qload2), "activate", + G_CALLBACK(gtkui_state_quickload), gpointer(2)); + + g_signal_connect(G_OBJECT(qload3), "activate", + G_CALLBACK(gtkui_state_quickload), gpointer(3)); + + g_signal_connect(G_OBJECT(qload4), "activate", + G_CALLBACK(gtkui_state_quickload), gpointer(4)); + + g_signal_connect(G_OBJECT(qsave0), "activate", + G_CALLBACK(gtkui_state_quicksave), gpointer(0)); + + g_signal_connect(G_OBJECT(qsave1), "activate", + G_CALLBACK(gtkui_state_quicksave), gpointer(1)); + + g_signal_connect(G_OBJECT(qsave2), "activate", + G_CALLBACK(gtkui_state_quicksave), gpointer(2)); + + g_signal_connect(G_OBJECT(qsave3), "activate", + G_CALLBACK(gtkui_state_quicksave), gpointer(3)); + + g_signal_connect(G_OBJECT(qsave4), "activate", + G_CALLBACK(gtkui_state_quicksave), gpointer(4)); + + g_signal_connect(G_OBJECT(screenshot), "activate", + G_CALLBACK(gtkui_screenshot_save), NULL); + + g_signal_connect(G_OBJECT(palette), "activate", + G_CALLBACK(gtkui_palette_load), NULL); + + g_signal_connect(G_OBJECT(moviesave), "activate", + G_CALLBACK(gtkui_movie_save), NULL); + + g_signal_connect(G_OBJECT(movieload), "activate", + G_CALLBACK(gtkui_movie_load), NULL); + + g_signal_connect(G_OBJECT(moviestop), "activate", + G_CALLBACK(gtkui_movie_stop), NULL); + + g_signal_connect(G_OBJECT(quit), "activate", + G_CALLBACK(gtkui_quit), NULL); + + // Emulator menu + g_signal_connect(G_OBJECT(cont), "activate", + G_CALLBACK(gtkui_play), NULL); + + g_signal_connect(G_OBJECT(pause), "activate", + G_CALLBACK(gtkui_pause), NULL); + + g_signal_connect(G_OBJECT(resetsoft), "activate", + G_CALLBACK(gtkui_cb_reset), gpointer(0)); + + g_signal_connect(G_OBJECT(resethard), "activate", + G_CALLBACK(gtkui_cb_reset), gpointer(1)); + + g_signal_connect(G_OBJECT(fullscreen), "activate", + G_CALLBACK(gtkui_video_toggle_fullscreen), NULL); + + g_signal_connect(G_OBJECT(diskflip), "activate", + G_CALLBACK(nst_fds_flip), NULL); + + g_signal_connect(G_OBJECT(diskswitch), "activate", + G_CALLBACK(nst_fds_switch), NULL); + + g_signal_connect(G_OBJECT(cheats), "activate", + G_CALLBACK(gtkui_cheats), NULL); + + g_signal_connect(G_OBJECT(configuration), "activate", + G_CALLBACK(gtkui_config), NULL); + + // Help menu + g_signal_connect(G_OBJECT(about), "activate", + G_CALLBACK(gtkui_about), NULL); + + // Mouse input events + gtk_widget_add_events(GTK_WIDGET(drawingarea), GDK_BUTTON_PRESS_MASK); + gtk_widget_add_events(GTK_WIDGET(drawingarea), GDK_BUTTON_RELEASE_MASK); + + gtk_widget_show_all(gtkwindow); + + nst_video_set_dimensions_screen(gtkui_video_get_dimensions()); + + if (conf.video_fullscreen) { gtkui_video_toggle_fullscreen(); } +} + +void gtkui_signals_init() { + // Key translation + if (nst_nsf()) { + g_signal_connect(G_OBJECT(gtkwindow), "key-press-event", + G_CALLBACK(gtkui_input_process_key_nsf), NULL); + + g_signal_connect(G_OBJECT(gtkwindow), "key-release-event", + G_CALLBACK(gtkui_input_process_key_nsf), NULL); + } + else { + g_signal_connect(G_OBJECT(gtkwindow), "key-press-event", + G_CALLBACK(gtkui_input_process_key), NULL); + + g_signal_connect(G_OBJECT(gtkwindow), "key-release-event", + G_CALLBACK(gtkui_input_process_key), NULL); + } + // Mouse translation + g_signal_connect(G_OBJECT(drawingarea), "button-press-event", + G_CALLBACK(gtkui_input_process_mouse), NULL); + + g_signal_connect(G_OBJECT(drawingarea), "button-release-event", + G_CALLBACK(gtkui_input_process_mouse), NULL); +} + +void gtkui_signals_deinit() { + // Key translation + g_signal_connect(G_OBJECT(gtkwindow), "key-press-event", + gtkui_input_null, NULL); + + g_signal_connect(G_OBJECT(gtkwindow), "key-release-event", + gtkui_input_null, NULL); + + // Mouse translation + g_signal_connect(G_OBJECT(drawingarea), "button-press-event", + gtkui_input_null, NULL); + + g_signal_connect(G_OBJECT(drawingarea), "button-release-event", + gtkui_input_null, NULL); +} + +void gtkui_resize() { + // Resize the GTK+ window + if (gtkwindow) { + video_set_dimensions(); + dimensions_t rendersize = nst_video_get_dimensions_render(); + gtk_widget_set_size_request(drawingarea, rendersize.w, rendersize.h); + } +} + +void gtkui_set_title(const char *title) { + gtk_window_set_title(GTK_WINDOW(gtkwindow), title); +} + +void gtkui_video_toggle_fullscreen() { + + video_toggle_fullscreen(); + + if (conf.video_fullscreen) { + gtk_widget_hide(menubar); + gtk_window_fullscreen(GTK_WINDOW(gtkwindow)); + if (nst_input_zapper_present()) { + gtkui_cursor_set(conf.misc_disable_cursor_special ? 0 : 2); + } + else {gtkui_cursor_set(0); } + } + else { + gtk_window_unfullscreen(GTK_WINDOW(gtkwindow)); + gtk_widget_show(menubar); + if (nst_input_zapper_present()) { + gtkui_cursor_set(conf.misc_disable_cursor_special ? 0 : 2); + } + else {gtkui_cursor_set(1); } + } + nst_video_set_dimensions_screen(gtkui_video_get_dimensions()); + video_init(); + gtkui_resize(); +} + +void gtkui_video_toggle_filter() { + video_toggle_filter(); + gtkui_resize(); + video_init(); +} + +void gtkui_video_toggle_scale() { + video_toggle_scalefactor(); + gtkui_resize(); + video_init(); +} + +GtkWidget *gtkui_about() { + // Pull up the About dialog + GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file_at_size(iconpath, 192, 192, NULL); + GtkWidget *aboutdialog = gtk_about_dialog_new(); + gtk_window_set_transient_for(GTK_WINDOW(aboutdialog), GTK_WINDOW(gtkwindow)); + + gtk_about_dialog_set_logo(GTK_ABOUT_DIALOG(aboutdialog), pixbuf); + gtk_about_dialog_set_program_name(GTK_ABOUT_DIALOG(aboutdialog), "Nestopia UE"); + gtk_about_dialog_set_version(GTK_ABOUT_DIALOG(aboutdialog), VERSION); + gtk_about_dialog_set_comments(GTK_ABOUT_DIALOG(aboutdialog), "Cycle-Accurate Nintendo Entertainment System Emulator"); + gtk_about_dialog_set_website(GTK_ABOUT_DIALOG(aboutdialog), "http://0ldsk00l.ca/nestopia/"); + gtk_about_dialog_set_copyright(GTK_ABOUT_DIALOG(aboutdialog), "(c) 2012-2018, R. Danbrook\n(c) 2007-2008, R. Belmont\n(c) 2003-2008, Martin Freij\n\nIcon based on art from Trollekop"); + gtk_dialog_run(GTK_DIALOG(aboutdialog)); + gtk_widget_destroy(aboutdialog); + + return aboutdialog; +} + +void gtkui_image_paths() { + // Set paths to SVG icons/images + snprintf(iconpath, sizeof(iconpath), "%s/icons/hicolor/scalable/apps/nestopia.svg", DATAROOTDIR); + snprintf(padpath, sizeof(padpath), "%s/icons/hicolor/scalable/apps/nespad.svg", DATAROOTDIR); + + // Load the SVG from local source dir if make install hasn't been done + struct stat svgstat; + if (stat(iconpath, &svgstat) == -1) { + snprintf(iconpath, sizeof(iconpath), "icons/svg/nestopia.svg"); + } + if (stat(padpath, &svgstat) == -1) { + snprintf(padpath, sizeof(padpath), "icons/svg/nespad.svg"); + } +} + +void gtkui_message(const char* message) { + GtkWidget *messagewindow = gtk_message_dialog_new( + GTK_WINDOW(gtkwindow), + GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_INFO, + GTK_BUTTONS_OK, + "%s", message); + gtk_dialog_run(GTK_DIALOG(messagewindow)); + gtk_widget_destroy(messagewindow); +} + +void gtkui_cursor_set(int curtype) { + // Set the cursor + GdkCursor *cursor; + GdkDisplay *display = gdk_display_get_default(); + + switch (curtype) { + case 0: cursor = gdk_cursor_new_from_name(display, "none"); break; + case 1: cursor = gdk_cursor_new_from_name(display, "default"); break; + case 2: cursor = gdk_cursor_new_from_name(display, "crosshair"); break; + default: cursor = gdk_cursor_new_from_name(display, "default"); break; + } + + GdkWindow *gdkwindow = gtk_widget_get_window(GTK_WIDGET(drawingarea)); + gdk_window_set_cursor(gdkwindow, cursor); + gdk_display_flush(display); + g_object_unref(cursor); +} + +void gtkui_play() { + gtkui_signals_init(); + nst_play(); + //gtkui_emuloop_start(); + if (nst_input_zapper_present()) { + gtkui_cursor_set(conf.misc_disable_cursor_special ? 0 : 2); + } + else { + gtkui_cursor_set(conf.misc_disable_cursor ? 0 : 1); + } +} + +void gtkui_pause() { + gtkui_signals_deinit(); + //gtkui_emuloop_stop(); + nst_pause(); +} + +int main(int argc, char *argv[]) { + + // Set up directories + nst_set_dirs(); + + // Set default config options + config_set_default(); + + // Read the config file and override defaults + config_file_read(nstpaths.nstdir); + + // Handle command line arguments + cli_handle_command(argc, argv); + + // Set default input keys + gtkui_input_set_default(); + + // Read the input config file and override defaults + gtkui_input_config_read(); + + // Set the video dimensions + video_set_dimensions(); + + // Set up callbacks + nst_set_callbacks(); + + // Initialize SDL Audio and Joystick + if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) < 0) { + fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); + return 1; + } + + // Set archive handler function pointer + nst_archive_select = >kui_archive_select; + + // Set audio function pointers + audio_set_funcs(); + + // Detect and set up Joysticks + nstsdl_input_joysticks_detect(); + nstsdl_input_conf_defaults(); + nstsdl_input_conf_read(); + + // Initialize and load FDS BIOS and NstDatabase.xml + nst_fds_bios_load(); + nst_db_load(); + + gtkui_init(argc, argv); + + // Load a rom from the command line + if (argc > 1) { + nst_load(argv[argc - 1]); + gtkui_play(); + gtkui_set_title(nstpaths.gamename); + } + + // Start GTK+ main loop + gtk_main(); + + // Remove the cartridge and shut down the NES + nst_unload(); + + // Unload the FDS BIOS, NstDatabase.xml, and the custom palette + nst_db_unload(); + nst_fds_bios_unload(); + nst_palette_unload(); + + // Deinitialize audio + audio_deinit(); + + // Deinitialize joysticks + nstsdl_input_joysticks_close(); + + // Write the input config file + nstsdl_input_conf_write(); + + // Write the input config file + gtkui_input_config_write(); + + // Write the config file + config_file_write(nstpaths.nstdir); + + return 0; +} diff -Nru nestopia-1.48/source/gtkui/gtkui_dialogs.cpp nestopia-1.49/source/gtkui/gtkui_dialogs.cpp --- nestopia-1.48/source/gtkui/gtkui_dialogs.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_dialogs.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,258 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2016 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include + +#include "nstcommon.h" +#include "video.h" +#include "config.h" + +#include "gtkui.h" +#include "gtkui_cheats.h" + +extern nstpaths_t nstpaths; +extern GtkWidget *gtkwindow; + +void gtkui_file_open() { + // Open a file using a GTK+ dialog + GtkWidget *dialog = gtk_file_chooser_dialog_new( + "Select a ROM", + GTK_WINDOW(gtkwindow), + GTK_FILE_CHOOSER_ACTION_OPEN, + "Cancel", GTK_RESPONSE_CANCEL, + "Open", GTK_RESPONSE_ACCEPT, + NULL); + + if(conf.misc_last_folder != NULL) + gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), conf.misc_last_folder); + + GtkFileFilter *filter = gtk_file_filter_new(); + + gtk_file_filter_set_name(filter, "NES ROMs and Archives"); + gtk_file_filter_add_pattern(filter, "*.nes"); + gtk_file_filter_add_pattern(filter, "*.fds"); + gtk_file_filter_add_pattern(filter, "*.unf"); + gtk_file_filter_add_pattern(filter, "*.unif"); + gtk_file_filter_add_pattern(filter, "*.nsf"); + gtk_file_filter_add_pattern(filter, "*.zip"); + gtk_file_filter_add_pattern(filter, "*.7z"); + gtk_file_filter_add_pattern(filter, "*.txz"); + gtk_file_filter_add_pattern(filter, "*.tar.xz"); + gtk_file_filter_add_pattern(filter, "*.xz"); + gtk_file_filter_add_pattern(filter, "*.tgz"); + gtk_file_filter_add_pattern(filter, "*.tar.gz"); + gtk_file_filter_add_pattern(filter, "*.gz"); + gtk_file_filter_add_pattern(filter, "*.tbz"); + gtk_file_filter_add_pattern(filter, "*.tar.bz2"); + gtk_file_filter_add_pattern(filter, "*.bz2"); + + gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); + + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + char *filename; + filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + + if(conf.misc_last_folder != NULL) + free(conf.misc_last_folder); + + conf.misc_last_folder = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(dialog)); + gtk_widget_destroy(dialog); + nst_load(filename); + gtkui_set_title(nstpaths.gamename); + gtkui_play(); + g_free(filename); + } + else { gtk_widget_destroy(dialog); } +} + +void gtkui_state_save() { + // Save a state from the GUI + GtkWidget *dialog = gtk_file_chooser_dialog_new("Save State (.nst)", + GTK_WINDOW(gtkwindow), + GTK_FILE_CHOOSER_ACTION_SAVE, + "Cancel", GTK_RESPONSE_CANCEL, + "Save", GTK_RESPONSE_ACCEPT, + NULL); + + char statepath[512]; + snprintf(statepath, sizeof(statepath), "%s.nst", nstpaths.statepath); + gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), statepath); + gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), nstpaths.statepath); + + if (gtk_dialog_run(GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { + char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + nst_state_save(filename); + g_free(filename); + } + + gtk_widget_destroy(dialog); +} + +void gtkui_state_load() { + // Load a state from the GUI + GtkWidget *dialog = gtk_file_chooser_dialog_new("Load State (.nst)", + GTK_WINDOW(gtkwindow), + GTK_FILE_CHOOSER_ACTION_OPEN, + "Cancel", GTK_RESPONSE_CANCEL, + "Open", GTK_RESPONSE_ACCEPT, + NULL); + + GtkFileFilter *filter = gtk_file_filter_new(); + gtk_file_filter_set_name(filter, "Nestopia Save States"); + gtk_file_filter_add_pattern(filter, "*.nst"); + gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); + gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), nstpaths.statepath); + + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + nst_state_load(filename); + g_free(filename); + } + + gtk_widget_destroy(dialog); +} + +void gtkui_screenshot_save() { + // Save a screenshot from the GUI + GtkWidget *dialog = gtk_file_chooser_dialog_new("Save screenshot (.png)", + GTK_WINDOW(gtkwindow), + GTK_FILE_CHOOSER_ACTION_SAVE, + "Cancel", GTK_RESPONSE_CANCEL, + "Save", GTK_RESPONSE_ACCEPT, + NULL); + + char sshotpath[512]; + char sshotfile[768]; + snprintf(sshotpath, sizeof(sshotpath), "%sscreenshots/", nstpaths.nstdir); + snprintf(sshotfile, sizeof(sshotfile), "%s%s.png", sshotpath, nstpaths.gamename); + gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), sshotfile); + gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), sshotpath); + + if (gtk_dialog_run(GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { + char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + video_screenshot(filename); + g_free(filename); + } + + gtk_widget_destroy(dialog); +} + +void gtkui_movie_save() { + // Save a movie from the GUI + GtkWidget *dialog = gtk_file_chooser_dialog_new("Save movie (.nsv)", + GTK_WINDOW(gtkwindow), + GTK_FILE_CHOOSER_ACTION_SAVE, + "Cancel", GTK_RESPONSE_CANCEL, + "Save", GTK_RESPONSE_ACCEPT, + NULL); + + char moviepath[512]; + snprintf(moviepath, sizeof(moviepath), "%s%s.nsv", nstpaths.nstdir, nstpaths.gamename); + gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), moviepath); + gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), nstpaths.nstdir); + + if (gtk_dialog_run(GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { + char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + nst_movie_save(filename); + g_free(filename); + } + + gtk_widget_destroy(dialog); +} + +void gtkui_movie_load() { + // Load a movie from the GUI + GtkWidget *dialog = gtk_file_chooser_dialog_new("Load movie (.nsv)", + GTK_WINDOW(gtkwindow), + GTK_FILE_CHOOSER_ACTION_OPEN, + "Cancel", GTK_RESPONSE_CANCEL, + "Open", GTK_RESPONSE_ACCEPT, + NULL); + + GtkFileFilter *filter = gtk_file_filter_new(); + gtk_file_filter_set_name(filter, "Nestopia movies"); + gtk_file_filter_add_pattern(filter, "*.nsv"); + gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); + gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), nstpaths.nstdir); + + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + nst_movie_load(filename); + g_free(filename); + } + + gtk_widget_destroy(dialog); +} + +void gtkui_movie_stop() { + nst_movie_stop(); +} + +void gtkui_cheats_load() { + // Load cheats from the GUI + GtkWidget *dialog = gtk_file_chooser_dialog_new("Load cheats (.xml)", + GTK_WINDOW(gtkwindow), + GTK_FILE_CHOOSER_ACTION_OPEN, + "Cancel", GTK_RESPONSE_CANCEL, + "Open", GTK_RESPONSE_ACCEPT, + NULL); + + GtkFileFilter *filter = gtk_file_filter_new(); + gtk_file_filter_set_name(filter, "Nestopia cheats"); + gtk_file_filter_add_pattern(filter, "*.xml"); + gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); + gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), nstpaths.nstdir); + + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + gtkui_cheats_fill_tree(filename); + g_free(filename); + } + + gtk_widget_destroy(dialog); +} + +void gtkui_palette_load() { + // Load a palette from the GUI + GtkWidget *dialog = gtk_file_chooser_dialog_new("Load palette (.pal)", + GTK_WINDOW(gtkwindow), + GTK_FILE_CHOOSER_ACTION_OPEN, + "Cancel", GTK_RESPONSE_CANCEL, + "Open", GTK_RESPONSE_ACCEPT, + NULL); + + GtkFileFilter *filter = gtk_file_filter_new(); + gtk_file_filter_set_name(filter, "NES Palettes"); + gtk_file_filter_add_pattern(filter, "*.pal"); + gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); + + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + nst_palette_load(filename); + nst_palette_save(); + g_free(filename); + conf.video_palette_mode = 2; + video_init(); + } + + gtk_widget_destroy(dialog); +} diff -Nru nestopia-1.48/source/gtkui/gtkui_dialogs.h nestopia-1.49/source/gtkui/gtkui_dialogs.h --- nestopia-1.48/source/gtkui/gtkui_dialogs.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_dialogs.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,18 @@ +#ifndef _GTKUI_DIALOGS_H_ +#define _GTKUI_DIALOGS_H_ + +void gtkui_file_open(); +void gtkui_state_save(); +void gtkui_state_load(); + +void gtkui_screenshot_save(); + +void gtkui_movie_save(); +void gtkui_movie_load(); +void gtkui_movie_stop(); + +void gtkui_cheats_load(); + +void gtkui_palette_load(); + +#endif diff -Nru nestopia-1.48/source/gtkui/gtkui.h nestopia-1.49/source/gtkui/gtkui.h --- nestopia-1.48/source/gtkui/gtkui.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,24 @@ +#ifndef _GTKUI_H_ +#define _GTKUI_H_ + +#include + +void gtkui_init(int argc, char *argv[]); +void gtkui_emuloop_start(); +void gtkui_emuloop_stop(); +void gtkui_create(); +void gtkui_resize(); +void gtkui_set_title(const char *title); +GtkWidget *gtkui_about(); +void gtkui_image_paths(); +void gtkui_message(const char* message); +void gtkui_cursor_set(int curtype); +void gtkui_video_toggle_fullscreen(); +void gtkui_video_toggle_filter(); +void gtkui_video_toggle_scale(); +void gtkui_signals_init(); +void gtkui_signals_deinit(); +void gtkui_play(); +void gtkui_pause(); + +#endif diff -Nru nestopia-1.48/source/gtkui/gtkui_input.cpp nestopia-1.49/source/gtkui/gtkui_input.cpp --- nestopia-1.48/source/gtkui/gtkui_input.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_input.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,388 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2017 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include "nstcommon.h" +#include "input.h" +#include "video.h" +#include "audio.h" +#include "ini.h" + +#include "sdlinput.h" + +#include "gtkui.h" +#include "gtkui_input.h" + +static ginputsettings_t inputconf; +static gkeys_t ui; +gpad_t pad[NUMGAMEPADS]; + +static char inputconfpath[256]; +static bool confrunning = false; +static guint keyval = 0; + +extern GtkWidget *configwindow; +extern nstpaths_t nstpaths; +extern Input::Controllers *cNstPads; + +static int gtkui_input_config_match(void* user, const char* section, const char* name, const char* value) { + // Match values from input config file and populate live config + ginputsettings_t* pconfig = (ginputsettings_t*)user; + + // User Interface + if (MATCH("ui", "qsave1")) { pconfig->qsave1 = strdup(value); } + else if (MATCH("ui", "qsave2")) { pconfig->qsave2 = strdup(value); } + else if (MATCH("ui", "qload1")) { pconfig->qload1 = strdup(value); } + else if (MATCH("ui", "qload2")) { pconfig->qload2 = strdup(value); } + else if (MATCH("ui", "screenshot")) { pconfig->screenshot = strdup(value); } + else if (MATCH("ui", "fdsflip")) { pconfig->fdsflip = strdup(value); } + else if (MATCH("ui", "fdsswitch")) { pconfig->fdsswitch = strdup(value); } + else if (MATCH("ui", "insertcoin1")) { pconfig->insertcoin1 = strdup(value); } + else if (MATCH("ui", "insertcoin2")) { pconfig->insertcoin2 = strdup(value); } + else if (MATCH("ui", "reset")) { pconfig->reset = strdup(value); } + else if (MATCH("ui", "ffspeed")) { pconfig->ffspeed = strdup(value); } + else if (MATCH("ui", "rwstart")) { pconfig->rwstart = strdup(value); } + else if (MATCH("ui", "rwstop")) { pconfig->rwstop = strdup(value); } + else if (MATCH("ui", "fullscreen")) { pconfig->fullscreen = strdup(value); } + else if (MATCH("ui", "filter")) { pconfig->filter = strdup(value); } + else if (MATCH("ui", "scalefactor")) { pconfig->scalefactor = strdup(value); } + + // Player 1 + else if (MATCH("gamepad1", "kb_u")) { pconfig->kb_p1u = strdup(value); } + else if (MATCH("gamepad1", "kb_d")) { pconfig->kb_p1d = strdup(value); } + else if (MATCH("gamepad1", "kb_l")) { pconfig->kb_p1l = strdup(value); } + else if (MATCH("gamepad1", "kb_r")) { pconfig->kb_p1r = strdup(value); } + else if (MATCH("gamepad1", "kb_select")) { pconfig->kb_p1select = strdup(value); } + else if (MATCH("gamepad1", "kb_start")) { pconfig->kb_p1start = strdup(value); } + else if (MATCH("gamepad1", "kb_a")) { pconfig->kb_p1a = strdup(value); } + else if (MATCH("gamepad1", "kb_b")) { pconfig->kb_p1b = strdup(value); } + else if (MATCH("gamepad1", "kb_ta")) { pconfig->kb_p1ta = strdup(value); } + else if (MATCH("gamepad1", "kb_tb")) { pconfig->kb_p1tb = strdup(value); } + + // Player 2 + else if (MATCH("gamepad2", "kb_u")) { pconfig->kb_p2u = strdup(value); } + else if (MATCH("gamepad2", "kb_d")) { pconfig->kb_p2d = strdup(value); } + else if (MATCH("gamepad2", "kb_l")) { pconfig->kb_p2l = strdup(value); } + else if (MATCH("gamepad2", "kb_r")) { pconfig->kb_p2r = strdup(value); } + else if (MATCH("gamepad2", "kb_select")) { pconfig->kb_p2select = strdup(value); } + else if (MATCH("gamepad2", "kb_start")) { pconfig->kb_p2start = strdup(value); } + else if (MATCH("gamepad2", "kb_a")) { pconfig->kb_p2a = strdup(value); } + else if (MATCH("gamepad2", "kb_b")) { pconfig->kb_p2b = strdup(value); } + else if (MATCH("gamepad2", "kb_ta")) { pconfig->kb_p2ta = strdup(value); } + else if (MATCH("gamepad2", "kb_tb")) { pconfig->kb_p2tb = strdup(value); } + + else { return 0; } + return 1; +} + +void gtkui_input_set_default() { + // Set the default input for GTK+ + + // Gamepads + pad[0].u = GDK_KEY_Up; + pad[0].d = GDK_KEY_Down; + pad[0].l = GDK_KEY_Left; + pad[0].r = GDK_KEY_Right; + pad[0].select = GDK_KEY_Shift_R; + pad[0].start = GDK_KEY_Return; + pad[0].a = GDK_KEY_z; + pad[0].b = GDK_KEY_a; + pad[0].ta = GDK_KEY_x; + pad[0].tb = GDK_KEY_s; + + pad[1].u = GDK_KEY_i; + pad[1].d = GDK_KEY_k; + pad[1].l = GDK_KEY_j; + pad[1].r = GDK_KEY_l; + pad[1].select = GDK_KEY_Shift_L; + pad[1].start = GDK_KEY_Control_L; + pad[1].a = GDK_KEY_m; + pad[1].b = GDK_KEY_n; + pad[1].ta = GDK_KEY_b; + pad[1].tb = GDK_KEY_v; + + // User Interface + ui.qsave1 = GDK_KEY_F5; + ui.qsave2 = GDK_KEY_F6; + ui.qload1 = GDK_KEY_F7; + ui.qload2 = GDK_KEY_F8; + ui.screenshot = GDK_KEY_F9; + ui.fdsflip = GDK_KEY_F3; + ui.fdsswitch = GDK_KEY_F4; + ui.insertcoin1 = GDK_KEY_F1; + ui.insertcoin2 = GDK_KEY_F2; + ui.reset = GDK_KEY_F12; + ui.ffspeed = GDK_KEY_grave; + ui.rwstart = GDK_KEY_BackSpace; + ui.rwstop = GDK_KEY_backslash; + ui.fullscreen = GDK_KEY_f; + ui.filter = GDK_KEY_t; + ui.scalefactor = GDK_KEY_g; +} + +void gtkui_input_config_read() { + // Read the input config file + snprintf(inputconfpath, sizeof(inputconfpath), "%sgtkinput.conf", nstpaths.nstdir); + if (ini_parse(inputconfpath, gtkui_input_config_match, &inputconf) < 0) { + fprintf(stderr, "Failed to load input config file %s: Using defaults.\n", inputconfpath); + } + else { + // Map the input settings from the config file + + // User Interface + ui.qsave1 = gdk_keyval_from_name(inputconf.qsave1); + ui.qsave2 = gdk_keyval_from_name(inputconf.qsave2); + ui.qload1 = gdk_keyval_from_name(inputconf.qload1); + ui.qload2 = gdk_keyval_from_name(inputconf.qload2); + ui.screenshot = gdk_keyval_from_name(inputconf.screenshot); + ui.fdsflip = gdk_keyval_from_name(inputconf.fdsflip); + ui.fdsswitch = gdk_keyval_from_name(inputconf.fdsswitch); + ui.insertcoin1 = gdk_keyval_from_name(inputconf.insertcoin1); + ui.insertcoin2 = gdk_keyval_from_name(inputconf.insertcoin2); + ui.reset = gdk_keyval_from_name(inputconf.reset); + ui.ffspeed = gdk_keyval_from_name(inputconf.ffspeed); + ui.rwstart = gdk_keyval_from_name(inputconf.rwstart); + ui.rwstop = gdk_keyval_from_name(inputconf.rwstop); + ui.fullscreen = gdk_keyval_from_name(inputconf.fullscreen); + ui.filter = gdk_keyval_from_name(inputconf.filter); + ui.scalefactor = gdk_keyval_from_name(inputconf.scalefactor); + + // Player 1 + pad[0].u = gdk_keyval_from_name(inputconf.kb_p1u); + pad[0].d = gdk_keyval_from_name(inputconf.kb_p1d); + pad[0].l = gdk_keyval_from_name(inputconf.kb_p1l); + pad[0].r = gdk_keyval_from_name(inputconf.kb_p1r); + pad[0].select = gdk_keyval_from_name(inputconf.kb_p1select); + pad[0].start = gdk_keyval_from_name(inputconf.kb_p1start); + pad[0].a = gdk_keyval_from_name(inputconf.kb_p1a); + pad[0].b = gdk_keyval_from_name(inputconf.kb_p1b); + pad[0].ta = gdk_keyval_from_name(inputconf.kb_p1ta); + pad[0].tb = gdk_keyval_from_name(inputconf.kb_p1tb); + + // Player 2 + pad[1].u = gdk_keyval_from_name(inputconf.kb_p2u); + pad[1].d = gdk_keyval_from_name(inputconf.kb_p2d); + pad[1].l = gdk_keyval_from_name(inputconf.kb_p2l); + pad[1].r = gdk_keyval_from_name(inputconf.kb_p2r); + pad[1].select = gdk_keyval_from_name(inputconf.kb_p2select); + pad[1].start = gdk_keyval_from_name(inputconf.kb_p2start); + pad[1].a = gdk_keyval_from_name(inputconf.kb_p2a); + pad[1].b = gdk_keyval_from_name(inputconf.kb_p2b); + pad[1].ta = gdk_keyval_from_name(inputconf.kb_p2ta); + pad[1].tb = gdk_keyval_from_name(inputconf.kb_p2tb); + } +} + +void gtkui_input_config_write() { + // Write out the input configuration file + + FILE *fp = fopen(inputconfpath, "w"); + if (fp != NULL) { + fprintf(fp, "; Nestopia UE GTK+ Input Configuration File\n\n"); + fprintf(fp, "; Values for keyboard input are these values with the GDK_KEY_ prefix removed:\n; https://git.gnome.org/browse/gtk+/plain/gdk/gdkkeysyms.h\n\n"); + + fprintf(fp, "[ui]\n"); + fprintf(fp, "qsave1=%s\n", gdk_keyval_name(ui.qsave1)); + fprintf(fp, "qsave2=%s\n", gdk_keyval_name(ui.qsave2)); + fprintf(fp, "qload1=%s\n", gdk_keyval_name(ui.qload1)); + fprintf(fp, "qload2=%s\n", gdk_keyval_name(ui.qload2)); + fprintf(fp, "screenshot=%s\n", gdk_keyval_name(ui.screenshot)); + fprintf(fp, "fdsflip=%s\n", gdk_keyval_name(ui.fdsflip)); + fprintf(fp, "fdsswitch=%s\n", gdk_keyval_name(ui.fdsswitch)); + fprintf(fp, "insertcoin1=%s\n", gdk_keyval_name(ui.insertcoin1)); + fprintf(fp, "insertcoin2=%s\n", gdk_keyval_name(ui.insertcoin2)); + fprintf(fp, "reset=%s\n", gdk_keyval_name(ui.reset)); + fprintf(fp, "ffspeed=%s\n", gdk_keyval_name(ui.ffspeed)); + fprintf(fp, "rwstart=%s\n", gdk_keyval_name(ui.rwstart)); + fprintf(fp, "rwstop=%s\n", gdk_keyval_name(ui.rwstop)); + fprintf(fp, "fullscreen=%s\n", gdk_keyval_name(ui.fullscreen)); + fprintf(fp, "filter=%s\n", gdk_keyval_name(ui.filter)); + fprintf(fp, "scalefactor=%s\n", gdk_keyval_name(ui.scalefactor)); + fprintf(fp, "\n"); // End of Section + + fprintf(fp, "[gamepad1]\n"); + fprintf(fp, "kb_u=%s\n", gdk_keyval_name(pad[0].u)); + fprintf(fp, "kb_d=%s\n", gdk_keyval_name(pad[0].d)); + fprintf(fp, "kb_l=%s\n", gdk_keyval_name(pad[0].l)); + fprintf(fp, "kb_r=%s\n", gdk_keyval_name(pad[0].r)); + fprintf(fp, "kb_select=%s\n", gdk_keyval_name(pad[0].select)); + fprintf(fp, "kb_start=%s\n", gdk_keyval_name(pad[0].start)); + fprintf(fp, "kb_a=%s\n", gdk_keyval_name(pad[0].a)); + fprintf(fp, "kb_b=%s\n", gdk_keyval_name(pad[0].b)); + fprintf(fp, "kb_ta=%s\n", gdk_keyval_name(pad[0].ta)); + fprintf(fp, "kb_tb=%s\n", gdk_keyval_name(pad[0].tb)); + fprintf(fp, "\n"); // End of Section + + fprintf(fp, "[gamepad2]\n"); + fprintf(fp, "kb_u=%s\n", gdk_keyval_name(pad[1].u)); + fprintf(fp, "kb_d=%s\n", gdk_keyval_name(pad[1].d)); + fprintf(fp, "kb_l=%s\n", gdk_keyval_name(pad[1].l)); + fprintf(fp, "kb_r=%s\n", gdk_keyval_name(pad[1].r)); + fprintf(fp, "kb_select=%s\n", gdk_keyval_name(pad[1].select)); + fprintf(fp, "kb_start=%s\n", gdk_keyval_name(pad[1].start)); + fprintf(fp, "kb_a=%s\n", gdk_keyval_name(pad[1].a)); + fprintf(fp, "kb_b=%s\n", gdk_keyval_name(pad[1].b)); + fprintf(fp, "kb_ta=%s\n", gdk_keyval_name(pad[1].ta)); + fprintf(fp, "kb_tb=%s\n", gdk_keyval_name(pad[1].tb)); + + fclose(fp); + } +} + +void gtkui_input_config_process_key(GtkWidget *widget, GdkEventKey *event, gpointer userdata) { + keyval = event->keyval; + if (keyval == GDK_KEY_Escape || keyval == GDK_KEY_space) { keyval = 0; } + confrunning = false; +} + +void gtkui_input_config_signals_init() { + // Key translation + g_signal_connect(G_OBJECT(configwindow), "key-press-event", + G_CALLBACK(gtkui_input_config_process_key), NULL); + + g_signal_connect(G_OBJECT(configwindow), "key-release-event", + G_CALLBACK(gtkui_input_config_process_key), NULL); +} + +void gtkui_input_config_signals_deinit() { + // Key translation + g_signal_connect(G_OBJECT(configwindow), "key-press-event", + gtkui_input_null, NULL); + + g_signal_connect(G_OBJECT(configwindow), "key-release-event", + gtkui_input_null, NULL); +} + +void gtkui_input_config_key(int pnum, int bnum) { + // Connect signals + gtkui_input_config_signals_init(); + + // Wait for input + confrunning = true; + while (confrunning) { gtk_main_iteration(); } + + // Set the keyval for the input item + if (keyval != 0) { + switch (bnum) { + case 0: pad[pnum].u = keyval; break; + case 1: pad[pnum].d = keyval; break; + case 2: pad[pnum].l = keyval; break; + case 3: pad[pnum].r = keyval; break; + case 4: pad[pnum].select = keyval; break; + case 5: pad[pnum].start = keyval; break; + case 6: pad[pnum].a = keyval; break; + case 7: pad[pnum].b = keyval; break; + case 8: pad[pnum].ta = keyval; break; + case 9: pad[pnum].tb = keyval; break; + default: break; + } + } + + // Disconnect signals + gtkui_input_config_signals_deinit(); +} + +void gtkui_input_config_js(int pnum, int bnum) { + // Wait for input + nstsdl_input_conf_button(pnum, bnum); +} + +void gtkui_input_null() {} + +int gtkui_input_process_key(GtkWidget *widget, GdkEventKey *event, gpointer userdata) { + // Process input from GDK events + + nesinput_t input; + + input.nescode = input.player = input.pressed = input.turboa = input.turbob = 0; + + for (int i = 0; i < NUMGAMEPADS; i++) { + if (event->keyval == pad[i].u) { input.player = i; input.nescode = Input::Controllers::Pad::UP; } + else if (event->keyval == pad[i].d) { input.player = i; input.nescode = Input::Controllers::Pad::DOWN; } + else if (event->keyval == pad[i].l) { input.player = i; input.nescode = Input::Controllers::Pad::LEFT; } + else if (event->keyval == pad[i].r) { input.player = i; input.nescode = Input::Controllers::Pad::RIGHT; } + else if (event->keyval == pad[i].select) { input.player = i; input.nescode = Input::Controllers::Pad::SELECT; } + else if (event->keyval == pad[i].start) { input.player = i; input.nescode = Input::Controllers::Pad::START; } + else if (event->keyval == pad[i].a) { input.player = i; input.nescode = Input::Controllers::Pad::A; } + else if (event->keyval == pad[i].b) { input.player = i; input.nescode = Input::Controllers::Pad::B; } + else if (event->keyval == pad[i].ta) { input.player = i; input.turboa = 1; input.nescode = Input::Controllers::Pad::A; } + else if (event->keyval == pad[i].tb) { input.player = i; input.turbob = 1; input.nescode = Input::Controllers::Pad::B; } + } + + switch(event->type) { + case GDK_KEY_PRESS: + //printf("Keyval: %x\n", event->keyval); + //printf("Keyval: %s\n", gdk_keyval_name(event->keyval)); + input.pressed = 1; + if (event->keyval == ui.qsave1) { nst_state_quicksave(0); } + else if (event->keyval == ui.qsave2) { nst_state_quicksave(1); } + else if (event->keyval == ui.qload1) { nst_state_quickload(0); } + else if (event->keyval == ui.qload2) { nst_state_quickload(1); } + else if (event->keyval == ui.screenshot) { video_screenshot(NULL); } + else if (event->keyval == ui.fdsflip) { nst_fds_flip(); } + else if (event->keyval == ui.fdsswitch) { nst_fds_switch(); } + else if (event->keyval == ui.insertcoin1) { cNstPads->vsSystem.insertCoin |= Input::Controllers::VsSystem::COIN_1; } + else if (event->keyval == ui.insertcoin2) { cNstPads->vsSystem.insertCoin |= Input::Controllers::VsSystem::COIN_2; } + else if (event->keyval == ui.reset) { nst_reset(0); } + else if (event->keyval == ui.ffspeed) { nst_timing_set_ffspeed(); } + else if (event->keyval == ui.rwstart) { nst_set_rewind(0); } + else if (event->keyval == ui.rwstop) { nst_set_rewind(1); } + else if (event->keyval == ui.filter) { gtkui_video_toggle_filter(); } + else if (event->keyval == ui.scalefactor) { gtkui_video_toggle_scale(); } + else if (event->keyval == gdk_keyval_from_name("space")) { cNstPads->pad[1].mic = 0x04; } + break; + case GDK_KEY_RELEASE: + input.pressed = 0; + if (event->keyval == ui.ffspeed) { nst_timing_set_default(); } + else if (event->keyval == ui.fullscreen) { gtkui_video_toggle_fullscreen(); } + else if (event->keyval == gdk_keyval_from_name("space")) { cNstPads->pad[1].mic = 0x00; } + break; + default: break; + } + + nst_input_inject(cNstPads, input); + + return TRUE; +} + +int gtkui_input_process_key_nsf(GtkWidget *widget, GdkEventKey *event, gpointer userdata) { + if (event->type == GDK_KEY_RELEASE) { + if (event->keyval == GDK_KEY_Up) { nst_nsf_play(); } + if (event->keyval == GDK_KEY_Down) { nst_nsf_stop(); } + if (event->keyval == GDK_KEY_Left) { nst_nsf_prev(); } + if (event->keyval == GDK_KEY_Right) { nst_nsf_next(); } + } + return TRUE; +} + +int gtkui_input_process_mouse(GtkWidget *widget, GdkEventButton *event, gpointer userdata) { + switch(event->type) { + case GDK_BUTTON_PRESS: + nst_input_inject_mouse(cNstPads, event->button, 1, (int)event->x, (int)event->y); + break; + + case GDK_BUTTON_RELEASE: + nst_input_inject_mouse(cNstPads, event->button, 0, (int)event->x, (int)event->y); + break; + default: break; + } + return TRUE; +} diff -Nru nestopia-1.48/source/gtkui/gtkui_input.h nestopia-1.49/source/gtkui/gtkui_input.h --- nestopia-1.48/source/gtkui/gtkui_input.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/gtkui/gtkui_input.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,99 @@ +#ifndef _GTKUI_INPUT_H_ +#define _GTKUI_INPUT_H_ + +typedef struct { + guint u; + guint d; + guint l; + guint r; + guint select; + guint start; + guint a; + guint b; + guint ta; + guint tb; +} gpad_t; + +typedef struct { + guint qsave1; + guint qsave2; + guint qload1; + guint qload2; + guint screenshot; + guint fdsflip; + guint fdsswitch; + guint insertcoin1; + guint insertcoin2; + guint reset; + guint ffspeed; + guint rwstart; + guint rwstop; + guint fullscreen; + guint filter; + guint scalefactor; +} gkeys_t; + +typedef struct { + // User Interface + char *qsave1; + char *qsave2; + char *qload1; + char *qload2; + + char *screenshot; + + char *fdsflip; + char *fdsswitch; + + char *insertcoin1; + char *insertcoin2; + + char *reset; + + char *ffspeed; + char *rwstart; + char *rwstop; + + char *fullscreen; + char *filter; + char *scalefactor; + + // Player 1 + char *kb_p1u; + char *kb_p1d; + char *kb_p1l; + char *kb_p1r; + char *kb_p1select; + char *kb_p1start; + char *kb_p1a; + char *kb_p1b; + char *kb_p1ta; + char *kb_p1tb; + + // Player 2 + char *kb_p2u; + char *kb_p2d; + char *kb_p2l; + char *kb_p2r; + char *kb_p2select; + char *kb_p2start; + char *kb_p2a; + char *kb_p2b; + char *kb_p2ta; + char *kb_p2tb; +} ginputsettings_t; + +void gtkui_input_set_default(); +void gtkui_input_config_read(); +void gtkui_input_config_write(); +void gtkui_input_config_process_key(GtkWidget *widget, GdkEventKey *event, gpointer userdata); +void gtkui_input_config_signals_init(); +void gtkui_input_config_signals_deinit(); +void gtkui_input_config_key(int pnum, int bnum); +void gtkui_input_config_js(int pnum, int bnum); +void gtkui_input_null(); +int gtkui_input_process_key(GtkWidget *widget, GdkEventKey *event, gpointer userdata); +int gtkui_input_process_key_nsf(GtkWidget *widget, GdkEventKey *event, gpointer userdata); +int gtkui_input_process_mouse(GtkWidget *widget, GdkEventButton *event, gpointer userdata); + +#endif diff -Nru nestopia-1.48/source/sdl/audio.cpp nestopia-1.49/source/sdl/audio.cpp --- nestopia-1.48/source/sdl/audio.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/sdl/audio.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,338 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2017 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include + +#include "nstcommon.h" +#include "config.h" +#include "audio.h" + +#ifdef _LIBAO +#include + +static ao_device *aodevice; +static ao_sample_format format; +#endif + +#ifdef _JACK +#define JACK_CLIENT_NAME "nestopia" +#define JACK_RB_SIZE 6400 + +#include +#include + +static jack_port_t *jack_output_port1, *jack_output_port2; +static jack_client_t *jack_client; +static jack_ringbuffer_t *jack_rb = NULL; +static bool jack_ready = false; +const size_t jack_sample_size = sizeof(jack_default_audio_sample_t); +#endif + +extern Emulator emulator; + +static SDL_AudioSpec spec, obtained; +static SDL_AudioDeviceID dev; + +static int16_t audiobuf[6400]; + +static int framerate, channels, bufsize; + +static bool paused = false; + +void (*audio_output)(); +void (*audio_deinit)(); + +void audio_output_sdl() { + while (SDL_GetQueuedAudioSize(dev) > (Uint32)bufsize) { + if (conf.timing_limiter) { SDL_Delay(1); } + } + SDL_QueueAudio(dev, (const void*)audiobuf, bufsize); + // Clear the audio queue arbitrarily to avoid it backing up too far + if (SDL_GetQueuedAudioSize(dev) > (Uint32)(bufsize * 3)) { SDL_ClearQueuedAudio(dev); } +} + +void audio_deinit_sdl() { + if (dev) { SDL_CloseAudioDevice(dev); } +} + +void audio_play() { + if (paused) { return; } + bufsize = 2 * channels * (conf.audio_sample_rate / framerate); + audio_output(); +} + +void audio_cb_sdl(void *data, uint8_t *stream, int len) { + uint8_t *soundbuf = (uint8_t*)audiobuf; + + for (int i = 0; i < len; i++) { + stream[i] = soundbuf[i]; + } +} + +void audio_init_sdl() { + spec.freq = conf.audio_sample_rate; + spec.format = AUDIO_S16SYS; + spec.channels = channels; + spec.silence = 0; + spec.samples = (conf.audio_sample_rate / framerate); + spec.userdata = 0; + spec.callback = NULL; // Use SDL_QueueAudio instead + //spec.callback = audio_cb_sdl; + + dev = SDL_OpenAudioDevice(NULL, 0, &spec, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE); + if (!dev) { + fprintf(stderr, "Error opening audio device.\n"); + } + else { + fprintf(stderr, "Audio: SDL - %dHz %d-bit, %d channel(s)\n", spec.freq, 16, spec.channels); + } + + SDL_PauseAudioDevice(dev, 1); // Setting to 0 unpauses +} + +#ifdef _LIBAO +void audio_output_ao() { + ao_play(aodevice, (char*)audiobuf, bufsize); +} + +void audio_deinit_ao() { + if (aodevice) { ao_close(aodevice); ao_shutdown(); } +} + +void audio_init_ao() { + ao_initialize(); + + int default_driver = ao_default_driver_id(); + + memset(&format, 0, sizeof(format)); + format.bits = 16; + format.channels = channels; + format.rate = conf.audio_sample_rate; + format.byte_format = AO_FMT_NATIVE; + + aodevice = ao_open_live(default_driver, &format, NULL); + if (aodevice == NULL) { + fprintf(stderr, "Error opening audio device.\n"); + aodevice = ao_open_live(ao_driver_id("null"), &format, NULL); + } + else { + fprintf(stderr, "Audio: libao - %dHz, %d-bit, %d channel(s)\n", format.rate, format.bits, format.channels); + } +} +#endif + +#ifdef _JACK +int audio_cb_jack(jack_nframes_t nframes, void *arg) { + jack_default_audio_sample_t *out1, *out2; + int i; + + if(!jack_ready) + return 0; + + out1 = (jack_default_audio_sample_t*) jack_port_get_buffer(jack_output_port1, nframes); + out2 = (jack_default_audio_sample_t*) jack_port_get_buffer(jack_output_port2, nframes); + // it is safe to not check if we have enough data + // because jack_ringbuffer_read does a noop if you ask for too much + for(i=0; ibuf, 0, jack_rb->size); + + jack_set_process_callback(jack_client, audio_cb_jack, NULL); + jack_on_shutdown(jack_client, audio_jack_shutdown, NULL); + + jack_output_port1 = jack_port_register(jack_client, "nes out left", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); + jack_output_port2 = jack_port_register(jack_client, "nes out right", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); + if((jack_output_port1 == NULL)||(jack_output_port2 == NULL)) { + fprintf(stderr, "Audio: jack - No new ports available\n"); + return; + } + jack_activate(jack_client); + ports = jack_get_ports(jack_client, NULL, NULL, JackPortIsPhysical | JackPortIsInput); + if(ports == NULL) { + fprintf(stderr, "Audio: jack - No playback ports available\n"); + return; + } + jack_connect(jack_client, jack_port_name(jack_output_port1), ports[0]); + jack_connect(jack_client, jack_port_name(jack_output_port2), ports[1]); + jack_free(ports); + jack_ready = true; +} + +void audio_output_jack() { + size_t i; + jack_default_audio_sample_t sample; + + if(!jack_ready) + return; + + if(bufsize > (jack_ringbuffer_write_space(jack_rb) / jack_sample_size)) { + fprintf(stderr, "Audio: jack - ringbuffer full!\n"); + bufsize = jack_ringbuffer_write_space(jack_rb) / jack_sample_size; + } + + for(i = 0; i < (bufsize/2); i++) { + // convert the audio to 32 bit float to make JACK happy + sample = (float) audiobuf[i]; + sample /= (float) 0x8000; + jack_ringbuffer_write(jack_rb, (char *) &sample, jack_sample_size); + } +} +#endif // _JACK + +void audio_set_funcs() { + if (conf.audio_api == 0) { // SDL + audio_output = &audio_output_sdl; + audio_deinit = &audio_deinit_sdl; + } + #ifdef _LIBAO + else if (conf.audio_api == 1) { // libao + audio_output = &audio_output_ao; + audio_deinit = &audio_deinit_ao; + } + #endif + #ifdef _JACK + else if (conf.audio_api == 2) { //JACK + audio_output = &audio_output_jack; + audio_deinit = &audio_deinit_jack; + } + #endif + else { // SDL + audio_output = &audio_output_sdl; + audio_deinit = &audio_deinit_sdl; + } +} + +void audio_init() { + // Initialize audio device + + // Set the framerate based on the region. For PAL: (60 / 6) * 5 = 50 + framerate = nst_pal() ? (conf.timing_speed / 6) * 5 : conf.timing_speed; + channels = conf.audio_stereo ? 2 : 1; + memset(audiobuf, 0, sizeof(audiobuf)); + + audio_set_funcs(); + + if (conf.audio_api == 0) { audio_init_sdl(); } + #ifdef _LIBAO + else if (conf.audio_api == 1) { audio_init_ao(); } + #endif + #ifdef _JACK + else if (conf.audio_api == 2) { audio_init_jack(); } + #endif + else { conf.audio_api = 0; audio_init_sdl(); } + + paused = false; +} + +void audio_pause() { + // Pause the SDL audio device + if (conf.audio_api == 0) { // SDL + SDL_PauseAudioDevice(dev, 1); + } + paused = true; +} + +void audio_unpause() { + // Unpause the SDL audio device + if (conf.audio_api == 0) { // SDL + SDL_PauseAudioDevice(dev, 0); + } + paused = false; +} + +void audio_set_params(Sound::Output *soundoutput) { + // Set audio parameters + Sound sound(emulator); + + sound.SetSampleBits(16); + sound.SetSampleRate(conf.audio_sample_rate); + + sound.SetSpeaker(conf.audio_stereo ? Sound::SPEAKER_STEREO : Sound::SPEAKER_MONO); + sound.SetSpeed(Sound::DEFAULT_SPEED); + + audio_adj_volume(); + + soundoutput->samples[0] = audiobuf; + soundoutput->length[0] = conf.audio_sample_rate / framerate; + soundoutput->samples[1] = NULL; + soundoutput->length[1] = 0; +} + +void audio_adj_volume() { + // Adjust the audio volume to the current settings + Sound sound(emulator); + sound.SetVolume(Sound::ALL_CHANNELS, conf.audio_volume); + sound.SetVolume(Sound::CHANNEL_SQUARE1, conf.audio_vol_sq1); + sound.SetVolume(Sound::CHANNEL_SQUARE2, conf.audio_vol_sq2); + sound.SetVolume(Sound::CHANNEL_TRIANGLE, conf.audio_vol_tri); + sound.SetVolume(Sound::CHANNEL_NOISE, conf.audio_vol_noise); + sound.SetVolume(Sound::CHANNEL_DPCM, conf.audio_vol_dpcm); + sound.SetVolume(Sound::CHANNEL_FDS, conf.audio_vol_fds); + sound.SetVolume(Sound::CHANNEL_MMC5, conf.audio_vol_mmc5); + sound.SetVolume(Sound::CHANNEL_VRC6, conf.audio_vol_vrc6); + sound.SetVolume(Sound::CHANNEL_VRC7, conf.audio_vol_vrc7); + sound.SetVolume(Sound::CHANNEL_N163, conf.audio_vol_n163); + sound.SetVolume(Sound::CHANNEL_S5B, conf.audio_vol_s5b); + + if (conf.audio_volume == 0) { memset(audiobuf, 0, sizeof(audiobuf)); } +} diff -Nru nestopia-1.48/source/sdl/audio.h nestopia-1.49/source/sdl/audio.h --- nestopia-1.48/source/sdl/audio.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/sdl/audio.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,20 @@ +#ifndef _AUDIO_H_ +#define _AUDIO_H_ + +#include +#include "core/api/NstApiEmulator.hpp" +#include "core/api/NstApiSound.hpp" + +using namespace Nes::Api; + +extern void (*audio_deinit)(); + +void audio_set_funcs(); +void audio_init(); +void audio_play(); +void audio_pause(); +void audio_unpause(); +void audio_set_params(Sound::Output *soundoutput); +void audio_adj_volume(); + +#endif diff -Nru nestopia-1.48/source/sdl/cursor.cpp nestopia-1.49/source/sdl/cursor.cpp --- nestopia-1.48/source/sdl/cursor.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/sdl/cursor.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,116 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2016 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include + +#include + +#include "cursor.h" + +static SDL_Cursor *cursor; + +// Most of this is adapted from the code example in the SDL documentation + +static const char *crosshair[] = { + " X ", + " X.X ", + " XXX ", + " X.X ", + " XXX ", + " X.X ", + " XXX ", + " X.X ", + " XXX ", + " X.X ", + " XXX ", + " XX.XX ", + " X.XXX.X ", + " XXXXXXXXXXXX XXXXXXXXXXXX ", + "X.X.X.X.X.X.X . X.X.X.X.X.X.X ", + " XXXXXXXXXXXX XXXXXXXXXXXX ", + " X.XXX.X ", + " XX.XX ", + " XXX ", + " X.X ", + " XXX ", + " X.X ", + " XXX ", + " X.X ", + " XXX ", + " X.X ", + " XXX ", + " X.X ", + " X ", + " ", + " ", + " ", + "14,14" // Center +}; + +static SDL_Cursor *cursor_init(const char *image[]) { + int i, row, col; + Uint8 data[4*32]; + Uint8 mask[4*32]; + int hot_x, hot_y; + + i = -1; + for (row=0; row<32; ++row) { + for ( col=0; col<32; ++col ) { + if ( col % 8 ) { + data[i] <<= 1; + mask[i] <<= 1; + } + else { + ++i; + data[i] = mask[i] = 0; + } + + switch (image[row][col]) { + case 'X': + data[i] |= 0x01; + mask[i] |= 0x01; + break; + + case '.': + mask[i] |= 0x01; + break; + + case ' ': break; + } + } + } + + sscanf(image[row], "%d,%d", &hot_x, &hot_y); + return SDL_CreateCursor(data, mask, 32, 32, hot_x, hot_y); +} + +void cursor_set_special(int type) { + // Set special cursors + cursor = cursor_init(crosshair); + SDL_SetCursor(cursor); +} + +void cursor_set_default() { + // Set the cursor to default + SDL_FreeCursor(cursor); +} diff -Nru nestopia-1.48/source/sdl/cursor.h nestopia-1.49/source/sdl/cursor.h --- nestopia-1.48/source/sdl/cursor.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/sdl/cursor.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,7 @@ +#ifndef _CURSOR_H_ +#define _CURSOR_H_ + +void cursor_set_special(int type); +void cursor_set_default(); + +#endif diff -Nru nestopia-1.48/source/sdl/sdlinput.cpp nestopia-1.49/source/sdl/sdlinput.cpp --- nestopia-1.48/source/sdl/sdlinput.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/sdl/sdlinput.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,924 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2018 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include + +#include +#ifdef _GTK +#include "gtkui/gtkui.h" +#endif + +#include "nstcommon.h" +#include "video.h" +#include "input.h" + +#include "ini.h" + +#include "sdlmain.h" +#include "sdlvideo.h" +#include "sdlinput.h" + +static SDL_Joystick *joystick; +gamepad_t player[NUMGAMEPADS]; +static uiinput_t ui; +static inputsettings_t inputconf; +static char inputconfpath[256]; +extern int drawtext; + +static unsigned char nescodes[TOTALBUTTONS] = { + Input::Controllers::Pad::UP, + Input::Controllers::Pad::DOWN, + Input::Controllers::Pad::LEFT, + Input::Controllers::Pad::RIGHT, + Input::Controllers::Pad::SELECT, + Input::Controllers::Pad::START, + Input::Controllers::Pad::A, + Input::Controllers::Pad::B, + Input::Controllers::Pad::A, + Input::Controllers::Pad::B, + Input::Controllers::Pad::UP, + Input::Controllers::Pad::DOWN, + Input::Controllers::Pad::LEFT, + Input::Controllers::Pad::RIGHT, + Input::Controllers::Pad::SELECT, + Input::Controllers::Pad::START, + Input::Controllers::Pad::A, + Input::Controllers::Pad::B, + Input::Controllers::Pad::A, + Input::Controllers::Pad::B +}; + +extern Emulator emulator; +extern nstpaths_t nstpaths; + +void nstsdl_input_joysticks_detect() { + // Initialize any joysticks + fprintf(stderr, "%i joystick(s) found:\n", SDL_NumJoysticks()); + + int i; + + for (i = 0; i < SDL_NumJoysticks(); i++) { + joystick = SDL_JoystickOpen(i); + printf("%s\n", SDL_JoystickName(joystick)); + } + + SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); + + nst_input_turbo_init(); +} + +void nstsdl_input_joysticks_close() { + // Deinitialize any joysticks + SDL_JoystickClose(joystick); +} + +void nstsdl_input_match_keyboard(Input::Controllers *controllers, SDL_Event event) { + // Match NES buttons to keyboard buttons + + nesinput_t input; + + input.nescode = 0x00; + input.player = 0; + input.pressed = 0; + input.turboa = 0; + input.turbob = 0; + + if (event.type == SDL_KEYDOWN) { input.pressed = 1; } + + for (int i = 0; i < NUMGAMEPADS; i++) { + if (player[i].u == event.key.keysym.scancode) { + input.nescode = Input::Controllers::Pad::UP; + input.player = i; + } + else if (player[i].d == event.key.keysym.scancode) { + input.nescode = Input::Controllers::Pad::DOWN; + input.player = i; + } + else if (player[i].l == event.key.keysym.scancode) { + input.nescode = Input::Controllers::Pad::LEFT; + input.player = i; + } + else if (player[i].r == event.key.keysym.scancode) { + input.nescode = Input::Controllers::Pad::RIGHT; + input.player = i; + } + else if (player[i].select == event.key.keysym.scancode) { + input.nescode = Input::Controllers::Pad::SELECT; + input.player = i; + } + else if (player[i].start == event.key.keysym.scancode) { + input.nescode = Input::Controllers::Pad::START; + input.player = i; + } + else if (player[i].a == event.key.keysym.scancode) { + input.nescode = Input::Controllers::Pad::A; + input.player = i; + } + else if (player[i].b == event.key.keysym.scancode) { + input.nescode = Input::Controllers::Pad::B; + input.player = i; + } + else if (player[i].ta == event.key.keysym.scancode) { + input.nescode = Input::Controllers::Pad::A; + input.player = i; + input.turboa = 1; + } + else if (player[i].tb == event.key.keysym.scancode) { + input.nescode = Input::Controllers::Pad::B; + input.player = i; + input.turbob = 1; + } + } + + nst_input_inject(controllers, input); + + if (event.key.keysym.scancode == ui.ffspeed && event.type == SDL_KEYDOWN) { nst_timing_set_ffspeed(); } + if (event.key.keysym.scancode == ui.ffspeed && event.type == SDL_KEYUP) { nst_timing_set_default(); } + + const Uint8 *keys = SDL_GetKeyboardState(NULL); + + // Mic emulation + if (keys[SDL_SCANCODE_SPACE]) { controllers->pad[1].mic = 0x04; } + else { controllers->pad[1].mic = 0x00; } + + // Insert Coins + controllers->vsSystem.insertCoin = 0; + if (keys[ui.insertcoin1]) { controllers->vsSystem.insertCoin |= Input::Controllers::VsSystem::COIN_1; } + if (keys[ui.insertcoin2]) { controllers->vsSystem.insertCoin |= Input::Controllers::VsSystem::COIN_2; } + + // Process non-game events + if (keys[ui.fdsflip]) { nst_fds_flip(); } + if (keys[ui.fdsswitch]) { nst_fds_switch(); } + if (keys[ui.qsave1]) { nst_state_quicksave(0); } + if (keys[ui.qsave2]) { nst_state_quicksave(1); } + if (keys[ui.qload1]) { nst_state_quickload(0); } + if (keys[ui.qload2]) { nst_state_quickload(1); } + + // Screenshot + if (keys[ui.screenshot]) { video_screenshot(NULL); } + + // Reset + if (keys[ui.reset]) { nst_reset(0); } + + // Rewinder + if (keys[ui.rwstart]) { nst_set_rewind(0); } + if (keys[ui.rwstop]) { nst_set_rewind(1); } + + // Video + if (event.key.keysym.scancode == ui.fullscreen && event.type == SDL_KEYUP) { nstsdl_video_toggle_fullscreen(); } + if (keys[ui.filter]) { nstsdl_video_toggle_filter(); } + if (keys[ui.scalefactor]) { nstsdl_video_toggle_scale(); } + + // NSF + if (nst_nsf()) { + if (keys[SDL_SCANCODE_UP]) { nst_nsf_play(); } + if (keys[SDL_SCANCODE_DOWN]) { nst_nsf_stop(); } + if (keys[SDL_SCANCODE_LEFT]) { nst_nsf_prev(); } + if (keys[SDL_SCANCODE_RIGHT]) { nst_nsf_next(); } + } + + // Input Config + if (keys[SDL_SCANCODE_LCTRL] && keys[SDL_SCANCODE_1]) { nstsdl_input_conf(0, 0); } // Keyboard Player 1 + if (keys[SDL_SCANCODE_LCTRL] && keys[SDL_SCANCODE_2]) { nstsdl_input_conf(0, 1); } // Keyboard Player 2 + if (keys[SDL_SCANCODE_LSHIFT] && keys[SDL_SCANCODE_1]) { nstsdl_input_conf(1, 0); } // Joystick Player 1 + if (keys[SDL_SCANCODE_LSHIFT] && keys[SDL_SCANCODE_2]) { nstsdl_input_conf(1, 1); } // Joystick Player 2 + + // Escape exits +#ifndef _GTK + if (keys[SDL_SCANCODE_ESCAPE]) { nst_schedule_quit(); } +#endif +} + +void nstsdl_input_match_mouse(Input::Controllers *controllers, SDL_Event event) { + // Match mouse input to NES input + int x, y; + SDL_GetMouseState(&x, &y); + nst_input_inject_mouse(controllers, event.button.button, event.type == SDL_MOUSEBUTTONDOWN ? 1 : 0, x, y); +} + +int nstsdl_input_checksign(int axisvalue) { + if (axisvalue <= 0) { return 0; } + else { return 1; } +} + +void nstsdl_input_match_joystick(Input::Controllers *controllers, SDL_Event event) { + // Match NES buttons to joystick input + int j; + + nesinput_t input, reverseinput; + + input.nescode = 0x00; + input.player = 0; + input.pressed = 0; + input.turboa = 0; + input.turbob = 0; + + // This is for releasing opposing directions + reverseinput.nescode = 0x00; + reverseinput.player = 0; + reverseinput.pressed = 0; + + SDL_Event buttons[TOTALBUTTONS] = { + player[0].ju, player[0].jd, player[0].jl, player[0].jr, + player[0].jselect, player[0].jstart, player[0].ja, player[0].jb, + player[0].jta, player[0].jtb, + + player[1].ju, player[1].jd, player[1].jl, player[1].jr, + player[1].jselect, player[1].jstart, player[1].ja, player[1].jb, + player[1].jta, player[1].jtb + }; + + SDL_Event rw[2] = { player[0].rwstart, player[0].rwstop }; + + switch(event.type) { + // Handle button input + case SDL_JOYBUTTONUP: + case SDL_JOYBUTTONDOWN: + // Gamepad input + for (j = 0; j < TOTALBUTTONS; j++) { + if (buttons[j].jbutton.button == event.jbutton.button + && buttons[j].jbutton.which == event.jbutton.which) { + input.nescode = nescodes[j]; + if (j >= NUMBUTTONS) { input.player = 1; } + // This is really dirty + if (j == 8 || j == 18) { input.turboa = 1; } + if (j == 9 || j == 19) { input.turbob = 1; } + } + } + input.pressed = event.jbutton.state; + + // Rewind + if (event.jbutton.button == rw[0].jbutton.button && event.jbutton.which == rw[0].jbutton.which) { nst_set_rewind(0); } + if (event.jbutton.button == rw[1].jbutton.button && event.jbutton.which == rw[1].jbutton.which) { nst_set_rewind(1); } + break; + + // Handling hat input can be a lot of fun if you like pain + case SDL_JOYHATMOTION: + unsigned char hu, hd, hl, hr; + hu = hd = hl = hr = 0; + + // Start a loop to check if input matches + for (j = 0; j < TOTALBUTTONS; j++) { + + // Read value of each hat direction on current hat + if (buttons[j].type == event.type + && buttons[j].jhat.which == event.jhat.which + && buttons[j].jhat.hat == event.jhat.hat) { + if (j >= NUMBUTTONS) { input.player = reverseinput.player = 1; } + + // Find the values at each hat position on the current hat + if (buttons[j].jhat.value == SDL_HAT_UP) { hu = nescodes[j]; } + else if (buttons[j].jhat.value == SDL_HAT_DOWN) { hd = nescodes[j]; } + else if (buttons[j].jhat.value == SDL_HAT_LEFT) { hl = nescodes[j]; } + else if (buttons[j].jhat.value == SDL_HAT_RIGHT) { hr = nescodes[j]; } + + input.pressed = 1; + + // Make sure opposing hat positions are turned off + switch(event.jhat.value) { + case SDL_HAT_UP: + input.nescode |= hu; + reverseinput.nescode |= hd |= hl |= hr; + break; + case SDL_HAT_LEFTUP: + input.nescode |= hu |= hl; + reverseinput.nescode |= hd |= hr; + break; + case SDL_HAT_RIGHTUP: + input.nescode |= hu |= hr; + reverseinput.nescode |= hd |= hl; + break; + case SDL_HAT_DOWN: + input.nescode |= hd; + reverseinput.nescode |= hu |= hl |= hr; + break; + case SDL_HAT_LEFTDOWN: + input.nescode |= hd |= hl; + reverseinput.nescode |= hu |= hr; + break; + case SDL_HAT_RIGHTDOWN: + input.nescode |= hd |= hr; + reverseinput.nescode |= hu |= hl; + break; + case SDL_HAT_LEFT: + input.nescode |= hl; + reverseinput.nescode |= hr |= hu |= hd; + break; + case SDL_HAT_RIGHT: + input.nescode |= hr; + reverseinput.nescode |= hl |= hu |= hd; + break; + default: + input.nescode |= hu |= hd |= hl |= hr; + break; + } + } + } + break; + + // Handle axis input + case SDL_JOYAXISMOTION: + for (j = 0; j < TOTALBUTTONS; j++) { + + int nvalue = nstsdl_input_checksign(event.jaxis.value); + + if (buttons[j].jaxis.axis == event.jaxis.axis + && buttons[j].jaxis.which == event.jaxis.which + && buttons[j].jaxis.type == event.jaxis.type + && buttons[j].jaxis.value == nvalue) { + + if (j >= NUMBUTTONS) { input.player = reverseinput.player = 1; } + + input.nescode = nescodes[j]; + } + + if (buttons[j].jaxis.axis == event.jaxis.axis + && buttons[j].jaxis.which == event.jaxis.which + && buttons[j].jaxis.type == event.jaxis.type + && buttons[j].jaxis.value == !nvalue) { + + reverseinput.nescode = nescodes[j]; + } + + if (abs(event.jaxis.value) > DEADZONE) { input.pressed = 1; } + } + break; + + default: break; + } + + nst_input_inject(controllers, reverseinput); + nst_input_inject(controllers, input); +} + +void nstsdl_input_conf_defaults() { + // Set default input config + ui.qsave1 = SDL_GetScancodeFromName("F5"); + ui.qsave2 = SDL_GetScancodeFromName("F6"); + ui.qload1 = SDL_GetScancodeFromName("F7"); + ui.qload2 = SDL_GetScancodeFromName("F8"); + + ui.screenshot = SDL_GetScancodeFromName("F9"); + + ui.fdsflip = SDL_GetScancodeFromName("F3"); + ui.fdsswitch = SDL_GetScancodeFromName("F4"); + + ui.insertcoin1 = SDL_GetScancodeFromName("F1"); + ui.insertcoin2 = SDL_GetScancodeFromName("F2"); + + ui.reset = SDL_GetScancodeFromName("F12"); + + ui.ffspeed = SDL_GetScancodeFromName("`"); + ui.rwstart = SDL_GetScancodeFromName("Backspace"); + ui.rwstop = SDL_GetScancodeFromName("\\"); + + ui.fullscreen = SDL_GetScancodeFromName("F"); + ui.filter = SDL_GetScancodeFromName("T"); + ui.scalefactor = SDL_GetScancodeFromName("G"); + + player[0].u = SDL_GetScancodeFromName("Up"); + player[0].d = SDL_GetScancodeFromName("Down"); + player[0].l = SDL_GetScancodeFromName("Left"); + player[0].r = SDL_GetScancodeFromName("Right"); + player[0].select = SDL_GetScancodeFromName("Right Shift"); + player[0].start = SDL_GetScancodeFromName("Return"); + player[0].a = SDL_GetScancodeFromName("Z"); + player[0].b = SDL_GetScancodeFromName("A"); + player[0].ta = SDL_GetScancodeFromName("X"); + player[0].tb = SDL_GetScancodeFromName("S"); + + player[0].ju = nstsdl_input_translate_string("j0h01"); + player[0].jd = nstsdl_input_translate_string("j0h04"); + player[0].jl = nstsdl_input_translate_string("j0h08"); + player[0].jr = nstsdl_input_translate_string("j0h02"); + player[0].jselect = nstsdl_input_translate_string("j0b8"); + player[0].jstart = nstsdl_input_translate_string("j0b9"); + player[0].ja = nstsdl_input_translate_string("j0b1"); + player[0].jb = nstsdl_input_translate_string("j0b0"); + player[0].jta = nstsdl_input_translate_string("j0b2"); + player[0].jtb = nstsdl_input_translate_string("j0b3"); + + player[0].rwstart = nstsdl_input_translate_string("j0b4"); + player[0].rwstop = nstsdl_input_translate_string("j0b5"); + + player[1].u = SDL_GetScancodeFromName("I"); + player[1].d = SDL_GetScancodeFromName("K"); + player[1].l = SDL_GetScancodeFromName("J"); + player[1].r = SDL_GetScancodeFromName("L"); + player[1].select = SDL_GetScancodeFromName("Left Shift"); + player[1].start = SDL_GetScancodeFromName("Left Ctrl"); + player[1].a = SDL_GetScancodeFromName("M"); + player[1].b = SDL_GetScancodeFromName("N"); + player[1].ta = SDL_GetScancodeFromName("B"); + player[1].tb = SDL_GetScancodeFromName("V"); + + player[1].ju = nstsdl_input_translate_string("j1h01"); + player[1].jd = nstsdl_input_translate_string("j1h04"); + player[1].jl = nstsdl_input_translate_string("j1h08"); + player[1].jr = nstsdl_input_translate_string("j1h02"); + player[1].jselect = nstsdl_input_translate_string("j1b8"); + player[1].jstart = nstsdl_input_translate_string("j1b9"); + player[1].ja = nstsdl_input_translate_string("j1b1"); + player[1].jb = nstsdl_input_translate_string("j1b0"); + player[1].jta = nstsdl_input_translate_string("j1b2"); + player[1].jtb = nstsdl_input_translate_string("j1b3"); +} + +void nstsdl_input_conf_set(SDL_Event event, int type, int pnum, int counter) { + // Set an input item to what was requested by configuration process + if (type == 0) { // Keyboard + switch(counter) { + case 0: player[pnum].u = event.key.keysym.scancode; break; + case 1: player[pnum].d = event.key.keysym.scancode; break; + case 2: player[pnum].l = event.key.keysym.scancode; break; + case 3: player[pnum].r = event.key.keysym.scancode; break; + case 4: player[pnum].select = event.key.keysym.scancode; break; + case 5: player[pnum].start = event.key.keysym.scancode; break; + case 6: player[pnum].a = event.key.keysym.scancode; break; + case 7: player[pnum].b = event.key.keysym.scancode; break; + case 8: player[pnum].ta = event.key.keysym.scancode; break; + case 9: player[pnum].tb = event.key.keysym.scancode; break; + default: break; + } + } + else if (type == 1) { // Joystick + switch(counter) { + case 0: player[pnum].ju = nstsdl_input_translate_string(nstsdl_input_translate_event(event)); break; + case 1: player[pnum].jd = nstsdl_input_translate_string(nstsdl_input_translate_event(event)); break; + case 2: player[pnum].jl = nstsdl_input_translate_string(nstsdl_input_translate_event(event)); break; + case 3: player[pnum].jr = nstsdl_input_translate_string(nstsdl_input_translate_event(event)); break; + case 4: player[pnum].jselect = nstsdl_input_translate_string(nstsdl_input_translate_event(event)); break; + case 5: player[pnum].jstart = nstsdl_input_translate_string(nstsdl_input_translate_event(event)); break; + case 6: player[pnum].ja = nstsdl_input_translate_string(nstsdl_input_translate_event(event)); break; + case 7: player[pnum].jb = nstsdl_input_translate_string(nstsdl_input_translate_event(event)); break; + case 8: player[pnum].jta = nstsdl_input_translate_string(nstsdl_input_translate_event(event)); break; + case 9: player[pnum].jtb = nstsdl_input_translate_string(nstsdl_input_translate_event(event)); break; + default: break; + } + } +} + +static int nstsdl_input_config_match(void* user, const char* section, const char* name, const char* value) { + // Match values from input config file and populate live config + inputsettings_t* pconfig = (inputsettings_t*)user; + + // User Interface + if (MATCH("ui", "qsave1")) { pconfig->qsave1 = strdup(value); } + else if (MATCH("ui", "qsave2")) { pconfig->qsave2 = strdup(value); } + else if (MATCH("ui", "qload1")) { pconfig->qload1 = strdup(value); } + else if (MATCH("ui", "qload2")) { pconfig->qload2 = strdup(value); } + + else if (MATCH("ui", "screenshot")) { pconfig->screenshot = strdup(value); } + + else if (MATCH("ui", "fdsflip")) { pconfig->fdsflip = strdup(value); } + else if (MATCH("ui", "fdsswitch")) { pconfig->fdsswitch = strdup(value); } + + else if (MATCH("ui", "insertcoin1")) { pconfig->insertcoin1 = strdup(value); } + else if (MATCH("ui", "insertcoin2")) { pconfig->insertcoin2 = strdup(value); } + + else if (MATCH("ui", "reset")) { pconfig->reset = strdup(value); } + + else if (MATCH("ui", "ffspeed")) { pconfig->ffspeed = strdup(value); } + else if (MATCH("ui", "rwstart")) { pconfig->rwstart = strdup(value); } + else if (MATCH("ui", "rwstop")) { pconfig->rwstop = strdup(value); } + + else if (MATCH("ui", "fullscreen")) { pconfig->fullscreen = strdup(value); } + else if (MATCH("ui", "filter")) { pconfig->filter = strdup(value); } + else if (MATCH("ui", "scalefactor")) { pconfig->scalefactor = strdup(value); } + + // Player 1 + else if (MATCH("gamepad1", "kb_u")) { pconfig->kb_p1u = strdup(value); } + else if (MATCH("gamepad1", "kb_d")) { pconfig->kb_p1d = strdup(value); } + else if (MATCH("gamepad1", "kb_l")) { pconfig->kb_p1l = strdup(value); } + else if (MATCH("gamepad1", "kb_r")) { pconfig->kb_p1r = strdup(value); } + else if (MATCH("gamepad1", "kb_select")) { pconfig->kb_p1select = strdup(value); } + else if (MATCH("gamepad1", "kb_start")) { pconfig->kb_p1start = strdup(value); } + else if (MATCH("gamepad1", "kb_a")) { pconfig->kb_p1a = strdup(value); } + else if (MATCH("gamepad1", "kb_b")) { pconfig->kb_p1b = strdup(value); } + else if (MATCH("gamepad1", "kb_ta")) { pconfig->kb_p1ta = strdup(value); } + else if (MATCH("gamepad1", "kb_tb")) { pconfig->kb_p1tb = strdup(value); } + + else if (MATCH("gamepad1", "js_u")) { pconfig->js_p1u = strdup(value); } + else if (MATCH("gamepad1", "js_d")) { pconfig->js_p1d = strdup(value); } + else if (MATCH("gamepad1", "js_l")) { pconfig->js_p1l = strdup(value); } + else if (MATCH("gamepad1", "js_r")) { pconfig->js_p1r = strdup(value); } + else if (MATCH("gamepad1", "js_select")) { pconfig->js_p1select = strdup(value); } + else if (MATCH("gamepad1", "js_start")) { pconfig->js_p1start = strdup(value); } + else if (MATCH("gamepad1", "js_a")) { pconfig->js_p1a = strdup(value); } + else if (MATCH("gamepad1", "js_b")) { pconfig->js_p1b = strdup(value); } + else if (MATCH("gamepad1", "js_ta")) { pconfig->js_p1ta = strdup(value); } + else if (MATCH("gamepad1", "js_tb")) { pconfig->js_p1tb = strdup(value); } + + else if (MATCH("gamepad1", "js_rwstart")) { pconfig->js_rwstart = strdup(value); } + else if (MATCH("gamepad1", "js_rwstop")) { pconfig->js_rwstop = strdup(value); } + + // Player 2 + else if (MATCH("gamepad2", "kb_u")) { pconfig->kb_p2u = strdup(value); } + else if (MATCH("gamepad2", "kb_d")) { pconfig->kb_p2d = strdup(value); } + else if (MATCH("gamepad2", "kb_l")) { pconfig->kb_p2l = strdup(value); } + else if (MATCH("gamepad2", "kb_r")) { pconfig->kb_p2r = strdup(value); } + else if (MATCH("gamepad2", "kb_select")) { pconfig->kb_p2select = strdup(value); } + else if (MATCH("gamepad2", "kb_start")) { pconfig->kb_p2start = strdup(value); } + else if (MATCH("gamepad2", "kb_a")) { pconfig->kb_p2a = strdup(value); } + else if (MATCH("gamepad2", "kb_b")) { pconfig->kb_p2b = strdup(value); } + else if (MATCH("gamepad2", "kb_ta")) { pconfig->kb_p2ta = strdup(value); } + else if (MATCH("gamepad2", "kb_tb")) { pconfig->kb_p2tb = strdup(value); } + + else if (MATCH("gamepad2", "js_u")) { pconfig->js_p2u = strdup(value); } + else if (MATCH("gamepad2", "js_d")) { pconfig->js_p2d = strdup(value); } + else if (MATCH("gamepad2", "js_l")) { pconfig->js_p2l = strdup(value); } + else if (MATCH("gamepad2", "js_r")) { pconfig->js_p2r = strdup(value); } + else if (MATCH("gamepad2", "js_select")) { pconfig->js_p2select = strdup(value); } + else if (MATCH("gamepad2", "js_start")) { pconfig->js_p2start = strdup(value); } + else if (MATCH("gamepad2", "js_a")) { pconfig->js_p2a = strdup(value); } + else if (MATCH("gamepad2", "js_b")) { pconfig->js_p2b = strdup(value); } + else if (MATCH("gamepad2", "js_ta")) { pconfig->js_p2ta = strdup(value); } + else if (MATCH("gamepad2", "js_tb")) { pconfig->js_p2tb = strdup(value); } + + else { return 0; } + return 1; +} + +void nstsdl_input_conf_read() { + // Read the input config file + snprintf(inputconfpath, sizeof(inputconfpath), "%sinput.conf", nstpaths.nstdir); + + if (ini_parse(inputconfpath, nstsdl_input_config_match, &inputconf) < 0) { + fprintf(stderr, "Failed to load input config file %s: Using defaults.\n", inputconfpath); + } + else { // Map the input settings from the config file + // User Interface + ui.qsave1 = SDL_GetScancodeFromName(inputconf.qsave1); + ui.qsave2 = SDL_GetScancodeFromName(inputconf.qsave2); + ui.qload1 = SDL_GetScancodeFromName(inputconf.qload1); + ui.qload2 = SDL_GetScancodeFromName(inputconf.qload2); + + ui.screenshot = SDL_GetScancodeFromName(inputconf.screenshot); + + ui.fdsflip = SDL_GetScancodeFromName(inputconf.fdsflip); + ui.fdsswitch = SDL_GetScancodeFromName(inputconf.fdsswitch); + + ui.insertcoin1 = SDL_GetScancodeFromName(inputconf.insertcoin1); + ui.insertcoin2 = SDL_GetScancodeFromName(inputconf.insertcoin2); + + ui.reset = SDL_GetScancodeFromName(inputconf.reset); + + ui.ffspeed = SDL_GetScancodeFromName(inputconf.ffspeed); + ui.rwstart = SDL_GetScancodeFromName(inputconf.rwstart); + ui.rwstop = SDL_GetScancodeFromName(inputconf.rwstop); + + ui.fullscreen = SDL_GetScancodeFromName(inputconf.fullscreen); + ui.filter = SDL_GetScancodeFromName(inputconf.filter); + ui.scalefactor = SDL_GetScancodeFromName(inputconf.scalefactor); + + // Player 1 + player[0].u = SDL_GetScancodeFromName(inputconf.kb_p1u); + player[0].d = SDL_GetScancodeFromName(inputconf.kb_p1d); + player[0].l = SDL_GetScancodeFromName(inputconf.kb_p1l); + player[0].r = SDL_GetScancodeFromName(inputconf.kb_p1r); + player[0].select = SDL_GetScancodeFromName(inputconf.kb_p1select); + player[0].start = SDL_GetScancodeFromName(inputconf.kb_p1start); + player[0].a = SDL_GetScancodeFromName(inputconf.kb_p1a); + player[0].b = SDL_GetScancodeFromName(inputconf.kb_p1b); + player[0].ta = SDL_GetScancodeFromName(inputconf.kb_p1ta); + player[0].tb = SDL_GetScancodeFromName(inputconf.kb_p1tb); + + player[0].ju = nstsdl_input_translate_string(inputconf.js_p1u); + player[0].jd = nstsdl_input_translate_string(inputconf.js_p1d); + player[0].jl = nstsdl_input_translate_string(inputconf.js_p1l); + player[0].jr = nstsdl_input_translate_string(inputconf.js_p1r); + player[0].jselect = nstsdl_input_translate_string(inputconf.js_p1select); + player[0].jstart = nstsdl_input_translate_string(inputconf.js_p1start); + player[0].ja = nstsdl_input_translate_string(inputconf.js_p1a); + player[0].jb = nstsdl_input_translate_string(inputconf.js_p1b); + player[0].jta = nstsdl_input_translate_string(inputconf.js_p1ta); + player[0].jtb = nstsdl_input_translate_string(inputconf.js_p1tb); + + if (inputconf.js_rwstart) { player[0].rwstart = nstsdl_input_translate_string(inputconf.js_rwstart); } + if (inputconf.js_rwstop) { player[0].rwstop = nstsdl_input_translate_string(inputconf.js_rwstop); } + + // Player 2 + player[1].u = SDL_GetScancodeFromName(inputconf.kb_p2u); + player[1].d = SDL_GetScancodeFromName(inputconf.kb_p2d); + player[1].l = SDL_GetScancodeFromName(inputconf.kb_p2l); + player[1].r = SDL_GetScancodeFromName(inputconf.kb_p2r); + player[1].select = SDL_GetScancodeFromName(inputconf.kb_p2select); + player[1].start = SDL_GetScancodeFromName(inputconf.kb_p2start); + player[1].a = SDL_GetScancodeFromName(inputconf.kb_p2a); + player[1].b = SDL_GetScancodeFromName(inputconf.kb_p2b); + player[1].ta = SDL_GetScancodeFromName(inputconf.kb_p2ta); + player[1].tb = SDL_GetScancodeFromName(inputconf.kb_p2tb); + + player[1].ju = nstsdl_input_translate_string(inputconf.js_p2u); + player[1].jd = nstsdl_input_translate_string(inputconf.js_p2d); + player[1].jl = nstsdl_input_translate_string(inputconf.js_p2l); + player[1].jr = nstsdl_input_translate_string(inputconf.js_p2r); + player[1].jselect = nstsdl_input_translate_string(inputconf.js_p2select); + player[1].jstart = nstsdl_input_translate_string(inputconf.js_p2start); + player[1].ja = nstsdl_input_translate_string(inputconf.js_p2a); + player[1].jb = nstsdl_input_translate_string(inputconf.js_p2b); + player[1].jta = nstsdl_input_translate_string(inputconf.js_p2ta); + player[1].jtb = nstsdl_input_translate_string(inputconf.js_p2tb); + } +} + +void nstsdl_input_conf_write() { + // Write out the input configuration file + FILE *fp = fopen(inputconfpath, "w"); + if (fp != NULL) { + fprintf(fp, "; Nestopia UE SDL Input Configuration File\n\n"); + fprintf(fp, "; Possible values for keyboard input are in the Key Name column:\n; https://wiki.libsdl.org/SDL_Scancode\n\n"); + fprintf(fp, "; Possible values for joystick input:\n; j[joystick number][a|b|h][button/hat/axis number][1/0 = +/- (axes only)]\n"); + fprintf(fp, "; Example: j0b3 = joystick 0, button 3. j1a11 = joystick 1, axis 1 +\n\n"); + fprintf(fp, "; Press Ctrl or Shift + [player number] to configure input in-game.\n; Ctrl for Keyboard, Shift for Joystick.\n"); + fprintf(fp, "; Example: Shift + 1 for Joystick input for Player 1\n\n"); + + fprintf(fp, "[ui]\n"); + fprintf(fp, "qsave1=%s\n", SDL_GetScancodeName(ui.qsave1)); + fprintf(fp, "qsave2=%s\n", SDL_GetScancodeName(ui.qsave2)); + fprintf(fp, "qload1=%s\n", SDL_GetScancodeName(ui.qload1)); + fprintf(fp, "qload2=%s\n", SDL_GetScancodeName(ui.qload2)); + + fprintf(fp, "screenshot=%s\n", SDL_GetScancodeName(ui.screenshot)); + + fprintf(fp, "fdsflip=%s\n", SDL_GetScancodeName(ui.fdsflip)); + fprintf(fp, "fdsswitch=%s\n", SDL_GetScancodeName(ui.fdsswitch)); + + fprintf(fp, "insertcoin1=%s\n", SDL_GetScancodeName(ui.insertcoin1)); + fprintf(fp, "insertcoin2=%s\n", SDL_GetScancodeName(ui.insertcoin2)); + + fprintf(fp, "reset=%s\n", SDL_GetScancodeName(ui.reset)); + + fprintf(fp, "ffspeed=%s\n", SDL_GetScancodeName(ui.ffspeed)); + fprintf(fp, "rwstart=%s\n", SDL_GetScancodeName(ui.rwstart)); + fprintf(fp, "rwstop=%s\n", SDL_GetScancodeName(ui.rwstop)); + + fprintf(fp, "fullscreen=%s\n", SDL_GetScancodeName(ui.fullscreen)); + fprintf(fp, "filter=%s\n", SDL_GetScancodeName(ui.filter)); + fprintf(fp, "scalefactor=%s\n", SDL_GetScancodeName(ui.scalefactor)); + fprintf(fp, "\n"); // End of Section + + fprintf(fp, "[gamepad1]\n"); + fprintf(fp, "kb_u=%s\n", SDL_GetScancodeName(player[0].u)); + fprintf(fp, "kb_d=%s\n", SDL_GetScancodeName(player[0].d)); + fprintf(fp, "kb_l=%s\n", SDL_GetScancodeName(player[0].l)); + fprintf(fp, "kb_r=%s\n", SDL_GetScancodeName(player[0].r)); + fprintf(fp, "kb_select=%s\n", SDL_GetScancodeName(player[0].select)); + fprintf(fp, "kb_start=%s\n", SDL_GetScancodeName(player[0].start)); + fprintf(fp, "kb_a=%s\n", SDL_GetScancodeName(player[0].a)); + fprintf(fp, "kb_b=%s\n", SDL_GetScancodeName(player[0].b)); + fprintf(fp, "kb_ta=%s\n", SDL_GetScancodeName(player[0].ta)); + fprintf(fp, "kb_tb=%s\n", SDL_GetScancodeName(player[0].tb)); + + fprintf(fp, "js_u=%s\n", nstsdl_input_translate_event(player[0].ju)); + fprintf(fp, "js_d=%s\n", nstsdl_input_translate_event(player[0].jd)); + fprintf(fp, "js_l=%s\n", nstsdl_input_translate_event(player[0].jl)); + fprintf(fp, "js_r=%s\n", nstsdl_input_translate_event(player[0].jr)); + fprintf(fp, "js_select=%s\n", nstsdl_input_translate_event(player[0].jselect)); + fprintf(fp, "js_start=%s\n", nstsdl_input_translate_event(player[0].jstart)); + fprintf(fp, "js_a=%s\n", nstsdl_input_translate_event(player[0].ja)); + fprintf(fp, "js_b=%s\n", nstsdl_input_translate_event(player[0].jb)); + fprintf(fp, "js_ta=%s\n", nstsdl_input_translate_event(player[0].jta)); + fprintf(fp, "js_tb=%s\n", nstsdl_input_translate_event(player[0].jtb)); + + fprintf(fp, "js_rwstart=%s\n", nstsdl_input_translate_event(player[0].rwstart)); + fprintf(fp, "js_rwstop=%s\n", nstsdl_input_translate_event(player[0].rwstop)); + fprintf(fp, "\n"); // End of Section + + fprintf(fp, "[gamepad2]\n"); + fprintf(fp, "kb_u=%s\n", SDL_GetScancodeName(player[1].u)); + fprintf(fp, "kb_d=%s\n", SDL_GetScancodeName(player[1].d)); + fprintf(fp, "kb_l=%s\n", SDL_GetScancodeName(player[1].l)); + fprintf(fp, "kb_r=%s\n", SDL_GetScancodeName(player[1].r)); + fprintf(fp, "kb_select=%s\n", SDL_GetScancodeName(player[1].select)); + fprintf(fp, "kb_start=%s\n", SDL_GetScancodeName(player[1].start)); + fprintf(fp, "kb_a=%s\n", SDL_GetScancodeName(player[1].a)); + fprintf(fp, "kb_b=%s\n", SDL_GetScancodeName(player[1].b)); + fprintf(fp, "kb_ta=%s\n", SDL_GetScancodeName(player[1].ta)); + fprintf(fp, "kb_tb=%s\n", SDL_GetScancodeName(player[1].tb)); + + fprintf(fp, "js_u=%s\n", nstsdl_input_translate_event(player[1].ju)); + fprintf(fp, "js_d=%s\n", nstsdl_input_translate_event(player[1].jd)); + fprintf(fp, "js_l=%s\n", nstsdl_input_translate_event(player[1].jl)); + fprintf(fp, "js_r=%s\n", nstsdl_input_translate_event(player[1].jr)); + fprintf(fp, "js_select=%s\n", nstsdl_input_translate_event(player[1].jselect)); + fprintf(fp, "js_start=%s\n", nstsdl_input_translate_event(player[1].jstart)); + fprintf(fp, "js_a=%s\n", nstsdl_input_translate_event(player[1].ja)); + fprintf(fp, "js_b=%s\n", nstsdl_input_translate_event(player[1].jb)); + fprintf(fp, "js_ta=%s\n", nstsdl_input_translate_event(player[1].jta)); + fprintf(fp, "js_tb=%s\n", nstsdl_input_translate_event(player[1].jtb)); + fprintf(fp, "\n"); // End of Section + + fclose(fp); + } +} + +void nstsdl_input_process(Input::Controllers *controllers, SDL_Event event) { + // Process input events + switch(event.type) { + case SDL_KEYUP: + case SDL_KEYDOWN: + nstsdl_input_match_keyboard(controllers, event); + break; + + case SDL_JOYBUTTONUP: + case SDL_JOYBUTTONDOWN: + case SDL_JOYAXISMOTION: + case SDL_JOYHATMOTION: + nstsdl_input_match_joystick(controllers, event); + break; + + case SDL_MOUSEBUTTONUP: + case SDL_MOUSEBUTTONDOWN: + nstsdl_input_match_mouse(controllers, event); + break; + + default: break; + } +} + +char* nstsdl_input_translate_event(SDL_Event event) { + // Translate an SDL_Event to an inputcode + static char inputcode[6]; + + switch(event.type) { + case SDL_JOYAXISMOTION: + sprintf(inputcode, "j%da%d%d", event.jaxis.which, event.jaxis.axis, nstsdl_input_checksign(event.jaxis.value)); + break; + + case SDL_JOYHATMOTION: + sprintf(inputcode, "j%dh%d%d", event.jhat.which, event.jhat.hat, event.jhat.value); + break; + + case SDL_JOYBUTTONUP: + case SDL_JOYBUTTONDOWN: + sprintf(inputcode, "j%db%d", event.jbutton.which, event.jbutton.button); + break; + } + return inputcode; +} + +SDL_Event nstsdl_input_translate_string(const char *string) { + // Translate an inputcode to an SDL_Event + SDL_Event event; + + int type, axis, value; + + int which = 0, whichdigits = 0; + + for (int i = 1; ; i++) { + if (isdigit(string[i])) { + whichdigits++; + } + else { + break; + } + } + + for (int i = 1; i <= whichdigits; i++) { + which += (string[i] - '0') * (pow (10, (whichdigits - i))); + } + + if ((unsigned char)string[whichdigits + 1] == 0x61) { // Axis + axis = string[whichdigits + 2] - '0'; + value = string[whichdigits + 3] - '0'; + event.type = SDL_JOYAXISMOTION; + event.jaxis.which = which; + event.jaxis.axis = axis; + event.jaxis.value = value; + } + else if ((unsigned char)string[whichdigits + 1] == 0x62) { // Button + value = string[whichdigits + 2] - '0'; + if (string[whichdigits + 3]) { + value = ((string[whichdigits + 2] - '0') * 10) + (string[whichdigits + 3] - '0'); + } + event.type = SDL_JOYBUTTONDOWN; + event.jbutton.which = which; + event.jbutton.button = value; + + } + else if ((unsigned char)string[whichdigits + 1] == 0x68) { // Hat + axis = string[whichdigits + 2] - '0'; + value = string[whichdigits + 3] - '0'; + event.type = SDL_JOYHATMOTION; + event.jhat.which = which; + event.jhat.hat = axis; + event.jhat.value = value; + } + else { + fprintf(stderr, "Malformed inputcode: %s\n", string); + } + + return event; +} + +void nstsdl_input_conf(int type, int pnum) { + // Configure Inputs + nst_pause(); + + SDL_Event event, eventbuf; + int axis = 0, axisnoise = 0, print = 0; + if (type == 0) { // Keyboard + for (int i = 0; i < 10;) { + if (print == i) { + nst_video_disp_inputconf(type, pnum, i); + nstsdl_video_swapbuffers(); + print++; + } + while (SDL_PollEvent(&event)) { + if (event.type == SDL_KEYDOWN) { nstsdl_input_conf_set(event, type, pnum, i); i++; } + } + } + } + else if (type == 1) { // Joystick + for (int i = 0; i < 10;) { + if (print == i) { + nst_video_disp_inputconf(type, pnum, i); + nstsdl_video_swapbuffers(); + print++; + } + + while (SDL_PollEvent(&event)) { + if (event.type == SDL_JOYAXISMOTION) { + if (abs(event.jaxis.value) >= DEADZONE) { + eventbuf = event; + axisnoise = 1; + axis = event.jaxis.axis; + } + else if (abs(event.jaxis.value) < DEADZONE && axisnoise && event.jaxis.axis == axis) { + nstsdl_input_conf_set(eventbuf, type, pnum, i); + axisnoise = 0; + i++; + } + } + else if (event.type == SDL_JOYHATMOTION) { + if (event.jhat.value != SDL_HAT_CENTERED) { + nstsdl_input_conf_set(event, type, pnum, i); + i++; + } + } + else if (event.type == SDL_JOYBUTTONDOWN) { + nstsdl_input_conf_set(event, type, pnum, i); + i++; + } + } + } + } + + nst_play(); +} + +void nstsdl_input_conf_button(int pnum, int bnum) { + // Configure Inputs for single Joystick Buttons + SDL_Event event, eventbuf; + int axis = 0, axisnoise = 0, confrunning = 1; + + while (confrunning) { + #ifdef _GTK + while (gtk_events_pending()) { gtk_main_iteration(); } + #endif + while (SDL_PollEvent(&event)) { + if (event.type == SDL_JOYAXISMOTION) { + if (abs(event.jaxis.value) >= DEADZONE) { + eventbuf = event; + axisnoise = 1; + axis = event.jaxis.axis; + } + else if (abs(event.jaxis.value) < DEADZONE && axisnoise && event.jaxis.axis == axis) { + nstsdl_input_conf_set(eventbuf, 1, pnum, bnum); + axisnoise = 0; + confrunning = 0; + } + } + else if (event.type == SDL_JOYHATMOTION) { + if (event.jhat.value != SDL_HAT_CENTERED) { + nstsdl_input_conf_set(event, 1, pnum, bnum); + confrunning = 0; + } + } + else if (event.type == SDL_JOYBUTTONDOWN) { + nstsdl_input_conf_set(event, 1, pnum, bnum); + confrunning = 0; + } + } + } +} diff -Nru nestopia-1.48/source/sdl/sdlinput.h nestopia-1.49/source/sdl/sdlinput.h --- nestopia-1.48/source/sdl/sdlinput.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/sdl/sdlinput.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,156 @@ +#ifndef _SDLINPUT_H_ +#define _SDLINPUT_H_ + +#define TOTALBUTTONS (NUMGAMEPADS*NUMBUTTONS) +#define DEADZONE (32768/3) + +#include "core/api/NstApiInput.hpp" + +typedef struct { + SDL_Scancode u; + SDL_Scancode d; + SDL_Scancode l; + SDL_Scancode r; + SDL_Scancode select; + SDL_Scancode start; + SDL_Scancode a; + SDL_Scancode b; + SDL_Scancode ta; + SDL_Scancode tb; + + SDL_Event ju; + SDL_Event jd; + SDL_Event jl; + SDL_Event jr; + SDL_Event jselect; + SDL_Event jstart; + SDL_Event ja; + SDL_Event jb; + SDL_Event jta; + SDL_Event jtb; + SDL_Event rwstart; + SDL_Event rwstop; +} gamepad_t; + +typedef struct { + SDL_Scancode qsave1; + SDL_Scancode qsave2; + SDL_Scancode qload1; + SDL_Scancode qload2; + + SDL_Scancode screenshot; + + SDL_Scancode fdsflip; + SDL_Scancode fdsswitch; + + SDL_Scancode insertcoin1; + SDL_Scancode insertcoin2; + + SDL_Scancode reset; + + SDL_Scancode ffspeed; + SDL_Scancode rwstart; + SDL_Scancode rwstop; + + SDL_Scancode fullscreen; + SDL_Scancode filter; + SDL_Scancode scalefactor; +} uiinput_t; + +typedef struct { + // User Interface + char *qsave1; + char *qsave2; + char *qload1; + char *qload2; + + char *screenshot; + + char *fdsflip; + char *fdsswitch; + + char *insertcoin1; + char *insertcoin2; + + char *reset; + + char *ffspeed; + char *rwstart; + char *rwstop; + + char *fullscreen; + char *filter; + char *scalefactor; + + // Player 1 + char *kb_p1u; + char *kb_p1d; + char *kb_p1l; + char *kb_p1r; + char *kb_p1select; + char *kb_p1start; + char *kb_p1a; + char *kb_p1b; + char *kb_p1ta; + char *kb_p1tb; + + char *js_p1u; + char *js_p1d; + char *js_p1l; + char *js_p1r; + char *js_p1select; + char *js_p1start; + char *js_p1a; + char *js_p1b; + char *js_p1ta; + char *js_p1tb; + + char *js_rwstart; + char *js_rwstop; + + // Player 2 + char *kb_p2u; + char *kb_p2d; + char *kb_p2l; + char *kb_p2r; + char *kb_p2select; + char *kb_p2start; + char *kb_p2a; + char *kb_p2b; + char *kb_p2ta; + char *kb_p2tb; + + char *js_p2u; + char *js_p2d; + char *js_p2l; + char *js_p2r; + char *js_p2select; + char *js_p2start; + char *js_p2a; + char *js_p2b; + char *js_p2ta; + char *js_p2tb; +} inputsettings_t; + + +void nstsdl_input_conf(int type, int pnum); +void nstsdl_input_conf_button(int pnum, int bnum); +void nstsdl_input_conf_defaults(); +void nstsdl_input_conf_set(SDL_Event event, int type, int pnum, int counter); +void nstsdl_input_conf_read(); +void nstsdl_input_conf_write(); + +void nstsdl_input_joysticks_detect(); +void nstsdl_input_joysticks_close(); + +void nstsdl_input_match_keyboard(Input::Controllers *controllers, SDL_Event event); +void nstsdl_input_match_mouse(Input::Controllers *controllers, SDL_Event event); +void nstsdl_input_match_joystick(Input::Controllers *controllers, SDL_Event event); +int nstsdl_input_checksign(int axisvalue); + +void nstsdl_input_process(Input::Controllers *controllers, SDL_Event event); + +char* nstsdl_input_translate_event(SDL_Event event); +SDL_Event nstsdl_input_translate_string(const char *string); + +#endif diff -Nru nestopia-1.48/source/sdl/sdlmain.cpp nestopia-1.49/source/sdl/sdlmain.cpp --- nestopia-1.48/source/sdl/sdlmain.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/sdl/sdlmain.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,169 @@ +/* + * Nestopia UE + * + * Copyright (C) 2007-2008 R. Belmont + * Copyright (C) 2012-2018 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +// Nst Common +#include "nstcommon.h" +#include "cli.h" +#include "audio.h" +#include "video.h" +#include "input.h" +#include "config.h" + +// Nst SDL +#include "sdlmain.h" +#include "sdlvideo.h" +#include "sdlinput.h" + +using namespace Nes::Api; + +static int nst_quit = 0; + +extern Input::Controllers *cNstPads; +extern nstpaths_t nstpaths; + +extern bool (*nst_archive_select)(const char*, char*, size_t); +extern void (*audio_deinit)(); + +void nst_schedule_quit() { + nst_quit = 1; +} + +int main(int argc, char *argv[]) { + // This is the main function + + // Set up directories + nst_set_dirs(); + + // Set default config options + config_set_default(); + + // Read the config file and override defaults + config_file_read(nstpaths.nstdir); + + // Exit if there is no CLI argument + if (argc == 1) { + cli_show_usage(); + return 0; + } + + // Handle command line arguments + cli_handle_command(argc, argv); + + // Set up callbacks + nst_set_callbacks(); + + // Initialize SDL + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) < 0) { + fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); + return 1; + } + + // Detect Joysticks + nstsdl_input_joysticks_detect(); + + // Set default input keys + nstsdl_input_conf_defaults(); + + // Read the input config file and override defaults + nstsdl_input_conf_read(); + + // Set archive handler function pointer + nst_archive_select = &nst_archive_select_file; + + // Set audio function pointers + audio_set_funcs(); + + // Set the video dimensions + video_set_dimensions(); + + // Initialize and load FDS BIOS and NstDatabase.xml + nst_fds_bios_load(); + nst_db_load(); + + // Load a rom from the command line + if (argc > 1) { + if (!nst_load(argv[argc - 1])) { nst_quit = 1; } + else { + // Create the window + nstsdl_video_create(); + nstsdl_video_set_title(nstpaths.gamename); + + // Set play in motion + nst_play(); + + // Set the cursor if needed + nstsdl_video_set_cursor(); + } + } + + // Start the main loop + SDL_Event event; + while (!nst_quit) { + nst_ogl_render(); + nstsdl_video_swapbuffers(); + + while (SDL_PollEvent(&event)) { + switch (event.type) { + case SDL_QUIT: + nst_quit = 1; + break; + + case SDL_KEYDOWN: + case SDL_KEYUP: + case SDL_JOYHATMOTION: + case SDL_JOYAXISMOTION: + case SDL_JOYBUTTONDOWN: + case SDL_JOYBUTTONUP: + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: + nstsdl_input_process(cNstPads, event); + break; + default: break; + } + } + + nst_emuloop(); + } + + // Remove the cartridge and shut down the NES + nst_unload(); + + // Unload the FDS BIOS, NstDatabase.xml, and the custom palette + nst_db_unload(); + nst_fds_bios_unload(); + nst_palette_unload(); + + // Deinitialize audio + audio_deinit(); + + // Deinitialize joysticks + nstsdl_input_joysticks_close(); + + // Write the input config file + nstsdl_input_conf_write(); + + // Write the config file + config_file_write(nstpaths.nstdir); + + return 0; +} diff -Nru nestopia-1.48/source/sdl/sdlmain.h nestopia-1.49/source/sdl/sdlmain.h --- nestopia-1.48/source/sdl/sdlmain.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/sdl/sdlmain.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,6 @@ +#ifndef _SDLMAIN_H_ +#define _SDLMAIN_H_ + +void nst_schedule_quit(); + +#endif diff -Nru nestopia-1.48/source/sdl/sdlvideo.cpp nestopia-1.49/source/sdl/sdlvideo.cpp --- nestopia-1.48/source/sdl/sdlvideo.cpp 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/sdl/sdlvideo.cpp 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,158 @@ +/* + * Nestopia UE + * + * Copyright (C) 2012-2018 R. Danbrook + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include + +// Nst Common +#include "nstcommon.h" +#include "config.h" +#include "video.h" +#include "input.h" + +// Nst SDL +#include "cursor.h" +#include "sdlvideo.h" + +static SDL_GLContext glcontext; +static SDL_Window *sdlwindow; + +extern nstpaths_t nstpaths; +extern Emulator emulator; + +void nstsdl_video_create() { + // Create the window + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); + + Uint32 windowflags = SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL; + + dimensions_t rendersize = nst_video_get_dimensions_render(); + + sdlwindow = SDL_CreateWindow( + NULL, // window title + SDL_WINDOWPOS_UNDEFINED, // initial x position + SDL_WINDOWPOS_UNDEFINED, // initial y position + rendersize.w, // width, in pixels + rendersize.h, // height, in pixels + windowflags); + + if(sdlwindow == NULL) { + fprintf(stderr, "Could not create window: %s\n", SDL_GetError()); + } + + glcontext = SDL_GL_CreateContext(sdlwindow); + SDL_GL_MakeCurrent(sdlwindow, glcontext); + SDL_GL_SetSwapInterval(conf.timing_vsync); + + if(glcontext == NULL) { + fprintf(stderr, "Could not create glcontext: %s\n", SDL_GetError()); + } + + fprintf(stderr, "OpenGL: %s\n", glGetString(GL_VERSION)); + + nst_video_set_dimensions_screen(nstsdl_video_get_dimensions()); + + // Fullscreen the window after creation + if (conf.video_fullscreen) { nstsdl_video_toggle_fullscreen(); } +} + +void nstsdl_video_destroy() { + // Destroy the video window + SDL_DestroyWindow(sdlwindow); +} + +dimensions_t nstsdl_video_get_dimensions() { + // Return the dimensions of the current screen + dimensions_t scrsize; + SDL_DisplayMode displaymode; + int displayindex = SDL_GetWindowDisplayIndex(sdlwindow); + SDL_GetDesktopDisplayMode(displayindex, &displaymode); + scrsize.w = displaymode.w; + scrsize.h = displaymode.h; + return scrsize; +} + +void nstsdl_video_resize() { + dimensions_t rendersize = nst_video_get_dimensions_render(); + SDL_SetWindowSize(sdlwindow, rendersize.w, rendersize.h); +} + +void nstsdl_video_set_cursor() { + // Set the cursor to what it needs to be + if (nst_input_zapper_present()) { + if (conf.misc_disable_cursor_special) { + SDL_ShowCursor(false); + } + else { + SDL_ShowCursor(true); // Must be set true before being modified if special + cursor_set_special(Input::ZAPPER); + } + } + else { + if (conf.misc_disable_cursor || conf.video_fullscreen) { SDL_ShowCursor(false); } + else { SDL_ShowCursor(true); } + } +} + +void nstsdl_video_set_title(const char *title) { + // Set the window title + SDL_SetWindowTitle(sdlwindow, title); +} + +void nstsdl_video_swapbuffers() { + // Swap Buffers + SDL_GL_SwapWindow(sdlwindow); +} + +void nstsdl_video_toggle_fullscreen() { + + video_toggle_fullscreen(); + + Uint32 flags; + if (conf.video_fullscreen) { flags = SDL_WINDOW_FULLSCREEN_DESKTOP; } + else { flags = 0; } + + SDL_SetWindowFullscreen(sdlwindow, flags); + + nstsdl_video_set_cursor(); + + nst_video_set_dimensions_screen(nstsdl_video_get_dimensions()); + + video_init(); + + nstsdl_video_resize(); +} + +void nstsdl_video_toggle_filter() { + video_toggle_filter(); + nst_video_set_dimensions_screen(nstsdl_video_get_dimensions()); + video_init(); + nstsdl_video_resize(); +} + +void nstsdl_video_toggle_scale() { + video_toggle_scalefactor(); + nst_video_set_dimensions_screen(nstsdl_video_get_dimensions()); + video_init(); + nstsdl_video_resize(); +} diff -Nru nestopia-1.48/source/sdl/sdlvideo.h nestopia-1.49/source/sdl/sdlvideo.h --- nestopia-1.48/source/sdl/sdlvideo.h 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/source/sdl/sdlvideo.h 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,19 @@ +#ifndef _SDLVIDEO_H_ +#define _SDLVIDEO_H_ + +void nstsdl_video_create(); +void nstsdl_video_destroy(); + +dimensions_t nstsdl_video_get_dimensions(); +void nstsdl_video_resize(); + +void nstsdl_video_set_cursor(); +void nstsdl_video_set_title(const char *title); + +void nstsdl_video_swapbuffers(); + +void nstsdl_video_toggle_fullscreen(); +void nstsdl_video_toggle_filter(); +void nstsdl_video_toggle_scale(); + +#endif diff -Nru nestopia-1.48/source/unix/audio.cpp nestopia-1.49/source/unix/audio.cpp --- nestopia-1.48/source/unix/audio.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/audio.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,244 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2017 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include -#include - -#include "config.h" -#include "audio.h" - -#ifndef _MINGW -#include - -static ao_device *aodevice; -static ao_sample_format format; -#endif - -extern settings_t conf; -extern Emulator emulator; -extern bool nst_pal; -extern bool updateok; - -static SDL_AudioSpec spec, obtained; -static SDL_AudioDeviceID dev; - -static int16_t audiobuf[6400]; - -static int framerate, channels, bufsize; - -static bool altspeed = false; -static bool paused = false; - -void (*audio_output)(); -void (*audio_deinit)(); - -void audio_output_sdl() { - //SDL_QueueAudio(dev, (const void*)audiobuf, bufsize); - // Clear the audio queue arbitrarily to avoid it backing up too far - //if (SDL_GetQueuedAudioSize(dev) > (Uint32)(bufsize * 3)) { SDL_ClearQueuedAudio(dev); } -} - -void audio_output_ao() { -#ifndef _MINGW - ao_play(aodevice, (char*)audiobuf, bufsize); -#endif -} - -void audio_deinit_sdl() { - SDL_CloseAudioDevice(dev); -} - -void audio_deinit_ao() { -#ifndef _MINGW - ao_close(aodevice); - ao_shutdown(); -#endif -} - -void audio_play() { - if (paused) { updateok = true; return; } - bufsize = 2 * channels * (conf.audio_sample_rate / framerate); - audio_output(); - updateok = true; -} - -void audio_cb_sdl(void *data, uint8_t *stream, int len) { - uint8_t *soundbuf = (uint8_t*)audiobuf; - - for (int i = 0; i < len; i++) { - stream[i] = soundbuf[i]; - } -} - -void audio_init_sdl() { - spec.freq = conf.audio_sample_rate; - spec.format = AUDIO_S16SYS; - spec.channels = channels; - spec.silence = 0; - spec.samples = (conf.audio_sample_rate / framerate); - spec.userdata = 0; - //spec.callback = NULL; // Use SDL_QueueAudio instead - spec.callback = audio_cb_sdl; - - dev = SDL_OpenAudioDevice(NULL, 0, &spec, &obtained, SDL_AUDIO_ALLOW_ANY_CHANGE); - if (!dev) { - fprintf(stderr, "Error opening audio device.\n"); - } - else { - fprintf(stderr, "Audio: SDL - %dHz %d-bit, %d channel(s)\n", spec.freq, 16, spec.channels); - } - - SDL_PauseAudioDevice(dev, 1); // Setting to 0 unpauses -} - -void audio_init_ao() { -#ifndef _MINGW - ao_initialize(); - - int default_driver = ao_default_driver_id(); - - memset(&format, 0, sizeof(format)); - format.bits = 16; - format.channels = channels; - format.rate = conf.audio_sample_rate; - format.byte_format = AO_FMT_NATIVE; - - aodevice = ao_open_live(default_driver, &format, NULL); - if (aodevice == NULL) { - fprintf(stderr, "Error opening audio device.\n"); - aodevice = ao_open_live(ao_driver_id("null"), &format, NULL); - } - else { - fprintf(stderr, "Audio: libao - %dHz, %d-bit, %d channel(s)\n", format.rate, format.bits, format.channels); - } -#endif -} - -void audio_init() { - // Initialize audio device - - // Set the framerate based on the region. For PAL: (60 / 6) * 5 = 50 - framerate = nst_pal ? (conf.timing_speed / 6) * 5 : conf.timing_speed; - channels = conf.audio_stereo ? 2 : 1; - memset(audiobuf, 0, sizeof(audiobuf)); - - #ifdef _MINGW - conf.audio_api = 0; // Set SDL audio for MinGW - #endif - - if (conf.audio_api == 0) { // SDL - audio_init_sdl(); - audio_output = &audio_output_sdl; - audio_deinit = &audio_deinit_sdl; - } - else if (conf.audio_api == 1) { // libao - audio_init_ao(); - audio_output = &audio_output_ao; - audio_deinit = &audio_deinit_ao; - } - - paused = false; -} - -void audio_pause() { - // Pause the SDL audio device - if (conf.audio_api == 0) { // SDL - SDL_PauseAudioDevice(dev, 1); - } - paused = true; -} - -void audio_unpause() { - // Unpause the SDL audio device - if (conf.audio_api == 0) { // SDL - SDL_PauseAudioDevice(dev, 0); - } - paused = false; -} - -void audio_set_params(Sound::Output *soundoutput) { - // Set audio parameters - Sound sound(emulator); - - sound.SetSampleBits(16); - sound.SetSampleRate(conf.audio_sample_rate); - - sound.SetSpeaker(conf.audio_stereo ? Sound::SPEAKER_STEREO : Sound::SPEAKER_MONO); - sound.SetSpeed(Sound::DEFAULT_SPEED); - - audio_adj_volume(); - - soundoutput->samples[0] = audiobuf; - soundoutput->length[0] = conf.audio_sample_rate / framerate; - soundoutput->samples[1] = NULL; - soundoutput->length[1] = 0; -} - -void audio_adj_volume() { - // Adjust the audio volume to the current settings - Sound sound(emulator); - sound.SetVolume(Sound::ALL_CHANNELS, conf.audio_volume); - sound.SetVolume(Sound::CHANNEL_SQUARE1, conf.audio_vol_sq1); - sound.SetVolume(Sound::CHANNEL_SQUARE2, conf.audio_vol_sq2); - sound.SetVolume(Sound::CHANNEL_TRIANGLE, conf.audio_vol_tri); - sound.SetVolume(Sound::CHANNEL_NOISE, conf.audio_vol_noise); - sound.SetVolume(Sound::CHANNEL_DPCM, conf.audio_vol_dpcm); - sound.SetVolume(Sound::CHANNEL_FDS, conf.audio_vol_fds); - sound.SetVolume(Sound::CHANNEL_MMC5, conf.audio_vol_mmc5); - sound.SetVolume(Sound::CHANNEL_VRC6, conf.audio_vol_vrc6); - sound.SetVolume(Sound::CHANNEL_VRC7, conf.audio_vol_vrc7); - sound.SetVolume(Sound::CHANNEL_N163, conf.audio_vol_n163); - sound.SetVolume(Sound::CHANNEL_S5B, conf.audio_vol_s5b); - - if (conf.audio_volume == 0) { memset(audiobuf, 0, sizeof(audiobuf)); } -} - -// Timing Functions - -bool timing_frameskip() { - // Calculate whether to skip a frame or not - - if (conf.audio_api == 0) { // SDL - // Wait until the audio is drained - //while (SDL_GetQueuedAudioSize(dev) > (Uint32)bufsize) { - // if (conf.timing_limiter) { SDL_Delay(1); } - //} - } - - static int fskip; - fskip = altspeed ? (fskip > 1 ? 0 : fskip + 1) : 0; - return fskip; -} - -void timing_set_default() { - // Set the framerate to the default - altspeed = false; - framerate = nst_pal ? (conf.timing_speed / 6) * 5 : conf.timing_speed; - //if (conf.audio_api == 0) { SDL_ClearQueuedAudio(dev); } -} - -void timing_set_altspeed() { - // Set the framerate to the alternate speed - altspeed = true; - framerate = conf.timing_altspeed; -} diff -Nru nestopia-1.48/source/unix/audio.h nestopia-1.49/source/unix/audio.h --- nestopia-1.48/source/unix/audio.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/audio.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -#ifndef _AUDIO_H_ -#define _AUDIO_H_ - -#include -#include "core/api/NstApiEmulator.hpp" -#include "core/api/NstApiSound.hpp" - -using namespace Nes::Api; - -extern void (*audio_deinit)(); - -void audio_init(); -void audio_play(); -void audio_pause(); -void audio_unpause(); -void audio_set_params(Sound::Output *soundoutput); -void audio_adj_volume(); - -bool timing_frameskip(); -void timing_set_default(); -void timing_set_altspeed(); - -#endif diff -Nru nestopia-1.48/source/unix/cheats.cpp nestopia-1.49/source/unix/cheats.cpp --- nestopia-1.48/source/unix/cheats.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/cheats.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,194 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include - -#include -#include - -#include "main.h" -#include "cheats.h" - -extern Emulator emulator; -extern nstpaths_t nstpaths; - -void cheats_init() { - // Initialize cheat engine - Cheats cheats(emulator); - Xml xml; - - cheats.ClearCodes(); - - std::ifstream cheatfile(nstpaths.cheatpath, std::ifstream::in|std::ifstream::binary); - - if (cheatfile.is_open()) { - xml.Read(cheatfile); - - if (xml.GetRoot().IsType(L"cheats")) { - - Xml::Node root(xml.GetRoot()); - Xml::Node node(root.GetFirstChild()); - - for (int i = 0; i < root.NumChildren(L"cheat"); i++) { - - if (node.GetAttribute(L"enabled").IsValue(L"1")) { - - if (node.GetChild(L"genie")) { // Game Genie - cheats_code_gg_add(node.GetChild(L"genie").GetValue()); - } - - else if (node.GetChild(L"rocky")) { // Pro Action Rocky - cheats_code_par_add(node.GetChild(L"rocky").GetValue()); - } - - else if (node.GetChild(L"address")) { // Raw - cheats_code_raw_add(node); - } - - //fprintf(stderr, "Cheat: %ls\n", node.GetChild(L"description").GetValue()); - } - node = node.GetNextSibling(); - } - } - cheatfile.close(); - } -} - -/*void cheats_list() { - // List the active cheats - Cheats cheats(emulator); - Cheats::Code code; - - char gg[9]; - - for (int i = 0; i < cheats.NumCodes(); i++) { - cheats.GetCode(i, code); - cheats.GameGenieEncode(code, gg); - - fprintf(stderr, "Cheat: %s\n", gg); - } -}*/ - -void cheats_code_gg_add(const wchar_t *data) { - // Add a Game Genie code - Cheats cheats(emulator); - Cheats::Code code; - - char gg[9]; - wcstombs(gg, data, sizeof(gg)); - - cheats.GameGenieDecode(gg, code); - cheats.SetCode(code); -} - -void cheats_code_par_add(const wchar_t *data) { - // Add a Pro Action Rocky code - Cheats cheats(emulator); - Cheats::Code code; - - char par[9]; - wcstombs(par, data, sizeof(par)); - - cheats.ProActionRockyDecode(par, code); - cheats.SetCode(code); -} - -void cheats_code_raw_add(Xml::Node node) { - // Add a Raw code - Cheats cheats(emulator); - Cheats::Code code; - - code.useCompare = false; - - code.address = node.GetChild(L"address").GetUnsignedValue(); - if (node.GetChild(L"value")) { - code.value = node.GetChild(L"value").GetUnsignedValue(); - } - if (node.GetChild(L"compare")) { - code.compare = node.GetChild(L"compare").GetUnsignedValue(); - code.useCompare = true; - } - cheats.SetCode(code); -} - -// DIP Switches -void dip_handle() { - // Handle the DIP switch file - DipSwitches dipswitches(emulator); - Xml xml; - - char dippath[512]; - snprintf(dippath, sizeof(dippath), "%s%s.dip", nstpaths.savedir, nstpaths.gamename); - - std::ifstream dipfile(dippath, std::ifstream::in|std::ifstream::binary); - - if (dipfile.is_open()) { - xml.Read(dipfile); - - if (xml.GetRoot().IsType(L"dipswitches")) { - Xml::Node root(xml.GetRoot()); - Xml::Node node(root.GetFirstChild()); - - for (int i = 0; i < root.NumChildren(L"dip"); i++) { - - if (node.GetChild(L"value")) { - dipswitches.SetValue(i, node.GetChild(L"value").GetUnsignedValue()); - } - node = node.GetNextSibling(); - } - } - dipfile.close(); - } - else { - Xml::Node root(xml.GetRoot()); - - root = xml.Create(L"dipswitches"); - root.AddAttribute(L"version", L"1.0"); - - wchar_t wbuf[32]; - char buf[2]; - - int numdips = dipswitches.NumDips(); - - if (numdips > 0) { - for (int i = 0; i < numdips; i++) { - Xml::Node node(root.AddChild(L"dip")); - - mbstowcs(wbuf, dipswitches.GetDipName(i), sizeof(wbuf)); - node.AddChild(L"description", wbuf); - - snprintf(buf, sizeof(buf), "%d", dipswitches.GetValue(i)); - mbstowcs(wbuf, buf, sizeof(buf)); - node.AddChild(L"value", wbuf); - } - } - - std::ofstream dipout(dippath, std::ifstream::out|std::ifstream::binary); - - if (dipout.is_open()) { - xml.Write(root, dipout); - } - - dipout.close(); - } -} diff -Nru nestopia-1.48/source/unix/cheats.h nestopia-1.49/source/unix/cheats.h --- nestopia-1.48/source/unix/cheats.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/cheats.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -#ifndef _CHEATS_H_ -#define _CHEATS_H_ - -#include "core/api/NstApiEmulator.hpp" -#include "core/api/NstApiCheats.hpp" -#include "core/api/NstApiDipSwitches.hpp" -#include "core/NstStream.hpp" -#include "core/NstXml.hpp" - -using namespace Nes::Api; - -typedef Nes::Core::Xml Xml; - -void cheats_init(); -void cheats_code_gg_add(const wchar_t *data); -void cheats_code_par_add(const wchar_t *data); -void cheats_code_raw_add(Xml::Node node); - -// DIP Switches -void dip_handle(); - -#endif diff -Nru nestopia-1.48/source/unix/cli.cpp nestopia-1.49/source/unix/cli.cpp --- nestopia-1.48/source/unix/cli.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/cli.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,182 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include -#include - -#include "main.h" -#include "cli.h" -#include "config.h" - -extern settings_t conf; - -void cli_error(const char *message) { - cli_show_usage(); - fprintf(stderr, "%s\n", message); - exit(1); -} - -void cli_show_usage() { - printf("Usage: nestopia [options] [FILE]\n"); - printf("\nOptions:\n"); - printf(" -d, --disablegui Disable GTK+ GUI\n"); - printf(" -e, --enablegui Enable GTK+ GUI\n\n"); - printf(" -f, --fullscreen Fullscreen mode\n"); - printf(" -w, --window Window mode\n\n"); - printf(" -l, --filter Video Filter\n"); - printf(" (0=None, 1=NTSC, 2=xBR, 3=HqX, 4=2xSaI, 5=ScaleX)\n\n"); - printf(" -m, --maskoverscan Mask overscan areas\n"); - printf(" -n, --no-maskoverscan Disable overscan masking\n\n"); - printf(" -o, --stretchfs Stretch to native resolution in fullscreen mode\n"); - printf(" -p, --preserveaspect Preserve aspect ratio in fullscreen mode\n\n"); - printf(" -s, --scalefactor Video scale factor (1-4)\n\n"); - printf(" -t, --tvaspect TV aspect ratio\n"); - printf(" -r, --no-tvaspect Regular aspect ratio\n\n"); - printf(" -u, --unlimitedsprites Remove sprite limit\n"); - printf(" -q, --spritelimit Enable sprite limit\n\n"); - printf(" -v, --version Show version information\n\n"); - printf("More options can be set in the configuration file.\n"); - printf("Options are saved, and do not need to be set on future invocations.\n\n"); -} - -void cli_show_version() { - printf("Nestopia UE %s\n", VERSION); -} - -void cli_handle_command(int argc, char *argv[]) { - int c; - int optint; - - while (1) { - static struct option long_options[] = { - {"disablegui", no_argument, 0, 'd'}, - {"enablegui", no_argument, 0, 'e'}, - {"fullscreen", no_argument, 0, 'f'}, - {"window", no_argument, 0, 'w'}, - {"help", no_argument, 0, 'h'}, - {"filter", required_argument, 0, 'l'}, - {"maskoverscan", no_argument, 0, 'm'}, - {"no-maskoverscan", no_argument, 0, 'n'}, - {"stretchfs", no_argument, 0, 'o'}, - {"preserveaspect", no_argument, 0, 'p'}, - {"scalefactor", required_argument, 0, 's'}, - {"tvaspect", no_argument, 0, 't'}, - {"no-tvaspect", no_argument, 0, 'r'}, - {"unlimitedsprites", no_argument, 0, 'u'}, - {"spritelimit", no_argument, 0, 'q'}, - {"version", no_argument, 0, 'v'}, - {0, 0, 0, 0} - }; - - int option_index = 0; - - c = getopt_long(argc, argv, "defhl:mnopqrs:tuvw", - long_options, &option_index); - - if (c == -1) { break; } - - switch(c) { - case 'd': - conf.misc_disable_gui = true; - break; - - case 'e': - conf.misc_disable_gui = false; - break; - - case 'f': - conf.video_fullscreen = true; - break; - - case 'w': - conf.video_fullscreen = false; - break; - - case 'h': - cli_show_usage(); - exit(0); - break; - - case 'l': - optint = atoi(optarg); - if (optint < 6) { - conf.video_filter = optint; - } - else { - cli_error("Error: Invalid filter"); - } - break; - - case 'm': - conf.video_unmask_overscan = false; - break; - - case 'n': - conf.video_unmask_overscan = true; - break; - - case 'o': - conf.video_stretch_aspect = true; - break; - - case 'p': - conf.video_stretch_aspect = false; - break; - - case 's': - optint = atoi(optarg); - if (optint < 5 && optint != 0) { - conf.video_scale_factor = optint; - } - else { - cli_error("Error: Invalid scale factor"); - } - break; - - case 't': - conf.video_tv_aspect = true; - break; - - case 'r': - conf.video_tv_aspect = false; - break; - - case 'u': - conf.video_unlimited_sprites = true; - break; - - case 'q': - conf.video_unlimited_sprites = false; - break; - - case 'v': - cli_show_version(); - exit(0); - break; - - default: - cli_error("Error: Invalid option"); - break; - } - } -} diff -Nru nestopia-1.48/source/unix/cli.h nestopia-1.49/source/unix/cli.h --- nestopia-1.48/source/unix/cli.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/cli.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -void cli_error(const char *message); -void cli_show_usage(); -void cli_show_version(); -void cli_handle_command(int argc, char *argv[]); diff -Nru nestopia-1.48/source/unix/config.cpp nestopia-1.49/source/unix/config.cpp --- nestopia-1.48/source/unix/config.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/config.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,279 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include -#include - -#include "main.h" -#include "config.h" -#include "ini.h" - -settings_t conf; - -char confpath[256]; -extern nstpaths_t nstpaths; - -void config_file_read() { - // Read the config file - - snprintf(confpath, sizeof(confpath), "%snestopia.conf", nstpaths.nstdir); - - if (ini_parse(confpath, config_match, &conf) < 0) { - fprintf(stderr, "Failed to read config file %s: Using defaults.\n", confpath); - } -} - -void config_file_write() { - // Write the config file - - FILE *fp = fopen(confpath, "w"); - if (fp != NULL) { - // Video - fprintf(fp, "; Nestopia UE Configuration File\n\n"); - fprintf(fp, "[video]\n"); - fprintf(fp, "; 0=None, 1=NTSC, 2=xBR, 3=HqX, 4=2xSaI, 5=ScaleX\n"); - fprintf(fp, "filter=%d\n\n", conf.video_filter); - fprintf(fp, "; Valid values are 1 to 4.\n"); - fprintf(fp, "scale_factor=%d\n\n", conf.video_scale_factor); - fprintf(fp, "; 0=YUV, 1=RGB, 2=Custom\n"); - fprintf(fp, "palette_mode=%d\n\n", conf.video_palette_mode); - fprintf(fp, "; 0=Consumer, 1=Canonical, 2=Alternative\n"); - fprintf(fp, "decoder=%d\n\n", conf.video_decoder); - fprintf(fp, "; Valid values are -100 to 100.\n"); - fprintf(fp, "brightness=%d\n", conf.video_brightness); - fprintf(fp, "saturation=%d\n", conf.video_saturation); - fprintf(fp, "contrast=%d\n\n", conf.video_contrast); - fprintf(fp, "; Valid values are -45 to 45.\n"); - fprintf(fp, "hue=%d\n\n", conf.video_hue); - fprintf(fp, "; 0=Composite, 1=S-Video, 2=RGB, 3=Monochrome, 4=Custom\n"); - fprintf(fp, "ntsc_mode=%d\n\n", conf.video_ntsc_mode); - fprintf(fp, "; Valid values are -100 to 100.\n"); - fprintf(fp, "ntsc_sharpness=%d\n", conf.video_ntsc_sharpness); - fprintf(fp, "ntsc_resolution=%d\n", conf.video_ntsc_resolution); - fprintf(fp, "ntsc_bleed=%d\n", conf.video_ntsc_bleed); - fprintf(fp, "ntsc_artifacts=%d\n", conf.video_ntsc_artifacts); - fprintf(fp, "ntsc_fringing=%d\n\n", conf.video_ntsc_fringing); - fprintf(fp, "; 0=None, 1=Some, 2=All\n"); - fprintf(fp, "xbr_corner_rounding=%d\n\n", conf.video_xbr_corner_rounding); - fprintf(fp, "; Valid values are 1 and 0.\n"); - fprintf(fp, "linear_filter=%d\n", conf.video_linear_filter); - fprintf(fp, "tv_aspect=%d\n", conf.video_tv_aspect); - fprintf(fp, "unmask_overscan=%d\n", conf.video_unmask_overscan); - fprintf(fp, "fullscreen=%d\n", conf.video_fullscreen); - fprintf(fp, "stretch_aspect=%d\n", conf.video_stretch_aspect); - fprintf(fp, "unlimited_sprites=%d\n", conf.video_unlimited_sprites); - fprintf(fp, "xbr_pixel_blending=%d\n", conf.video_xbr_pixel_blending); - fprintf(fp, "\n"); // End of Section - - // Audio - fprintf(fp, "[audio]\n"); - fprintf(fp, "; 0=SDL, 1=libao\n"); - fprintf(fp, "api=%d\n\n", conf.audio_api); - fprintf(fp, "; Valid values are 1 and 0.\n"); - fprintf(fp, "stereo=%d\n\n", conf.audio_stereo); - fprintf(fp, "; Valid values are 11025, 22050, 44100, 48000, and 96000.\n"); - fprintf(fp, "sample_rate=%d\n\n", conf.audio_sample_rate); - fprintf(fp, "; Valid values are 0 to 100.\n"); - fprintf(fp, "volume=%d\n", conf.audio_volume); - fprintf(fp, "vol_sq1=%d\n", conf.audio_vol_sq1); - fprintf(fp, "vol_sq2=%d\n", conf.audio_vol_sq2); - fprintf(fp, "vol_tri=%d\n", conf.audio_vol_tri); - fprintf(fp, "vol_noise=%d\n", conf.audio_vol_noise); - fprintf(fp, "vol_dpcm=%d\n", conf.audio_vol_dpcm); - fprintf(fp, "vol_fds=%d\n", conf.audio_vol_fds); - fprintf(fp, "vol_mmc5=%d\n", conf.audio_vol_mmc5); - fprintf(fp, "vol_vrc6=%d\n", conf.audio_vol_vrc6); - fprintf(fp, "vol_vrc7=%d\n", conf.audio_vol_vrc7); - fprintf(fp, "vol_n163=%d\n", conf.audio_vol_n163); - fprintf(fp, "vol_s5b=%d\n", conf.audio_vol_s5b); - fprintf(fp, "\n"); // End of Section - - // Timing - fprintf(fp, "[timing]\n"); - fprintf(fp, "; Base speed for NTSC in Frames per Second.\n"); - fprintf(fp, "speed=%d\n\n", conf.timing_speed); - fprintf(fp, "; Alternate speed (slow down or fast forward)\n"); - fprintf(fp, "altspeed=%d\n\n", conf.timing_altspeed); - fprintf(fp, "; Pulse turbo buttons every n frames. Minimum value is 2.\n"); - fprintf(fp, "turbopulse=%d\n\n", conf.timing_turbopulse); - fprintf(fp, "; Valid values are 1 and 0.\n"); - fprintf(fp, "vsync=%d\n", conf.timing_vsync); - fprintf(fp, "limiter=%d\n", conf.timing_limiter); - fprintf(fp, "\n"); // End of Section - - // Misc - fprintf(fp, "[misc]\n"); - fprintf(fp, "; 0=Auto, 1=NTSC, 2=PAL, 3=Famicom, 4=Dendy\n"); - fprintf(fp, "default_system=%d\n\n", conf.misc_default_system); - fprintf(fp, "; Valid values are 1 and 0.\n"); - fprintf(fp, "soft_patching=%d\n", conf.misc_soft_patching); - //fprintf(fp, "suppress_screensaver=%d\n", conf.misc_suppress_screensaver); - fprintf(fp, "genie_distortion=%d\n", conf.misc_genie_distortion); - fprintf(fp, "disable_gui=%d\n", conf.misc_disable_gui); - fprintf(fp, "disable_cursor=%d\n", conf.misc_disable_cursor); - fprintf(fp, "config_pause=%d\n", conf.misc_config_pause); - fprintf(fp, "last_folder=%s\n", conf.misc_last_folder); - fprintf(fp, "; 0=0x00, 1=0xFF, 2=Random\n"); - fprintf(fp, "power_state=%d\n", conf.misc_power_state); - - fclose(fp); - } - else { - fprintf(stderr, "Failed to write config file %s.\n", confpath); - } -} - -void config_set_default() { - - // Video - conf.video_filter = 0; - conf.video_scale_factor = 2; - conf.video_palette_mode = 0; - conf.video_decoder = 0; - conf.video_brightness = 0; // -100 to 100 - conf.video_saturation = 0; // -100 to 100 - conf.video_contrast = 0; // -100 to 100 - conf.video_hue = 0; // -45 to 45 - conf.video_ntsc_mode = 0; - conf.video_ntsc_sharpness = 0; // -100 to 100 - conf.video_ntsc_resolution = 0; // -100 to 100 - conf.video_ntsc_bleed = 0; // -100 to 100 - conf.video_ntsc_artifacts = 0; // -100 to 100 - conf.video_ntsc_fringing = 0; // -100 to 100 - conf.video_xbr_corner_rounding = 0; - conf.video_linear_filter = false; - conf.video_tv_aspect = false; - conf.video_unmask_overscan = false; - conf.video_fullscreen = false; - conf.video_stretch_aspect = false; - conf.video_unlimited_sprites = false; - conf.video_xbr_pixel_blending = false; - - // Audio - conf.audio_api = 1; - conf.audio_stereo = false; - conf.audio_sample_rate = 44100; - conf.audio_volume = 85; - conf.audio_vol_sq1 = 85; - conf.audio_vol_sq2 = 85; - conf.audio_vol_tri = 85; - conf.audio_vol_noise = 85; - conf.audio_vol_dpcm = 85; - conf.audio_vol_fds = 85; - conf.audio_vol_mmc5 = 85; - conf.audio_vol_vrc6 = 85; - conf.audio_vol_vrc7 = 85; - conf.audio_vol_n163 = 85; - conf.audio_vol_s5b = 85; - - // Timing - conf.timing_speed = 60; - conf.timing_altspeed = 180; - conf.timing_turbopulse = 3; - conf.timing_vsync = true; - conf.timing_limiter = true; - - // Misc - conf.misc_default_system = 0; - conf.misc_soft_patching = true; - //conf.misc_suppress_screensaver = true; - conf.misc_genie_distortion = false; - conf.misc_disable_gui = false; - conf.misc_disable_cursor = false; - conf.misc_config_pause = false; - #ifdef _MINGW - conf.misc_disable_gui = true; // Disable GUI for MinGW - #endif - #ifdef _APPLE - conf.misc_config_pause = true; // Always pause on OS X - #endif - conf.misc_last_folder = NULL; - conf.misc_power_state = 0; -} - -static int config_match(void* user, const char* section, const char* name, const char* value) { - // Match values from config file and populate live config - settings_t* pconfig = (settings_t*)user; - - // Video - if (MATCH("video", "filter")) { pconfig->video_filter = atoi(value); } - else if (MATCH("video", "scale_factor")) { pconfig->video_scale_factor = atoi(value); } - else if (MATCH("video", "palette_mode")) { pconfig->video_palette_mode = atoi(value); } - else if (MATCH("video", "decoder")) { pconfig->video_decoder = atoi(value); } - else if (MATCH("video", "brightness")) { pconfig->video_brightness = atoi(value); } - else if (MATCH("video", "saturation")) { pconfig->video_saturation = atoi(value); } - else if (MATCH("video", "contrast")) { pconfig->video_contrast = atoi(value); } - else if (MATCH("video", "hue")) { pconfig->video_hue = atoi(value); } - else if (MATCH("video", "ntsc_mode")) { pconfig->video_ntsc_mode = atoi(value); } - else if (MATCH("video", "ntsc_sharpness")) { pconfig->video_ntsc_sharpness = atoi(value); } - else if (MATCH("video", "ntsc_resolution")) { pconfig->video_ntsc_resolution = atoi(value); } - else if (MATCH("video", "ntsc_bleed")) { pconfig->video_ntsc_bleed = atoi(value); } - else if (MATCH("video", "ntsc_artifacts")) { pconfig->video_ntsc_artifacts = atoi(value); } - else if (MATCH("video", "ntsc_fringing")) { pconfig->video_ntsc_fringing = atoi(value); } - else if (MATCH("video", "xbr_corner_rounding")) { pconfig->video_xbr_corner_rounding = atoi(value); } - else if (MATCH("video", "linear_filter")) { pconfig->video_linear_filter = atoi(value); } - else if (MATCH("video", "tv_aspect")) { pconfig->video_tv_aspect = atoi(value); } - else if (MATCH("video", "unmask_overscan")) { pconfig->video_unmask_overscan = atoi(value); } - else if (MATCH("video", "fullscreen")) { pconfig->video_fullscreen = atoi(value); } - else if (MATCH("video", "stretch_aspect")) { pconfig->video_stretch_aspect = atoi(value); } - else if (MATCH("video", "unlimited_sprites")) { pconfig->video_unlimited_sprites = atoi(value); } - else if (MATCH("video", "xbr_pixel_blending")) { pconfig->video_xbr_pixel_blending = atoi(value); } - - // Audio - else if (MATCH("audio", "api")) { pconfig->audio_api = atoi(value); } - else if (MATCH("audio", "stereo")) { pconfig->audio_stereo = atoi(value); } - else if (MATCH("audio", "sample_rate")) { pconfig->audio_sample_rate = atoi(value); } - else if (MATCH("audio", "volume")) { pconfig->audio_volume = atoi(value); } - else if (MATCH("audio", "vol_sq1")) { pconfig->audio_vol_sq1 = atoi(value); } - else if (MATCH("audio", "vol_sq2")) { pconfig->audio_vol_sq2 = atoi(value); } - else if (MATCH("audio", "vol_tri")) { pconfig->audio_vol_tri = atoi(value); } - else if (MATCH("audio", "vol_noise")) { pconfig->audio_vol_noise = atoi(value); } - else if (MATCH("audio", "vol_dpcm")) { pconfig->audio_vol_dpcm = atoi(value); } - else if (MATCH("audio", "vol_fds")) { pconfig->audio_vol_fds = atoi(value); } - else if (MATCH("audio", "vol_mmc5")) { pconfig->audio_vol_mmc5 = atoi(value); } - else if (MATCH("audio", "vol_vrc6")) { pconfig->audio_vol_vrc6 = atoi(value); } - else if (MATCH("audio", "vol_vrc7")) { pconfig->audio_vol_vrc7 = atoi(value); } - else if (MATCH("audio", "vol_n163")) { pconfig->audio_vol_n163 = atoi(value); } - else if (MATCH("audio", "vol_s5b")) { pconfig->audio_vol_s5b = atoi(value); } - - // Timing - else if (MATCH("timing", "speed")) { pconfig->timing_speed = atoi(value); } - else if (MATCH("timing", "altspeed")) { pconfig->timing_altspeed = atoi(value); } - else if (MATCH("timing", "turbopulse")) { pconfig->timing_turbopulse = atoi(value); } - else if (MATCH("timing", "vsync")) { pconfig->timing_vsync = atoi(value); } - else if (MATCH("timing", "limiter")) { pconfig->timing_limiter = atoi(value); } - - // Misc - else if (MATCH("misc", "default_system")) { pconfig->misc_default_system = atoi(value); } - else if (MATCH("misc", "soft_patching")) { pconfig->misc_soft_patching = atoi(value); } - //else if (MATCH("misc", "suppress_screensaver")) { pconfig->misc_suppress_screensaver = atoi(value); } - else if (MATCH("misc", "genie_distortion")) { pconfig->misc_genie_distortion = atoi(value); } - else if (MATCH("misc", "disable_gui")) { pconfig->misc_disable_gui = atoi(value); } - else if (MATCH("misc", "config_pause")) { pconfig->misc_config_pause = atoi(value); } - else if (MATCH("misc", "disable_cursor")) { pconfig->misc_disable_cursor = atoi(value); } - else if (MATCH("misc", "last_folder")) { pconfig->misc_last_folder = strdup(value); } - else if (MATCH("misc", "power_state")) { pconfig->misc_power_state = atoi(value); } - - else { return 0; } - return 1; -} diff -Nru nestopia-1.48/source/unix/config.h nestopia-1.49/source/unix/config.h --- nestopia-1.48/source/unix/config.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/config.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -#ifndef _CONFIG_H_ -#define _CONFIG_H_ - -typedef struct { - - // Video - int video_filter; - int video_scale_factor; - int video_palette_mode; - int video_decoder; - int video_brightness; - int video_saturation; - int video_contrast; - int video_hue; - int video_ntsc_mode; - int video_ntsc_sharpness; - int video_ntsc_resolution; - int video_ntsc_bleed; - int video_ntsc_artifacts; - int video_ntsc_fringing; - int video_xbr_corner_rounding; - bool video_linear_filter; - bool video_tv_aspect; - bool video_unmask_overscan; - bool video_fullscreen; - bool video_stretch_aspect; - bool video_unlimited_sprites; - bool video_xbr_pixel_blending; - - // Audio - int audio_api; - bool audio_stereo; - int audio_sample_rate; - int audio_volume; - int audio_vol_sq1; - int audio_vol_sq2; - int audio_vol_tri; - int audio_vol_noise; - int audio_vol_dpcm; - int audio_vol_fds; - int audio_vol_mmc5; - int audio_vol_vrc6; - int audio_vol_vrc7; - int audio_vol_n163; - int audio_vol_s5b; - - // Timing - int timing_speed; - int timing_altspeed; - int timing_turbopulse; - bool timing_vsync; - bool timing_limiter; - - // Misc - //int misc_video_region; - int misc_default_system; - bool misc_soft_patching; - //bool misc_suppress_screensaver; - bool misc_genie_distortion; - bool misc_disable_gui; - bool misc_disable_cursor; - bool misc_config_pause; - char* misc_last_folder; - int misc_power_state; -} settings_t; - -void config_file_read(); -void config_file_write(); -void config_set_default(); -static int config_match(void* user, const char* section, const char* name, const char* value); -#endif diff -Nru nestopia-1.48/source/unix/cursor.cpp nestopia-1.49/source/unix/cursor.cpp --- nestopia-1.48/source/unix/cursor.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/cursor.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,116 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include - -#include - -#include "cursor.h" - -static SDL_Cursor *cursor; - -// Most of this is adapted from the code example in the SDL documentation - -static const char *crosshair[] = { - " X ", - " X.X ", - " XXX ", - " X.X ", - " XXX ", - " X.X ", - " XXX ", - " X.X ", - " XXX ", - " X.X ", - " XXX ", - " XX.XX ", - " X.XXX.X ", - " XXXXXXXXXXXX XXXXXXXXXXXX ", - "X.X.X.X.X.X.X . X.X.X.X.X.X.X ", - " XXXXXXXXXXXX XXXXXXXXXXXX ", - " X.XXX.X ", - " XX.XX ", - " XXX ", - " X.X ", - " XXX ", - " X.X ", - " XXX ", - " X.X ", - " XXX ", - " X.X ", - " XXX ", - " X.X ", - " X ", - " ", - " ", - " ", - "14,14" // Center -}; - -static SDL_Cursor *cursor_init(const char *image[]) { - int i, row, col; - Uint8 data[4*32]; - Uint8 mask[4*32]; - int hot_x, hot_y; - - i = -1; - for (row=0; row<32; ++row) { - for ( col=0; col<32; ++col ) { - if ( col % 8 ) { - data[i] <<= 1; - mask[i] <<= 1; - } - else { - ++i; - data[i] = mask[i] = 0; - } - - switch (image[row][col]) { - case 'X': - data[i] |= 0x01; - mask[i] |= 0x01; - break; - - case '.': - mask[i] |= 0x01; - break; - - case ' ': break; - } - } - } - - sscanf(image[row], "%d,%d", &hot_x, &hot_y); - return SDL_CreateCursor(data, mask, 32, 32, hot_x, hot_y); -} - -void cursor_set_special(int type) { - // Set special cursors - cursor = cursor_init(crosshair); - SDL_SetCursor(cursor); -} - -void cursor_set_default() { - // Set the cursor to default - SDL_FreeCursor(cursor); -} diff -Nru nestopia-1.48/source/unix/cursor.h nestopia-1.49/source/unix/cursor.h --- nestopia-1.48/source/unix/cursor.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/cursor.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -#ifndef _CURSOR_H_ -#define _CURSOR_H_ - -void cursor_set_special(int type); -void cursor_set_default(); - -#endif diff -Nru nestopia-1.48/source/unix/font.h nestopia-1.49/source/unix/font.h --- nestopia-1.48/source/unix/font.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/font.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,99 +0,0 @@ -const char *nesfont[] = { -" .. . . . . . ", // 0 -" ..+ .+ .+ . . . . . + . . +", -" ..+ .+ .+ ...... . +. + . .+ . + ", -" ..+ ++ ++ .++.++ +. + . .+. ..... ..... . + ", -" ..+ .+ .+ . +. +.+ + +.+++ +++++ . + ", -" ++ ...... . +. . . .+. .+ .. .. . + ", -" .. .++.++ . + . + +.+ + + ..+ ..+ . + ", -" ++ + + + + + .++ ++ + ", -" ..... .. ..... ..... ... ....... ..... ....... ..... ..... .... ", // 8 -"..+++.. ...+ ..+++.. ..+++.. ....+ ..++++++..+++.. ..+++..+..+++.. ..+++.. .. .. .. .. ..++.. ", -"..+ ..+ ..+ ..+ ..+ ++ ..+ ..+..+ ...... ..+ ++ ++ ..++..+ ..+..+ ..+ ..+ ..+ ..++ ..... .. ++ ..+ ", -"..+ ..+ ..+ ++ ..++ ....++..++..+ ..+++.. ...... ..++ .....++ ......+ ++ ++ .++ +++++ .+ ..++ ", -"..+ ..+ ..+ .. ++ ++.. ..+ ..+ ++ ..+..+++.. ..+ ..+++.. +++..+ .+ .+ ..++ ", -"..+ ..+ ..+ ..++ .. ..+....... .. ..+..+ ..+ ..++ ..+ ..+.. ..+ .. ..+ .. ..... ..+ ++ ", -" .....++ .... ....... .....++ +++..++ .....++ .....++ ..+ .....++ .....++ ..+ ..+ .. +++++ ..++ .. ", -" +++++ ++++ +++++++ +++++ ++ +++++ +++++ ++ +++++ +++++ ++ .++ ++ ++ ++ ", -" ... ...... .... ..... ....... ....... ..... .. .. .... ..... .. .. .. . . . .. ..... ", // 16 -" ..+.. ..+++.. ..++.. ..++.. ..++++++..++++++..+++.. ..+ ..+ ..++ +..++..+ ..++..+ .. ..+.. ..+..+++.. ", -" .++ .+ ..+ ..+..++ ++..+ .. ..+ ..+ ..+ ++..+ ..+ ..+ ..+ ..+..++ ..+ ... ...+... ..+..+ ..+", -" ..+ .. ......++..+ ..+ ..+...... ...... ..+.... .......+ ..+ ..+ ....++ ..+ .......+.... ..+..+ ..+", -" .......+..+++.. ..+ ..+ ..+..+++++ ..+++++ ..+ +..+..+++..+ ..+ ..+ ..+.. ..+ ..+.+..+..+....+..+ ..+", -" ..+++..+..+ ..+ .. .. ..+ ..++..+ ..+ ..+ ..+..+ ..+ ..+ .. ..+ ..+ .. ..+ ..+ +..+..+ ...+..+ ..+", -" ..+ ..+......++ ....++.....++ ....... ..+ .....++..+ ..+ .... ....++ ..+ .. ....... ..+ ..+..+ ..+ .....++", -" ++ ++ ++++++ ++++ +++++ +++++++ ++ +++++ ++ ++ ++++ ++++ ++ ++ +++++++ ++ ++ ++ ++ +++++ ", -"...... ..... ...... ..... ...... .. .. .. .. .. .. .. .. .. .. ...... ", // 24 -"..+++.. ..+++.. ..+++.. ..+++.. +..+++ ..+ ..+..+ ..+..+ ..+..+ ..+..+ ..+ +++..+ .. .. ", -"..+ ..+..+ ..+..+ ..+..+ ++ ..+ ..+ ..+..+ ..+..+. ..+ .. ..++..+ ..+ ..++ ..++ .. ", -"..+ ..+..+ ..+..+ ...+ ..... ..+ ..+ ..+..+ ..+..+.+..+ ...++ ....++ ..++ .++ .+ ", -"......++..+.. .+.....+++ +++.. ..+ ..+ ..+ .. ..++.......+ ..+.. ..++ ..++ .+ .+ ", -"..+++++ ..+ .. +..+... .. ..+ ..+ ..+ ..+ ..+..+ ...+...+..++ .. ..+ ..++ .. ..+ ", -"..+ ... .. ..+ ... .....++ ..+ .....++ ...++ .++ .++..+ ..+ ..+ ...... .. ..++ ....... ", -" ++ +++ ++ ++ +++ +++++ ++ +++++ +++ + + ++ ++ ++ ++++++ ++ ++ +++++++", -" .. .. .. ... .. .. ... ", // 32 -" ..+ ..+ ..+ ..+++ ..+ .. .. ..+ ..+ ", -" .++ .... ..... ..... .....+ .... ..+ ..... ..+ ++ ++ ..+ .. ..+ ... .. ..... .... ", -" + ..++.. ..++.. ..+++++ ..++..+ ..++.. ...... ..++..+ ..... .. .. ..+..++ ..+ ..+. .. ..++.. ..++.. ", -" ..+ ..+ ..+ ..+ ..+ ..+ ..+ ......+ +..+++ ..+ ..+ ..++.. ..+ ..+ ....++ ..+ ..+.+..+..+ ..+ ..+ ..+ ", -" ..+ ..+ ..+ ..+ ..+ ..+ ..+ ..+++++ ..+ .....+ ..+ ..+ ..+ ..+ ..+.. ..+ ..+.+..+..+ ..+ ..+ ..+ ", -" ... .. .....++ ..... .....+ ..... ..+ ++..+ ..+ ..+ ..+ .. ..+ ..+ .. ..+ ..+.+..+..+ ..+ ....++ ", -" +++ ++ +++++ +++++ +++++ +++++ ++ ....++ ++ ++ ++ ....++ ++ ++ ++ ++ + ++ ++ ++ ++++ ", -" .. ", // 40 -" ..+ .. .. ", -"..... ..... .. ... .... ...... .. .. .. .. .. .. .. .. .. .. ...... ..++ .. ", -"..++.. ..++..+ ... +++ ..++++ +..+++ ..+ ..+ ..+ ..+ ..+. ..+ .. ..++..+ ..+ ++..++ .++ .+ .. . ", -"..+ ..+ ..+ ..+ ..++ .... ..+ ..+ ..+ ..+ ..+ ..+.+..+ ...++ ....++ ..++ .+ .+ . +.. + ", -".....++ .....+ ..+ ++.. ..+ ..+ ..+ ....++ ..+.+..+ ..+.. ..++ ..++ .. ..+ + ++ ", -"..++++ ++..+ ..+ .....++ ... ....++ ..++ .. ..++..++ .. ..++ ...... .. ..++ ", -"..+ ... ++ +++++ +++ ++++ ++ ++ ++ ++ ++..++ ++++++ ++ ++ "}; - -const char *nesfont2[] = { -" .. .. .. .. .. .. ... .. .. .. .. ", // 0 -" .... .. .. .. .. ..... .. .. .. .. .. .. .. .. .. .. .. ", -" .... .. .. ....... .. .. .. ... .. .. .. .... .. .. ", -" .... .. .. .... .. ... .. .. .. .............. ...... .. ", -" .. ....... .. .. .. ... .. .. .... .. .. ", -" .. .. .. ..... .. .. .. .. .. .. .. .. .. .. .. .. ", -" .. .. .. .. .. ... .. .. .. .. .. . ", -" .. .. ", -" ... .. ..... ...... ... ...... .... ....... ..... ..... .. .. .... ", // 8 -" . .. ... .. .. .. .... .. .. .. .. .. .. .. .. .. .. .. .. .. .. ", -".. .. .. ... .. .. .. ...... .. .. .. .. .. .. .. .. .. ...... .. .. ", -".. .. .. .... .... .. .. .. ...... .. ..... ...... .. .. .. ", -".. .. .. .... .. ....... .. .. .. .. .. .. .. .. .. .. ", -" .. . .. ... .. .. .. .. .. .. .. .. .. .. .. .. .. .. ...... .. ", -" ... ...... ....... ..... .. ..... ..... .. ..... .... .. .. .. .. .. ", -" .. ", -" ..... ... ...... .... ..... ....... ....... ..... .. .. ...... .... .. .. .. .. .. .. .. ..... ", // 16 -".. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ... ... ... .. .. .. ", -".. .... .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ....... .... .. .. .. ", -".. .... .. .. ...... .. .. .. ...... ...... .. ... ....... .. .. .... .. ....... ....... .. .. ", -".. .... ....... .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..... .. .. . .. .. .... .. .. ", -".. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ... .. .. .. .. ... .. .. ", -" .... .. .. ...... .... ..... ....... .. ..... .. .. ...... ..... .. ... ...... .. .. .. .. ..... ", -" ", -"...... ..... ...... .... ...... .. .. .. .. .. .. .. .. .. .. ....... .... .. .... . ", // 24 -".. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ... ... .. .. ... .. .. .. ... ", -".. .. .. .. .. .. .. .. .. .. .. .. .. . .. ..... .. .. ... .. .. .. .. .. ", -".. .. .. .. .. ... ..... .. .. .. ... ... ....... ... .... ... .. .. .. .. .. ", -"...... .. .... ..... .. .. .. .. ..... ....... ..... .. ... .. .. .. ", -".. .. .. .. ... .. .. .. .. .. ... ... ... ... ... .. ... .. .. .. ", -".. .... . .. ... ..... .. ..... . .. .. .. .. .. ....... .... . .... ", -" ........", -" .. .. .. ... .. .. .. ", // 32 -" .. .. .. .. .. .. .. .. .. ", -" .. .... ..... ..... ..... .... .. ..... .. .. . .. ... .. ..... .... ", -" .. .. .. .. .. .. .. .. .. ...... .. .. ..... .. .. .. . .. .. . .. .. .. .. .. ", -" .. .. .. .. .. .. .. ...... .. .. .. .. .. .. .. .. . .. .. . .. .. .. .. .. ", -" .. .. .. .. .. .. .. .. .. ..... .. .. .. .. ..... .. .. . .. .. .. .. .. ", -" ... .. ..... ..... ..... ..... .. .. .. .. .. .. .. .. .. .. .. . .. .. .. .... ", -" .... .... ", -" .. ... .. ... ... .. ", // 40 -" .. .. .. .. .. ... . ", -" ..... ..... .. ... .... ...... .. .. .. .. .. .. .. .. .. .. ...... .. .. .. ... ", -" .. .. .. .. ... . .. .. .. .. .. .. . .. .. .. .. .. .. ... ... .. .. ", -" .. .. .. .. .. .... .. .. .. .. .. .. . .. ... . .. .. .. .. .. .. .. ", -" ..... ..... .. .. .. .. .. . . .. . .. .. .. .. .. .. .. .. .. .. ", -" .. .. .. ..... ... .... .. .. .. .. .. .. ...... ... .. ... ....... ", -" .. .. .. "}; diff -Nru nestopia-1.48/source/unix/gtkui/gtkui_archive.cpp nestopia-1.49/source/unix/gtkui/gtkui_archive.cpp --- nestopia-1.48/source/unix/gtkui/gtkui_archive.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui_archive.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,202 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include -#include - -#include "../main.h" -#include "../config.h" - -#include "gtkui.h" -#include "gtkui_archive.h" - -bool windowopen, cancelled; - -GtkWidget *archivewindow; - -extern settings_t conf; - -bool gtkui_archive_handle(const char *filename, char *reqfile, size_t reqsize) { - // Select a filename to pull out of the archive - struct archive *a; - struct archive_entry *entry; - int r, numarchives = 0; - - cancelled = false; - - a = archive_read_new(); - archive_read_support_filter_all(a); - archive_read_support_format_all(a); - r = archive_read_open_filename(a, filename, 10240); - - // Test if it's actually an archive - if (r != ARCHIVE_OK) { - r = archive_read_free(a); - return false; - } - // If it is an archive, handle it - else { - // Don't try to bring up a GUI selector if the GUI is disabled - if (conf.misc_disable_gui) { - // Fill the treestore with the filenames - while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { - const char *currentfile = archive_entry_pathname(entry); - if (nst_archive_checkext(currentfile)) { - snprintf(reqfile, reqsize, "%s", currentfile); - break; - } - } - archive_read_data_skip(a); - // Free the archive - r = archive_read_free(a); - return true; - } - - // Set up the archive window - GtkTreeIter iter; - GtkTreeModel *model; - GtkTreeSelection *selection; - - archivewindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); - gtk_window_set_title(GTK_WINDOW(archivewindow), "Choose File from Archive"); - gtk_window_set_modal(GTK_WINDOW(archivewindow), TRUE); - - GtkWidget *archivebox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); - gtk_container_add(GTK_CONTAINER(archivewindow), archivebox); - gtk_widget_show(archivebox); - - GtkWidget *scrolledwindow = gtk_scrolled_window_new(NULL, NULL); - gtk_box_pack_start(GTK_BOX(archivebox), scrolledwindow, TRUE, TRUE, 0); - gtk_widget_set_size_request(scrolledwindow, 340, 340); - gtk_widget_show(scrolledwindow); - - GtkWidget *buttonbox = gtk_widget_new(GTK_TYPE_BOX, "halign", GTK_ALIGN_END, NULL); - gtk_box_pack_start(GTK_BOX(archivebox), buttonbox, FALSE, TRUE, 0); - gtk_widget_show(buttonbox); - - GtkWidget *treeview = gtk_tree_view_new(); - gtk_container_add(GTK_CONTAINER(scrolledwindow), treeview); - gtk_tree_view_set_fixed_height_mode(GTK_TREE_VIEW (treeview), FALSE); - gtk_widget_show(treeview); - - GtkTreeStore *treestore = gtk_tree_store_new(1, G_TYPE_STRING); - - gtk_tree_view_set_model(GTK_TREE_VIEW(treeview), GTK_TREE_MODEL(treestore)); - - // Fill the treestore with the filenames - while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { - const char *currentfile = archive_entry_pathname(entry); - if (nst_archive_checkext(currentfile)) { - gtk_tree_store_append(treestore, &iter, NULL); - gtk_tree_store_set(treestore, &iter, 0, currentfile, -1); - numarchives++; - snprintf(reqfile, reqsize, "%s", currentfile); - } - archive_read_data_skip(a); - } - // Free the archive - r = archive_read_free(a); - - // If there are no valid files in the archive, return - if (numarchives == 0) { return false; } - // If there's only one file, don't bring up the selector - else if (numarchives == 1) { return true; } - - GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); - - GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes( - "NES file", - renderer, - "text", 0, - NULL); - - gtk_tree_view_append_column(GTK_TREE_VIEW (treeview), column); - - GtkWidget *cancelbutton = gtk_widget_new( - GTK_TYPE_BUTTON, - "label", GTK_STOCK_CANCEL, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_button_set_use_stock(GTK_BUTTON(cancelbutton), TRUE); - gtk_box_pack_start(GTK_BOX(buttonbox), cancelbutton, FALSE, FALSE, 0); - gtk_widget_show(cancelbutton); - - GtkWidget *okbutton = gtk_widget_new( - GTK_TYPE_BUTTON, - "label", GTK_STOCK_OK, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_button_set_use_stock(GTK_BUTTON(okbutton), TRUE); - gtk_box_pack_start(GTK_BOX(buttonbox), okbutton, FALSE, FALSE, 0); - gtk_widget_show(okbutton); - - selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)); - - g_signal_connect(G_OBJECT(okbutton), "clicked", - G_CALLBACK(gtkui_archive_ok), NULL); - - g_signal_connect(G_OBJECT(cancelbutton), "clicked", - G_CALLBACK(gtkui_archive_cancel), NULL); - - g_signal_connect(G_OBJECT(treeview), "row-activated", - G_CALLBACK(gtkui_archive_ok), NULL); - - g_signal_connect(G_OBJECT(archivewindow), "destroy", - G_CALLBACK(gtkui_archive_cancel), NULL); - - gtk_widget_show(archivewindow); - - // Freeze the rest of the program until a selection is made - windowopen = true; - while (windowopen) { - gtk_main_iteration_do(TRUE); - if (cancelled) { return false; } - } - - gchar *reqbuf; - selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)); - gtk_tree_selection_get_selected(selection, &model, &iter); - gtk_tree_model_get(model, &iter, 0, &reqbuf, -1); - - gtk_widget_destroy(archivewindow); - - snprintf(reqfile, reqsize, "%s", reqbuf); - return true; - } - return false; -} - -void gtkui_archive_ok() { - windowopen = false; -} - -void gtkui_archive_cancel() { - cancelled = true; - gtk_widget_destroy(archivewindow); -} diff -Nru nestopia-1.48/source/unix/gtkui/gtkui_archive.h nestopia-1.49/source/unix/gtkui/gtkui_archive.h --- nestopia-1.48/source/unix/gtkui/gtkui_archive.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui_archive.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -#ifndef _GTKUI_ARCHIVE_H_ -#define _GTKUI_ARCHIVE_H_ - -bool gtkui_archive_handle(const char *filename, char *reqfile, size_t reqsize); -void gtkui_archive_ok(); -void gtkui_archive_cancel(); - -#endif diff -Nru nestopia-1.48/source/unix/gtkui/gtkui_callbacks.cpp nestopia-1.49/source/unix/gtkui/gtkui_callbacks.cpp --- nestopia-1.48/source/unix/gtkui/gtkui_callbacks.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui_callbacks.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,480 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include - -#include "../main.h" -#include "../config.h" -#include "../video.h" - -#include "gtkui.h" -#include "gtkui_callbacks.h" - -extern settings_t conf; -extern bool playing, kbactivate, confrunning; - -//// Menu //// - -void gtkui_cb_reset(GtkWidget *reset, int hard) { - // Reset the NES from the GUI - nst_reset(hard); -} - -void gtkui_cb_nothing() { - // Do nothing -} - -void gtkui_cb_video_refresh() { - // Refresh the Video output after changes - if (playing) { - video_init(); - } - else { video_set_dimensions(); } -} - -// Video // - -void gtkui_cb_video_filter(GtkComboBox *combobox, gpointer userdata) { - // Change the video filter - conf.video_filter = gtk_combo_box_get_active(combobox); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_scale(GtkComboBox *combobox, gpointer userdata) { - // Change the scale factor - conf.video_scale_factor = gtk_combo_box_get_active(combobox) + 1; - - // The scalex filter only allows 3x scale and crashes otherwise - if (conf.video_filter == 5 && conf.video_scale_factor == 4) { - conf.video_scale_factor = 3; - } - - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_ntscmode(GtkComboBox *combobox, gpointer userdata) { - // Change the NTSC Mode - conf.video_ntsc_mode = gtk_combo_box_get_active(combobox); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_xbrrounding(GtkComboBox *combobox, gpointer userdata) { - // Set xBR corner rounding parameters - conf.video_xbr_corner_rounding = gtk_combo_box_get_active(combobox); - gtkui_cb_video_refresh(); - video_toggle_filterupdate(); -} - -void gtkui_cb_video_xbrpixblend(GtkToggleButton *togglebutton, gpointer userdata) { - // Set xBR pixel blending parameters - conf.video_xbr_pixel_blending = gtk_toggle_button_get_active(togglebutton); - gtkui_cb_video_refresh(); - video_toggle_filterupdate(); -} - -void gtkui_cb_video_linear_filter(GtkToggleButton *togglebutton, gpointer userdata) { - // Set linear filter - conf.video_linear_filter = gtk_toggle_button_get_active(togglebutton); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_tv_aspect(GtkToggleButton *togglebutton, gpointer userdata) { - // Set TV aspect ratio - conf.video_tv_aspect = gtk_toggle_button_get_active(togglebutton); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_unmask_overscan(GtkToggleButton *togglebutton, gpointer userdata) { - // Set overscan mask - conf.video_unmask_overscan = gtk_toggle_button_get_active(togglebutton); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_stretch_aspect(GtkToggleButton *togglebutton, gpointer userdata) { - // Set aspect ratio stretching/preservation - conf.video_stretch_aspect = gtk_toggle_button_get_active(togglebutton); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_unlimited_sprites(GtkToggleButton *togglebutton, gpointer userdata) { - // Set sprite limit - conf.video_unlimited_sprites = gtk_toggle_button_get_active(togglebutton); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_palette(GtkComboBox *combobox, gpointer userdata) { - // Change the video palette - conf.video_palette_mode = gtk_combo_box_get_active(combobox); - gtkui_cb_video_refresh(); - // this doesn't work unless there's a restart - fix -} - -void gtkui_cb_video_decoder(GtkComboBox *combobox, gpointer userdata) { - // Change the YUV Decoder - conf.video_decoder = gtk_combo_box_get_active(combobox); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_brightness(GtkRange *range, gpointer userdata) { - // Change video brightness - conf.video_brightness = (int)gtk_range_get_value(range); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_saturation(GtkRange *range, gpointer userdata) { - // Change video saturation - conf.video_saturation = (int)gtk_range_get_value(range); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_contrast(GtkRange *range, gpointer userdata) { - // Change video contrast - conf.video_contrast = (int)gtk_range_get_value(range); - gtkui_cb_video_refresh(); -} - -void gtkui_cb_video_hue(GtkRange *range, gpointer userdata) { - // Change video hue - conf.video_hue = (int)gtk_range_get_value(range); - gtkui_cb_video_refresh(); -} - -// Audio // - -void gtkui_cb_audio_api(GtkComboBox *combobox, gpointer userdata) { - // Change the Audio API - if (playing) { - nst_pause(); - conf.audio_api = gtk_combo_box_get_active(combobox); - nst_play(); - } - else { conf.audio_api = gtk_combo_box_get_active(combobox); } -} - -void gtkui_cb_audio_samplerate(GtkComboBox *combobox, gpointer userdata) { - // Change the Sample Rate - switch (gtk_combo_box_get_active(combobox)) { - case 0: - conf.audio_sample_rate = 11025; - break; - case 1: - conf.audio_sample_rate = 22050; - break; - case 2: - conf.audio_sample_rate = 44100; - break; - case 3: - conf.audio_sample_rate = 48000; - break; - case 4: - conf.audio_sample_rate = 96000; - break; - default: - conf.audio_sample_rate = 44100; - break; - } - - if (playing) { - nst_pause(); - nst_play(); - } -} - -void gtkui_cb_audio_stereo(GtkToggleButton *togglebutton, gpointer userdata) { - // Toggle Stereo - conf.audio_stereo = gtk_toggle_button_get_active(togglebutton); - - if (playing) { - nst_pause(); - nst_play(); - } -} - -//// Input //// - -void gtkui_cb_input_turbopulse(GtkRange *range, gpointer userdata) { - // Change turbo pulse - conf.timing_turbopulse = (int)gtk_range_get_value(range); -} - -//// Misc //// - -void gtkui_cb_misc_default_system(GtkComboBox *combobox, gpointer userdata) { - // Select the default system - conf.misc_default_system = gtk_combo_box_get_active(combobox); -} - -void gtkui_cb_misc_power_state(GtkComboBox *combobox, gpointer userdata) { - // Select the default system - conf.misc_power_state = gtk_combo_box_get_active(combobox); -} - -void gtkui_cb_timing_altspeed(GtkRange *range, gpointer userdata) { - // Set altspeed - conf.timing_altspeed = (int)gtk_range_get_value(range); -} - -void gtkui_cb_timing_vsync(GtkToggleButton *togglebutton, gpointer userdata) { - // Toggle vsync - conf.timing_vsync = gtk_toggle_button_get_active(togglebutton); -} - -void gtkui_cb_timing_limiter(GtkToggleButton *togglebutton, gpointer userdata) { - // Set the limiter on or off - conf.timing_limiter = gtk_toggle_button_get_active(togglebutton); -} - -void gtkui_cb_misc_soft_patching(GtkToggleButton *togglebutton, gpointer userdata) { - // Enable or Disable automatic soft patching - conf.misc_soft_patching = gtk_toggle_button_get_active(togglebutton); -} - -void gtkui_cb_misc_genie_distortion(GtkToggleButton *togglebutton, gpointer userdata) { - // Enable or Disable Game Genie Sound Distortion - conf.misc_genie_distortion = gtk_toggle_button_get_active(togglebutton); -} - -void gtkui_cb_misc_disable_gui(GtkToggleButton *togglebutton, gpointer userdata) { - // Enable or Disable the GUI - conf.misc_disable_gui = gtk_toggle_button_get_active(togglebutton); -} - -void gtkui_cb_misc_disable_cursor(GtkToggleButton *togglebutton, gpointer userdata) { - // Enable or Disable the Cursor - conf.misc_disable_cursor = gtk_toggle_button_get_active(togglebutton); - video_set_cursor(); -} - -void gtkui_cb_misc_config_pause(GtkToggleButton *togglebutton, gpointer userdata) { - // Enable or Disable the GUI - conf.misc_config_pause = gtk_toggle_button_get_active(togglebutton); -} - -//// Key Translation //// - -// This function is based on code from FCEUX -unsigned int gtkui_cb_translate_gdk_sdl(int gdk_keyval) { - // Translate GDK keys to SDL keys - - if (!(gdk_keyval & 0xFF00)) { - gdk_keyval = tolower(gdk_keyval); - return gdk_keyval; - } - - if (gdk_keyval & 0xFFFF0000) { - fprintf(stderr, "Unhandled extended key: 0x%08X\n", gdk_keyval); - return 0; - } - - // Non-ASCII symbol. - static const SDL_Keycode gdk_to_sdl_table[0x100] = { - // 0x00 - 0x0F - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - SDLK_BACKSPACE, SDLK_TAB, SDLK_RETURN, SDLK_CLEAR, - 0x0000, SDLK_RETURN, 0x0000, 0x0000, - - // 0x10 - 0x1F - 0x0000, 0x0000, 0x0000, SDLK_PAUSE, - SDLK_SCROLLLOCK, SDLK_SYSREQ, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, SDLK_ESCAPE, - 0x0000, 0x0000, 0x0000, 0x0000, - - // 0x20 - 0x2F - SDLK_APPLICATION, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - - // 0x30 - 0x3F [Japanese keys] - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - - // 0x40 - 0x4F [unused] - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - - // 0x50 - 0x5F - SDLK_HOME, SDLK_LEFT, SDLK_UP, SDLK_RIGHT, - SDLK_DOWN, SDLK_PAGEUP, SDLK_PAGEDOWN, SDLK_END, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - - // 0x60 - 0x6F - 0x0000, SDLK_PRINTSCREEN, 0x0000, SDLK_INSERT, - SDLK_UNDO, 0x0000, 0x0000, SDLK_MENU, - 0x0000, SDLK_HELP, SDLK_PAUSE, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - - // 0x70 - 0x7F [mostly unused, except for Alt Gr and Num Lock] - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, SDLK_MODE, SDLK_NUMLOCKCLEAR, - - // 0x80 - 0x8F [mostly unused, except for some numeric keypad keys] - SDLK_KP_5, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, SDLK_KP_ENTER, 0x0000, 0x0000, - - // 0x90 - 0x9F - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, SDLK_KP_7, SDLK_KP_4, SDLK_KP_8, - SDLK_KP_6, SDLK_KP_2, SDLK_KP_9, SDLK_KP_3, - SDLK_KP_1, SDLK_KP_5, SDLK_KP_0, SDLK_KP_PERIOD, - - // 0xA0 - 0xAF - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, SDLK_KP_MULTIPLY, SDLK_KP_PLUS, - 0x0000, SDLK_KP_MINUS, SDLK_KP_PERIOD, SDLK_KP_DIVIDE, - - // 0xB0 - 0xBF - SDLK_KP_0, SDLK_KP_1, SDLK_KP_2, SDLK_KP_3, - SDLK_KP_4, SDLK_KP_5, SDLK_KP_6, SDLK_KP_7, - SDLK_KP_8, SDLK_KP_9, 0x0000, 0x0000, - 0x0000, SDLK_KP_EQUALS, SDLK_F1, SDLK_F2, - - // 0xC0 - 0xCF - SDLK_F3, SDLK_F4, SDLK_F5, SDLK_F6, - SDLK_F7, SDLK_F8, SDLK_F9, SDLK_F10, - SDLK_F11, SDLK_F12, SDLK_F13, SDLK_F14, - SDLK_F15, 0x0000, 0x0000, 0x0000, - - // 0xD0 - 0xDF [L* and R* function keys] - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - - // 0xE0 - 0xEF - 0x0000, SDLK_LSHIFT, SDLK_RSHIFT, SDLK_LCTRL, - SDLK_RCTRL, SDLK_CAPSLOCK, 0x0000, SDLK_LGUI, - SDLK_RGUI, SDLK_LALT, SDLK_RALT, SDLK_LGUI, - SDLK_RGUI, 0x0000, 0x0000, 0x0000, - - // 0xF0 - 0xFF [mostly unused, except for Delete] - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, SDLK_DELETE, - }; - - SDL_Keycode sdl_keycode = gdk_to_sdl_table[gdk_keyval & 0xFF]; - - return sdl_keycode; -} - -int gtkui_cb_convert_key(GtkWidget *grab, GdkEventKey *event, gpointer userdata) { - // Convert GDK events to SDL events - - SDL_Event sdlevent; - SDL_Keycode sdlkeycode; - int keystate; - - if (userdata) { - kbactivate = true; - return FALSE; - } - else { kbactivate = false; } - - switch (event->type) { - case GDK_KEY_PRESS: - sdlevent.type = SDL_KEYDOWN; - sdlevent.key.state = SDL_PRESSED; - keystate = 1; - break; - - case GDK_KEY_RELEASE: - sdlevent.type = SDL_KEYUP; - sdlevent.key.state = SDL_RELEASED; - keystate = 0; - break; - - default: - fprintf(stderr, "Unhandled GDK event type: %d", event->type); - return FALSE; - break; - } - - sdlkeycode = (SDL_Keycode)gtkui_cb_translate_gdk_sdl(event->keyval); - sdlevent.key.keysym.sym = sdlkeycode; - sdlevent.key.keysym.scancode = SDL_GetScancodeFromKey(sdlevent.key.keysym.sym); - - if (sdlkeycode != 0 && (playing || confrunning)) { - SDL_PushEvent(&sdlevent); - - const Uint8 *statebuffer = SDL_GetKeyboardState(NULL); - Uint8 *state = (Uint8*)statebuffer; - state[SDL_GetScancodeFromKey(sdlkeycode)] = keystate; - } - // Allow GTK+ to process this key. - return FALSE; -} - -int gtkui_cb_convert_mouse(GtkDrawingArea *area, GdkEventButton *event, gpointer userdata) { - // Convert GDK mouse clicks to SDL mouse clicks - SDL_Event sdlevent; - - switch(event->type) { - case GDK_BUTTON_PRESS: - sdlevent.type = SDL_MOUSEBUTTONDOWN; - sdlevent.button.state = SDL_PRESSED; - break; - - case GDK_BUTTON_RELEASE: - sdlevent.type = SDL_MOUSEBUTTONUP; - sdlevent.button.state = SDL_RELEASED; - break; - - default: break; - } - - sdlevent.button.button = event->button == 1 ? SDL_BUTTON_LEFT : SDL_BUTTON_RIGHT; - sdlevent.button.x = (int)event->x; - sdlevent.button.y = (int)event->y; - - SDL_PushEvent(&sdlevent); - - return FALSE; -} - -void gtkui_drag_data(GtkWidget *widget, GdkDragContext *dragcontext, gint x, gint y, GtkSelectionData *seldata, guint info, guint time, gpointer data) { - // Handle the Drag and Drop - if ((widget == NULL) || (dragcontext == NULL) || (seldata == NULL)) { return; } - - if (info == 0) { - gchar *fileuri = (gchar*)gtk_selection_data_get_data(seldata); - gchar *filename = g_filename_from_uri(fileuri, NULL, NULL); - - // Dirty hack. g_filename_from_uri adds a \r\n to the string - size_t ln = strlen(filename) - 2; - if (filename[ln] == '\r') { filename[ln] = '\0'; } - - nst_load(filename); - } -} diff -Nru nestopia-1.48/source/unix/gtkui/gtkui_callbacks.h nestopia-1.49/source/unix/gtkui/gtkui_callbacks.h --- nestopia-1.48/source/unix/gtkui/gtkui_callbacks.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui_callbacks.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -#ifndef _GTKUI_CALLBACKS_H_ -#define _GTKUI_CALLBACKS_H_ - -void gtkui_cb_reset(GtkWidget *reset, int hard); -void gtkui_cb_nothing(); -void gtkui_cb_video_refresh(); - -void gtkui_cb_video_filter(GtkComboBox *combobox, gpointer userdata); -void gtkui_cb_video_scale(GtkComboBox *combobox, gpointer userdata); -void gtkui_cb_video_ntscmode(GtkComboBox *combobox, gpointer userdata); -void gtkui_cb_video_xbrrounding(GtkComboBox *combobox, gpointer userdata); -void gtkui_cb_video_xbrpixblend(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_video_linear_filter(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_video_tv_aspect(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_video_unmask_overscan(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_video_stretch_aspect(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_video_unlimited_sprites(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_video_palette(GtkComboBox *combobox, gpointer userdata); -void gtkui_cb_video_decoder(GtkComboBox *combobox, gpointer userdata); -void gtkui_cb_video_brightness(GtkRange *range, gpointer userdata); -void gtkui_cb_video_saturation(GtkRange *range, gpointer userdata); -void gtkui_cb_video_contrast(GtkRange *range, gpointer userdata); -void gtkui_cb_video_hue(GtkRange *range, gpointer userdata); - -void gtkui_cb_audio_api(GtkComboBox *combobox, gpointer userdata); -void gtkui_cb_audio_samplerate(GtkComboBox *combobox, gpointer userdata); -void gtkui_cb_audio_stereo(GtkToggleButton *togglebutton, gpointer userdata); - -void gtkui_cb_input_turbopulse(GtkRange *range, gpointer userdata); - -void gtkui_cb_misc_default_system(GtkComboBox *combobox, gpointer userdata); -void gtkui_cb_misc_power_state(GtkComboBox *combobox, gpointer userdata); -void gtkui_cb_timing_altspeed(GtkRange *range, gpointer userdata); -void gtkui_cb_timing_vsync(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_timing_limiter(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_misc_soft_patching(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_misc_genie_distortion(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_misc_disable_gui(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_misc_disable_cursor(GtkToggleButton *togglebutton, gpointer userdata); -void gtkui_cb_misc_config_pause(GtkToggleButton *togglebutton, gpointer userdata); - -unsigned int gtkui_cb_translate_gdk_sdl(int gdk_keyval); -int gtkui_cb_convert_key(GtkWidget *grab, GdkEventKey *event, gpointer userdata); -int gtkui_cb_convert_mouse(GtkDrawingArea *area, GdkEventButton *event, gpointer userdata); - -void gtkui_drag_data(GtkWidget *widget, GdkDragContext *dragcontext, gint x, gint y, GtkSelectionData *seldata, guint info, guint time, gpointer data); - -#endif diff -Nru nestopia-1.48/source/unix/gtkui/gtkui_cheats.cpp nestopia-1.49/source/unix/gtkui/gtkui_cheats.cpp --- nestopia-1.48/source/unix/gtkui/gtkui_cheats.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui_cheats.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,626 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include - -#include - -#include "../main.h" -#include "../config.h" -#include "../cheats.h" - -#include "gtkui.h" -#include "gtkui_callbacks.h" -#include "gtkui_cheats.h" -#include "gtkui_dialogs.h" - -extern settings_t conf; -extern nstpaths_t nstpaths; -extern Emulator emulator; - -GtkWidget *cheatwindow; -GtkTreeStore *treestore; -GtkWidget *treeview; -GtkWidget *descedit, *ggedit, *paredit; -GtkWidget *infobar, *infolabel; - -Xml savexml; -Xml::Node saveroot; - -GtkWidget *gtkui_cheats() { - // Create the Cheats window - - if (cheatwindow) { return NULL; } - - cheatwindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); - gtk_window_set_title(GTK_WINDOW (cheatwindow), "Cheat Manager"); - - GtkWidget *cheatbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); - gtk_container_add(GTK_CONTAINER(cheatwindow), cheatbox); - - GtkWidget *scrolledwindow = gtk_scrolled_window_new(NULL, NULL); - gtk_box_pack_start(GTK_BOX(cheatbox), scrolledwindow, TRUE, TRUE, 0); - gtk_widget_set_size_request(scrolledwindow, 512, 256); - - treeview = gtk_tree_view_new(); - gtk_container_add(GTK_CONTAINER (scrolledwindow), treeview); - - infobar = gtk_info_bar_new(); - infolabel = gtk_widget_new(GTK_TYPE_LABEL,"label", "", NULL); - gtk_box_pack_start(GTK_BOX(cheatbox), infobar, TRUE, TRUE, 0); - - GtkWidget *content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(infobar)); - gtk_box_pack_start(GTK_BOX(content_area), infolabel, TRUE, TRUE, 0); - - GtkWidget *opensavebox = gtk_widget_new(GTK_TYPE_BOX, "halign", GTK_ALIGN_END, NULL); - gtk_box_pack_start(GTK_BOX(cheatbox), opensavebox, FALSE, FALSE, 0); - - GtkWidget *cheatopen = gtk_widget_new( - GTK_TYPE_BUTTON, - "label", GTK_STOCK_OPEN, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_button_set_use_stock(GTK_BUTTON(cheatopen), TRUE); - gtk_box_pack_start(GTK_BOX(opensavebox), cheatopen, FALSE, FALSE, 0); - - GtkWidget *cheatclear = gtk_widget_new( - GTK_TYPE_BUTTON, - "label", GTK_STOCK_CLEAR, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_button_set_use_stock(GTK_BUTTON(cheatclear), TRUE); - gtk_box_pack_start(GTK_BOX(opensavebox), cheatclear, FALSE, FALSE, 0); - - GtkWidget *cheatremove = gtk_widget_new( - GTK_TYPE_BUTTON, - "label", GTK_STOCK_REMOVE, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_button_set_use_stock(GTK_BUTTON(cheatremove), TRUE); - gtk_box_pack_start(GTK_BOX(opensavebox), cheatremove, FALSE, FALSE, 0); - - GtkWidget *descbox = gtk_widget_new( - GTK_TYPE_BOX, - "halign", GTK_ALIGN_END, - NULL); - gtk_box_pack_start(GTK_BOX(cheatbox), descbox, FALSE, FALSE, 0); - - GtkWidget *desclabel = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "Description:", - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-left", 8, - "margin-right", 8, - NULL); - gtk_box_pack_start(GTK_BOX(descbox), desclabel, FALSE, FALSE, 0); - - descedit = gtk_widget_new( - GTK_TYPE_ENTRY, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_box_pack_start(GTK_BOX(descbox), descedit, TRUE, TRUE, 0); - - GtkWidget *ggbox = gtk_widget_new( - GTK_TYPE_BOX, - "halign", GTK_ALIGN_END, - NULL); - gtk_box_pack_start(GTK_BOX(cheatbox), ggbox, FALSE, FALSE, 0); - - GtkWidget *gglabel = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "Game Genie:", - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-left", 8, - "margin-right", 8, - NULL); - gtk_box_pack_start(GTK_BOX(ggbox), gglabel, FALSE, FALSE, 0); - - ggedit = gtk_widget_new( - GTK_TYPE_ENTRY, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_box_pack_start(GTK_BOX(ggbox), ggedit, TRUE, TRUE, 0); - - GtkWidget *genieadd = gtk_widget_new( - GTK_TYPE_BUTTON, - "label", GTK_STOCK_ADD, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_button_set_use_stock(GTK_BUTTON(genieadd), TRUE); - gtk_box_pack_start(GTK_BOX(ggbox), genieadd, FALSE, FALSE, 0); - - GtkWidget *parbox = gtk_widget_new( - GTK_TYPE_BOX, - "halign", GTK_ALIGN_END, - NULL); - gtk_box_pack_start(GTK_BOX(cheatbox), parbox, FALSE, FALSE, 0); - - GtkWidget *parlabel = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "Pro Action Rocky:", - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-left", 8, - "margin-right", 8, - NULL); - gtk_box_pack_start(GTK_BOX(parbox), parlabel, FALSE, FALSE, 0); - - paredit = gtk_widget_new( - GTK_TYPE_ENTRY, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_box_pack_start(GTK_BOX(parbox), paredit, FALSE, FALSE, 0); - - GtkWidget *paradd = gtk_widget_new( - GTK_TYPE_BUTTON, - "label", GTK_STOCK_ADD, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_button_set_use_stock(GTK_BUTTON(paradd), TRUE); - gtk_box_pack_start(GTK_BOX(parbox), paradd, FALSE, FALSE, 0); - - GtkWidget *cheatok = gtk_widget_new( - GTK_TYPE_BUTTON, - "label", GTK_STOCK_OK, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_button_set_use_stock(GTK_BUTTON(cheatok), TRUE); - gtk_box_pack_start(GTK_BOX(cheatbox), cheatok, FALSE, FALSE, 0); - - gtk_tree_view_set_fixed_height_mode(GTK_TREE_VIEW(treeview), FALSE); - - treestore = gtk_tree_store_new(5, G_TYPE_BOOLEAN, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING); - gtk_tree_view_set_model(GTK_TREE_VIEW(treeview), GTK_TREE_MODEL(treestore)); - - GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); - GtkCellRenderer *checkbox = gtk_cell_renderer_toggle_new(); - - GtkTreeViewColumn *column[5]; - // create the display columns - column[0] = gtk_tree_view_column_new_with_attributes("Enable", checkbox, "active", 0, NULL); - column[1] = gtk_tree_view_column_new_with_attributes("Game Genie", renderer, "text", 1, NULL); - column[2] = gtk_tree_view_column_new_with_attributes("PAR", renderer, "text", 2, NULL); - column[3] = gtk_tree_view_column_new_with_attributes("Raw", renderer, "text", 3, NULL); - column[4] = gtk_tree_view_column_new_with_attributes("Description", renderer, "text", 4, NULL); - - // add the display column and renderer to the tree view - gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column[0]); - gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column[1]); - gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column[2]); - gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column[3]); - gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column[4]); - - gtkui_cheats_fill_tree(nstpaths.cheatpath); - - /*g_signal_connect(G_OBJECT(checkbox), "toggled", - G_CALLBACK(gtkui_cheats_check), NULL);*/ - - g_signal_connect(G_OBJECT(treeview), "row-activated", - G_CALLBACK(gtkui_cheats_toggle), NULL); - - g_signal_connect(G_OBJECT(cheatopen), "clicked", - G_CALLBACK(gtkui_cheats_load), NULL); - - g_signal_connect(G_OBJECT(cheatclear), "clicked", - G_CALLBACK(gtkui_cheats_clear), NULL); - - g_signal_connect(G_OBJECT(cheatremove), "clicked", - G_CALLBACK(gtkui_cheats_remove), NULL); - - g_signal_connect(G_OBJECT(genieadd), "clicked", - G_CALLBACK(gtkui_cheats_gg_add), NULL); - - g_signal_connect(G_OBJECT(paradd), "clicked", - G_CALLBACK(gtkui_cheats_par_add), NULL); - - g_signal_connect(G_OBJECT(cheatok), "clicked", - G_CALLBACK(gtkui_cheats_ok), NULL); - - g_signal_connect(G_OBJECT(cheatwindow), "destroy", - G_CALLBACK(gtkui_cheats_ok), NULL); - - gtk_widget_show_all(cheatwindow); - gtk_widget_hide(infobar); - - return cheatwindow; -} - -void gtkui_cheats_check(GtkWidget *widget, gchar *element, gpointer userdata) { - // This function doesn't work. Fix later. - GtkTreeIter iter; - - bool value; - - // Read the value of the checkbox - value = gtk_cell_renderer_toggle_get_active((GtkCellRendererToggle*)widget); - - // Flip the value and set it - value ^= 1; - gtk_cell_renderer_toggle_set_active((GtkCellRendererToggle*)widget, value); -} - -void gtkui_cheats_toggle(GtkWidget *widget, gpointer userdata) { - // Toggle a cheat on or off - GtkTreeIter iter; - GtkTreeModel *model; - GtkTreeSelection *selection; - - bool value; - - // Get the selected item - selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); - gtk_tree_selection_get_selected(selection, &model, &iter); - - // Read the value of the checkbox - gtk_tree_model_get(model, &iter, 0, &value, -1); - - // Flip the value and set it - value ^= 1; - gtk_tree_store_set(treestore, &iter, 0, value, -1); - - //Re-initialize the cheats - Cheats cheats(emulator); - cheats.ClearCodes(); - - gtk_tree_model_foreach(GTK_TREE_MODEL(model), gtkui_cheats_scan_list, NULL); -} - -void gtkui_cheats_fill_tree(char *filename) { - // Fill the cheat list - Xml xml; - - GtkTreeIter iter; - - bool enabled = false; - - char codebuf[9]; - char descbuf[512]; - - gtkui_cheats_clear(); - - std::ifstream cheatfile(filename, std::ifstream::in|std::ifstream::binary); - - if (cheatfile.is_open()) { - xml.Read(cheatfile); - - if (xml.GetRoot().IsType(L"cheats")) { - - Xml::Node root(xml.GetRoot()); - Xml::Node node(root.GetFirstChild()); - - for (int i = 0; i < root.NumChildren(L"cheat"); i++) { - - wcstombs(descbuf, node.GetChild(L"description").GetValue(), sizeof(descbuf)); - - // Check if the cheat is enabled - node.GetAttribute(L"enabled").IsValue(L"1") ? enabled = true : enabled = false; - - // Add the cheats to the list - if (node.GetChild(L"genie")) { // Game Genie - wcstombs(codebuf, node.GetChild(L"genie").GetValue(), sizeof(codebuf)); - gtk_tree_store_append(treestore, &iter, NULL); - gtk_tree_store_set(treestore, &iter, - 0, enabled, - 1, codebuf, - 4, descbuf, - -1); - if (enabled) { cheats_code_gg_add(node.GetChild(L"genie").GetValue()); } - } - - else if (node.GetChild(L"rocky")) { // Pro Action Rocky - wcstombs(codebuf, node.GetChild(L"rocky").GetValue(), sizeof(codebuf)); - gtk_tree_store_append(treestore, &iter, NULL); - gtk_tree_store_set(treestore, &iter, - 0, enabled, - 2, codebuf, - 4, descbuf, - -1); - if (enabled) { cheats_code_par_add(node.GetChild(L"rocky").GetValue()); } - } - - else if (node.GetChild(L"address")) { // Raw - char rawbuf[11]; - snprintf(rawbuf, sizeof(rawbuf), - "%04lu %02lu %02lu", - node.GetChild(L"address").GetUnsignedValue(), - node.GetChild(L"value").GetUnsignedValue(), - node.GetChild(L"compare").GetUnsignedValue()); - - gtk_tree_store_append(treestore, &iter, NULL); - gtk_tree_store_set(treestore, &iter, - 0, enabled, - 3, rawbuf, - 4, descbuf, - -1); - if (enabled) { cheats_code_raw_add(node); } - } - - node = node.GetNextSibling(); - } - } - cheatfile.close(); - } -} - -void gtkui_cheats_save() { - // Save the cheat list - std::ofstream cheatfile(nstpaths.cheatpath, std::ifstream::out|std::ifstream::binary); - - if (cheatfile.is_open()) { - - GtkTreeModel *model; - model = gtk_tree_view_get_model(GTK_TREE_VIEW(treeview)); - - saveroot = (savexml.GetRoot()); - - saveroot = savexml.Create( L"cheats" ); - saveroot.AddAttribute( L"version", L"1.0" ); - - gtk_tree_model_foreach(GTK_TREE_MODEL(model), gtkui_cheats_write_list, NULL); - - savexml.Write(saveroot, cheatfile); - cheatfile.close(); - } - else { return; } -} - -void gtkui_cheats_gg_add(GtkWidget *widget, gpointer userdata) { - // Add a Game Genie code to the list - GtkTreeIter iter; - - Cheats cheats(emulator); - Cheats::Code code; - - char codebuf[9]; - char descbuf[512]; - - snprintf(codebuf, sizeof(codebuf), "%.8s", gtk_entry_get_text(GTK_ENTRY(ggedit))); - snprintf(descbuf, sizeof(descbuf), "%s", gtk_entry_get_text(GTK_ENTRY(descedit))); - - if (cheats.GameGenieDecode(codebuf, code) == Nes::RESULT_OK) { - gtk_tree_store_append(treestore, &iter, NULL); - gtk_tree_store_set(treestore, &iter, - 0, true, - 1, codebuf, - 4, descbuf, - -1); - gtk_entry_set_text(GTK_ENTRY(descedit), ""); - gtk_entry_set_text(GTK_ENTRY(ggedit), ""); - gtk_entry_set_text(GTK_ENTRY(paredit), ""); - gtk_widget_hide(infobar); - gtk_label_set_text(GTK_LABEL(infolabel), ""); - cheats.SetCode(code); - } - else { - gtk_info_bar_set_message_type(GTK_INFO_BAR(infobar), GTK_MESSAGE_ERROR); - gtk_label_set_text(GTK_LABEL(infolabel), "Error: Invalid Game Genie code"); - gtk_widget_show(infobar); - } -} - -void gtkui_cheats_par_add(GtkWidget *widget, gpointer userdata) { - // Add a Pro Action Rocky code to the list - GtkTreeIter iter; - - Cheats cheats(emulator); - Cheats::Code code; - - char codebuf[9]; - char descbuf[512]; - - snprintf(codebuf, sizeof(codebuf), "%.8s", gtk_entry_get_text(GTK_ENTRY(paredit))); - snprintf(descbuf, sizeof(descbuf), "%s", gtk_entry_get_text(GTK_ENTRY(descedit))); - - if (cheats.ProActionRockyDecode(codebuf, code) == Nes::RESULT_OK) { - gtk_tree_store_append(treestore, &iter, NULL); - gtk_tree_store_set(treestore, &iter, - 0, true, - 1, codebuf, - 4, descbuf, - -1); - gtk_entry_set_text(GTK_ENTRY(descedit), ""); - gtk_entry_set_text(GTK_ENTRY(ggedit), ""); - gtk_entry_set_text(GTK_ENTRY(paredit), ""); - gtk_widget_hide(infobar); - gtk_label_set_text(GTK_LABEL(infolabel), ""); - cheats.SetCode(code); - } - else { - gtk_info_bar_set_message_type(GTK_INFO_BAR(infobar), GTK_MESSAGE_ERROR); - gtk_label_set_text(GTK_LABEL(infolabel), "Error: Invalid PAR code"); - gtk_widget_show(infobar); - } -} - -void gtkui_cheats_remove(GtkWidget *widget, gpointer userdata) { - // Remove a cheat from the list - GtkTreeIter iter; - GtkTreeModel *model; - GtkTreeSelection *selection; - - // Get the selected item - selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)); - gtk_tree_selection_get_selected(selection, &model, &iter); - - // Remove the cheat - if (gtk_tree_store_iter_is_valid(treestore, &iter)) { - gtk_tree_store_remove(treestore, &iter); - } - - //Re-initialize the cheats - Cheats cheats(emulator); - cheats.ClearCodes(); - - gtk_tree_model_foreach(GTK_TREE_MODEL(model), gtkui_cheats_scan_list, NULL); -} - -void gtkui_cheats_ok() { - // Save the cheats and close the window - gtkui_cheats_save(); - gtk_widget_destroy(cheatwindow); - cheatwindow = NULL; -} - -void gtkui_cheats_clear() { - // Clear the list - gtk_tree_store_clear(treestore); - Cheats cheats(emulator); - cheats.ClearCodes(); -} - -gboolean gtkui_cheats_scan_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer userdata) { - // Scan through the list of cheats - Cheats cheats(emulator); - Cheats::Code code; - - bool enabled; - gchar *ggcode, *parcode, *rawcode, *description; - - gtk_tree_model_get(model, iter, 0, &enabled, 1, &ggcode, 2, &parcode, 3, &rawcode, 4, &description, -1); - - if (enabled) { - if (ggcode) { - cheats.GameGenieDecode(ggcode, code); - cheats.SetCode(code); - } - else if (parcode) { - cheats.ProActionRockyDecode(parcode, code); - cheats.SetCode(code); - } - else if (rawcode) { - code.useCompare = false; - - int addr, value, compare; - char buf[5]; - - snprintf(buf, sizeof(buf), "%c%c%c%c", rawcode[0], rawcode[1], rawcode[2], rawcode[3]); - sscanf(buf, "%x", &addr); - - snprintf(buf, sizeof(buf), "%c%c", rawcode[5], rawcode[6]); - sscanf(buf, "%x", &value); - - snprintf(buf, sizeof(buf), "%c%c", rawcode[8], rawcode[9]); - sscanf(buf, "%x", &compare); - - code.address = addr; - code.value = value; - code.compare = compare; - - if (compare) { code.useCompare = true; } - - cheats.SetCode(code); - } - } - - g_free(ggcode); - g_free(parcode); - g_free(rawcode); - g_free(description); - - return false; -} - -gboolean gtkui_cheats_write_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer userdata) { - // Write entries to the cheat file - bool enabled; - gchar *ggcode, *parcode, *rawcode, *description; - - char buf[9]; - wchar_t wbuf[9]; - - gtk_tree_model_get(model, iter, 0, &enabled, 1, &ggcode, 2, &parcode, 3, &rawcode, 4, &description, -1); - - Xml::Node node(saveroot.AddChild(L"cheat")); - node.AddAttribute(L"enabled", enabled ? L"1" : L"0"); - - if (ggcode) { - snprintf(buf, sizeof(buf), "%s", ggcode); - mbstowcs(wbuf, buf, 9); - node.AddChild(L"genie", wbuf); - } - if (parcode) { - snprintf(buf, sizeof(buf), "%s", parcode); - mbstowcs(wbuf, buf, 9); - node.AddChild(L"rocky", wbuf); - } - if (rawcode) { - snprintf(buf, sizeof(buf), "0x%c%c%c%c", rawcode[0], rawcode[1], rawcode[2], rawcode[3]); - mbstowcs(wbuf, buf, 9); - node.AddChild(L"address", wbuf); - - snprintf(buf, sizeof(buf), "0x%c%c", rawcode[5], rawcode[6]); - mbstowcs(wbuf, buf, 9); - node.AddChild(L"value", wbuf); - - snprintf(buf, sizeof(buf), "0x%c%c", rawcode[8], rawcode[9]); - mbstowcs(wbuf, buf, 9); - node.AddChild(L"compare", wbuf); - } - if (description) { - char descbuf[512]; - wchar_t wdescbuf[512]; - - snprintf(descbuf, sizeof(descbuf), "%s", description); - mbstowcs(wdescbuf, descbuf, 512); - node.AddChild(L"description", wdescbuf); - } - - g_free(ggcode); - g_free(parcode); - g_free(rawcode); - g_free(description); - - return false; -} diff -Nru nestopia-1.48/source/unix/gtkui/gtkui_cheats.h nestopia-1.49/source/unix/gtkui/gtkui_cheats.h --- nestopia-1.48/source/unix/gtkui/gtkui_cheats.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui_cheats.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -#ifndef _GTKUI_CHEATS_H_ -#define _GTKUI_CHEATS_H_ - -GtkWidget *gtkui_cheats(); -void gtkui_cheats_check(GtkWidget *widget, gchar *element, gpointer userdata); -void gtkui_cheats_toggle(GtkWidget *widget, gpointer userdata); -void gtkui_cheats_fill_tree(char *filename); -void gtkui_cheats_save(); -void gtkui_cheats_gg_add(GtkWidget *widget, gpointer userdata); -void gtkui_cheats_par_add(GtkWidget *widget, gpointer userdata); -void gtkui_cheats_remove(GtkWidget *widget, gpointer userdata); -void gtkui_cheats_ok(); -void gtkui_cheats_clear(); -gboolean gtkui_cheats_scan_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer userdata); -gboolean gtkui_cheats_write_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer userdata); - -#endif diff -Nru nestopia-1.48/source/unix/gtkui/gtkui_config.cpp nestopia-1.49/source/unix/gtkui/gtkui_config.cpp --- nestopia-1.48/source/unix/gtkui/gtkui_config.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui_config.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,1349 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include -#include - -#include "../main.h" -#include "../config.h" -#include "../audio.h" -#include "../input.h" - -#include "gtkui.h" -#include "gtkui_callbacks.h" -#include "gtkui_config.h" - -extern settings_t conf; -extern gamepad_t player[NUMGAMEPADS]; -extern char padpath[512]; -extern bool playing; -extern bool confrunning; - -GtkWidget *configwindow; -GtkWidget *notebook; -gint tabnum = 0; - -// Audio -GtkWidget *scale_audio_volume[NUMCHANNELS]; -GtkAdjustment *adj_audio_volume[NUMCHANNELS]; - -// Input -GtkWidget *combo_input_player; -GtkWidget *combo_input_type; -GtkWidget *inputconfbutton; -GtkWidget *entry_input[NUMBUTTONS]; - -GtkTreeStore *treestore_input; - -GtkWidget *gtkui_config() { - // Create the Configuration window - - if (configwindow) { return NULL; } - if (conf.misc_config_pause) { if (playing) { nst_pause(); } } - - configwindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); - gtk_window_set_title(GTK_WINDOW(configwindow), "Configuration"); - - GtkWidget *box_upper = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); - GtkWidget *box_lower = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); - notebook = gtk_notebook_new(); - - gtk_container_add(GTK_CONTAINER(configwindow), box_upper); - - // Video // - GtkWidget *box_video = gtk_widget_new( - GTK_TYPE_BOX, - "orientation", GTK_ORIENTATION_HORIZONTAL, - "margin-top", MARGIN_TB, - "margin-bottom", MARGIN_TB, - NULL); - GtkWidget *box_video_l = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); - GtkWidget *box_video_r = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); - - // Filter - GtkWidget *box_video_filter = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_video_filter = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "Filter:", - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - GtkWidget *combo_video_filter = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "None"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "NTSC"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "xBR"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "HqX"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "2xSaI"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_filter), "ScaleX"); - - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_filter), conf.video_filter); - - gtk_box_pack_start(GTK_BOX(box_video_filter), label_video_filter, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_filter), combo_video_filter, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_l), box_video_filter, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_video_filter), "changed", - G_CALLBACK(gtkui_cb_video_filter), NULL); - - // Scale Factor - GtkWidget *box_video_scale = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_video_scale = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "Scale Factor:", - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - GtkWidget *combo_video_scale = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "1x"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "2x"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "3x"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_scale), "4x"); - - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_scale), conf.video_scale_factor - 1); - - gtk_box_pack_start(GTK_BOX(box_video_scale), label_video_scale, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_scale), combo_video_scale, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_l), box_video_scale, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_video_scale), "changed", - G_CALLBACK(gtkui_cb_video_scale), NULL); - - // NTSC Mode - GtkWidget *box_video_ntscmode = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_video_ntscmode = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "NTSC Mode:", - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - GtkWidget *combo_video_ntscmode = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_ntscmode), "Composite"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_ntscmode), "S-Video"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_ntscmode), "RGB"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_ntscmode), "Monochrome"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_ntscmode), "Custom"); - - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_ntscmode), conf.video_ntsc_mode); - - gtk_box_pack_start(GTK_BOX(box_video_ntscmode), label_video_ntscmode, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_ntscmode), combo_video_ntscmode, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_l), box_video_ntscmode, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_video_ntscmode), "changed", - G_CALLBACK(gtkui_cb_video_ntscmode), NULL); - - // xBR Corner Rounding - GtkWidget *box_video_xbrrounding = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_video_xbrrounding = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "xBR Corner Rounding:", - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - GtkWidget *combo_video_xbrrounding = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_xbrrounding), "None"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_xbrrounding), "Some"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_xbrrounding), "All"); - - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_xbrrounding), conf.video_xbr_corner_rounding); - - gtk_box_pack_start(GTK_BOX(box_video_xbrrounding), label_video_xbrrounding, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_xbrrounding), combo_video_xbrrounding, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_l), box_video_xbrrounding, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_video_xbrrounding), "changed", - G_CALLBACK(gtkui_cb_video_xbrrounding), NULL); - - // xBR Pixel Blending - GtkWidget *check_video_xbrpixblend = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "xBR Pixel Blending", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_xbrpixblend), conf.video_xbr_pixel_blending); - - gtk_box_pack_start(GTK_BOX(box_video_l), check_video_xbrpixblend, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_video_xbrpixblend), "toggled", - G_CALLBACK(gtkui_cb_video_xbrpixblend), NULL); - - // Linear Filter - GtkWidget *check_video_linear_filter = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Linear Filter", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_linear_filter), conf.video_linear_filter); - - gtk_box_pack_start(GTK_BOX(box_video_l), check_video_linear_filter, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_video_linear_filter), "toggled", - G_CALLBACK(gtkui_cb_video_linear_filter), NULL); - - // TV Aspect - GtkWidget *check_video_tv_aspect = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "TV Aspect Ratio", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_tv_aspect), conf.video_tv_aspect); - - gtk_box_pack_start(GTK_BOX(box_video_l), check_video_tv_aspect, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_video_tv_aspect), "toggled", - G_CALLBACK(gtkui_cb_video_tv_aspect), NULL); - - // Mask Overscan - GtkWidget *check_video_unmask_overscan = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Unmask Overscan", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_unmask_overscan), conf.video_unmask_overscan); - - gtk_box_pack_start(GTK_BOX(box_video_l), check_video_unmask_overscan, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_video_unmask_overscan), "toggled", - G_CALLBACK(gtkui_cb_video_unmask_overscan), NULL); - - // Stretch Aspect - GtkWidget *check_video_stretch_aspect = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Stretch Aspect Ratio", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_stretch_aspect), conf.video_stretch_aspect); - - gtk_box_pack_start(GTK_BOX(box_video_l), check_video_stretch_aspect, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_video_stretch_aspect), "toggled", - G_CALLBACK(gtkui_cb_video_stretch_aspect), NULL); - - // Unlimited Sprites - GtkWidget *check_video_unlimited_sprites = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Unlimited Sprites", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_video_unlimited_sprites), conf.video_unlimited_sprites); - - gtk_box_pack_start(GTK_BOX(box_video_l), check_video_unlimited_sprites, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_video_unlimited_sprites), "toggled", - G_CALLBACK(gtkui_cb_video_unlimited_sprites), NULL); - - // Palette Mode - GtkWidget *box_video_palette = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_video_palette = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "Palette Mode:", - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - NULL); - GtkWidget *combo_video_palette = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_palette), "YUV"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_palette), "RGB"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_palette), "Custom"); - - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_palette), conf.video_palette_mode); - - gtk_box_pack_start(GTK_BOX(box_video_palette), label_video_palette, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_palette), combo_video_palette, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_r), box_video_palette, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_video_palette), "changed", - G_CALLBACK(gtkui_cb_video_palette), NULL); - - // YUV Decoder - GtkWidget *box_video_decoder = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_video_decoder = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "YUV Decoder:", - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - NULL); - GtkWidget *combo_video_decoder = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_decoder), "Consumer"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_decoder), "Canonical"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_video_decoder), "Alternative"); - - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_video_decoder), conf.video_decoder); - - gtk_box_pack_start(GTK_BOX(box_video_decoder), label_video_decoder, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_decoder), combo_video_decoder, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video_r), box_video_decoder, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_video_decoder), "changed", - G_CALLBACK(gtkui_cb_video_decoder), NULL); - - // Brightness - GtkAdjustment *adj_video_brightness = gtk_adjustment_new(conf.video_brightness, -100, 100, 1, 5, 0); - GtkWidget *frame_video_brightness = gtk_frame_new("Brightness"); - GtkWidget *scale_video_brightness = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - "margin-right", MARGIN_LR, - "orientation", GTK_ORIENTATION_HORIZONTAL, - "adjustment", adj_video_brightness, - "width-request", 201, - "height-request", 32, - "digits", 0, - NULL); - gtk_container_add(GTK_CONTAINER(frame_video_brightness), scale_video_brightness); - gtk_box_pack_start(GTK_BOX(box_video_r), frame_video_brightness, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(scale_video_brightness), "value-changed", - G_CALLBACK(gtkui_cb_video_brightness), NULL); - - // Saturation - GtkAdjustment *adj_video_saturation = gtk_adjustment_new(conf.video_saturation, -100, 100, 1, 5, 0); - GtkWidget *frame_video_saturation = gtk_frame_new("Saturation"); - GtkWidget *scale_video_saturation = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - "margin-right", MARGIN_LR, - "orientation", GTK_ORIENTATION_HORIZONTAL, - "adjustment", adj_video_saturation, - "width-request", 201, - "height-request", 32, - "digits", 0, - NULL); - gtk_container_add(GTK_CONTAINER(frame_video_saturation), scale_video_saturation); - gtk_box_pack_start(GTK_BOX(box_video_r), frame_video_saturation, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(scale_video_saturation), "value-changed", - G_CALLBACK(gtkui_cb_video_saturation), NULL); - - // Contrast - GtkAdjustment *adj_video_contrast = gtk_adjustment_new(conf.video_contrast, -100, 100, 1, 5, 0); - GtkWidget *frame_video_contrast = gtk_frame_new("Contrast"); - GtkWidget *scale_video_contrast = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - "margin-right", MARGIN_LR, - "orientation", GTK_ORIENTATION_HORIZONTAL, - "adjustment", adj_video_contrast, - "width-request", 201, - "height-request", 32, - "digits", 0, - NULL); - gtk_container_add(GTK_CONTAINER(frame_video_contrast), scale_video_contrast); - gtk_box_pack_start(GTK_BOX(box_video_r), frame_video_contrast, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(scale_video_contrast), "value-changed", - G_CALLBACK(gtkui_cb_video_contrast), NULL); - - // Hue - GtkAdjustment *adj_video_hue = gtk_adjustment_new(conf.video_hue, -45, 45, 1, 5, 0); - GtkWidget *frame_video_hue = gtk_frame_new("Hue"); - GtkWidget *scale_video_hue = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - "margin-right", MARGIN_LR, - "orientation", GTK_ORIENTATION_HORIZONTAL, - "adjustment", adj_video_hue, - "width-request", 91, - "height-request", 32, - "digits", 0, - NULL); - gtk_container_add(GTK_CONTAINER(frame_video_hue), scale_video_hue); - gtk_box_pack_start(GTK_BOX(box_video_r), frame_video_hue, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(scale_video_hue), "value-changed", - G_CALLBACK(gtkui_cb_video_hue), NULL); - - gtk_box_pack_start(GTK_BOX(box_video), box_video_l, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_video), box_video_r, FALSE, FALSE, MARGIN_LR); - - // Audio // - GtkWidget *box_audio = gtk_widget_new( - GTK_TYPE_BOX, - "orientation", GTK_ORIENTATION_VERTICAL, - "margin-top", MARGIN_TB, - "margin-bottom", MARGIN_TB, - NULL); - - // Audio API - GtkWidget *box_audio_api = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_audio_api = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "API:", - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - GtkWidget *combo_audio_api = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_api), "SDL"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_api), "libao"); - - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_api), conf.audio_api); - - gtk_box_pack_start(GTK_BOX(box_audio_api), label_audio_api, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_audio_api), combo_audio_api, FALSE, FALSE, 0); - #if SDL_VERSION_ATLEAST(2,0,4) - gtk_box_pack_start(GTK_BOX(box_audio), box_audio_api, FALSE, FALSE, 0); - #endif - - g_signal_connect(G_OBJECT(combo_audio_api), "changed", - G_CALLBACK(gtkui_cb_audio_api), NULL); - - // Sample Rate - GtkWidget *box_audio_samplerate = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_audio_samplerate = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "Sample Rate:", - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - GtkWidget *combo_audio_samplerate = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_samplerate), "11025Hz"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_samplerate), "22050Hz"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_samplerate), "44100Hz"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_samplerate), "48000Hz"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_audio_samplerate), "96000Hz"); - - switch (conf.audio_sample_rate) { - case 11025: - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 0); - break; - case 22050: - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 1); - break; - case 44100: - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 2); - break; - case 48000: - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 3); - break; - case 96000: - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 4); - break; - default: - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_audio_samplerate), 2); - break; - } - - gtk_box_pack_start(GTK_BOX(box_audio_samplerate), label_audio_samplerate, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_audio_samplerate), combo_audio_samplerate, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_audio), box_audio_samplerate, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_audio_samplerate), "changed", - G_CALLBACK(gtkui_cb_audio_samplerate), NULL); - - // Stereo - GtkWidget *check_audio_stereo = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Stereo", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_audio_stereo), conf.audio_stereo); - - gtk_box_pack_start(GTK_BOX(box_audio), check_audio_stereo, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_audio_stereo), "toggled", - G_CALLBACK(gtkui_cb_audio_stereo), NULL); - - // Volume - GtkWidget *label_audio_volume[NUMCHANNELS]; - - // The Grid - GtkWidget *grid_audio_volume = gtk_widget_new( - GTK_TYPE_GRID, - "column-homogeneous", TRUE, - "column-spacing", MARGIN_LR, - "row-spacing", MARGIN_TB, - "margin", MARGIN_TB, - NULL); - - // Master - label_audio_volume[0] = gtk_widget_new(GTK_TYPE_LABEL, "label", "Master", NULL); - adj_audio_volume[0] = gtk_adjustment_new(conf.audio_volume, 0, 100, 1, 5, 0); - scale_audio_volume[0] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[0], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[0], 0, 0, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[0], 0, 1, 1, 1); - - g_signal_connect(G_OBJECT(scale_audio_volume[0]), "value-changed", - G_CALLBACK(gtkui_audio_volume_master), NULL); - - // Square1 - label_audio_volume[1] = gtk_widget_new(GTK_TYPE_LABEL, "label", "Square1", NULL); - adj_audio_volume[1] = gtk_adjustment_new(conf.audio_vol_sq1, 0, 100, 1, 5, 0); - scale_audio_volume[1] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[1], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[1], 1, 0, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[1], 1, 1, 1, 1); - - // Square2 - label_audio_volume[2] = gtk_widget_new(GTK_TYPE_LABEL, "label", "Square2", NULL); - adj_audio_volume[2] = gtk_adjustment_new(conf.audio_vol_sq2, 0, 100, 1, 5, 0); - scale_audio_volume[2] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[2], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[2], 2, 0, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[2], 2, 1, 1, 1); - - // Triangle - label_audio_volume[3] = gtk_widget_new(GTK_TYPE_LABEL, "label", "Triangle", NULL); - adj_audio_volume[3] = gtk_adjustment_new(conf.audio_vol_tri, 0, 100, 1, 5, 0); - scale_audio_volume[3] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[3], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[3], 3, 0, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[3], 3, 1, 1, 1); - - // Noise - label_audio_volume[4] = gtk_widget_new(GTK_TYPE_LABEL, "label", "Noise", NULL); - adj_audio_volume[4] = gtk_adjustment_new(conf.audio_vol_noise, 0, 100, 1, 5, 0); - scale_audio_volume[4] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[4], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[4], 4, 0, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[4], 4, 1, 1, 1); - - // Noise - label_audio_volume[5] = gtk_widget_new(GTK_TYPE_LABEL, "label", "DPCM", NULL); - adj_audio_volume[5] = gtk_adjustment_new(conf.audio_vol_dpcm, 0, 100, 1, 5, 0); - scale_audio_volume[5] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[5], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[5], 5, 0, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[5], 5, 1, 1, 1); - - // FDS - label_audio_volume[6] = gtk_widget_new(GTK_TYPE_LABEL, "label", "FDS", NULL); - adj_audio_volume[6] = gtk_adjustment_new(conf.audio_vol_fds, 0, 100, 1, 5, 0); - scale_audio_volume[6] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[6], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[6], 0, 2, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[6], 0, 3, 1, 1); - - // MMC5 - label_audio_volume[7] = gtk_widget_new(GTK_TYPE_LABEL, "label", "MMC5", NULL); - adj_audio_volume[7] = gtk_adjustment_new(conf.audio_vol_mmc5, 0, 100, 1, 5, 0); - scale_audio_volume[7] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[7], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[7], 1, 2, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[7], 1, 3, 1, 1); - - // VRC6 - label_audio_volume[8] = gtk_widget_new(GTK_TYPE_LABEL, "label", "VRC6", NULL); - adj_audio_volume[8] = gtk_adjustment_new(conf.audio_vol_vrc6, 0, 100, 1, 5, 0); - scale_audio_volume[8] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[8], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[8], 2, 2, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[8], 2, 3, 1, 1); - - // VRC7 - label_audio_volume[9] = gtk_widget_new(GTK_TYPE_LABEL, "label", "VRC7", NULL); - adj_audio_volume[9] = gtk_adjustment_new(conf.audio_vol_vrc7, 0, 100, 1, 5, 0); - scale_audio_volume[9] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[9], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[9], 3, 2, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[9], 3, 3, 1, 1); - - // N163 - label_audio_volume[10] = gtk_widget_new(GTK_TYPE_LABEL, "label", "N163", NULL); - adj_audio_volume[10] = gtk_adjustment_new(conf.audio_vol_n163, 0, 100, 1, 5, 0); - scale_audio_volume[10] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[10], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[10], 4, 2, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[10], 4, 3, 1, 1); - - // S5B - label_audio_volume[11] = gtk_widget_new(GTK_TYPE_LABEL, "label", "S5B", NULL); - adj_audio_volume[11] = gtk_adjustment_new(conf.audio_vol_s5b, 0, 100, 1, 5, 0); - scale_audio_volume[11] = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_CENTER, - "orientation", GTK_ORIENTATION_VERTICAL, - "adjustment", adj_audio_volume[11], - "width-request", 32, - "height-request", 100, - "inverted", TRUE, - "digits", 0, - NULL); - - gtk_grid_attach(GTK_GRID(grid_audio_volume), label_audio_volume[11], 5, 2, 1, 1); - gtk_grid_attach(GTK_GRID(grid_audio_volume), scale_audio_volume[11], 5, 3, 1, 1); - - // Set the callbacks for every control but master - for (int i = 1; i < NUMCHANNELS; i++) { - g_signal_connect(G_OBJECT(scale_audio_volume[i]), "value-changed", - G_CALLBACK(gtkui_audio_volume), NULL); - } - - // Pack the grid into the box - gtk_box_pack_start(GTK_BOX(box_audio), grid_audio_volume, FALSE, FALSE, 0); - - // Input // - GtkWidget *box_input = gtk_widget_new( - GTK_TYPE_BOX, - "orientation", GTK_ORIENTATION_HORIZONTAL, - "margin-top", MARGIN_TB, - "margin-bottom", MARGIN_TB, - NULL); - - // NES Controller - GtkWidget *box_input_l = gtk_widget_new(GTK_TYPE_BOX, "halign", GTK_ALIGN_START, "orientation", GTK_ORIENTATION_VERTICAL, NULL); - GtkWidget *nespad = gtk_widget_new( - GTK_TYPE_IMAGE, - "halign", GTK_ALIGN_CENTER, - "expand", FALSE, - "file", padpath, - "margin", MARGIN_TB, - NULL); - gtk_box_pack_start(GTK_BOX(box_input_l), nespad, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_input), box_input_l, FALSE, FALSE, 0); - - // Turbo Pulse - GtkAdjustment *adj_input_turbopulse = gtk_adjustment_new(conf.timing_turbopulse, 2, 9, 1, 5, 0); - GtkWidget *box_input_turbopulse = gtk_widget_new( - GTK_TYPE_BOX, - "halign", GTK_ALIGN_END, - "orientation", GTK_ORIENTATION_HORIZONTAL, - "margin-bottom", MARGIN_TB, - "margin-right", MARGIN_LR, - NULL); - GtkWidget *label_input_turbopulse = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "Turbo Pulse", - "halign", GTK_ALIGN_START, - "margin-top", MARGIN_TB, - "margin-right", MARGIN_LR, - NULL); - GtkWidget *scale_input_turbopulse = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_START, - "orientation", GTK_ORIENTATION_HORIZONTAL, - "adjustment", adj_input_turbopulse, - "width-request", 60, - "height-request", 32, - "digits", 0, - NULL); - gtk_box_pack_start(GTK_BOX(box_input_turbopulse), label_input_turbopulse, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_input_turbopulse), scale_input_turbopulse, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_input_l), box_input_turbopulse, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(scale_input_turbopulse), "value-changed", - G_CALLBACK(gtkui_cb_input_turbopulse), NULL); - - // Options Box - GtkWidget *box_input_r = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); - gtk_box_pack_start(GTK_BOX(box_input), box_input_r, FALSE, FALSE, 0); - - // Player Select - combo_input_player = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_END, - "margin-top", MARGIN_TB, - "margin-bottom", MARGIN_TB, - "margin-right", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT (combo_input_player), "Player 1"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT (combo_input_player), "Player 2"); - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_input_player), 0); - gtk_box_pack_start(GTK_BOX(box_input_l), combo_input_player, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_input_player), "changed", - G_CALLBACK(gtkui_config_input_refresh), NULL); - - // Device Type Select - combo_input_type = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_END, - "margin-top", MARGIN_TB, - "margin-bottom", MARGIN_TB, - "margin-right", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT (combo_input_type), "Keyboard"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT (combo_input_type), "Joystick"); - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_input_type), 0); - gtk_box_pack_start(GTK_BOX(box_input_l), combo_input_type, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_input_type), "changed", - G_CALLBACK(gtkui_config_input_refresh), NULL); - - // Key Translation - g_signal_connect(G_OBJECT(configwindow), "key-press-event", - G_CALLBACK(gtkui_cb_convert_key), gpointer(1)); - - g_signal_connect(G_OBJECT(configwindow), "key-release-event", - G_CALLBACK(gtkui_cb_convert_key), NULL); - - // The Treeview - GtkWidget *treeview = gtk_widget_new(GTK_TYPE_TREE_VIEW, - "margin-top", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_tree_view_set_fixed_height_mode(GTK_TREE_VIEW (treeview), FALSE); - gtk_tree_view_set_enable_search(GTK_TREE_VIEW(treeview), FALSE); - - treestore_input = gtk_tree_store_new(2, G_TYPE_STRING, G_TYPE_STRING); - - gtk_tree_view_set_model(GTK_TREE_VIEW(treeview), GTK_TREE_MODEL(treestore_input)); - - GtkTreeIter iter; - GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); - - GtkTreeViewColumn *columns[2]; - columns[0] = gtk_tree_view_column_new_with_attributes( - "Button", renderer, "text", 0, NULL); - - columns[1] = gtk_tree_view_column_new_with_attributes( - "Mapping", renderer, "text", 1, NULL); - gtk_tree_view_column_set_expand(columns[1], TRUE); - - gtk_tree_view_append_column(GTK_TREE_VIEW (treeview), columns[0]); - gtk_tree_view_append_column(GTK_TREE_VIEW (treeview), columns[1]); - - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Up", 1, SDL_GetScancodeName(player[0].u), -1); - - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Down", 1, SDL_GetScancodeName(player[0].d), -1); - - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Left", 1, SDL_GetScancodeName(player[0].l), -1); - - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Right", 1, SDL_GetScancodeName(player[0].r), -1); - - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Select", 1, SDL_GetScancodeName(player[0].select), -1); - - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Start", 1, SDL_GetScancodeName(player[0].start), -1); - - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "A", 1, SDL_GetScancodeName(player[0].a), -1); - - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "B", 1, SDL_GetScancodeName(player[0].b), -1); - - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Turbo A", 1, SDL_GetScancodeName(player[0].ta), -1); - - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Turbo B", 1, SDL_GetScancodeName(player[0].tb), -1); - - gtk_box_pack_start(GTK_BOX(box_input_r), treeview, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(treeview), "row-activated", - G_CALLBACK(gtkui_config_input_activate), NULL); - - // The Input Defaults button - GtkWidget *inputdefaults = gtk_widget_new( - GTK_TYPE_BUTTON, - "label", "Defaults", - "halign", GTK_ALIGN_START, - "margin-top", MARGIN_TB * 2, - "margin-left", MARGIN_LR, - NULL); - gtk_box_pack_start(GTK_BOX(box_input_r), inputdefaults, FALSE, FALSE, 0); - - // Connect the button to a callback - g_signal_connect(G_OBJECT(inputdefaults), "clicked", - G_CALLBACK(gtkui_config_input_defaults), NULL); - - // Misc // - GtkWidget *box_misc = gtk_widget_new( - GTK_TYPE_BOX, - "orientation", GTK_ORIENTATION_VERTICAL, - "margin-top", MARGIN_TB, - "margin-bottom", MARGIN_TB, - NULL); - - // Default System - GtkWidget *box_misc_default_system = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_misc_default_system = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "Default System:", - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - GtkWidget *combo_misc_default_system = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_default_system), "Auto"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_default_system), "NTSC"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_default_system), "PAL"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_default_system), "Famicom"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_default_system), "Dendy"); - - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_misc_default_system), conf.misc_default_system); - - gtk_box_pack_start(GTK_BOX(box_misc_default_system), label_misc_default_system, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_misc_default_system), combo_misc_default_system, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_misc), box_misc_default_system, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_misc_default_system), "changed", - G_CALLBACK(gtkui_cb_misc_default_system), NULL); - - // RAM Power-on State - GtkWidget *box_misc_power_state = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_misc_power_state = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "RAM Power-on State:", - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - GtkWidget *combo_misc_power_state = gtk_widget_new( - GTK_TYPE_COMBO_BOX_TEXT, - "halign", GTK_ALIGN_START, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - NULL); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_power_state), "0x00"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_power_state), "0xFF"); - gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_misc_power_state), "Random"); - - gtk_combo_box_set_active(GTK_COMBO_BOX(combo_misc_power_state), conf.misc_power_state); - - gtk_box_pack_start(GTK_BOX(box_misc_power_state), label_misc_power_state, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_misc_power_state), combo_misc_power_state, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_misc), box_misc_power_state, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(combo_misc_power_state), "changed", - G_CALLBACK(gtkui_cb_misc_power_state), NULL); - - // Alternate Speed - GtkAdjustment *adj_timing_altspeed = gtk_adjustment_new(conf.timing_altspeed, 1, 240, 1, 5, 0); - GtkWidget *box_timing_altspeed = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - GtkWidget *label_timing_altspeed = gtk_widget_new( - GTK_TYPE_LABEL, - "label", "Alternate Speed", - "halign", GTK_ALIGN_START, - "margin-top", MARGIN_TB, - "margin-bottom", MARGIN_TB, - "margin-left", MARGIN_LR, - "margin-right", MARGIN_LR, - NULL); - GtkWidget *scale_timing_altspeed = gtk_widget_new( - GTK_TYPE_SCALE, - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - "orientation", GTK_ORIENTATION_HORIZONTAL, - "adjustment", adj_timing_altspeed, - "width-request", 239, - "height-request", 32, - "digits", 0, - NULL); - gtk_box_pack_start(GTK_BOX(box_timing_altspeed), label_timing_altspeed, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_timing_altspeed), scale_timing_altspeed, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_misc), box_timing_altspeed, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(scale_timing_altspeed), "value-changed", - G_CALLBACK(gtkui_cb_timing_altspeed), NULL); - - // Vsync - GtkWidget *check_timing_vsync = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Vsync", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_timing_vsync), conf.timing_vsync); - - gtk_box_pack_start(GTK_BOX(box_misc), check_timing_vsync, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_timing_vsync), "toggled", - G_CALLBACK(gtkui_cb_timing_vsync), NULL); - - // Limiter - GtkWidget *check_timing_limiter = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Speed Limiter", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_timing_limiter), conf.timing_limiter); - - gtk_box_pack_start(GTK_BOX(box_misc), check_timing_limiter, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_timing_limiter), "toggled", - G_CALLBACK(gtkui_cb_timing_limiter), NULL); - - // Soft Patching - GtkWidget *check_misc_soft_patching = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Automatic Soft Patching", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_soft_patching), conf.misc_soft_patching); - - gtk_box_pack_start(GTK_BOX(box_misc), check_misc_soft_patching, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_misc_soft_patching), "toggled", - G_CALLBACK(gtkui_cb_misc_soft_patching), NULL); - - // Game Genie Sound Distortion - GtkWidget *check_misc_genie_distortion = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Game Genie Sound Distortion", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_genie_distortion), conf.misc_genie_distortion); - - gtk_box_pack_start(GTK_BOX(box_misc), check_misc_genie_distortion, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_misc_genie_distortion), "toggled", - G_CALLBACK(gtkui_cb_misc_genie_distortion), NULL); - - // Disable GUI - GtkWidget *check_misc_disable_gui = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Disable GUI", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_disable_gui), conf.misc_disable_gui); - - //gtk_box_pack_start(GTK_BOX(box_misc), check_misc_disable_gui, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_misc_disable_gui), "toggled", - G_CALLBACK(gtkui_cb_misc_disable_gui), NULL); - - // Disable Cursor - GtkWidget *check_misc_disable_cursor = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Disable Cursor", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_disable_cursor), conf.misc_disable_cursor); - - gtk_box_pack_start(GTK_BOX(box_misc), check_misc_disable_cursor, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_misc_disable_cursor), "toggled", - G_CALLBACK(gtkui_cb_misc_disable_cursor), NULL); - - // Pause While Configuration Open - #ifndef _APPLE - GtkWidget *check_misc_config_pause = gtk_widget_new( - GTK_TYPE_CHECK_BUTTON, - "label", "Pause While Configuration Open", - "halign", GTK_ALIGN_START, - "margin-left", MARGIN_LR, - NULL); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_misc_config_pause), conf.misc_config_pause); - - gtk_box_pack_start(GTK_BOX(box_misc), check_misc_config_pause, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(check_misc_config_pause), "toggled", - G_CALLBACK(gtkui_cb_misc_config_pause), NULL); - #endif - - // Structuring the notebook - GtkWidget *label_video = gtk_label_new("Video"); - GtkWidget *label_audio = gtk_label_new("Audio"); - GtkWidget *label_input = gtk_label_new("Input"); - GtkWidget *label_misc = gtk_label_new("Misc"); - gtk_notebook_append_page(GTK_NOTEBOOK(notebook), box_video, label_video); - gtk_notebook_append_page(GTK_NOTEBOOK(notebook), box_audio, label_audio); - gtk_notebook_append_page(GTK_NOTEBOOK(notebook), box_input, label_input); - gtk_notebook_append_page(GTK_NOTEBOOK(notebook), box_misc, label_misc); - - // The OK button - GtkWidget *okbutton = gtk_widget_new( - GTK_TYPE_BUTTON, - "label", GTK_STOCK_OK, - "halign", GTK_ALIGN_END, - "margin-top", 8, - "margin-bottom", 8, - "margin-right", 8, - NULL); - gtk_button_set_use_stock(GTK_BUTTON(okbutton), TRUE); - - // Connect the OK button to a callback - g_signal_connect(G_OBJECT(okbutton), "clicked", - G_CALLBACK(gtkui_config_ok), NULL); - - // Structuring the window - gtk_box_pack_start(GTK_BOX(box_upper), notebook, TRUE, TRUE, 0); - gtk_box_pack_start(GTK_BOX(box_upper), box_lower, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box_lower), okbutton, FALSE, FALSE, 0); - - g_signal_connect(G_OBJECT(configwindow), "destroy", - G_CALLBACK(gtkui_config_ok), NULL); - - gtk_widget_show_all(configwindow); - - gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), tabnum); - - return configwindow; -} - -void gtkui_config_ok() { - if (confrunning) { confrunning = false; } - tabnum = gtk_notebook_get_current_page(GTK_NOTEBOOK(notebook)); - gtk_widget_destroy(configwindow); - configwindow = NULL; - nst_play(); -} - -void gtkui_audio_volume() { - // Set the audio volume on specific channels - conf.audio_vol_sq1 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[1]); - conf.audio_vol_sq2 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[2]); - conf.audio_vol_tri = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[3]); - conf.audio_vol_noise = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[4]); - conf.audio_vol_dpcm = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[5]); - conf.audio_vol_fds = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[6]); - conf.audio_vol_mmc5 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[7]); - conf.audio_vol_vrc6 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[8]); - conf.audio_vol_vrc7 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[9]); - conf.audio_vol_n163 = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[10]); - conf.audio_vol_s5b = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[11]); - audio_adj_volume(); -} - -void gtkui_audio_volume_master() { - // Set the audio volume on all channels - conf.audio_volume = (int)gtk_range_get_value((GtkRange*)scale_audio_volume[0]); - - for (int i = 1; i < NUMCHANNELS; i++) { - gtk_adjustment_set_value(adj_audio_volume[i], gtk_range_get_value((GtkRange*)scale_audio_volume[0])); - } - - gtkui_audio_volume(); -} - -void gtkui_config_input_activate(GtkWidget *widget, GtkTreePath *path, gpointer userdata) { - // React to a button configuration request - GtkTreeIter iter; - GtkTreeModel *model; - GtkTreeSelection *selection; - - int pnum = gtk_combo_box_get_active(GTK_COMBO_BOX(combo_input_player)); - int type = gtk_combo_box_get_active(GTK_COMBO_BOX(combo_input_type)); - - // Get the selected item - selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); - gtk_tree_selection_get_selected(selection, &model, &iter); - - path = gtk_tree_model_get_path(model, &iter); - int bnum = gtk_tree_path_get_indices(path)[0]; - - // Replace the text with the current key - gtk_tree_store_set(treestore_input, &iter, 1, "Set Key...", -1); - - // Set the key - input_configure_item(pnum, bnum, type); - - // Replace the text with the new key - //gtkui_config_input_fields(type, pnum); // This can be used in place of the below if statement - if (type == 0) { // Keyboard - switch (bnum) { - case 0: - gtk_tree_store_set(treestore_input, &iter, 1, SDL_GetScancodeName(player[pnum].u), -1); - break; - case 1: - gtk_tree_store_set(treestore_input, &iter, 1, SDL_GetScancodeName(player[pnum].d), -1); - break; - case 2: - gtk_tree_store_set(treestore_input, &iter, 1, SDL_GetScancodeName(player[pnum].l), -1); - break; - case 3: - gtk_tree_store_set(treestore_input, &iter, 1, SDL_GetScancodeName(player[pnum].r), -1); - break; - case 4: - gtk_tree_store_set(treestore_input, &iter, 1, SDL_GetScancodeName(player[pnum].select), -1); - break; - case 5: - gtk_tree_store_set(treestore_input, &iter, 1, SDL_GetScancodeName(player[pnum].start), -1); - break; - case 6: - gtk_tree_store_set(treestore_input, &iter, 1, SDL_GetScancodeName(player[pnum].a), -1); - break; - case 7: - gtk_tree_store_set(treestore_input, &iter, 1, SDL_GetScancodeName(player[pnum].b), -1); - break; - case 8: - gtk_tree_store_set(treestore_input, &iter, 1, SDL_GetScancodeName(player[pnum].ta), -1); - break; - case 9: - gtk_tree_store_set(treestore_input, &iter, 1, SDL_GetScancodeName(player[pnum].tb), -1); - break; - default: break; - } - } - else { // Joystick - switch (bnum) { - case 0: - gtk_tree_store_set(treestore_input, &iter, 1, input_translate_event(player[pnum].ju), -1); - break; - case 1: - gtk_tree_store_set(treestore_input, &iter, 1, input_translate_event(player[pnum].jd), -1); - break; - case 2: - gtk_tree_store_set(treestore_input, &iter, 1, input_translate_event(player[pnum].jl), -1); - break; - case 3: - gtk_tree_store_set(treestore_input, &iter, 1, input_translate_event(player[pnum].jr), -1); - break; - case 4: - gtk_tree_store_set(treestore_input, &iter, 1, input_translate_event(player[pnum].jselect), -1); - break; - case 5: - gtk_tree_store_set(treestore_input, &iter, 1, input_translate_event(player[pnum].jstart), -1); - break; - case 6: - gtk_tree_store_set(treestore_input, &iter, 1, input_translate_event(player[pnum].ja), -1); - break; - case 7: - gtk_tree_store_set(treestore_input, &iter, 1, input_translate_event(player[pnum].jb), -1); - break; - case 8: - gtk_tree_store_set(treestore_input, &iter, 1, input_translate_event(player[pnum].jta), -1); - break; - case 9: - gtk_tree_store_set(treestore_input, &iter, 1, input_translate_event(player[pnum].jtb), -1); - break; - default: break; - } - } -} - -void gtkui_config_input_refresh() { - // Refresh the input fields - int pnum = gtk_combo_box_get_active(GTK_COMBO_BOX(combo_input_player)); - int type = gtk_combo_box_get_active(GTK_COMBO_BOX(combo_input_type)); - gtkui_config_input_fields(type, pnum); -} - -void gtkui_config_input_fields(int type, int pnum) { - // Set the text in the input fields based on the current settings - GtkTreeIter iter; - - gtk_tree_store_clear(treestore_input); - - if (type == 0) { - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Up", 1, SDL_GetScancodeName(player[pnum].u), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Down", 1, SDL_GetScancodeName(player[pnum].d), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Left", 1, SDL_GetScancodeName(player[pnum].l), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Right", 1, SDL_GetScancodeName(player[pnum].r), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Select", 1, SDL_GetScancodeName(player[pnum].select), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Start", 1, SDL_GetScancodeName(player[pnum].start), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "A", 1, SDL_GetScancodeName(player[pnum].a), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "B", 1, SDL_GetScancodeName(player[pnum].b), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Turbo A", 1, SDL_GetScancodeName(player[pnum].ta), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Turbo B", 1, SDL_GetScancodeName(player[pnum].tb), -1); - } - if (type == 1) { - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Up", 1, input_translate_event(player[pnum].ju), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Down", 1, input_translate_event(player[pnum].jd), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Left", 1, input_translate_event(player[pnum].jl), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Right", 1, input_translate_event(player[pnum].jr), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Select", 1, input_translate_event(player[pnum].jselect), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Start", 1, input_translate_event(player[pnum].jstart), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "A", 1, input_translate_event(player[pnum].ja), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "B", 1, input_translate_event(player[pnum].jb), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Turbo A", 1, input_translate_event(player[pnum].jta), -1); - gtk_tree_store_append(treestore_input, &iter, NULL); - gtk_tree_store_set(treestore_input, &iter, 0, "Turbo B", 1, input_translate_event(player[pnum].jtb), -1); - } -} - -void gtkui_config_input_defaults() { - // Restore input defaults - input_set_default(); - gtkui_config_input_refresh(); -} diff -Nru nestopia-1.48/source/unix/gtkui/gtkui_config.h nestopia-1.49/source/unix/gtkui/gtkui_config.h --- nestopia-1.48/source/unix/gtkui/gtkui_config.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui_config.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -#ifndef _GTKUI_CONFIG_H_ -#define _GTKUI_CONFIG_H_ - -#define MARGIN_TB 5 -#define MARGIN_LR 10 - -#define NUMCHANNELS 12 - -GtkWidget *gtkui_config(); -void gtkui_config_ok(); -void gtkui_audio_volume(); -void gtkui_audio_volume_master(); -void gtkui_config_input_activate(GtkWidget *widget, GtkTreePath *path, gpointer userdata); -void gtkui_config_input_refresh(); -void gtkui_config_input_fields(int type, int pnum); -void gtkui_config_input_defaults(); - -#endif diff -Nru nestopia-1.48/source/unix/gtkui/gtkui.cpp nestopia-1.49/source/unix/gtkui/gtkui.cpp --- nestopia-1.48/source/unix/gtkui/gtkui.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,480 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2017 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include -#include - -#include "../main.h" -#include "../config.h" -#include "../video.h" - -#include "gtkui.h" -#include "gtkui_callbacks.h" -#include "gtkui_config.h" -#include "gtkui_cheats.h" -#include "gtkui_dialogs.h" - -GtkWidget *gtkwindow; -GtkWidget *statusbar; -GtkWidget *menubar; -GtkWidget *drawingarea; - -char iconpath[512]; -char padpath[512]; - -extern dimensions_t basesize, rendersize; -extern settings_t conf; - -void gtkui_init(int argc, char *argv[]) { - // Initialize the GTK+ GUI - gtk_init(&argc, &argv); - #ifndef _APPLE - gtkui_create(); - #endif -} - -void gtkui_state_quickload(GtkWidget *widget, gpointer userdata) { - // Wrapper function to quickload states - nst_state_quickload(GPOINTER_TO_INT(userdata)); -} - -void gtkui_state_quicksave(GtkWidget *widget, gpointer userdata) { - // Wrapper function to quicksave states - nst_state_quicksave(GPOINTER_TO_INT(userdata)); -} - -void gtkui_open_recent(GtkWidget *widget, gpointer userdata) { - // Open a recently used item - gchar *uri = gtk_recent_chooser_get_current_uri((GtkRecentChooser*)widget); - nst_load(g_filename_from_uri(uri, NULL, NULL)); -} - -void gtkui_create() { - // Create the GTK+ Window - - gtkui_image_paths(); - GdkPixbuf *icon = gdk_pixbuf_new_from_file(iconpath, NULL); - - char title[24]; - snprintf(title, sizeof(title), "Nestopia UE %s", VERSION); - - gtkwindow = gtk_window_new(GTK_WINDOW_TOPLEVEL); - gtk_window_set_icon(GTK_WINDOW(gtkwindow), icon); - gtk_window_set_title(GTK_WINDOW(gtkwindow), title); - gtk_window_set_resizable(GTK_WINDOW(gtkwindow), FALSE); - - GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); - gtk_container_add(GTK_CONTAINER(gtkwindow), box); - - // Define the menubar and menus - menubar = gtk_menu_bar_new(); - - // Define the File menu - GtkWidget *filemenu = gtk_menu_new(); - GtkWidget *file = gtk_menu_item_new_with_mnemonic("_File"); - GtkWidget *open = gtk_image_menu_item_new_from_stock(GTK_STOCK_OPEN, NULL); - GtkWidget *recent = gtk_image_menu_item_new_with_label("Open Recent"); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(recent), gtk_image_new_from_stock(GTK_STOCK_OPEN, GTK_ICON_SIZE_MENU)); - GtkWidget *sep_open = gtk_separator_menu_item_new(); - GtkWidget *stateload = gtk_image_menu_item_new_with_mnemonic("_Load State..."); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(stateload), gtk_image_new_from_stock(GTK_STOCK_GO_BACK, GTK_ICON_SIZE_MENU)); - GtkWidget *statesave = gtk_image_menu_item_new_with_mnemonic("_Save State..."); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(statesave), gtk_image_new_from_stock(GTK_STOCK_SAVE, GTK_ICON_SIZE_MENU)); - - GtkWidget *quickload = gtk_image_menu_item_new_with_label("Quick Load"); - GtkWidget *qloadmenu = gtk_menu_new(); - GtkWidget *qload0 = gtk_image_menu_item_new_with_label("0"); - GtkWidget *qload1 = gtk_image_menu_item_new_with_label("1"); - GtkWidget *qload2 = gtk_image_menu_item_new_with_label("2"); - GtkWidget *qload3 = gtk_image_menu_item_new_with_label("3"); - GtkWidget *qload4 = gtk_image_menu_item_new_with_label("4"); - - GtkWidget *quicksave = gtk_image_menu_item_new_with_label("Quick Save"); - GtkWidget *qsavemenu = gtk_menu_new(); - GtkWidget *qsave0 = gtk_image_menu_item_new_with_label("0"); - GtkWidget *qsave1 = gtk_image_menu_item_new_with_label("1"); - GtkWidget *qsave2 = gtk_image_menu_item_new_with_label("2"); - GtkWidget *qsave3 = gtk_image_menu_item_new_with_label("3"); - GtkWidget *qsave4 = gtk_image_menu_item_new_with_label("4"); - - GtkWidget *sep_state = gtk_separator_menu_item_new(); - GtkWidget *screenshot = gtk_image_menu_item_new_with_mnemonic("S_creenshot..."); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(screenshot), gtk_image_new_from_stock(GTK_STOCK_SELECT_COLOR, GTK_ICON_SIZE_MENU)); - GtkWidget *sep_screenshot = gtk_separator_menu_item_new(); - GtkWidget *movieload = gtk_image_menu_item_new_with_label("Load Movie..."); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(movieload), gtk_image_new_from_stock(GTK_STOCK_OPEN, GTK_ICON_SIZE_MENU)); - GtkWidget *moviesave = gtk_image_menu_item_new_with_label("Record Movie..."); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(moviesave), gtk_image_new_from_stock(GTK_STOCK_MEDIA_RECORD, GTK_ICON_SIZE_MENU)); - GtkWidget *moviestop = gtk_image_menu_item_new_with_label("Stop Movie"); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(moviestop), gtk_image_new_from_stock(GTK_STOCK_MEDIA_STOP, GTK_ICON_SIZE_MENU)); - GtkWidget *sep_movie = gtk_separator_menu_item_new(); - GtkWidget *quit = gtk_image_menu_item_new_from_stock(GTK_STOCK_QUIT, NULL); - - // Set up the recently used items - GtkWidget *recent_items = gtk_recent_chooser_menu_new(); - GtkRecentFilter *recent_filter = gtk_recent_filter_new(); - gtk_recent_filter_add_pattern(recent_filter, "*.nes"); - gtk_recent_filter_add_pattern(recent_filter, "*.fds"); - gtk_recent_filter_add_pattern(recent_filter, "*.unf"); - gtk_recent_filter_add_pattern(recent_filter, "*.unif"); - gtk_recent_filter_add_pattern(recent_filter, "*.nsf"); - gtk_recent_filter_add_pattern(recent_filter, "*.zip"); - gtk_recent_filter_add_pattern(recent_filter, "*.7z"); - gtk_recent_filter_add_pattern(recent_filter, "*.txz"); - gtk_recent_filter_add_pattern(recent_filter, "*.tar.xz"); - gtk_recent_filter_add_pattern(recent_filter, "*.xz"); - gtk_recent_filter_add_pattern(recent_filter, "*.tgz"); - gtk_recent_filter_add_pattern(recent_filter, "*.tar.gz"); - gtk_recent_filter_add_pattern(recent_filter, "*.gz"); - gtk_recent_filter_add_pattern(recent_filter, "*.tbz"); - gtk_recent_filter_add_pattern(recent_filter, "*.tar.bz2"); - gtk_recent_filter_add_pattern(recent_filter, "*.bz2"); - gtk_recent_chooser_add_filter(GTK_RECENT_CHOOSER(recent_items), recent_filter); - - // Populate the File menu - gtk_menu_item_set_submenu(GTK_MENU_ITEM(file), filemenu); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), open); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), recent); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(recent), recent_items); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), sep_open); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), stateload); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), statesave); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), quickload); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(quickload), qloadmenu); - gtk_menu_shell_append(GTK_MENU_SHELL(qloadmenu), qload0); - gtk_menu_shell_append(GTK_MENU_SHELL(qloadmenu), qload1); - gtk_menu_shell_append(GTK_MENU_SHELL(qloadmenu), qload2); - gtk_menu_shell_append(GTK_MENU_SHELL(qloadmenu), qload3); - gtk_menu_shell_append(GTK_MENU_SHELL(qloadmenu), qload4); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), quicksave); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(quicksave), qsavemenu); - gtk_menu_shell_append(GTK_MENU_SHELL(qsavemenu), qsave0); - gtk_menu_shell_append(GTK_MENU_SHELL(qsavemenu), qsave1); - gtk_menu_shell_append(GTK_MENU_SHELL(qsavemenu), qsave2); - gtk_menu_shell_append(GTK_MENU_SHELL(qsavemenu), qsave3); - gtk_menu_shell_append(GTK_MENU_SHELL(qsavemenu), qsave4); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), sep_state); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), screenshot); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), sep_screenshot); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), movieload); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), moviesave); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), moviestop); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), sep_movie); - gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), quit); - - // Define the Emulator menu - GtkWidget *emulatormenu = gtk_menu_new(); - GtkWidget *emu = gtk_menu_item_new_with_mnemonic("_Emulator"); - GtkWidget *cont = gtk_image_menu_item_new_with_mnemonic("C_ontinue"); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(cont), gtk_image_new_from_stock(GTK_STOCK_MEDIA_PLAY, GTK_ICON_SIZE_MENU)); - GtkWidget *pause = gtk_image_menu_item_new_from_stock(GTK_STOCK_MEDIA_PAUSE, NULL); - GtkWidget *sep_pause = gtk_separator_menu_item_new(); - GtkWidget *resetsoft = gtk_image_menu_item_new_with_mnemonic("_Reset (Soft)"); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(resetsoft), gtk_image_new_from_stock(GTK_STOCK_REFRESH, GTK_ICON_SIZE_MENU)); - GtkWidget *resethard = gtk_image_menu_item_new_with_mnemonic("Reset (_Hard)"); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(resethard), gtk_image_new_from_stock(GTK_STOCK_REFRESH, GTK_ICON_SIZE_MENU)); - GtkWidget *sep_reset = gtk_separator_menu_item_new(); - GtkWidget *fullscreen = gtk_image_menu_item_new_from_stock(GTK_STOCK_FULLSCREEN, NULL); - GtkWidget *sep_fullscreen = gtk_separator_menu_item_new(); - GtkWidget *diskflip = gtk_image_menu_item_new_with_mnemonic("Flip FDS _Disk"); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(diskflip), gtk_image_new_from_stock(GTK_STOCK_FLOPPY, GTK_ICON_SIZE_MENU)); - GtkWidget *diskswitch = gtk_image_menu_item_new_with_mnemonic("_Switch FDS Disk"); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(diskswitch), gtk_image_new_from_stock(GTK_STOCK_FLOPPY, GTK_ICON_SIZE_MENU)); - GtkWidget *sep_disk = gtk_separator_menu_item_new(); - GtkWidget *cheats = gtk_image_menu_item_new_with_mnemonic("Ch_eats..."); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(cheats), gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_MENU)); - GtkWidget *sep_cheats = gtk_separator_menu_item_new(); - GtkWidget *configuration = gtk_image_menu_item_new_with_mnemonic("_Configuration..."); - gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(configuration), gtk_image_new_from_stock(GTK_STOCK_PREFERENCES, GTK_ICON_SIZE_MENU)); - - // Populate the Emulator menu - gtk_menu_item_set_submenu(GTK_MENU_ITEM(emu), emulatormenu); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), cont); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), pause); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), sep_pause); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), resetsoft); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), resethard); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), sep_reset); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), fullscreen); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), sep_fullscreen); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), diskflip); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), diskswitch); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), sep_disk); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), cheats); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), sep_cheats); - gtk_menu_shell_append(GTK_MENU_SHELL(emulatormenu), configuration); - - // Define the Help menu - GtkWidget *helpmenu = gtk_menu_new(); - GtkWidget *help = gtk_menu_item_new_with_mnemonic("_Help"); - GtkWidget *about = gtk_image_menu_item_new_from_stock(GTK_STOCK_ABOUT, NULL); - - // Populate the Help menu - gtk_menu_item_set_submenu(GTK_MENU_ITEM(help), helpmenu); - gtk_menu_shell_append(GTK_MENU_SHELL(helpmenu), about); - - // Put the menus into the menubar - gtk_menu_shell_append(GTK_MENU_SHELL(menubar), file); - gtk_menu_shell_append(GTK_MENU_SHELL(menubar), emu); - gtk_menu_shell_append(GTK_MENU_SHELL(menubar), help); - - // Create the DrawingArea/OpenGL context - drawingarea = gtk_drawing_area_new(); - //gtk_widget_set_double_buffered(drawingarea, FALSE); - - g_object_set_data(G_OBJECT(gtkwindow), "area", drawingarea); - - // Set the Drawing Area to be the size of the game output - gtk_widget_set_size_request(drawingarea, rendersize.w, rendersize.h); - - // Create the statusbar - GtkWidget *statusbar = gtk_statusbar_new(); - - // Pack the box with the menubar, drawingarea, and statusbar - gtk_box_pack_start(GTK_BOX(box), menubar, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(box), drawingarea, TRUE, TRUE, 0); - //gtk_box_pack_start(GTK_BOX(box), statusbar, FALSE, FALSE, 0); - - // Make it dark if there's a dark theme - GtkSettings *gtksettings = gtk_settings_get_default(); - g_object_set(G_OBJECT(gtksettings), "gtk-application-prefer-dark-theme", TRUE, NULL); - - // Set up the Drag and Drop target - GtkTargetEntry target_entry[1]; - - target_entry[0].target = (gchar*)"text/uri-list"; - target_entry[0].flags = 0; - target_entry[0].info = 0; - - gtk_drag_dest_set(drawingarea, (GtkDestDefaults)(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT | GTK_DEST_DEFAULT_DROP), - target_entry, sizeof(target_entry) / sizeof(GtkTargetEntry), (GdkDragAction)(GDK_ACTION_MOVE | GDK_ACTION_COPY)); - - // Connect the signals - g_signal_connect(G_OBJECT(drawingarea), "drag-data-received", - G_CALLBACK(gtkui_drag_data), NULL); - - g_signal_connect(G_OBJECT(gtkwindow), "delete_event", - G_CALLBACK(nst_schedule_quit), NULL); - - // File menu - g_signal_connect(G_OBJECT(open), "activate", - G_CALLBACK(gtkui_file_open), NULL); - - g_signal_connect(G_OBJECT(recent_items), "item-activated", - G_CALLBACK(gtkui_open_recent), NULL); - - g_signal_connect(G_OBJECT(stateload), "activate", - G_CALLBACK(gtkui_state_load), NULL); - - g_signal_connect(G_OBJECT(statesave), "activate", - G_CALLBACK(gtkui_state_save), NULL); - - g_signal_connect(G_OBJECT(qload0), "activate", - G_CALLBACK(gtkui_state_quickload), gpointer(0)); - - g_signal_connect(G_OBJECT(qload1), "activate", - G_CALLBACK(gtkui_state_quickload), gpointer(1)); - - g_signal_connect(G_OBJECT(qload2), "activate", - G_CALLBACK(gtkui_state_quickload), gpointer(2)); - - g_signal_connect(G_OBJECT(qload3), "activate", - G_CALLBACK(gtkui_state_quickload), gpointer(3)); - - g_signal_connect(G_OBJECT(qload4), "activate", - G_CALLBACK(gtkui_state_quickload), gpointer(4)); - - g_signal_connect(G_OBJECT(qsave0), "activate", - G_CALLBACK(gtkui_state_quicksave), gpointer(0)); - - g_signal_connect(G_OBJECT(qsave1), "activate", - G_CALLBACK(gtkui_state_quicksave), gpointer(1)); - - g_signal_connect(G_OBJECT(qsave2), "activate", - G_CALLBACK(gtkui_state_quicksave), gpointer(2)); - - g_signal_connect(G_OBJECT(qsave3), "activate", - G_CALLBACK(gtkui_state_quicksave), gpointer(3)); - - g_signal_connect(G_OBJECT(qsave4), "activate", - G_CALLBACK(gtkui_state_quicksave), gpointer(4)); - - g_signal_connect(G_OBJECT(screenshot), "activate", - G_CALLBACK(gtkui_screenshot_save), NULL); - - g_signal_connect(G_OBJECT(moviesave), "activate", - G_CALLBACK(gtkui_movie_save), NULL); - - g_signal_connect(G_OBJECT(movieload), "activate", - G_CALLBACK(gtkui_movie_load), NULL); - - g_signal_connect(G_OBJECT(moviestop), "activate", - G_CALLBACK(gtkui_movie_stop), NULL); - - g_signal_connect(G_OBJECT(quit), "activate", - G_CALLBACK(nst_schedule_quit), NULL); - - // Emulator menu - g_signal_connect(G_OBJECT(cont), "activate", - G_CALLBACK(nst_play), NULL); - - g_signal_connect(G_OBJECT(pause), "activate", - G_CALLBACK(nst_pause), NULL); - - g_signal_connect(G_OBJECT(resetsoft), "activate", - G_CALLBACK(gtkui_cb_reset), gpointer(0)); - - g_signal_connect(G_OBJECT(resethard), "activate", - G_CALLBACK(gtkui_cb_reset), gpointer(1)); - - g_signal_connect(G_OBJECT(fullscreen), "activate", - G_CALLBACK(video_toggle_fullscreen), NULL); - - g_signal_connect(G_OBJECT(diskflip), "activate", - G_CALLBACK(nst_flip_disk), NULL); - - g_signal_connect(G_OBJECT(diskswitch), "activate", - G_CALLBACK(nst_switch_disk), NULL); - - g_signal_connect(G_OBJECT(cheats), "activate", - G_CALLBACK(gtkui_cheats), NULL); - - g_signal_connect(G_OBJECT(configuration), "activate", - G_CALLBACK(gtkui_config), NULL); - - // Help menu - g_signal_connect(G_OBJECT(about), "activate", - G_CALLBACK(gtkui_about), NULL); - - // Key translation - g_signal_connect(G_OBJECT(gtkwindow), "key-press-event", - G_CALLBACK(gtkui_cb_convert_key), NULL); - - g_signal_connect(G_OBJECT(gtkwindow), "key-release-event", - G_CALLBACK(gtkui_cb_convert_key), NULL); - - // Mouse translation - gtk_widget_add_events(GTK_WIDGET(drawingarea), GDK_BUTTON_PRESS_MASK); - gtk_widget_add_events(GTK_WIDGET(drawingarea), GDK_BUTTON_RELEASE_MASK); - - g_signal_connect(G_OBJECT(drawingarea), "button-press-event", - G_CALLBACK(gtkui_cb_convert_mouse), NULL); - - g_signal_connect(G_OBJECT(drawingarea), "button-release-event", - G_CALLBACK(gtkui_cb_convert_mouse), NULL); - - gtk_widget_show_all(gtkwindow); -} - -void gtkui_resize() { - // Resize the GTK+ window - if (gtkwindow) { - gtk_widget_set_size_request(drawingarea, rendersize.w, rendersize.h); - } -} - -void gtkui_set_title(const char *title) { - #ifndef _APPLE - gtk_window_set_title(GTK_WINDOW(gtkwindow), title); - #endif -} - -void gtkui_toggle_fullscreen() { - if (conf.video_fullscreen) { - gtk_widget_hide(menubar); - gtk_window_fullscreen(GTK_WINDOW(gtkwindow)); - } - else { - gtk_window_unfullscreen(GTK_WINDOW(gtkwindow)); - gtk_widget_show(menubar); - } - gtkui_resize(); -} - -GtkWidget *gtkui_about() { - // Pull up the About dialog - GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file_at_size(iconpath, 192, 192, NULL); - GtkWidget *aboutdialog = gtk_about_dialog_new(); - gtk_window_set_transient_for(GTK_WINDOW(aboutdialog), GTK_WINDOW(gtkwindow)); - - gtk_about_dialog_set_logo(GTK_ABOUT_DIALOG(aboutdialog), pixbuf); - gtk_about_dialog_set_program_name(GTK_ABOUT_DIALOG(aboutdialog), "Nestopia UE"); - gtk_about_dialog_set_version(GTK_ABOUT_DIALOG(aboutdialog), VERSION); - gtk_about_dialog_set_comments(GTK_ABOUT_DIALOG(aboutdialog), "Cycle-Accurate Nintendo Entertainment System Emulator"); - gtk_about_dialog_set_website(GTK_ABOUT_DIALOG(aboutdialog), "http://0ldsk00l.ca/nestopia/"); - gtk_about_dialog_set_copyright(GTK_ABOUT_DIALOG(aboutdialog), "(c) 2012-2017, R. Danbrook\n(c) 2007-2008, R. Belmont\n(c) 2003-2008, Martin Freij\n\nIcon based on art from Trollekop"); - gtk_dialog_run(GTK_DIALOG(aboutdialog)); - gtk_widget_destroy(aboutdialog); - - return aboutdialog; -} - -void gtkui_image_paths() { - // Set paths to SVG icons/images - snprintf(iconpath, sizeof(iconpath), "%s/icons/hicolor/scalable/apps/nestopia.svg", DATAROOTDIR); - snprintf(padpath, sizeof(padpath), "%s/icons/hicolor/scalable/apps/nespad.svg", DATAROOTDIR); - - // Load the SVG from local source dir if make install hasn't been done - struct stat svgstat; - if (stat(iconpath, &svgstat) == -1) { - snprintf(iconpath, sizeof(iconpath), "source/unix/icons/nestopia.svg"); - } - if (stat(padpath, &svgstat) == -1) { - snprintf(padpath, sizeof(padpath), "source/unix/icons/nespad.svg"); - } -} - -void gtkui_message(const char* message) { - GtkWidget *messagewindow = gtk_message_dialog_new( - GTK_WINDOW(gtkwindow), - GTK_DIALOG_DESTROY_WITH_PARENT, - GTK_MESSAGE_INFO, - GTK_BUTTONS_OK, - "%s", message); - gtk_dialog_run(GTK_DIALOG(messagewindow)); - gtk_widget_destroy(messagewindow); -} - -void gtkui_cursor_set_crosshair() { - // Set the cursor to a crosshair - GdkCursor *cursor; - cursor = gdk_cursor_new(GDK_CROSSHAIR); - - GdkWindow *gdkwindow = gtk_widget_get_window(GTK_WIDGET(drawingarea)); - - gdk_window_set_cursor(gdkwindow, cursor); - gdk_flush(); - gdk_cursor_unref(cursor); -} - -void gtkui_cursor_set_default() { - // Set the cursor to the default - GdkCursor *cursor; - cursor = gdk_cursor_new(GDK_LEFT_PTR); - - GdkWindow *gdkwindow = gtk_widget_get_window(GTK_WIDGET(drawingarea)); - - gdk_window_set_cursor(gdkwindow, cursor); - gdk_flush(); - gdk_cursor_unref(cursor); -} diff -Nru nestopia-1.48/source/unix/gtkui/gtkui_dialogs.cpp nestopia-1.49/source/unix/gtkui/gtkui_dialogs.cpp --- nestopia-1.48/source/unix/gtkui/gtkui_dialogs.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui_dialogs.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,231 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include "../main.h" -#include "../video.h" -#include "../config.h" - -#include "gtkui.h" -#include "gtkui_cheats.h" - -extern nstpaths_t nstpaths; -extern settings_t conf; -extern GtkWidget *gtkwindow; - -void gtkui_file_open() { - // Open a file using a GTK+ dialog - GtkWidget *dialog = gtk_file_chooser_dialog_new( - "Select a ROM", - GTK_WINDOW(gtkwindow), - GTK_FILE_CHOOSER_ACTION_OPEN, - GTK_STOCK_CANCEL, - GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, - GTK_RESPONSE_ACCEPT, - NULL); - - if(conf.misc_last_folder != NULL) - gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), conf.misc_last_folder); - - GtkFileFilter *filter = gtk_file_filter_new(); - - gtk_file_filter_set_name(filter, "NES ROMs and Archives"); - gtk_file_filter_add_pattern(filter, "*.nes"); - gtk_file_filter_add_pattern(filter, "*.fds"); - gtk_file_filter_add_pattern(filter, "*.unf"); - gtk_file_filter_add_pattern(filter, "*.unif"); - gtk_file_filter_add_pattern(filter, "*.nsf"); - gtk_file_filter_add_pattern(filter, "*.zip"); - gtk_file_filter_add_pattern(filter, "*.7z"); - gtk_file_filter_add_pattern(filter, "*.txz"); - gtk_file_filter_add_pattern(filter, "*.tar.xz"); - gtk_file_filter_add_pattern(filter, "*.xz"); - gtk_file_filter_add_pattern(filter, "*.tgz"); - gtk_file_filter_add_pattern(filter, "*.tar.gz"); - gtk_file_filter_add_pattern(filter, "*.gz"); - gtk_file_filter_add_pattern(filter, "*.tbz"); - gtk_file_filter_add_pattern(filter, "*.tar.bz2"); - gtk_file_filter_add_pattern(filter, "*.bz2"); - - gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); - - if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { - char *filename; - filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - - if(conf.misc_last_folder != NULL) - free(conf.misc_last_folder); - - conf.misc_last_folder = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(dialog)); - gtk_widget_destroy(dialog); - nst_load(filename); - g_free(filename); - } - else { gtk_widget_destroy(dialog); } -} - -void gtkui_state_save() { - // Save a state from the GUI - GtkWidget *dialog = gtk_file_chooser_dialog_new("Save State (.nst)", - GTK_WINDOW(gtkwindow), - GTK_FILE_CHOOSER_ACTION_SAVE, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, - NULL); - - char statepath[512]; - snprintf(statepath, sizeof(statepath), "%s.nst", nstpaths.statepath); - gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), statepath); - gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), nstpaths.statepath); - - if (gtk_dialog_run(GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { - char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - nst_state_save(filename); - g_free(filename); - } - - gtk_widget_destroy(dialog); -} - -void gtkui_state_load() { - // Load a state from the GUI - GtkWidget *dialog = gtk_file_chooser_dialog_new("Load State (.nst)", - GTK_WINDOW(gtkwindow), - GTK_FILE_CHOOSER_ACTION_OPEN, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL); - - GtkFileFilter *filter = gtk_file_filter_new(); - gtk_file_filter_set_name(filter, "Nestopia Save States"); - gtk_file_filter_add_pattern(filter, "*.nst"); - gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); - gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), nstpaths.statepath); - - if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { - char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - nst_state_load(filename); - g_free(filename); - } - - gtk_widget_destroy(dialog); -} - -void gtkui_screenshot_save() { - // Save a screenshot from the GUI - GtkWidget *dialog = gtk_file_chooser_dialog_new("Save screenshot (.png)", - GTK_WINDOW(gtkwindow), - GTK_FILE_CHOOSER_ACTION_SAVE, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, - NULL); - - char sshotpath[512]; - char sshotfile[768]; - snprintf(sshotpath, sizeof(sshotpath), "%sscreenshots/", nstpaths.nstdir); - snprintf(sshotfile, sizeof(sshotfile), "%s%s.png", sshotpath, nstpaths.gamename); - gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), sshotfile); - gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), sshotpath); - - if (gtk_dialog_run(GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { - char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - video_screenshot(filename); - g_free(filename); - } - - gtk_widget_destroy(dialog); -} - -void gtkui_movie_save() { - // Save a movie from the GUI - GtkWidget *dialog = gtk_file_chooser_dialog_new("Save movie (.nsv)", - GTK_WINDOW(gtkwindow), - GTK_FILE_CHOOSER_ACTION_SAVE, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, - NULL); - - char moviepath[512]; - snprintf(moviepath, sizeof(moviepath), "%s%s.nsv", nstpaths.nstdir, nstpaths.gamename); - gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), moviepath); - gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), nstpaths.nstdir); - - if (gtk_dialog_run(GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { - char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - nst_movie_save(filename); - g_free(filename); - } - - gtk_widget_destroy(dialog); -} - -void gtkui_movie_load() { - // Load a movie from the GUI - GtkWidget *dialog = gtk_file_chooser_dialog_new("Load movie (.nsv)", - GTK_WINDOW(gtkwindow), - GTK_FILE_CHOOSER_ACTION_OPEN, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL); - - GtkFileFilter *filter = gtk_file_filter_new(); - gtk_file_filter_set_name(filter, "Nestopia movies"); - gtk_file_filter_add_pattern(filter, "*.nsv"); - gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); - gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), nstpaths.nstdir); - - if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { - char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - nst_movie_load(filename); - g_free(filename); - } - - gtk_widget_destroy(dialog); -} - -void gtkui_movie_stop() { - nst_movie_stop(); -} - -void gtkui_cheats_load() { - // Load cheats from the GUI - GtkWidget *dialog = gtk_file_chooser_dialog_new("Load cheats (.xml)", - GTK_WINDOW(gtkwindow), - GTK_FILE_CHOOSER_ACTION_OPEN, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL); - - GtkFileFilter *filter = gtk_file_filter_new(); - gtk_file_filter_set_name(filter, "Nestopia cheats"); - gtk_file_filter_add_pattern(filter, "*.xml"); - gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); - gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), nstpaths.nstdir); - - if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { - char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); - gtkui_cheats_fill_tree(filename); - g_free(filename); - } - - gtk_widget_destroy(dialog); -} diff -Nru nestopia-1.48/source/unix/gtkui/gtkui_dialogs.h nestopia-1.49/source/unix/gtkui/gtkui_dialogs.h --- nestopia-1.48/source/unix/gtkui/gtkui_dialogs.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui_dialogs.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -#ifndef _GTKUI_DIALOGS_H_ -#define _GTKUI_DIALOGS_H_ - -void gtkui_file_open(); -void gtkui_state_save(); -void gtkui_state_load(); - -void gtkui_screenshot_save(); - -void gtkui_movie_save(); -void gtkui_movie_load(); -void gtkui_movie_stop(); - -void gtkui_cheats_load(); - -#endif diff -Nru nestopia-1.48/source/unix/gtkui/gtkui.h nestopia-1.49/source/unix/gtkui/gtkui.h --- nestopia-1.48/source/unix/gtkui/gtkui.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/gtkui/gtkui.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -#ifndef _GTKUI_H_ -#define _GTKUI_H_ - -#include - -#ifdef _MINGW -#include -#elif _APPLE -#else -#include -#endif - -void gtkui_init(int argc, char *argv[]); -void gtkui_create(); -void gtkui_resize(); -void gtkui_set_title(const char *title); -GtkWidget *gtkui_about(); -void gtkui_image_paths(); -void gtkui_message(const char* message); -void gtkui_cursor_set_crosshair(); -void gtkui_cursor_set_default(); -void gtkui_toggle_fullscreen(); - -#endif Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/source/unix/icons/128/nestopia.png and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/source/unix/icons/128/nestopia.png differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/source/unix/icons/32/nestopia.png and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/source/unix/icons/32/nestopia.png differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/source/unix/icons/48/nestopia.png and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/source/unix/icons/48/nestopia.png differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/source/unix/icons/64/nestopia.png and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/source/unix/icons/64/nestopia.png differ Binary files /tmp/tmpex9F1p/wN_KdM4CB3/nestopia-1.48/source/unix/icons/96/nestopia.png and /tmp/tmpex9F1p/a8bwTa4t2e/nestopia-1.49/source/unix/icons/96/nestopia.png differ diff -Nru nestopia-1.48/source/unix/icons/nestopia.desktop nestopia-1.49/source/unix/icons/nestopia.desktop --- nestopia-1.48/source/unix/icons/nestopia.desktop 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/icons/nestopia.desktop 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -[Desktop Entry] -Name=Nestopia -Comment=Accurate NES Emulator -Exec=nestopia -e %f -Icon=nestopia -Terminal=false -Type=Application -Categories=Game;Emulator; diff -Nru nestopia-1.48/source/unix/icons/svg/nespad.svg nestopia-1.49/source/unix/icons/svg/nespad.svg --- nestopia-1.48/source/unix/icons/svg/nespad.svg 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/icons/svg/nespad.svg 1970-01-01 00:00:00.000000000 +0000 @@ -1,729 +0,0 @@ - - - -image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 -M/LLQSIgTXANqqqu/m68XACKqCfC - - - \ No newline at end of file diff -Nru nestopia-1.48/source/unix/icons/svg/nestopia.svg nestopia-1.49/source/unix/icons/svg/nestopia.svg --- nestopia-1.48/source/unix/icons/svg/nestopia.svg 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/icons/svg/nestopia.svg 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - diff -Nru nestopia-1.48/source/unix/ini.cpp nestopia-1.49/source/unix/ini.cpp --- nestopia-1.48/source/unix/ini.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/ini.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,196 +0,0 @@ -/* inih -- simple .INI file parser - -Copyright (c) 2009, Brush Technology -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of Brush Technology nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY BRUSH TECHNOLOGY ''AS IS'' AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL BRUSH TECHNOLOGY BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -#include -#include -#include - -#include "ini.h" - -#if !INI_USE_STACK -#include -#endif - -#define MAX_SECTION 50 -#define MAX_NAME 50 - -/* Strip whitespace chars off end of given string, in place. Return s. */ -static char* rstrip(char* s) -{ - char* p = s + strlen(s); - while (p > s && isspace((unsigned char)(*--p))) - *p = '\0'; - return s; -} - -/* Return pointer to first non-whitespace char in given string. */ -static char* lskip(const char* s) -{ - while (*s && isspace((unsigned char)(*s))) - s++; - return (char*)s; -} - -/* Return pointer to first char c or ';' comment in given string, or pointer to - null at end of string if neither found. ';' must be prefixed by a whitespace - character to register as a comment. */ -static char* find_char_or_comment(const char* s, char c) -{ - int was_whitespace = 0; - while (*s && *s != c && !(was_whitespace && *s == ';')) { - was_whitespace = isspace((unsigned char)(*s)); - s++; - } - return (char*)s; -} - -/* Version of strncpy that ensures dest (size bytes) is null-terminated. */ -static char* strncpy0(char* dest, const char* src, size_t size) -{ - strncpy(dest, src, size); - dest[size - 1] = '\0'; - return dest; -} - -/* See documentation in header file. */ -int ini_parse_file(FILE* file, - int (*handler)(void*, const char*, const char*, - const char*), - void* user) -{ - /* Uses a fair bit of stack (use heap instead if you need to) */ -#if INI_USE_STACK - char line[INI_MAX_LINE]; -#else - char* line; -#endif - char section[MAX_SECTION] = ""; - char prev_name[MAX_NAME] = ""; - - char* start; - char* end; - char* name; - char* value; - int lineno = 0; - int error = 0; - -#if !INI_USE_STACK - line = (char*)malloc(INI_MAX_LINE); - if (!line) { - return -2; - } -#endif - - /* Scan through file line by line */ - while (fgets(line, INI_MAX_LINE, file) != NULL) { - lineno++; - - start = line; -#if INI_ALLOW_BOM - if (lineno == 1 && (unsigned char)start[0] == 0xEF && - (unsigned char)start[1] == 0xBB && - (unsigned char)start[2] == 0xBF) { - start += 3; - } -#endif - start = lskip(rstrip(start)); - - if (*start == ';' || *start == '#') { - /* Per Python ConfigParser, allow '#' comments at start of line */ - } -#if INI_ALLOW_MULTILINE - else if (*prev_name && *start && start > line) { - /* Non-black line with leading whitespace, treat as continuation - of previous name's value (as per Python ConfigParser). */ - if (!handler(user, section, prev_name, start) && !error) - error = lineno; - } -#endif - else if (*start == '[') { - /* A "[section]" line */ - end = find_char_or_comment(start + 1, ']'); - if (*end == ']') { - *end = '\0'; - strncpy0(section, start + 1, sizeof(section)); - *prev_name = '\0'; - } - else if (!error) { - /* No ']' found on section line */ - error = lineno; - } - } - else if (*start && *start != ';') { - /* Not a comment, must be a name[=:]value pair */ - end = find_char_or_comment(start, '='); - if (*end != '=') { - end = find_char_or_comment(start, ':'); - } - if (*end == '=' || *end == ':') { - *end = '\0'; - name = rstrip(start); - value = lskip(end + 1); - end = find_char_or_comment(value, '\0'); - if (*end == ';') - *end = '\0'; - rstrip(value); - - /* Valid name[=:]value pair found, call handler */ - strncpy0(prev_name, name, sizeof(prev_name)); - if (!handler(user, section, name, value) && !error) - error = lineno; - } - else if (!error) { - /* No '=' or ':' found on name[=:]value line */ - error = lineno; - } - } - } - -#if !INI_USE_STACK - free(line); -#endif - - return error; -} - -/* See documentation in header file. */ -int ini_parse(const char* filename, - int (*handler)(void*, const char*, const char*, const char*), - void* user) -{ - FILE* file; - int error; - - file = fopen(filename, "r"); - if (!file) - return -1; - error = ini_parse_file(file, handler, user); - fclose(file); - return error; -} diff -Nru nestopia-1.48/source/unix/ini.h nestopia-1.49/source/unix/ini.h --- nestopia-1.48/source/unix/ini.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/ini.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,96 +0,0 @@ -/* inih -- simple .INI file parser - -Copyright (c) 2009, Brush Technology -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of Brush Technology nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY BRUSH TECHNOLOGY ''AS IS'' AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL BRUSH TECHNOLOGY BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -#ifndef __INI_H__ -#define __INI_H__ - -/* Make this header file easier to include in C++ code */ -#ifdef __cplusplus -extern "C" { -#endif - -#include - -/* Parse given INI-style file. May have [section]s, name=value pairs - (whitespace stripped), and comments starting with ';' (semicolon). Section - is "" if name=value pair parsed before any section heading. name:value - pairs are also supported as a concession to Python's ConfigParser. - - For each name=value pair parsed, call handler function with given user - pointer as well as section, name, and value (data only valid for duration - of handler call). Handler should return nonzero on success, zero on error. - - Returns 0 on success, line number of first error on parse error (doesn't - stop on first error), -1 on file open error, or -2 on memory allocation - error (only when INI_USE_STACK is zero). -*/ -int ini_parse(const char* filename, - int (*handler)(void* user, const char* section, - const char* name, const char* value), - void* user); - -/* Same as ini_parse(), but takes a FILE* instead of filename. This doesn't - close the file when it's finished -- the caller must do that. */ -int ini_parse_file(FILE* file, - int (*handler)(void* user, const char* section, - const char* name, const char* value), - void* user); - -/* Nonzero to allow multi-line value parsing, in the style of Python's - ConfigParser. If allowed, ini_parse() will call the handler with the same - name for each subsequent line parsed. */ -#ifndef INI_ALLOW_MULTILINE -#define INI_ALLOW_MULTILINE 1 -#endif - -/* Nonzero to allow a UTF-8 BOM sequence (0xEF 0xBB 0xBF) at the start of - the file. See http://code.google.com/p/inih/issues/detail?id=21 */ -#ifndef INI_ALLOW_BOM -#define INI_ALLOW_BOM 1 -#endif - -/* Nonzero to use stack, zero to use heap (malloc/free). */ -#ifndef INI_USE_STACK -#define INI_USE_STACK 1 -#endif - -/* Maximum line length for any line in INI file. */ -#ifndef INI_MAX_LINE -#define INI_MAX_LINE 200 -#endif - -#ifndef MATCH -#define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0 -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* __INI_H__ */ diff -Nru nestopia-1.48/source/unix/input.cpp nestopia-1.49/source/unix/input.cpp --- nestopia-1.48/source/unix/input.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/input.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,1123 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include -#include - -#ifdef _GTK -#include "gtkui/gtkui.h" -#include "gtkui/gtkui_config.h" -#endif - -#include "main.h" -#include "config.h" -#include "audio.h" -#include "video.h" -#include "input.h" -#include "ini.h" - -extern settings_t conf; -extern nstpaths_t nstpaths; -extern dimensions_t rendersize; -extern SDL_DisplayMode displaymode; -extern Emulator emulator; -extern bool nst_nsf; - -bool confrunning, kbactivate = false; - -inputsettings_t inputconf; -uiinput_t ui; -gamepad_t player[NUMGAMEPADS]; - -char inputconfpath[256]; - -turbo_t turbostate; -turbo_t turbotoggle; - -SDL_Joystick *joystick; - -static unsigned char nescodes[TOTALBUTTONS] = { - Input::Controllers::Pad::UP, - Input::Controllers::Pad::DOWN, - Input::Controllers::Pad::LEFT, - Input::Controllers::Pad::RIGHT, - Input::Controllers::Pad::SELECT, - Input::Controllers::Pad::START, - Input::Controllers::Pad::A, - Input::Controllers::Pad::B, - Input::Controllers::Pad::A, - Input::Controllers::Pad::B, - Input::Controllers::Pad::UP, - Input::Controllers::Pad::DOWN, - Input::Controllers::Pad::LEFT, - Input::Controllers::Pad::RIGHT, - Input::Controllers::Pad::SELECT, - Input::Controllers::Pad::START, - Input::Controllers::Pad::A, - Input::Controllers::Pad::B, - Input::Controllers::Pad::A, - Input::Controllers::Pad::B -}; - -void input_init() { - // Initialize input - - char controller[32]; - - for (int i = 0; i < NUMGAMEPADS; i++) { - Input(emulator).AutoSelectController(i); - - switch(Input(emulator).GetConnectedController(i)) { - case Input::UNCONNECTED: - snprintf(controller, sizeof(controller), "%s", "Unconnected"); - break; - case Input::PAD1: - case Input::PAD2: - case Input::PAD3: - case Input::PAD4: - snprintf(controller, sizeof(controller), "%s", "Standard Pad"); - break; - case Input::ZAPPER: - snprintf(controller, sizeof(controller), "%s", "Zapper"); - break; - case Input::PADDLE: - snprintf(controller, sizeof(controller), "%s", "Arkanoid Paddle"); - break; - case Input::POWERPAD: - snprintf(controller, sizeof(controller), "%s", "Power Pad"); - break; - case Input::POWERGLOVE: - snprintf(controller, sizeof(controller), "%s", "Power Glove"); - break; - case Input::MOUSE: - snprintf(controller, sizeof(controller), "%s", "Mouse"); - break; - case Input::ROB: - snprintf(controller, sizeof(controller), "%s", "R.O.B."); - break; - case Input::FAMILYTRAINER: - snprintf(controller, sizeof(controller), "%s", "Family Trainer"); - break; - case Input::FAMILYKEYBOARD: - snprintf(controller, sizeof(controller), "%s", "Family Keyboard"); - break; - case Input::SUBORKEYBOARD: - snprintf(controller, sizeof(controller), "%s", "Subor Keyboard"); - break; - case Input::DOREMIKKOKEYBOARD: - snprintf(controller, sizeof(controller), "%s", "Doremikko Keyboard"); - break; - case Input::HORITRACK: - snprintf(controller, sizeof(controller), "%s", "Hori Track"); - break; - case Input::PACHINKO: - snprintf(controller, sizeof(controller), "%s", "Pachinko"); - break; - case Input::OEKAKIDSTABLET: - snprintf(controller, sizeof(controller), "%s", "Oeka Kids Tablet"); - break; - case Input::KONAMIHYPERSHOT: - snprintf(controller, sizeof(controller), "%s", "Konami Hypershot"); - break; - case Input::BANDAIHYPERSHOT: - snprintf(controller, sizeof(controller), "%s", "Bandai Hypershot"); - break; - case Input::CRAZYCLIMBER: - snprintf(controller, sizeof(controller), "%s", "Crazy Climber"); - break; - case Input::MAHJONG: - snprintf(controller, sizeof(controller), "%s", "Mahjong"); - break; - case Input::EXCITINGBOXING: - snprintf(controller, sizeof(controller), "%s", "Exciting Boxing"); - break; - case Input::TOPRIDER: - snprintf(controller, sizeof(controller), "%s", "Top Rider"); - break; - case Input::POKKUNMOGURAA: - snprintf(controller, sizeof(controller), "%s", "Pokkun Moguraa"); - break; - case Input::PARTYTAP: - snprintf(controller, sizeof(controller), "%s", "PartyTap"); - break; - case Input::TURBOFILE: - snprintf(controller, sizeof(controller), "%s", "Turbo File"); - break; - case Input::BARCODEWORLD: - snprintf(controller, sizeof(controller), "%s", "Barcode World"); - break; - default: - snprintf(controller, sizeof(controller), "%s", "Unknown"); - break; - } - - fprintf(stderr, "Port %d: %s\n", i + 1, controller); - } - - video_set_cursor(); -} - -void input_joysticks_detect() { - // Initialize any joysticks - printf("%i joystick(s) found:\n", SDL_NumJoysticks()); - - int i; - - for (i = 0; i < SDL_NumJoysticks(); i++) { - joystick = SDL_JoystickOpen(i); - printf("%s\n", SDL_JoystickName(joystick)); - } - - SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); - - turbostate.p1a = turbotoggle.p1a = 0; - turbostate.p1b = turbotoggle.p1b = 0; - turbostate.p2a = turbotoggle.p2a = 0; - turbostate.p2b = turbotoggle.p2b = 0; -} - -void input_joysticks_close() { - // Deinitialize any joysticks - SDL_JoystickClose(joystick); -} - -void input_process(Input::Controllers *controllers, SDL_Event event) { - // Process input events - - // Match keyboard and joystick input - switch(event.type) { - case SDL_KEYUP: - case SDL_KEYDOWN: - input_match_keyboard(controllers, event); - break; - - case SDL_JOYBUTTONUP: - case SDL_JOYBUTTONDOWN: - case SDL_JOYAXISMOTION: - case SDL_JOYHATMOTION: - input_match_joystick(controllers, event); - break; - - case SDL_MOUSEBUTTONUP: - case SDL_MOUSEBUTTONDOWN: - input_match_mouse(controllers, event); - break; - - default: break; - } -} - -void input_pulse_turbo(Input::Controllers *controllers) { - // Pulse the turbo buttons if they're pressed - if (turbostate.p1a) { - turbotoggle.p1a++; - if (turbotoggle.p1a >= conf.timing_turbopulse) { - turbotoggle.p1a = 0; - controllers->pad[0].buttons &= ~Input::Controllers::Pad::A; - } - else { controllers->pad[0].buttons |= Input::Controllers::Pad::A; } - } - - if (turbostate.p1b) { - turbotoggle.p1b++; - if (turbotoggle.p1b >= conf.timing_turbopulse) { - turbotoggle.p1b = 0; - controllers->pad[0].buttons &= ~Input::Controllers::Pad::B; - } - else { controllers->pad[0].buttons |= Input::Controllers::Pad::B; } - } - - if (turbostate.p2a) { - turbotoggle.p2a++; - if (turbotoggle.p2a >= conf.timing_turbopulse) { - turbotoggle.p2a = 0; - controllers->pad[1].buttons &= ~Input::Controllers::Pad::A; - } - else { controllers->pad[1].buttons |= Input::Controllers::Pad::A; } - } - - if (turbostate.p2b) { - turbotoggle.p2b++; - if (turbotoggle.p2b >= conf.timing_turbopulse) { - turbotoggle.p2b = 0; - controllers->pad[1].buttons &= ~Input::Controllers::Pad::B; - } - else { controllers->pad[1].buttons |= Input::Controllers::Pad::B; } - } -} - -void input_inject(Input::Controllers *controllers, nesinput_t input) { - // Insert the input signal into the NES - if (input.pressed) { - controllers->pad[input.player].buttons |= input.nescode; - - if (input.turboa) { input.player == 0 ? turbostate.p1a = true : turbostate.p2a = true; } - if (input.turbob) { input.player == 0 ? turbostate.p1b = true : turbostate.p2b = true; } - } - else { - controllers->pad[input.player].buttons &= ~input.nescode; - - if (input.turboa) { input.player == 0 ? turbostate.p1a = false : turbostate.p2a = false; } - if (input.turbob) { input.player == 0 ? turbostate.p1b = false : turbostate.p2b = false; } - } -} - -void input_match_joystick(Input::Controllers *controllers, SDL_Event event) { - // Match NES buttons to joystick input - int j; - - nesinput_t input, reverseinput; - - input.nescode = 0x00; - input.player = 0; - input.pressed = 0; - input.turboa = 0; - input.turbob = 0; - - // This is for releasing opposing directions - reverseinput.nescode = 0x00; - reverseinput.player = 0; - reverseinput.pressed = 0; - - SDL_Event buttons[TOTALBUTTONS] = { - player[0].ju, player[0].jd, player[0].jl, player[0].jr, - player[0].jselect, player[0].jstart, player[0].ja, player[0].jb, - player[0].jta, player[0].jtb, - - player[1].ju, player[1].jd, player[1].jl, player[1].jr, - player[1].jselect, player[1].jstart, player[1].ja, player[1].jb, - player[1].jta, player[1].jtb - }; - - switch(event.type) { - // Handle button input - case SDL_JOYBUTTONUP: - case SDL_JOYBUTTONDOWN: - for (j = 0; j < TOTALBUTTONS; j++) { - if (buttons[j].jbutton.button == event.jbutton.button - && buttons[j].jbutton.which == event.jbutton.which) { - input.nescode = nescodes[j]; - if (j >= NUMBUTTONS) { input.player = 1; } - // This is really dirty - if (j == 8 || j == 18) { input.turboa = 1; } - if (j == 9 || j == 19) { input.turbob = 1; } - } - } - input.pressed = event.jbutton.state; - break; - - // Handling hat input can be a lot of fun if you like pain - case SDL_JOYHATMOTION: - unsigned char hu, hd, hl, hr; - hu = hd = hl = hr = 0; - - // Start a loop to check if input matches - for (j = 0; j < TOTALBUTTONS; j++) { - - // Read value of each hat direction on current hat - if (buttons[j].type == event.type - && buttons[j].jhat.which == event.jhat.which - && buttons[j].jhat.hat == event.jhat.hat) { - if (j >= NUMBUTTONS) { input.player = reverseinput.player = 1; } - - // Find the values at each hat position on the current hat - if (buttons[j].jhat.value == SDL_HAT_UP) { hu = nescodes[j]; } - else if (buttons[j].jhat.value == SDL_HAT_DOWN) { hd = nescodes[j]; } - else if (buttons[j].jhat.value == SDL_HAT_LEFT) { hl = nescodes[j]; } - else if (buttons[j].jhat.value == SDL_HAT_RIGHT) { hr = nescodes[j]; } - - input.pressed = 1; - - // Make sure opposing hat positions are turned off - switch(event.jhat.value) { - case SDL_HAT_UP: - input.nescode |= hu; - reverseinput.nescode |= hd |= hl |= hr; - break; - case SDL_HAT_LEFTUP: - input.nescode |= hu |= hl; - reverseinput.nescode |= hd |= hr; - break; - case SDL_HAT_RIGHTUP: - input.nescode |= hu |= hr; - reverseinput.nescode |= hd |= hl; - break; - case SDL_HAT_DOWN: - input.nescode |= hd; - reverseinput.nescode |= hu |= hl |= hr; - break; - case SDL_HAT_LEFTDOWN: - input.nescode |= hd |= hl; - reverseinput.nescode |= hu |= hr; - break; - case SDL_HAT_RIGHTDOWN: - input.nescode |= hd |= hr; - reverseinput.nescode |= hu |= hl; - break; - case SDL_HAT_LEFT: - input.nescode |= hl; - reverseinput.nescode |= hr |= hu |= hd; - break; - case SDL_HAT_RIGHT: - input.nescode |= hr; - reverseinput.nescode |= hl |= hu |= hd; - break; - default: - input.nescode |= hu |= hd |= hl |= hr; - break; - } - } - } - break; - - // Handle axis input - case SDL_JOYAXISMOTION: - for (j = 0; j < TOTALBUTTONS; j++) { - - int nvalue = input_checksign(event.jaxis.value); - - if (buttons[j].jaxis.axis == event.jaxis.axis - && buttons[j].jaxis.which == event.jaxis.which - && buttons[j].jaxis.type == event.jaxis.type - && buttons[j].jaxis.value == nvalue) { - - if (j >= NUMBUTTONS) { input.player = reverseinput.player = 1; } - - input.nescode = nescodes[j]; - } - - if (buttons[j].jaxis.axis == event.jaxis.axis - && buttons[j].jaxis.which == event.jaxis.which - && buttons[j].jaxis.type == event.jaxis.type - && buttons[j].jaxis.value == !nvalue) { - - reverseinput.nescode = nescodes[j]; - } - - if (abs(event.jaxis.value) > DEADZONE) { input.pressed = 1; } - } - break; - - default: break; - } - - input_inject(controllers, reverseinput); - input_inject(controllers, input); -} - -void input_match_keyboard(Input::Controllers *controllers, SDL_Event event) { - // Match NES buttons to keyboard buttons - - nesinput_t input; - - input.nescode = 0x00; - input.player = 0; - input.pressed = 0; - input.turboa = 0; - input.turbob = 0; - - if (event.type == SDL_KEYDOWN) { input.pressed = 1; } - - for (int i = 0; i < NUMGAMEPADS; i++) { - if (player[i].u == event.key.keysym.scancode) { - input.nescode = Input::Controllers::Pad::UP; - input.player = i; - } - else if (player[i].d == event.key.keysym.scancode) { - input.nescode = Input::Controllers::Pad::DOWN; - input.player = i; - } - else if (player[i].l == event.key.keysym.scancode) { - input.nescode = Input::Controllers::Pad::LEFT; - input.player = i; - } - else if (player[i].r == event.key.keysym.scancode) { - input.nescode = Input::Controllers::Pad::RIGHT; - input.player = i; - } - else if (player[i].select == event.key.keysym.scancode) { - input.nescode = Input::Controllers::Pad::SELECT; - input.player = i; - } - else if (player[i].start == event.key.keysym.scancode) { - input.nescode = Input::Controllers::Pad::START; - input.player = i; - } - else if (player[i].a == event.key.keysym.scancode) { - input.nescode = Input::Controllers::Pad::A; - input.player = i; - } - else if (player[i].b == event.key.keysym.scancode) { - input.nescode = Input::Controllers::Pad::B; - input.player = i; - } - else if (player[i].ta == event.key.keysym.scancode) { - input.nescode = Input::Controllers::Pad::A; - input.player = i; - input.turboa = 1; - } - else if (player[i].tb == event.key.keysym.scancode) { - input.nescode = Input::Controllers::Pad::B; - input.player = i; - input.turbob = 1; - } - } - - input_inject(controllers, input); - - if (event.key.keysym.scancode == ui.altspeed && event.type == SDL_KEYDOWN) { timing_set_altspeed(); } - if (event.key.keysym.scancode == ui.altspeed && event.type == SDL_KEYUP) { timing_set_default(); } - - const Uint8 *keys = SDL_GetKeyboardState(NULL); - - // Insert Coins - controllers->vsSystem.insertCoin = 0; - if (keys[ui.insertcoin1]) { controllers->vsSystem.insertCoin |= Input::Controllers::VsSystem::COIN_1; } - if (keys[ui.insertcoin2]) { controllers->vsSystem.insertCoin |= Input::Controllers::VsSystem::COIN_2; } - - // Process non-game events - if (keys[ui.fdsflip]) { nst_flip_disk(); } - if (keys[ui.fdsswitch]) { nst_switch_disk(); } - if (keys[ui.qsave1]) { nst_state_quicksave(0); } - if (keys[ui.qsave2]) { nst_state_quicksave(1); } - if (keys[ui.qload1]) { nst_state_quickload(0); } - if (keys[ui.qload2]) { nst_state_quickload(1); } - - // Screenshot - if (keys[ui.screenshot]) { video_screenshot(NULL); } - - // Reset - if (keys[ui.reset]) { nst_reset(0); } - - // Rewinder - if (keys[ui.rwstart]) { nst_set_rewind(0); } - if (keys[ui.rwstop]) { nst_set_rewind(1); } - - // Video - if (event.key.keysym.scancode == ui.fullscreen && event.type == SDL_KEYUP) { video_toggle_fullscreen(); } - if (keys[ui.filter]) { video_toggle_filter(); } - if (keys[ui.scalefactor]) { video_toggle_scalefactor(); } - - // NSF - if (nst_nsf) { - Nsf nsf(emulator); - - if (keys[SDL_SCANCODE_UP]) { - nsf.PlaySong(); - video_clear_buffer(); - video_disp_nsf(); - } - if (keys[SDL_SCANCODE_DOWN]) { - //nsf.StopSong(); - } - if (keys[SDL_SCANCODE_LEFT]) { - nsf.SelectPrevSong(); - video_clear_buffer(); - video_disp_nsf(); - } - if (keys[SDL_SCANCODE_RIGHT]) { - nsf.SelectNextSong(); - video_clear_buffer(); - video_disp_nsf(); - } - } - - // Escape exits when not in GUI mode - if (keys[SDL_SCANCODE_ESCAPE]) { - if (conf.misc_disable_gui) { nst_schedule_quit(); } - } -} - -void input_match_mouse(Input::Controllers *controllers, SDL_Event event) { - // Match mouse input to NES input - int x, y; - double xaspect; - double yaspect; - #ifdef _GTK - if (conf.misc_disable_gui) { SDL_GetMouseState(&x, &y); } - else { - x = event.button.x; - y = event.button.y; - } - #else - SDL_GetMouseState(&x, &y); - #endif - - switch(event.type) { - case SDL_MOUSEBUTTONUP: - controllers->zapper.fire = false; - break; - - case SDL_MOUSEBUTTONDOWN: - // Get X coords - if (conf.video_filter == 1) { // NTSC - xaspect = (double)(Video::Output::WIDTH) / (double)(Video::Output::NTSC_WIDTH / 2); - } - else if (conf.video_tv_aspect) { - xaspect = (double)(Video::Output::WIDTH) / (double)(TV_WIDTH); - } - else { xaspect = 1.0; } - - // Calculate fullscreen X coords - if (conf.video_fullscreen) { - if (conf.video_stretch_aspect) { - xaspect = (double)(conf.video_scale_factor * Video::Output::WIDTH) / (double)(displaymode.w); - } - else { - // Remove the same amount of pixels as the black area to the left of the screen - x -= displaymode.w / 2.0f - rendersize.w / 2.0f; - xaspect = (double)(conf.video_scale_factor * Video::Output::WIDTH) / (double)(rendersize.w); - } - } - controllers->zapper.x = (int)(x * xaspect) / conf.video_scale_factor; - - // Get Y coords - if (conf.video_unmask_overscan) { - controllers->zapper.y = y / conf.video_scale_factor; - } - else { - controllers->zapper.y = (y + OVERSCAN_TOP * conf.video_scale_factor) / conf.video_scale_factor; - } - - // Calculate fullscreen Y coords - if (conf.video_fullscreen) { - yaspect = (double)(conf.video_scale_factor * Video::Output::HEIGHT) / (double)(displaymode.h); - controllers->zapper.y = (y * yaspect) / conf.video_scale_factor; - } - - // Offscreen - if(event.button.button != SDL_BUTTON_LEFT) { controllers->zapper.x = ~1U; } - - controllers->zapper.fire = true; - break; - - default: break; - } -} - -char* input_translate_event(SDL_Event event) { - // Translate an SDL_Event to an inputcode - static char inputcode[6]; - - switch(event.type) { - case SDL_JOYAXISMOTION: - sprintf(inputcode, "j%da%d%d", event.jaxis.which, event.jaxis.axis, input_checksign(event.jaxis.value)); - break; - - case SDL_JOYHATMOTION: - sprintf(inputcode, "j%dh%d%d", event.jhat.which, event.jhat.hat, event.jhat.value); - break; - - case SDL_JOYBUTTONUP: - case SDL_JOYBUTTONDOWN: - sprintf(inputcode, "j%db%d", event.jbutton.which, event.jbutton.button); - break; - } - return inputcode; -} - -SDL_Event input_translate_string(const char *string) { - // Translate an inputcode to an SDL_Event - SDL_Event event; - - int type, which, axis, value; - - if ((unsigned char)string[2] == 0x61) { // Axis - which = string[1] - '0'; - axis = string[3] - '0'; - value = string[4] - '0'; - event.type = SDL_JOYAXISMOTION; - event.jaxis.which = which; - event.jaxis.axis = axis; - event.jaxis.value = value; - } - else if ((unsigned char)string[2] == 0x62) { // Button - which = string[1] - '0'; - value = string[3] - '0'; - if (string[4]) { - value = ((string[3] - '0') * 10) + (string[4] - '0'); - } - event.type = SDL_JOYBUTTONDOWN; - event.jbutton.which = which; - event.jbutton.button = value; - - } - else if ((unsigned char)string[2] == 0x68) { // Hat - which = string[1] - '0'; - axis = string[3] - '0'; - value = string[4] - '0'; - event.type = SDL_JOYHATMOTION; - event.jhat.which = which; - event.jhat.hat = axis; - event.jhat.value = value; - } - else { - fprintf(stderr, "Malformed inputcode: %s\n", string); - } - - return event; -} - -int input_checksign(int axisvalue) { - - if (axisvalue <= 0) { return 0; } - else { return 1; } -} - -void input_config_read() { - // Read the input config file - snprintf(inputconfpath, sizeof(inputconfpath), "%sinput.conf", nstpaths.nstdir); - - if (ini_parse(inputconfpath, input_config_match, &inputconf) < 0) { - fprintf(stderr, "Failed to load input config file %s: Using defaults.\n", inputconfpath); - } - else { - // Map the input settings from the config file - - // User Interface - ui.qsave1 = SDL_GetScancodeFromName(inputconf.qsave1); - ui.qsave2 = SDL_GetScancodeFromName(inputconf.qsave2); - ui.qload1 = SDL_GetScancodeFromName(inputconf.qload1); - ui.qload2 = SDL_GetScancodeFromName(inputconf.qload2); - - ui.screenshot = SDL_GetScancodeFromName(inputconf.screenshot); - - ui.fdsflip = SDL_GetScancodeFromName(inputconf.fdsflip); - ui.fdsswitch = SDL_GetScancodeFromName(inputconf.fdsswitch); - - ui.insertcoin1 = SDL_GetScancodeFromName(inputconf.insertcoin1); - ui.insertcoin2 = SDL_GetScancodeFromName(inputconf.insertcoin2); - - ui.reset = SDL_GetScancodeFromName(inputconf.reset); - - ui.altspeed = SDL_GetScancodeFromName(inputconf.altspeed); - ui.rwstart = SDL_GetScancodeFromName(inputconf.rwstart); - ui.rwstop = SDL_GetScancodeFromName(inputconf.rwstop); - - ui.fullscreen = SDL_GetScancodeFromName(inputconf.fullscreen); - ui.filter = SDL_GetScancodeFromName(inputconf.filter); - ui.scalefactor = SDL_GetScancodeFromName(inputconf.scalefactor); - - // Player 1 - player[0].u = SDL_GetScancodeFromName(inputconf.kb_p1u); - player[0].d = SDL_GetScancodeFromName(inputconf.kb_p1d); - player[0].l = SDL_GetScancodeFromName(inputconf.kb_p1l); - player[0].r = SDL_GetScancodeFromName(inputconf.kb_p1r); - player[0].select = SDL_GetScancodeFromName(inputconf.kb_p1select); - player[0].start = SDL_GetScancodeFromName(inputconf.kb_p1start); - player[0].a = SDL_GetScancodeFromName(inputconf.kb_p1a); - player[0].b = SDL_GetScancodeFromName(inputconf.kb_p1b); - player[0].ta = SDL_GetScancodeFromName(inputconf.kb_p1ta); - player[0].tb = SDL_GetScancodeFromName(inputconf.kb_p1tb); - - player[0].ju = input_translate_string(inputconf.js_p1u); - player[0].jd = input_translate_string(inputconf.js_p1d); - player[0].jl = input_translate_string(inputconf.js_p1l); - player[0].jr = input_translate_string(inputconf.js_p1r); - player[0].jselect = input_translate_string(inputconf.js_p1select); - player[0].jstart = input_translate_string(inputconf.js_p1start); - player[0].ja = input_translate_string(inputconf.js_p1a); - player[0].jb = input_translate_string(inputconf.js_p1b); - player[0].jta = input_translate_string(inputconf.js_p1ta); - player[0].jtb = input_translate_string(inputconf.js_p1tb); - - // Player 2 - player[1].u = SDL_GetScancodeFromName(inputconf.kb_p2u); - player[1].d = SDL_GetScancodeFromName(inputconf.kb_p2d); - player[1].l = SDL_GetScancodeFromName(inputconf.kb_p2l); - player[1].r = SDL_GetScancodeFromName(inputconf.kb_p2r); - player[1].select = SDL_GetScancodeFromName(inputconf.kb_p2select); - player[1].start = SDL_GetScancodeFromName(inputconf.kb_p2start); - player[1].a = SDL_GetScancodeFromName(inputconf.kb_p2a); - player[1].b = SDL_GetScancodeFromName(inputconf.kb_p2b); - player[1].ta = SDL_GetScancodeFromName(inputconf.kb_p2ta); - player[1].tb = SDL_GetScancodeFromName(inputconf.kb_p2tb); - - player[1].ju = input_translate_string(inputconf.js_p2u); - player[1].jd = input_translate_string(inputconf.js_p2d); - player[1].jl = input_translate_string(inputconf.js_p2l); - player[1].jr = input_translate_string(inputconf.js_p2r); - player[1].jselect = input_translate_string(inputconf.js_p2select); - player[1].jstart = input_translate_string(inputconf.js_p2start); - player[1].ja = input_translate_string(inputconf.js_p2a); - player[1].jb = input_translate_string(inputconf.js_p2b); - player[1].jta = input_translate_string(inputconf.js_p2ta); - player[1].jtb = input_translate_string(inputconf.js_p2tb); - } -} - -void input_config_write() { - // Write out the input configuration file - - FILE *fp = fopen(inputconfpath, "w"); - if (fp != NULL) { - fprintf(fp, "; Nestopia UE Input Configuration File\n\n"); - fprintf(fp, "; Possible values for keyboard input are in the Key Name column:\n; https://wiki.libsdl.org/SDL_Scancode\n\n"); - fprintf(fp, "; Possible values for joystick input:\n; j[joystick number][a|b|h][button/hat/axis number][1/0 = +/- (axes only)]\n"); - fprintf(fp, "; Example: j0b3 = joystick 0, button 3. j1a11 = joystick 1, axis 1 +\n\n"); - - fprintf(fp, "[ui]\n"); - fprintf(fp, "qsave1=%s\n", SDL_GetScancodeName(ui.qsave1)); - fprintf(fp, "qsave2=%s\n", SDL_GetScancodeName(ui.qsave2)); - fprintf(fp, "qload1=%s\n", SDL_GetScancodeName(ui.qload1)); - fprintf(fp, "qload2=%s\n", SDL_GetScancodeName(ui.qload2)); - - fprintf(fp, "screenshot=%s\n", SDL_GetScancodeName(ui.screenshot)); - - fprintf(fp, "fdsflip=%s\n", SDL_GetScancodeName(ui.fdsflip)); - fprintf(fp, "fdsswitch=%s\n", SDL_GetScancodeName(ui.fdsswitch)); - - fprintf(fp, "insertcoin1=%s\n", SDL_GetScancodeName(ui.insertcoin1)); - fprintf(fp, "insertcoin2=%s\n", SDL_GetScancodeName(ui.insertcoin2)); - - fprintf(fp, "reset=%s\n", SDL_GetScancodeName(ui.reset)); - - fprintf(fp, "altspeed=%s\n", SDL_GetScancodeName(ui.altspeed)); - fprintf(fp, "rwstart=%s\n", SDL_GetScancodeName(ui.rwstart)); - fprintf(fp, "rwstop=%s\n", SDL_GetScancodeName(ui.rwstop)); - - fprintf(fp, "fullscreen=%s\n", SDL_GetScancodeName(ui.fullscreen)); - fprintf(fp, "filter=%s\n", SDL_GetScancodeName(ui.filter)); - fprintf(fp, "scalefactor=%s\n", SDL_GetScancodeName(ui.scalefactor)); - fprintf(fp, "\n"); // End of Section - - fprintf(fp, "[gamepad1]\n"); - fprintf(fp, "kb_u=%s\n", SDL_GetScancodeName(player[0].u)); - fprintf(fp, "kb_d=%s\n", SDL_GetScancodeName(player[0].d)); - fprintf(fp, "kb_l=%s\n", SDL_GetScancodeName(player[0].l)); - fprintf(fp, "kb_r=%s\n", SDL_GetScancodeName(player[0].r)); - fprintf(fp, "kb_select=%s\n", SDL_GetScancodeName(player[0].select)); - fprintf(fp, "kb_start=%s\n", SDL_GetScancodeName(player[0].start)); - fprintf(fp, "kb_a=%s\n", SDL_GetScancodeName(player[0].a)); - fprintf(fp, "kb_b=%s\n", SDL_GetScancodeName(player[0].b)); - fprintf(fp, "kb_ta=%s\n", SDL_GetScancodeName(player[0].ta)); - fprintf(fp, "kb_tb=%s\n", SDL_GetScancodeName(player[0].tb)); - - fprintf(fp, "js_u=%s\n", input_translate_event(player[0].ju)); - fprintf(fp, "js_d=%s\n", input_translate_event(player[0].jd)); - fprintf(fp, "js_l=%s\n", input_translate_event(player[0].jl)); - fprintf(fp, "js_r=%s\n", input_translate_event(player[0].jr)); - fprintf(fp, "js_select=%s\n", input_translate_event(player[0].jselect)); - fprintf(fp, "js_start=%s\n", input_translate_event(player[0].jstart)); - fprintf(fp, "js_a=%s\n", input_translate_event(player[0].ja)); - fprintf(fp, "js_b=%s\n", input_translate_event(player[0].jb)); - fprintf(fp, "js_ta=%s\n", input_translate_event(player[0].jta)); - fprintf(fp, "js_tb=%s\n", input_translate_event(player[0].jtb)); - fprintf(fp, "\n"); // End of Section - - fprintf(fp, "[gamepad2]\n"); - fprintf(fp, "kb_u=%s\n", SDL_GetScancodeName(player[1].u)); - fprintf(fp, "kb_d=%s\n", SDL_GetScancodeName(player[1].d)); - fprintf(fp, "kb_l=%s\n", SDL_GetScancodeName(player[1].l)); - fprintf(fp, "kb_r=%s\n", SDL_GetScancodeName(player[1].r)); - fprintf(fp, "kb_select=%s\n", SDL_GetScancodeName(player[1].select)); - fprintf(fp, "kb_start=%s\n", SDL_GetScancodeName(player[1].start)); - fprintf(fp, "kb_a=%s\n", SDL_GetScancodeName(player[1].a)); - fprintf(fp, "kb_b=%s\n", SDL_GetScancodeName(player[1].b)); - fprintf(fp, "kb_ta=%s\n", SDL_GetScancodeName(player[1].ta)); - fprintf(fp, "kb_tb=%s\n", SDL_GetScancodeName(player[1].tb)); - - fprintf(fp, "js_u=%s\n", input_translate_event(player[1].ju)); - fprintf(fp, "js_d=%s\n", input_translate_event(player[1].jd)); - fprintf(fp, "js_l=%s\n", input_translate_event(player[1].jl)); - fprintf(fp, "js_r=%s\n", input_translate_event(player[1].jr)); - fprintf(fp, "js_select=%s\n", input_translate_event(player[1].jselect)); - fprintf(fp, "js_start=%s\n", input_translate_event(player[1].jstart)); - fprintf(fp, "js_a=%s\n", input_translate_event(player[1].ja)); - fprintf(fp, "js_b=%s\n", input_translate_event(player[1].jb)); - fprintf(fp, "js_ta=%s\n", input_translate_event(player[1].jta)); - fprintf(fp, "js_tb=%s\n", input_translate_event(player[1].jtb)); - fprintf(fp, "\n"); // End of Section - - fclose(fp); - } -} - -void input_set_default() { - // Set default input config - - ui.qsave1 = SDL_GetScancodeFromName("F5"); - ui.qsave2 = SDL_GetScancodeFromName("F6"); - ui.qload1 = SDL_GetScancodeFromName("F7"); - ui.qload2 = SDL_GetScancodeFromName("F8"); - - ui.screenshot = SDL_GetScancodeFromName("F9"); - - ui.fdsflip = SDL_GetScancodeFromName("F3"); - ui.fdsswitch = SDL_GetScancodeFromName("F4"); - - ui.insertcoin1 = SDL_GetScancodeFromName("F1"); - ui.insertcoin2 = SDL_GetScancodeFromName("F2"); - - ui.reset = SDL_GetScancodeFromName("F12"); - - ui.altspeed = SDL_GetScancodeFromName("`"); - ui.rwstart = SDL_GetScancodeFromName("Backspace"); - ui.rwstop = SDL_GetScancodeFromName("\\"); - - ui.fullscreen = SDL_GetScancodeFromName("F"); - ui.filter = SDL_GetScancodeFromName("T"); - ui.scalefactor = SDL_GetScancodeFromName("G"); - - player[0].u = SDL_GetScancodeFromName("Up"); - player[0].d = SDL_GetScancodeFromName("Down"); - player[0].l = SDL_GetScancodeFromName("Left"); - player[0].r = SDL_GetScancodeFromName("Right"); - player[0].select = SDL_GetScancodeFromName("Right Shift"); - player[0].start = SDL_GetScancodeFromName("Return"); - player[0].a = SDL_GetScancodeFromName("Z"); - player[0].b = SDL_GetScancodeFromName("A"); - player[0].ta = SDL_GetScancodeFromName("X"); - player[0].tb = SDL_GetScancodeFromName("S"); - - player[0].ju = input_translate_string("j0h01"); - player[0].jd = input_translate_string("j0h04"); - player[0].jl = input_translate_string("j0h08"); - player[0].jr = input_translate_string("j0h02"); - player[0].jselect = input_translate_string("j0b8"); - player[0].jstart = input_translate_string("j0b9"); - player[0].ja = input_translate_string("j0b1"); - player[0].jb = input_translate_string("j0b0"); - player[0].jta = input_translate_string("j0b2"); - player[0].jtb = input_translate_string("j0b3"); - - player[1].u = SDL_GetScancodeFromName("I"); - player[1].d = SDL_GetScancodeFromName("K"); - player[1].l = SDL_GetScancodeFromName("J"); - player[1].r = SDL_GetScancodeFromName("L"); - player[1].select = SDL_GetScancodeFromName("Left Shift"); - player[1].start = SDL_GetScancodeFromName("Left Ctrl"); - player[1].a = SDL_GetScancodeFromName("M"); - player[1].b = SDL_GetScancodeFromName("N"); - player[1].ta = SDL_GetScancodeFromName("B"); - player[1].tb = SDL_GetScancodeFromName("V"); - - player[1].ju = input_translate_string("j1h01"); - player[1].jd = input_translate_string("j1h04"); - player[1].jl = input_translate_string("j1h08"); - player[1].jr = input_translate_string("j1h02"); - player[1].jselect = input_translate_string("j1b8"); - player[1].jstart = input_translate_string("j1b9"); - player[1].ja = input_translate_string("j1b1"); - player[1].jb = input_translate_string("j1b0"); - player[1].jta = input_translate_string("j1b2"); - player[1].jtb = input_translate_string("j1b3"); -} - -static int input_config_match(void* user, const char* section, const char* name, const char* value) { - // Match values from input config file and populate live config - inputsettings_t* pconfig = (inputsettings_t*)user; - - // User Interface - if (MATCH("ui", "qsave1")) { pconfig->qsave1 = strdup(value); } - else if (MATCH("ui", "qsave2")) { pconfig->qsave2 = strdup(value); } - else if (MATCH("ui", "qload1")) { pconfig->qload1 = strdup(value); } - else if (MATCH("ui", "qload2")) { pconfig->qload2 = strdup(value); } - - else if (MATCH("ui", "screenshot")) { pconfig->screenshot = strdup(value); } - - else if (MATCH("ui", "fdsflip")) { pconfig->fdsflip = strdup(value); } - else if (MATCH("ui", "fdsswitch")) { pconfig->fdsswitch = strdup(value); } - - else if (MATCH("ui", "insertcoin1")) { pconfig->insertcoin1 = strdup(value); } - else if (MATCH("ui", "insertcoin2")) { pconfig->insertcoin2 = strdup(value); } - - else if (MATCH("ui", "reset")) { pconfig->reset = strdup(value); } - - else if (MATCH("ui", "altspeed")) { pconfig->altspeed = strdup(value); } - else if (MATCH("ui", "rwstart")) { pconfig->rwstart = strdup(value); } - else if (MATCH("ui", "rwstop")) { pconfig->rwstop = strdup(value); } - - else if (MATCH("ui", "fullscreen")) { pconfig->fullscreen = strdup(value); } - else if (MATCH("ui", "filter")) { pconfig->filter = strdup(value); } - else if (MATCH("ui", "scalefactor")) { pconfig->scalefactor = strdup(value); } - - // Player 1 - else if (MATCH("gamepad1", "kb_u")) { pconfig->kb_p1u = strdup(value); } - else if (MATCH("gamepad1", "kb_d")) { pconfig->kb_p1d = strdup(value); } - else if (MATCH("gamepad1", "kb_l")) { pconfig->kb_p1l = strdup(value); } - else if (MATCH("gamepad1", "kb_r")) { pconfig->kb_p1r = strdup(value); } - else if (MATCH("gamepad1", "kb_select")) { pconfig->kb_p1select = strdup(value); } - else if (MATCH("gamepad1", "kb_start")) { pconfig->kb_p1start = strdup(value); } - else if (MATCH("gamepad1", "kb_a")) { pconfig->kb_p1a = strdup(value); } - else if (MATCH("gamepad1", "kb_b")) { pconfig->kb_p1b = strdup(value); } - else if (MATCH("gamepad1", "kb_ta")) { pconfig->kb_p1ta = strdup(value); } - else if (MATCH("gamepad1", "kb_tb")) { pconfig->kb_p1tb = strdup(value); } - - else if (MATCH("gamepad1", "js_u")) { pconfig->js_p1u = strdup(value); } - else if (MATCH("gamepad1", "js_d")) { pconfig->js_p1d = strdup(value); } - else if (MATCH("gamepad1", "js_l")) { pconfig->js_p1l = strdup(value); } - else if (MATCH("gamepad1", "js_r")) { pconfig->js_p1r = strdup(value); } - else if (MATCH("gamepad1", "js_select")) { pconfig->js_p1select = strdup(value); } - else if (MATCH("gamepad1", "js_start")) { pconfig->js_p1start = strdup(value); } - else if (MATCH("gamepad1", "js_a")) { pconfig->js_p1a = strdup(value); } - else if (MATCH("gamepad1", "js_b")) { pconfig->js_p1b = strdup(value); } - else if (MATCH("gamepad1", "js_ta")) { pconfig->js_p1ta = strdup(value); } - else if (MATCH("gamepad1", "js_tb")) { pconfig->js_p1tb = strdup(value); } - - // Player 2 - else if (MATCH("gamepad2", "kb_u")) { pconfig->kb_p2u = strdup(value); } - else if (MATCH("gamepad2", "kb_d")) { pconfig->kb_p2d = strdup(value); } - else if (MATCH("gamepad2", "kb_l")) { pconfig->kb_p2l = strdup(value); } - else if (MATCH("gamepad2", "kb_r")) { pconfig->kb_p2r = strdup(value); } - else if (MATCH("gamepad2", "kb_select")) { pconfig->kb_p2select = strdup(value); } - else if (MATCH("gamepad2", "kb_start")) { pconfig->kb_p2start = strdup(value); } - else if (MATCH("gamepad2", "kb_a")) { pconfig->kb_p2a = strdup(value); } - else if (MATCH("gamepad2", "kb_b")) { pconfig->kb_p2b = strdup(value); } - else if (MATCH("gamepad2", "kb_ta")) { pconfig->kb_p2ta = strdup(value); } - else if (MATCH("gamepad2", "kb_tb")) { pconfig->kb_p2tb = strdup(value); } - - else if (MATCH("gamepad2", "js_u")) { pconfig->js_p2u = strdup(value); } - else if (MATCH("gamepad2", "js_d")) { pconfig->js_p2d = strdup(value); } - else if (MATCH("gamepad2", "js_l")) { pconfig->js_p2l = strdup(value); } - else if (MATCH("gamepad2", "js_r")) { pconfig->js_p2r = strdup(value); } - else if (MATCH("gamepad2", "js_select")) { pconfig->js_p2select = strdup(value); } - else if (MATCH("gamepad2", "js_start")) { pconfig->js_p2start = strdup(value); } - else if (MATCH("gamepad2", "js_a")) { pconfig->js_p2a = strdup(value); } - else if (MATCH("gamepad2", "js_b")) { pconfig->js_p2b = strdup(value); } - else if (MATCH("gamepad2", "js_ta")) { pconfig->js_p2ta = strdup(value); } - else if (MATCH("gamepad2", "js_tb")) { pconfig->js_p2tb = strdup(value); } - - else { return 0; } - return 1; -} - -int input_configure_item(int pnum, int bnum, int type) { - // Configure an input item - - if (confrunning) { return 0; } - - SDL_Event event, eventbuf; - - int axis = 0, axisnoise = 0, counter = 0; - - // Enter and Space hack - bool etoggle = true; - if (kbactivate) { - etoggle = false; - } - - confrunning = true; - bool confstop = false; - while (confrunning) { - #ifdef _GTK - while (gtk_events_pending()) { - gtk_main_iteration_do(FALSE); - } - #endif - while(SDL_PollEvent(&event)) { - // Time to quit? - switch (event.key.keysym.sym) { - case SDLK_ESCAPE: - confrunning = false; - break; - default: break; - } - // Process the event - if (type == 0) { // Keyboard - switch(event.type) { - case SDL_KEYUP: - // Enter and Space need to be handled separately - if (event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_SPACE) { - if (etoggle) { input_set_item(event, type, pnum, bnum); } - else { etoggle = true; break; } - } - else { - input_set_item(event, type, pnum, bnum); - } - confstop = true; - break; - default: break; - } - } - else if (type == 1) { // Joystick - switch(event.type) { - case SDL_JOYBUTTONDOWN: - input_set_item(event, type, pnum, bnum); - confstop = true; - break; - - case SDL_JOYHATMOTION: - if (event.jhat.value != SDL_HAT_CENTERED) { - input_set_item(event, type, pnum, bnum); - confstop = true; - } - break; - - case SDL_JOYAXISMOTION: - if (abs(event.jaxis.value) >= DEADZONE) { - eventbuf = event; - axisnoise = 1; - axis = event.jaxis.axis; - } - - else if (abs(event.jaxis.value) < DEADZONE && axisnoise && event.jaxis.axis == axis) { - input_set_item(eventbuf, type, pnum, bnum); - axisnoise = 0; - confstop = true; - } - break; - - default: break; - } - } - } - if (confstop) { confrunning = false; } - } - - return 1; -} - -void input_set_item(SDL_Event event, int type, int pnum, int counter) { - // Set an input item to what was requested by configuration process - if (type == 0) { // Keyboard - switch(counter) { - case 0: player[pnum].u = event.key.keysym.scancode; break; - case 1: player[pnum].d = event.key.keysym.scancode; break; - case 2: player[pnum].l = event.key.keysym.scancode; break; - case 3: player[pnum].r = event.key.keysym.scancode; break; - case 4: player[pnum].select = event.key.keysym.scancode; break; - case 5: player[pnum].start = event.key.keysym.scancode; break; - case 6: player[pnum].a = event.key.keysym.scancode; break; - case 7: player[pnum].b = event.key.keysym.scancode; break; - case 8: player[pnum].ta = event.key.keysym.scancode; break; - case 9: player[pnum].tb = event.key.keysym.scancode; break; - default: break; - } - } - else if (type == 1) { // Joystick - switch(counter) { - case 0: player[pnum].ju = input_translate_string(input_translate_event(event)); break; - case 1: player[pnum].jd = input_translate_string(input_translate_event(event)); break; - case 2: player[pnum].jl = input_translate_string(input_translate_event(event)); break; - case 3: player[pnum].jr = input_translate_string(input_translate_event(event)); break; - case 4: player[pnum].jselect = input_translate_string(input_translate_event(event)); break; - case 5: player[pnum].jstart = input_translate_string(input_translate_event(event)); break; - case 6: player[pnum].ja = input_translate_string(input_translate_event(event)); break; - case 7: player[pnum].jb = input_translate_string(input_translate_event(event)); break; - case 8: player[pnum].jta = input_translate_string(input_translate_event(event)); break; - case 9: player[pnum].jtb = input_translate_string(input_translate_event(event)); break; - default: break; - } - } -} diff -Nru nestopia-1.48/source/unix/input.h nestopia-1.49/source/unix/input.h --- nestopia-1.48/source/unix/input.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/input.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,173 +0,0 @@ -#ifndef _INPUT_H_ -#define _INPUT_H_ - -#define NUMGAMEPADS 2 -#define NUMBUTTONS 10 -#define TOTALBUTTONS (NUMGAMEPADS*NUMBUTTONS) -#define DEADZONE (32768/3) - -#include -#include "core/api/NstApiInput.hpp" -#include "core/api/NstApiVideo.hpp" -#include "core/api/NstApiNsf.hpp" - -using namespace Nes::Api; - -typedef struct { - SDL_Scancode qsave1; - SDL_Scancode qsave2; - SDL_Scancode qload1; - SDL_Scancode qload2; - - SDL_Scancode screenshot; - - SDL_Scancode fdsflip; - SDL_Scancode fdsswitch; - - SDL_Scancode insertcoin1; - SDL_Scancode insertcoin2; - - SDL_Scancode reset; - - SDL_Scancode altspeed; - SDL_Scancode rwstart; - SDL_Scancode rwstop; - - SDL_Scancode fullscreen; - SDL_Scancode filter; - SDL_Scancode scalefactor; -} uiinput_t; - -typedef struct { - SDL_Scancode u; - SDL_Scancode d; - SDL_Scancode l; - SDL_Scancode r; - SDL_Scancode select; - SDL_Scancode start; - SDL_Scancode a; - SDL_Scancode b; - SDL_Scancode ta; - SDL_Scancode tb; - - SDL_Event ju; - SDL_Event jd; - SDL_Event jl; - SDL_Event jr; - SDL_Event jselect; - SDL_Event jstart; - SDL_Event ja; - SDL_Event jb; - SDL_Event jta; - SDL_Event jtb; -} gamepad_t; - -typedef struct { - // User Interface - char *qsave1; - char *qsave2; - char *qload1; - char *qload2; - - char *screenshot; - - char *fdsflip; - char *fdsswitch; - - char *insertcoin1; - char *insertcoin2; - - char *reset; - - char *altspeed; - char *rwstart; - char *rwstop; - - char *fullscreen; - char *filter; - char *scalefactor; - - // Player 1 - char *kb_p1u; - char *kb_p1d; - char *kb_p1l; - char *kb_p1r; - char *kb_p1select; - char *kb_p1start; - char *kb_p1a; - char *kb_p1b; - char *kb_p1ta; - char *kb_p1tb; - - char *js_p1u; - char *js_p1d; - char *js_p1l; - char *js_p1r; - char *js_p1select; - char *js_p1start; - char *js_p1a; - char *js_p1b; - char *js_p1ta; - char *js_p1tb; - - // Player 2 - char *kb_p2u; - char *kb_p2d; - char *kb_p2l; - char *kb_p2r; - char *kb_p2select; - char *kb_p2start; - char *kb_p2a; - char *kb_p2b; - char *kb_p2ta; - char *kb_p2tb; - - char *js_p2u; - char *js_p2d; - char *js_p2l; - char *js_p2r; - char *js_p2select; - char *js_p2start; - char *js_p2a; - char *js_p2b; - char *js_p2ta; - char *js_p2tb; -} inputsettings_t; - -typedef struct { - unsigned char player; - unsigned char nescode; - unsigned char pressed; - unsigned char turboa; - unsigned char turbob; -} nesinput_t; - -typedef struct { - int p1a; - int p1b; - int p2a; - int p2b; -} turbo_t; - -void input_init(); -void input_joysticks_detect(); -void input_joysticks_close(); -void input_process(Input::Controllers *controllers, SDL_Event event); -void input_pulse_turbo(Input::Controllers *controllers); -void input_inject(Input::Controllers *controllers, nesinput_t input); -void input_match_joystick(Input::Controllers *controllers, SDL_Event event); -void input_match_keyboard(Input::Controllers *controllers, SDL_Event event); -void input_match_mouse(Input::Controllers *controllers, SDL_Event event); -char* input_translate_event(SDL_Event event); -SDL_Event input_translate_string(const char *string); -int input_checksign(int axisvalue); -void input_config_read_new(); -void input_config_read(); -void input_config_write(); -void input_set_default(); -static int input_config_match(void* user, const char* section, const char* name, const char* value); - -int input_configure_item(int pnum, int bnum, int type); -void input_set_item(SDL_Event event, int type, int pnum, int counter); - -#endif diff -Nru nestopia-1.48/source/unix/main.cpp nestopia-1.49/source/unix/main.cpp --- nestopia-1.48/source/unix/main.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/main.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,1098 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2007-2008 R. Belmont - * Copyright (C) 2012-2016 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef _MINGW -#include -#endif -#ifndef _MINGW -#include -#include -#endif - -#include "core/api/NstApiEmulator.hpp" -#include "core/api/NstApiVideo.hpp" -#include "core/api/NstApiSound.hpp" -#include "core/api/NstApiInput.hpp" -#include "core/api/NstApiMachine.hpp" -#include "core/api/NstApiUser.hpp" -#include "core/api/NstApiFds.hpp" -#include "core/api/NstApiDipSwitches.hpp" -#include "core/api/NstApiRewinder.hpp" -#include "core/api/NstApiCartridge.hpp" -#include "core/api/NstApiMovie.hpp" -#include "core/api/NstApiNsf.hpp" - -#include "main.h" -#include "cli.h" -#include "audio.h" -#include "video.h" -#include "input.h" -#include "config.h" -#include "cheats.h" - -#ifdef _GTK -#include "gtkui/gtkui.h" -#include "gtkui/gtkui_archive.h" -#endif - -using namespace Nes::Api; - -// base class, all interfaces derives from this -Emulator emulator; - -bool loaded = false; -bool playing = false; -bool updateok = false; - -bool nst_pal = false; -bool nst_nsf = false; - -static int nst_quit = 0; - -nstpaths_t nstpaths; - -void *custompalette = NULL; - -static Video::Output *cNstVideo; -static Sound::Output *cNstSound; -static Input::Controllers *cNstPads; -static Cartridge::Database::Entry dbentry; - -static std::ifstream *nstdb; -static std::ifstream *fdsbios; - -static std::ifstream *moviefile; -static std::fstream *movierecfile; - -extern void (*audio_deinit)(); - -extern settings_t conf; -extern bool altspeed; - -extern int drawtext; -extern char textbuf[32]; - -extern bool drawtime; -extern char timebuf[6]; - -// ******************* -// emulation callbacks -// ******************* - -// called right before Nestopia is about to write pixels -static bool NST_CALLBACK VideoLock(void* userData, Video::Output& video) { - video.pitch = video_lock_screen(video.pixels); - return true; // true=lock success, false=lock failed (Nestopia will carry on but skip video) -} - -// called right after Nestopia has finished writing pixels (not called if previous lock failed) -static void NST_CALLBACK VideoUnlock(void* userData, Video::Output& video) { - video_unlock_screen(video.pixels); -} - -static bool NST_CALLBACK SoundLock(void* userData, Sound::Output& sound) { - return true; -} - -static void NST_CALLBACK SoundUnlock(void* userData, Sound::Output& sound) { - // Do Nothing -} - -static void NST_CALLBACK nst_cb_event(void *userData, User::Event event, const void* data) { - // Handle special events - switch (event) { - case User::EVENT_CPU_JAM: - fprintf(stderr, "Cpu: Jammed\n"); - break; - case User::EVENT_CPU_UNOFFICIAL_OPCODE: - fprintf(stderr, "Cpu: Unofficial Opcode %s\n", (const char*)data); - break; - case User::EVENT_DISPLAY_TIMER: - fprintf(stderr, "\r%s", (const char*)data); - snprintf(timebuf, sizeof(timebuf), "%s", (const char*)data + strlen((char*)data) - 5); - drawtime = true; - break; - default: break; - } -} - -static void NST_CALLBACK nst_cb_log(void *userData, const char *string, unsigned long int length) { - // Print logging information to stderr - fprintf(stderr, "%s", string); -} - -static void NST_CALLBACK nst_cb_file(void *userData, User::File& file) { - unsigned char *compbuffer; - int compsize, compoffset; - char *filename; - - switch (file.GetAction()) { - case User::File::LOAD_ROM: - // Nothing here for now - break; - - case User::File::LOAD_SAMPLE: - case User::File::LOAD_SAMPLE_MOERO_PRO_YAKYUU: - case User::File::LOAD_SAMPLE_MOERO_PRO_YAKYUU_88: - case User::File::LOAD_SAMPLE_MOERO_PRO_TENNIS: - case User::File::LOAD_SAMPLE_TERAO_NO_DOSUKOI_OOZUMOU: - case User::File::LOAD_SAMPLE_AEROBICS_STUDIO: - // Nothing here for now - break; - - case User::File::LOAD_BATTERY: // load in battery data from a file - case User::File::LOAD_EEPROM: // used by some Bandai games, can be treated the same as battery files - case User::File::LOAD_TAPE: // for loading Famicom cassette tapes - case User::File::LOAD_TURBOFILE: // for loading turbofile data - { - std::ifstream batteryFile(nstpaths.savename, std::ifstream::in|std::ifstream::binary); - - if (batteryFile.is_open()) { file.SetContent(batteryFile); } - break; - } - - case User::File::SAVE_BATTERY: // save battery data to a file - case User::File::SAVE_EEPROM: // can be treated the same as battery files - case User::File::SAVE_TAPE: // for saving Famicom cassette tapes - case User::File::SAVE_TURBOFILE: // for saving turbofile data - { - std::ofstream batteryFile(nstpaths.savename, std::ifstream::out|std::ifstream::binary); - const void* savedata; - unsigned long savedatasize; - - file.GetContent(savedata, savedatasize); - - if (batteryFile.is_open()) { batteryFile.write((const char*) savedata, savedatasize); } - - break; - } - - case User::File::LOAD_FDS: // for loading modified Famicom Disk System files - { - char fdsname[512]; - - snprintf(fdsname, sizeof(fdsname), "%s.ups", nstpaths.fdssave); - - std::ifstream batteryFile( fdsname, std::ifstream::in|std::ifstream::binary ); - - // no ups, look for ips - if (!batteryFile.is_open()) - { - snprintf(fdsname, sizeof(fdsname), "%s.ips", nstpaths.fdssave); - - std::ifstream batteryFile( fdsname, std::ifstream::in|std::ifstream::binary ); - - if (!batteryFile.is_open()) - { - return; - } - - file.SetPatchContent(batteryFile); - return; - } - - file.SetPatchContent(batteryFile); - break; - } - - case User::File::SAVE_FDS: // for saving modified Famicom Disk System files - { - char fdsname[512]; - - snprintf(fdsname, sizeof(fdsname), "%s.ups", nstpaths.fdssave); - - std::ofstream fdsFile( fdsname, std::ifstream::out|std::ifstream::binary ); - - if (fdsFile.is_open()) - file.GetPatchContent( User::File::PATCH_UPS, fdsFile ); - - break; - } - } -} - -static void nst_unload() { - // Remove the cartridge and shut down the NES - Machine machine(emulator); - - if (!loaded) { return; } - - // Power down the NES - fprintf(stderr, "\rEmulation stopped\n"); - machine.Power(false); - - // Remove the cartridge - machine.Unload(); -} - -void nst_pause() { - // Pauses the game - if (playing) { - audio_pause(); - audio_deinit(); - } - - playing = false; - video_set_cursor(); -} - -void nst_fds_info() { - Fds fds(emulator); - - const char* disk; - const char* side; - - fds.GetCurrentDisk() == 0 ? disk = "1" : disk = "2"; - fds.GetCurrentDiskSide() == 0 ? side = "A" : side = "B"; - - fprintf(stderr, "Fds: Disk %s Side %s\n", disk, side); - snprintf(textbuf, sizeof(textbuf), "Disk %s Side %s", disk, side); drawtext = 120; -} - -void nst_flip_disk() { - // Flips the FDS disk - Fds fds(emulator); - - if (fds.CanChangeDiskSide()) { - fds.ChangeSide(); - nst_fds_info(); - } -} - -void nst_switch_disk() { - // Switches the FDS disk in multi-disk games - Fds fds(emulator); - - int currentdisk = fds.GetCurrentDisk(); - - // If it's a multi-disk game, eject and insert the other disk - if (fds.GetNumDisks() > 1) { - fds.EjectDisk(); - fds.InsertDisk(!currentdisk, 0); - nst_fds_info(); - } -} - -static Machine::FavoredSystem nst_default_system() { - switch (conf.misc_default_system) { - case 2: - return Machine::FAVORED_NES_PAL; - break; - - case 3: - return Machine::FAVORED_FAMICOM; - break; - - case 4: - return Machine::FAVORED_DENDY; - break; - - default: - return Machine::FAVORED_NES_NTSC; - break; - } -} - -void nst_dipswitch() { - // Print DIP switch information and call handler - DipSwitches dipswitches(emulator); - - int numdips = dipswitches.NumDips(); - - if (numdips > 0) { - for (int i = 0; i < numdips; i++) { - fprintf(stderr, "%d: %s\n", i, dipswitches.GetDipName(i)); - int numvalues = dipswitches.NumValues(i); - - for (int j = 0; j < numvalues; j++) { - fprintf(stderr, " %d: %s\n", j, dipswitches.GetValueName(i, j)); - } - } - dip_handle(); - } -} - -void nst_state_save(char *filename) { - // Save a state by filename - Machine machine(emulator); - - std::ofstream statefile(filename, std::ifstream::out|std::ifstream::binary); - - if (statefile.is_open()) { machine.SaveState(statefile, Nes::Api::Machine::NO_COMPRESSION); } - fprintf(stderr, "State Saved: %s\n", filename); - snprintf(textbuf, sizeof(textbuf), "State Saved."); drawtext = 120; -} - -void nst_state_load(char *filename) { - // Load a state by filename - Machine machine(emulator); - - std::ifstream statefile(filename, std::ifstream::in|std::ifstream::binary); - - if (statefile.is_open()) { machine.LoadState(statefile); } - fprintf(stderr, "State Loaded: %s\n", filename); - snprintf(textbuf, sizeof(textbuf), "State Loaded."); drawtext = 120; -} - -void nst_state_quicksave(int slot) { - // Quick Save State - char slotpath[520]; - snprintf(slotpath, sizeof(slotpath), "%s_%d.nst", nstpaths.statepath, slot); - nst_state_save(slotpath); -} - - -void nst_state_quickload(int slot) { - // Quick Load State - char slotpath[520]; - snprintf(slotpath, sizeof(slotpath), "%s_%d.nst", nstpaths.statepath, slot); - - struct stat qloadstat; - if (stat(slotpath, &qloadstat) == -1) { - fprintf(stderr, "No State to Load\n"); drawtext = 120; - snprintf(textbuf, sizeof(textbuf), "No State to Load."); - return; - } - - nst_state_load(slotpath); -} - -void nst_movie_save(char *filename) { - // Save/Record a movie - Movie movie(emulator); - - movierecfile = new std::fstream(filename, std::ifstream::out|std::ifstream::binary); - - if (movierecfile->is_open()) { - movie.Record((std::iostream&)*movierecfile, Nes::Api::Movie::CLEAN); - } - else { - delete movierecfile; - movierecfile = NULL; - } -} - -void nst_movie_load(char *filename) { - // Load and play a movie - Movie movie(emulator); - - moviefile = new std::ifstream(filename, std::ifstream::in|std::ifstream::binary); - - if (moviefile->is_open()) { - movie.Play(*moviefile); - } - else { - delete moviefile; - moviefile = NULL; - } -} - -void nst_movie_stop() { - // Stop any movie that is playing or recording - Movie movie(emulator); - - if (movie.IsPlaying() || movie.IsRecording()) { - movie.Stop(); - movierecfile = NULL; - delete movierecfile; - moviefile = NULL; - delete moviefile; - } -} - -void nst_play() { - // Play the game - if (playing || !loaded) { return; } - - video_init(); - audio_init(); - input_init(); - cheats_init(); - - cNstVideo = new Video::Output; - cNstSound = new Sound::Output; - cNstPads = new Input::Controllers; - - audio_set_params(cNstSound); - audio_unpause(); - - if (nst_nsf) { - Nsf nsf(emulator); - nsf.PlaySong(); - video_disp_nsf(); - } - - updateok = false; - playing = true; -} - -void nst_reset(bool hardreset) { - // Reset the machine (soft or hard) - Machine machine(emulator); - Fds fds(emulator); - machine.SetRamPowerState(conf.misc_power_state); - machine.Reset(hardreset); - - // Set the FDS disk to defaults - fds.EjectDisk(); - fds.InsertDisk(0, 0); -} - -void nst_schedule_quit() { - nst_quit = 1; -} - -void nst_set_dirs() { - // Set up system directories -#ifdef _MINGW - snprintf(nstpaths.nstdir, sizeof(nstpaths.nstdir), ""); -#else - // create system directory if it doesn't exist - snprintf(nstpaths.nstdir, sizeof(nstpaths.nstdir), "%s/.nestopia/", getenv("HOME")); - if (mkdir(nstpaths.nstdir, 0755) && errno != EEXIST) { - fprintf(stderr, "Failed to create %s: %d\n", nstpaths.nstdir, errno); - } -#endif - // create save and state directories if they don't exist - char dirstr[256]; - snprintf(dirstr, sizeof(dirstr), "%ssave", nstpaths.nstdir); -#ifdef _MINGW - if (mkdir(dirstr) && errno != EEXIST) { -#else - if (mkdir(dirstr, 0755) && errno != EEXIST) { -#endif - fprintf(stderr, "Failed to create %s: %d\n", dirstr, errno); - } - - snprintf(dirstr, sizeof(dirstr), "%sstate", nstpaths.nstdir); -#ifdef _MINGW - if (mkdir(dirstr) && errno != EEXIST) { -#else - if (mkdir(dirstr, 0755) && errno != EEXIST) { -#endif - fprintf(stderr, "Failed to create %s: %d\n", dirstr, errno); - } - - // create cheats directory if it doesn't exist - snprintf(dirstr, sizeof(dirstr), "%scheats", nstpaths.nstdir); -#ifdef _MINGW - if (mkdir(dirstr) && errno != EEXIST) { -#else - if (mkdir(dirstr, 0755) && errno != EEXIST) { -#endif - fprintf(stderr, "Failed to create %s: %d\n", dirstr, errno); - } - - // create screenshots directory if it doesn't exist - snprintf(dirstr, sizeof(dirstr), "%sscreenshots", nstpaths.nstdir); -#ifdef _MINGW - if (mkdir(dirstr) && errno != EEXIST) { -#else - if (mkdir(dirstr, 0755) && errno != EEXIST) { -#endif - fprintf(stderr, "Failed to create %s: %d\n", dirstr, errno); - } - - // Construct the custom palette path - snprintf(nstpaths.palettepath, sizeof(nstpaths.palettepath), "%s%s", nstpaths.nstdir, "custom.pal"); -} - -void nst_set_region() { - // Set the region - Machine machine(emulator); - Cartridge::Database database(emulator); - - /*if (database.IsLoaded()) { - std::ifstream dbfile(filename, std::ios::in|std::ios::binary); - Cartridge::Profile profile; - Cartridge::ReadInes(dbfile, nst_default_system(), profile); - dbentry = database.FindEntry(profile.hash, nst_default_system()); - printf("Mapper: %d\n", dbentry.GetMapper()); - }*/ - - switch (conf.misc_default_system) { - case 0: machine.SetMode(machine.GetDesiredMode()); break; // Auto - case 1: machine.SetMode(Machine::NTSC); break; // NTSC - case 2: machine.SetMode(Machine::PAL); break; // PAL - case 3: machine.SetMode(Machine::NTSC); break; // Famicom - case 4: machine.SetMode(Machine::PAL); break; // Dendy - } - - if (machine.GetMode() == Machine::PAL) { - fprintf(stderr, "Region: PAL\n"); - nst_pal = true; - } - else { - fprintf(stderr, "Region: NTSC\n"); - nst_pal = false; - } -} - -void nst_set_rewind(int direction) { - // Set the rewinder backward or forward - switch (direction) { - case 0: - Rewinder(emulator).SetDirection(Rewinder::BACKWARD); - break; - - case 1: - Rewinder(emulator).SetDirection(Rewinder::FORWARD); - break; - - default: break; - } -} - -void nst_set_paths(const char *filename) { - - // Set up the save directory - snprintf(nstpaths.savedir, sizeof(nstpaths.savedir), "%ssave/", nstpaths.nstdir); - - // Copy the full file path to the savename variable - snprintf(nstpaths.savename, sizeof(nstpaths.savename), "%s", filename); - - // strip the . and extention off the filename for saving - for (int i = strlen(nstpaths.savename)-1; i > 0; i--) { - if (nstpaths.savename[i] == '.') { - nstpaths.savename[i] = '\0'; - break; - } - } - - // Get the name of the game minus file path and extension - snprintf(nstpaths.gamename, sizeof(nstpaths.gamename), "%s", basename(nstpaths.savename)); - - // Construct save path - snprintf(nstpaths.savename, sizeof(nstpaths.savename), "%s%s%s", nstpaths.savedir, nstpaths.gamename, ".sav"); - - // Construct path for FDS save patches - snprintf(nstpaths.fdssave, sizeof(nstpaths.fdssave), "%s%s", nstpaths.savedir, nstpaths.gamename); - - // Construct the save state path - snprintf(nstpaths.statepath, sizeof(nstpaths.statepath), "%sstate/%s", nstpaths.nstdir, nstpaths.gamename); - - // Construct the cheat path - snprintf(nstpaths.cheatpath, sizeof(nstpaths.cheatpath), "%scheats/%s.xml", nstpaths.nstdir, nstpaths.gamename); -} - -bool nst_archive_checkext(const char *filename) { - // Check if the file extension is valid - int len = strlen(filename); - - if ((!strcasecmp(&filename[len-4], ".nes")) || - (!strcasecmp(&filename[len-4], ".fds")) || - (!strcasecmp(&filename[len-4], ".nsf")) || - (!strcasecmp(&filename[len-4], ".unf")) || - (!strcasecmp(&filename[len-5], ".unif"))|| - (!strcasecmp(&filename[len-4], ".xml"))) { - return true; - } - return false; -} - -bool nst_archive_handle(const char *filename, char **rom, int *romsize, const char *reqfile) { - // Handle archives -#ifndef _MINGW - struct archive *a; - struct archive_entry *entry; - int r; - int64_t entrysize; - - a = archive_read_new(); - archive_read_support_filter_all(a); - archive_read_support_format_all(a); - r = archive_read_open_filename(a, filename, 10240); - - // Test if it's actually an archive - if (r != ARCHIVE_OK) { - r = archive_read_free(a); - return false; - } - - // Scan through the archive for files - while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { - char *rombuf; - const char *currentfile = archive_entry_pathname(entry); - - if (nst_archive_checkext(currentfile)) { - nst_set_paths(currentfile); - - // If there's a specific file we want, load it - if (reqfile != NULL) { - if (!strcmp(currentfile, reqfile)) { - entrysize = archive_entry_size(entry); - rombuf = (char*)malloc(entrysize); - archive_read_data(a, rombuf, entrysize); - archive_read_data_skip(a); - r = archive_read_free(a); - *romsize = entrysize; - *rom = rombuf; - return true; - } - } - // Otherwise just take the first file in the archive - else { - entrysize = archive_entry_size(entry); - rombuf = (char*)malloc(entrysize); - archive_read_data(a, rombuf, entrysize); - archive_read_data_skip(a); - r = archive_read_free(a); - *romsize = entrysize; - *rom = rombuf; - return true; - } - } - } -#endif - return false; -} - -bool nst_find_patch(char *filename) { - // Check for a patch in the same directory as the game - FILE *file; - - if (!conf.misc_soft_patching) { - return 0; - } - - snprintf(filename, sizeof(nstpaths.savename), "%s.ips", nstpaths.gamename); - - if ((file = fopen(filename, "rb")) != NULL) { - fclose(file); - return 1; - } - else { - snprintf(filename, sizeof(nstpaths.savename), "%s.ups", nstpaths.gamename); - - if ((file = fopen(filename, "rb")) != NULL) { - fclose(file); - return 1; - } - } - - return 0; -} - -void nst_load_db() { - Nes::Api::Cartridge::Database database(emulator); - char dbpath[512]; - - if (nstdb) { return; } - - // Try to open the database file - snprintf(dbpath, sizeof(dbpath), "%sNstDatabase.xml", nstpaths.nstdir); - nstdb = new std::ifstream(dbpath, std::ifstream::in|std::ifstream::binary); - - if (nstdb->is_open()) { - database.Load(*nstdb); - database.Enable(true); - return; - } -#ifndef _MINGW - // If it fails, try looking in the data directory - snprintf(dbpath, sizeof(dbpath), "%s/NstDatabase.xml", DATADIR); - nstdb = new std::ifstream(dbpath, std::ifstream::in|std::ifstream::binary); - - if (nstdb->is_open()) { - database.Load(*nstdb); - database.Enable(true); - return; - } - - // If that fails, try looking in the working directory - char *pwd = getenv("PWD"); - snprintf(dbpath, sizeof(dbpath), "%s/NstDatabase.xml", pwd); - nstdb = new std::ifstream(dbpath, std::ifstream::in|std::ifstream::binary); - - if (nstdb->is_open()) { - database.Load(*nstdb); - database.Enable(true); - return; - } -#endif - else { - fprintf(stderr, "NstDatabase.xml not found!\n"); - delete nstdb; - nstdb = NULL; - } -} - -void nst_load_fds_bios() { - // Load the Famicom Disk System BIOS - Nes::Api::Fds fds(emulator); - char biospath[512]; - - if (fdsbios) { return; } - - snprintf(biospath, sizeof(biospath), "%sdisksys.rom", nstpaths.nstdir); - - fdsbios = new std::ifstream(biospath, std::ifstream::in|std::ifstream::binary); - - if (fdsbios->is_open()) { - fds.SetBIOS(fdsbios); - } - else { - fprintf(stderr, "Fds: BIOS not found: %s\n", biospath); - delete fdsbios; - fdsbios = NULL; - } -} - -void nst_load_palette(const char *filename) { - // Load a custom palette - - FILE *file; - long filesize; // File size in bytes - size_t result; - - file = fopen(filename, "rb"); - - if (!file) { - if (conf.video_palette_mode == 2) { - fprintf(stderr, "Custom palette: not found: %s\n", filename); - conf.video_palette_mode = 0; - } - return; - } - - fseek(file, 0, SEEK_END); - filesize = ftell(file); - fseek(file, 0, SEEK_SET); - - if (custompalette) { free(custompalette); } - custompalette = malloc(filesize * sizeof(uint8_t)); - - result = fread(custompalette, sizeof(uint8_t), filesize, file); - - fclose(file); -} - -void nst_load(const char *filename) { - // Load a Game ROM - Machine machine(emulator); - Nsf nsf(emulator); - Sound sound(emulator); - Nes::Result result; - char *rom; - int romsize; - char patchname[512]; - - // Pause play before pulling out a cartridge - if (playing) { nst_pause(); } - - // Pull out any inserted cartridges - nst_unload(); drawtime = false; - - // Handle the file as an archive if it is one - #ifdef _GTK - char reqname[256]; - bool isarchive = gtkui_archive_handle(filename, reqname, sizeof(reqname)); - - if (isarchive) { - nst_archive_handle(filename, &rom, &romsize, reqname); - #else - if (nst_archive_handle(filename, &rom, &romsize, NULL)) { - #endif - // Convert the malloc'd char* to an istream - std::string rombuf(rom, romsize); - std::istringstream file(rombuf); - result = machine.Load(file, nst_default_system()); - } - // Otherwise just load the file - else { - std::ifstream file(filename, std::ios::in|std::ios::binary); - - // Set the file paths - nst_set_paths(filename); - - if (nst_find_patch(patchname)) { // Load with a patch if there is one - std::ifstream pfile(patchname, std::ios::in|std::ios::binary); - Machine::Patch patch(pfile, false); - result = machine.Load(file, nst_default_system(), patch); - } - else { result = machine.Load(file, nst_default_system()); } - } - - if (NES_FAILED(result)) { - char errorstring[32]; - #ifdef _GTK - if (conf.video_fullscreen) { video_toggle_fullscreen(); } - #endif - switch (result) { - case Nes::RESULT_ERR_INVALID_FILE: - snprintf(errorstring, sizeof(errorstring), "Error: Invalid file"); - break; - - case Nes::RESULT_ERR_OUT_OF_MEMORY: - snprintf(errorstring, sizeof(errorstring), "Error: Out of Memory"); - break; - - case Nes::RESULT_ERR_CORRUPT_FILE: - snprintf(errorstring, sizeof(errorstring), "Error: Corrupt or Missing File"); - break; - - case Nes::RESULT_ERR_UNSUPPORTED_MAPPER: - snprintf(errorstring, sizeof(errorstring), "Error: Unsupported Mapper"); - break; - - case Nes::RESULT_ERR_MISSING_BIOS: - snprintf(errorstring, sizeof(errorstring), "Error: Missing Fds BIOS"); - break; - - default: - snprintf(errorstring, sizeof(errorstring), "Error: %d", result); - break; - } - - fprintf(stderr, "%s\n", errorstring); - #ifdef _GTK - if (conf.misc_disable_gui) { cli_error(errorstring); } - else { - if (conf.video_fullscreen) { - video_destroy(); - conf.video_fullscreen = false; - video_create(); - video_set_cursor(); - } - gtkui_message(errorstring); - } - #endif - - return; - } - - // Deal with any DIP Switches - nst_dipswitch(); - - // Set the region - nst_set_region(); - - if (machine.Is(Machine::DISK)) { - Fds fds(emulator); - fds.InsertDisk(0, 0); - nst_fds_info(); - } - - // Check if this is an NSF - nst_nsf = (machine.Is(Machine::SOUND)); - if (nst_nsf) { nsf.StopSong(); } - - // Check if sound distortion should be enabled - sound.SetGenie(conf.misc_genie_distortion); - - // Note that something is loaded - loaded = 1; - - // Set the title - video_set_title(nstpaths.gamename); - #ifdef _GTK - if (!conf.misc_disable_gui) { gtkui_set_title(nstpaths.gamename); } - #endif - - // Set the RAM's power state - machine.SetRamPowerState(conf.misc_power_state); - - // Power on - machine.Power(true); - - nst_play(); -} - -int main(int argc, char *argv[]) { - // This is the main function - - static SDL_Event event; - void *userData = (void*)0xDEADC0DE; - - // Set up directories - nst_set_dirs(); - - // Set default config options - config_set_default(); - - // Read the config file and override defaults - config_file_read(); - - // Exit if there is no CLI argument - #ifdef _GTK - if (argc == 1 && conf.misc_disable_gui) { - #else - if (argc == 1) { - #endif - cli_show_usage(); - return 0; - } - - // Handle command line arguments - cli_handle_command(argc, argv); - - // Initialize SDL - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) < 0) { - fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); - return 1; - } - - // Detect Joysticks - input_joysticks_detect(); - - // Set default input keys - input_set_default(); - - // Read the input config file and override defaults - input_config_read(); - - // Load the custom palette - nst_load_palette(nstpaths.palettepath); - - // Set the video dimensions - video_set_dimensions(); - - // Create the window - #ifdef _GTK - if (!conf.misc_disable_gui) { gtkui_init(argc, argv); } - #endif - video_create(); - - // Set up the callbacks - Video::Output::lockCallback.Set(VideoLock, userData); - Video::Output::unlockCallback.Set(VideoUnlock, userData); - - Sound::Output::lockCallback.Set(SoundLock, userData); - Sound::Output::unlockCallback.Set(SoundUnlock, userData); - - User::fileIoCallback.Set(nst_cb_file, userData); - User::logCallback.Set(nst_cb_log, userData); - User::eventCallback.Set(nst_cb_event, userData); - - // Initialize and load FDS BIOS and NstDatabase.xml - nstdb = NULL; - fdsbios = NULL; - nst_load_db(); - nst_load_fds_bios(); - - // Load a rom from the command line - if (argc > 1) { - #ifdef _GTK // This is a dirty hack - if (conf.misc_disable_gui) { - nst_load(argv[argc - 1]); - if (!loaded) { - fprintf(stderr, "Fatal: Could not load ROM\n"); - exit(1); - } - } - else { - if (strcmp(argv[argc - 1], "-e")) { nst_load(argv[argc - 1]); } - } - #else - conf.misc_disable_gui = true; - nst_load(argv[argc - 1]); - if (!loaded) { - fprintf(stderr, "Fatal: Could not load ROM\n"); - exit(1); - } - #endif - } - - // Start the main loop - nst_quit = 0; - - while (!nst_quit) { - #if defined(_APPLE) && defined(_GTK) - if (!playing) { gtk_main_iteration_do(TRUE); } - #elif _GTK - while (gtk_events_pending()) { - gtk_main_iteration_do(TRUE); - } - if (!playing) { gtk_main_iteration_do(TRUE); } - #endif - if (playing) { - while (SDL_PollEvent(&event)) { - switch (event.type) { - case SDL_QUIT: - nst_quit = 1; - break; - - case SDL_KEYDOWN: - case SDL_KEYUP: - case SDL_JOYHATMOTION: - case SDL_JOYAXISMOTION: - case SDL_JOYBUTTONDOWN: - case SDL_JOYBUTTONUP: - case SDL_MOUSEBUTTONDOWN: - case SDL_MOUSEBUTTONUP: - input_process(cNstPads, event); - break; - default: break; - } - } - - if (NES_SUCCEEDED(Rewinder(emulator).Enable(true))) { - Rewinder(emulator).EnableSound(true); - } - - audio_play(); - - if (updateok) { - // Pulse the turbo buttons - input_pulse_turbo(cNstPads); - - // Execute a frame - if (timing_frameskip()) { - emulator.Execute(NULL, cNstSound, cNstPads); - } - else { emulator.Execute(cNstVideo, cNstSound, cNstPads); } - } - } - } - - // Remove the cartridge and shut down the NES - nst_unload(); - - // Unload the FDS BIOS, NstDatabase.xml, and the custom palette - if (nstdb) { delete nstdb; nstdb = NULL; } - if (fdsbios) { delete fdsbios; fdsbios = NULL; } - if (custompalette) { free(custompalette); } - - // Deinitialize audio - audio_deinit(); - - // Deinitialize joysticks - input_joysticks_close(); - - // Write the input config file - input_config_write(); - - // Write the config file - config_file_write(); - - return 0; -} diff -Nru nestopia-1.48/source/unix/main.h nestopia-1.49/source/unix/main.h --- nestopia-1.48/source/unix/main.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/main.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -#ifndef _MAIN_H_ -#define _MAIN_H_ - -#define VERSION "1.48" - -typedef struct { - char nstdir[256]; - char savedir[256]; - char gamename[256]; - char savename[512]; - char fdssave[512]; - char statepath[512]; - char cheatpath[512]; - char palettepath[512]; -} nstpaths_t; - -bool nst_archive_checkext(const char *filename); -bool nst_archive_handle(const char *filename, char **rom, int *romsize, const char *reqfile); -bool nst_find_patch(char *filename); -void nst_load_db(); -void nst_load_fds_bios(); -void nst_load_palette(const char *filename); -void nst_load(const char *filename); -void nst_play(); -void nst_pause(); -void nst_reset(bool hardreset); -void nst_schedule_quit(); -void nst_set_dirs(); -void nst_set_region(); -void nst_set_rewind(int direction); - -void nst_set_paths(const char *filename); - -void nst_state_save(char *filename); -void nst_state_load(char *filename); -void nst_state_quicksave(int isvst); -void nst_state_quickload(int isvst); - -void nst_movie_save(char *filename); -void nst_movie_load(char *filename); -void nst_movie_stop(); - -void nst_fds_info(); -void nst_flip_disk(); -void nst_switch_disk(); - -void nst_dipswitch(); - -#endif diff -Nru nestopia-1.48/source/unix/png.cpp nestopia-1.49/source/unix/png.cpp --- nestopia-1.48/source/unix/png.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/png.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,6136 +0,0 @@ -/* -LodePNG version 20141130 - -Copyright (c) 2005-2014 Lode Vandevenne - -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 "png.h" - -#include -#include - -#ifdef LODEPNG_COMPILE_CPP -#include -#endif /*LODEPNG_COMPILE_CPP*/ - -#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/ -#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/ -#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/ -#endif /*_MSC_VER */ - -/* -This source file is built up in the following large parts. The code sections -with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way. --Tools for C and common code for PNG and Zlib --C Code for Zlib (huffman, deflate, ...) --C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...) --The C++ wrapper around all of the above -*/ - -/*The malloc, realloc and free functions defined here with "lodepng_" in front -of the name, so that you can easily change them to others related to your -platform if needed. Everything else in the code calls these. Pass --DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out -#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and -define them in your own project's source files without needing to change -lodepng source code. Don't forget to remove "static" if you copypaste them -from here.*/ - -#ifdef LODEPNG_COMPILE_ALLOCATORS -static void* lodepng_malloc(size_t size) -{ - return malloc(size); -} - -static void* lodepng_realloc(void* ptr, size_t new_size) -{ - return realloc(ptr, new_size); -} - -static void lodepng_free(void* ptr) -{ - free(ptr); -} -#else /*LODEPNG_COMPILE_ALLOCATORS*/ -void* lodepng_malloc(size_t size); -void* lodepng_realloc(void* ptr, size_t new_size); -void lodepng_free(void* ptr); -#endif /*LODEPNG_COMPILE_ALLOCATORS*/ - -/* ////////////////////////////////////////////////////////////////////////// */ -/* ////////////////////////////////////////////////////////////////////////// */ -/* // Tools for C, and common code for PNG and Zlib. // */ -/* ////////////////////////////////////////////////////////////////////////// */ -/* ////////////////////////////////////////////////////////////////////////// */ - -/* -Often in case of an error a value is assigned to a variable and then it breaks -out of a loop (to go to the cleanup phase of a function). This macro does that. -It makes the error handling code shorter and more readable. - -Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83); -*/ -#define CERROR_BREAK(errorvar, code)\ -{\ - errorvar = code;\ - break;\ -} - -/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/ -#define ERROR_BREAK(code) CERROR_BREAK(error, code) - -/*Set error var to the error code, and return it.*/ -#define CERROR_RETURN_ERROR(errorvar, code)\ -{\ - errorvar = code;\ - return code;\ -} - -/*Try the code, if it returns error, also return the error.*/ -#define CERROR_TRY_RETURN(call)\ -{\ - unsigned error = call;\ - if(error) return error;\ -} - -/*Set error var to the error code, and return from the void function.*/ -#define CERROR_RETURN(errorvar, code)\ -{\ - errorvar = code;\ - return;\ -} - -/* -About uivector, ucvector and string: --All of them wrap dynamic arrays or text strings in a similar way. --LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version. --The string tools are made to avoid problems with compilers that declare things like strncat as deprecated. --They're not used in the interface, only internally in this file as static functions. --As with many other structs in this file, the init and cleanup functions serve as ctor and dtor. -*/ - -#ifdef LODEPNG_COMPILE_ZLIB -/*dynamic vector of unsigned ints*/ -typedef struct uivector -{ - unsigned* data; - size_t size; /*size in number of unsigned longs*/ - size_t allocsize; /*allocated size in bytes*/ -} uivector; - -static void uivector_cleanup(void* p) -{ - ((uivector*)p)->size = ((uivector*)p)->allocsize = 0; - lodepng_free(((uivector*)p)->data); - ((uivector*)p)->data = NULL; -} - -/*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned uivector_reserve(uivector* p, size_t allocsize) -{ - if(allocsize > p->allocsize) - { - size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); - void* data = lodepng_realloc(p->data, newsize); - if(data) - { - p->allocsize = newsize; - p->data = (unsigned*)data; - } - else return 0; /*error: not enough memory*/ - } - return 1; -} - -/*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned uivector_resize(uivector* p, size_t size) -{ - if(!uivector_reserve(p, size * sizeof(unsigned))) return 0; - p->size = size; - return 1; /*success*/ -} - -/*resize and give all new elements the value*/ -static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) -{ - size_t oldsize = p->size, i; - if(!uivector_resize(p, size)) return 0; - for(i = oldsize; i < size; ++i) p->data[i] = value; - return 1; -} - -static void uivector_init(uivector* p) -{ - p->data = NULL; - p->size = p->allocsize = 0; -} - -#ifdef LODEPNG_COMPILE_ENCODER -/*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned uivector_push_back(uivector* p, unsigned c) -{ - if(!uivector_resize(p, p->size + 1)) return 0; - p->data[p->size - 1] = c; - return 1; -} - -/*copy q to p, returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned uivector_copy(uivector* p, const uivector* q) -{ - size_t i; - if(!uivector_resize(p, q->size)) return 0; - for(i = 0; i != q->size; ++i) p->data[i] = q->data[i]; - return 1; -} -#endif /*LODEPNG_COMPILE_ENCODER*/ -#endif /*LODEPNG_COMPILE_ZLIB*/ - -/* /////////////////////////////////////////////////////////////////////////// */ - -/*dynamic vector of unsigned chars*/ -typedef struct ucvector -{ - unsigned char* data; - size_t size; /*used size*/ - size_t allocsize; /*allocated size*/ -} ucvector; - -/*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned ucvector_reserve(ucvector* p, size_t allocsize) -{ - if(allocsize > p->allocsize) - { - size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); - void* data = lodepng_realloc(p->data, newsize); - if(data) - { - p->allocsize = newsize; - p->data = (unsigned char*)data; - } - else return 0; /*error: not enough memory*/ - } - return 1; -} - -/*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned ucvector_resize(ucvector* p, size_t size) -{ - if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0; - p->size = size; - return 1; /*success*/ -} - -#ifdef LODEPNG_COMPILE_PNG - -static void ucvector_cleanup(void* p) -{ - ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0; - lodepng_free(((ucvector*)p)->data); - ((ucvector*)p)->data = NULL; -} - -static void ucvector_init(ucvector* p) -{ - p->data = NULL; - p->size = p->allocsize = 0; -} - -#ifdef LODEPNG_COMPILE_DECODER -/*resize and give all new elements the value*/ -static unsigned ucvector_resizev(ucvector* p, size_t size, unsigned char value) -{ - size_t oldsize = p->size, i; - if(!ucvector_resize(p, size)) return 0; - for(i = oldsize; i < size; ++i) p->data[i] = value; - return 1; -} -#endif /*LODEPNG_COMPILE_DECODER*/ -#endif /*LODEPNG_COMPILE_PNG*/ - -#ifdef LODEPNG_COMPILE_ZLIB -/*you can both convert from vector to buffer&size and vica versa. If you use -init_buffer to take over a buffer and size, it is not needed to use cleanup*/ -static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) -{ - p->data = buffer; - p->allocsize = p->size = size; -} -#endif /*LODEPNG_COMPILE_ZLIB*/ - -#if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER) -/*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned ucvector_push_back(ucvector* p, unsigned char c) -{ - if(!ucvector_resize(p, p->size + 1)) return 0; - p->data[p->size - 1] = c; - return 1; -} -#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ - - -/* ////////////////////////////////////////////////////////////////////////// */ - -#ifdef LODEPNG_COMPILE_PNG -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS -/*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned string_resize(char** out, size_t size) -{ - char* data = (char*)lodepng_realloc(*out, size + 1); - if(data) - { - data[size] = 0; /*null termination char*/ - *out = data; - } - return data != 0; -} - -/*init a {char*, size_t} pair for use as string*/ -static void string_init(char** out) -{ - *out = NULL; - string_resize(out, 0); -} - -/*free the above pair again*/ -static void string_cleanup(char** out) -{ - lodepng_free(*out); - *out = NULL; -} - -static void string_set(char** out, const char* in) -{ - size_t insize = strlen(in), i; - if(string_resize(out, insize)) - { - for(i = 0; i != insize; ++i) - { - (*out)[i] = in[i]; - } - } -} -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ -#endif /*LODEPNG_COMPILE_PNG*/ - -/* ////////////////////////////////////////////////////////////////////////// */ - -unsigned lodepng_read32bitInt(const unsigned char* buffer) -{ - return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); -} - -#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER) -/*buffer must have at least 4 allocated bytes available*/ -static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) -{ - buffer[0] = (unsigned char)((value >> 24) & 0xff); - buffer[1] = (unsigned char)((value >> 16) & 0xff); - buffer[2] = (unsigned char)((value >> 8) & 0xff); - buffer[3] = (unsigned char)((value ) & 0xff); -} -#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ - -#ifdef LODEPNG_COMPILE_ENCODER -static void lodepng_add32bitInt(ucvector* buffer, unsigned value) -{ - ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/ - lodepng_set32bitInt(&buffer->data[buffer->size - 4], value); -} -#endif /*LODEPNG_COMPILE_ENCODER*/ - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / File IO / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -#ifdef LODEPNG_COMPILE_DISK - -unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) -{ - FILE* file; - long size; - - /*provide some proper output values if error will happen*/ - *out = 0; - *outsize = 0; - - file = fopen(filename, "rb"); - if(!file) return 78; - - /*get filesize:*/ - fseek(file , 0 , SEEK_END); - size = ftell(file); - rewind(file); - - /*read contents of the file into the vector*/ - *outsize = 0; - *out = (unsigned char*)lodepng_malloc((size_t)size); - if(size && (*out)) (*outsize) = fread(*out, 1, (size_t)size, file); - - fclose(file); - if(!(*out) && size) return 83; /*the above malloc failed*/ - return 0; -} - -/*write given buffer to the file, overwriting the file, it doesn't append to it.*/ -unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) -{ - FILE* file; - file = fopen(filename, "wb" ); - if(!file) return 79; - fwrite((char*)buffer , 1 , buffersize, file); - fclose(file); - return 0; -} - -#endif /*LODEPNG_COMPILE_DISK*/ - -/* ////////////////////////////////////////////////////////////////////////// */ -/* ////////////////////////////////////////////////////////////////////////// */ -/* // End of common code and tools. Begin of Zlib related code. // */ -/* ////////////////////////////////////////////////////////////////////////// */ -/* ////////////////////////////////////////////////////////////////////////// */ - -#ifdef LODEPNG_COMPILE_ZLIB -#ifdef LODEPNG_COMPILE_ENCODER -/*TODO: this ignores potential out of memory errors*/ -#define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit)\ -{\ - /*add a new byte at the end*/\ - if(((*bitpointer) & 7) == 0) ucvector_push_back(bitstream, (unsigned char)0);\ - /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/\ - (bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));\ - ++(*bitpointer);\ -} - -static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) -{ - size_t i; - for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1)); -} - -static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) -{ - size_t i; - for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1)); -} -#endif /*LODEPNG_COMPILE_ENCODER*/ - -#ifdef LODEPNG_COMPILE_DECODER - -#define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1) - -static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream) -{ - unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream)); - ++(*bitpointer); - return result; -} - -static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) -{ - unsigned result = 0, i; - for(i = 0; i != nbits; ++i) - { - result += ((unsigned)READBIT(*bitpointer, bitstream)) << i; - ++(*bitpointer); - } - return result; -} -#endif /*LODEPNG_COMPILE_DECODER*/ - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / Deflate - Huffman / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -#define FIRST_LENGTH_CODE_INDEX 257 -#define LAST_LENGTH_CODE_INDEX 285 -/*256 literals, the end code, some length codes, and 2 unused codes*/ -#define NUM_DEFLATE_CODE_SYMBOLS 288 -/*the distance codes have their own symbols, 30 used, 2 unused*/ -#define NUM_DISTANCE_SYMBOLS 32 -/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/ -#define NUM_CODE_LENGTH_CODES 19 - -/*the base lengths represented by codes 257-285*/ -static const unsigned LENGTHBASE[29] - = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, - 67, 83, 99, 115, 131, 163, 195, 227, 258}; - -/*the extra bits used by codes 257-285 (added to base length)*/ -static const unsigned LENGTHEXTRA[29] - = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, - 4, 4, 4, 4, 5, 5, 5, 5, 0}; - -/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/ -static const unsigned DISTANCEBASE[30] - = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, - 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; - -/*the extra bits of backwards distances (added to base)*/ -static const unsigned DISTANCEEXTRA[30] - = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, - 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; - -/*the order in which "code length alphabet code lengths" are stored, out of this -the huffman tree of the dynamic huffman tree lengths is generated*/ -static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES] - = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - -/* ////////////////////////////////////////////////////////////////////////// */ - -/* -Huffman tree struct, containing multiple representations of the tree -*/ -typedef struct HuffmanTree -{ - unsigned* tree2d; - unsigned* tree1d; - unsigned* lengths; /*the lengths of the codes of the 1d-tree*/ - unsigned maxbitlen; /*maximum number of bits a single code can get*/ - unsigned numcodes; /*number of symbols in the alphabet = number of codes*/ -} HuffmanTree; - -/*function used for debug purposes to draw the tree in ascii art with C++*/ -/* -static void HuffmanTree_draw(HuffmanTree* tree) -{ - std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl; - for(size_t i = 0; i != tree->tree1d.size; ++i) - { - if(tree->lengths.data[i]) - std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl; - } - std::cout << std::endl; -}*/ - -static void HuffmanTree_init(HuffmanTree* tree) -{ - tree->tree2d = 0; - tree->tree1d = 0; - tree->lengths = 0; -} - -static void HuffmanTree_cleanup(HuffmanTree* tree) -{ - lodepng_free(tree->tree2d); - lodepng_free(tree->tree1d); - lodepng_free(tree->lengths); -} - -/*the tree representation used by the decoder. return value is error*/ -static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) -{ - unsigned nodefilled = 0; /*up to which node it is filled*/ - unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/ - unsigned n, i; - - tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned)); - if(!tree->tree2d) return 83; /*alloc fail*/ - - /* - convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means - uninited, a value >= numcodes is an address to another bit, a value < numcodes - is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as - many columns as codes - 1. - A good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. - Here, the internal nodes are stored (what their 0 and 1 option point to). - There is only memory for such good tree currently, if there are more nodes - (due to too long length codes), error 55 will happen - */ - for(n = 0; n < tree->numcodes * 2; ++n) - { - tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/ - } - - for(n = 0; n < tree->numcodes; ++n) /*the codes*/ - { - for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/ - { - unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1); - /*oversubscribed, see comment in lodepng_error_text*/ - if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55; - if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ - { - if(i + 1 == tree->lengths[n]) /*last bit*/ - { - tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/ - treepos = 0; - } - else - { - /*put address of the next step in here, first that address has to be found of course - (it's just nodefilled + 1)...*/ - ++nodefilled; - /*addresses encoded with numcodes added to it*/ - tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes; - treepos = nodefilled; - } - } - else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes; - } - } - - for(n = 0; n < tree->numcodes * 2; ++n) - { - if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/ - } - - return 0; -} - -/* -Second step for the ...makeFromLengths and ...makeFromFrequencies functions. -numcodes, lengths and maxbitlen must already be filled in correctly. return -value is error. -*/ -static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) -{ - uivector blcount; - uivector nextcode; - unsigned error = 0; - unsigned bits, n; - - uivector_init(&blcount); - uivector_init(&nextcode); - - tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned)); - if(!tree->tree1d) error = 83; /*alloc fail*/ - - if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0) - || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0)) - error = 83; /*alloc fail*/ - - if(!error) - { - /*step 1: count number of instances of each code length*/ - for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]]; - /*step 2: generate the nextcode values*/ - for(bits = 1; bits <= tree->maxbitlen; ++bits) - { - nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1; - } - /*step 3: generate all the codes*/ - for(n = 0; n != tree->numcodes; ++n) - { - if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++; - } - } - - uivector_cleanup(&blcount); - uivector_cleanup(&nextcode); - - if(!error) return HuffmanTree_make2DTree(tree); - else return error; -} - -/* -given the code lengths (as stored in the PNG file), generate the tree as defined -by Deflate. maxbitlen is the maximum bits that a code in the tree can have. -return value is error. -*/ -static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen, - size_t numcodes, unsigned maxbitlen) -{ - unsigned i; - tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); - if(!tree->lengths) return 83; /*alloc fail*/ - for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i]; - tree->numcodes = (unsigned)numcodes; /*number of symbols*/ - tree->maxbitlen = maxbitlen; - return HuffmanTree_makeFromLengths2(tree); -} - -#ifdef LODEPNG_COMPILE_ENCODER - -/* -A coin, this is the terminology used for the package-merge algorithm and the -coin collector's problem. This is used to generate the huffman tree. -A coin can be multiple coins (when they're merged) -*/ -typedef struct Coin -{ - uivector symbols; - float weight; /*the sum of all weights in this coin*/ -} Coin; - -static void coin_init(Coin* c) -{ - uivector_init(&c->symbols); -} - -/*argument c is void* so that this dtor can be given as function pointer to the vector resize function*/ -static void coin_cleanup(void* c) -{ - uivector_cleanup(&((Coin*)c)->symbols); -} - -static void coin_copy(Coin* c1, const Coin* c2) -{ - c1->weight = c2->weight; - uivector_copy(&c1->symbols, &c2->symbols); -} - -static void add_coins(Coin* c1, const Coin* c2) -{ - size_t i; - for(i = 0; i != c2->symbols.size; ++i) uivector_push_back(&c1->symbols, c2->symbols.data[i]); - c1->weight += c2->weight; -} - -static void init_coins(Coin* coins, size_t num) -{ - size_t i; - for(i = 0; i != num; ++i) coin_init(&coins[i]); -} - -static void cleanup_coins(Coin* coins, size_t num) -{ - size_t i; - for(i = 0; i != num; ++i) coin_cleanup(&coins[i]); -} - -static int coin_compare(const void* a, const void* b) { - float wa = ((const Coin*)a)->weight; - float wb = ((const Coin*)b)->weight; - return wa > wb ? 1 : wa < wb ? -1 : 0; -} - -static unsigned append_symbol_coins(Coin* coins, const unsigned* frequencies, unsigned numcodes, size_t sum) -{ - unsigned i; - unsigned j = 0; /*index of present symbols*/ - for(i = 0; i != numcodes; ++i) - { - if(frequencies[i] != 0) /*only include symbols that are present*/ - { - coins[j].weight = frequencies[i] / (float)sum; - uivector_push_back(&coins[j].symbols, i); - ++j; - } - } - return 0; -} - -unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, - size_t numcodes, unsigned maxbitlen) -{ - unsigned i, j; - size_t sum = 0, numpresent = 0; - unsigned error = 0; - Coin* coins; /*the coins of the currently calculated row*/ - Coin* prev_row; /*the previous row of coins*/ - size_t numcoins; - size_t coinmem; - - if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ - - for(i = 0; i != numcodes; ++i) - { - if(frequencies[i] > 0) - { - ++numpresent; - sum += frequencies[i]; - } - } - - for(i = 0; i != numcodes; ++i) lengths[i] = 0; - - /*ensure at least two present symbols. There should be at least one symbol - according to RFC 1951 section 3.2.7. To decoders incorrectly require two. To - make these work as well ensure there are at least two symbols. The - Package-Merge code below also doesn't work correctly if there's only one - symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/ - if(numpresent == 0) - { - lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/ - } - else if(numpresent == 1) - { - for(i = 0; i != numcodes; ++i) - { - if(frequencies[i]) - { - lengths[i] = 1; - lengths[i == 0 ? 1 : 0] = 1; - break; - } - } - } - else - { - /*Package-Merge algorithm represented by coin collector's problem - For every symbol, maxbitlen coins will be created*/ - - coinmem = numpresent * 2; /*max amount of coins needed with the current algo*/ - coins = (Coin*)lodepng_malloc(sizeof(Coin) * coinmem); - prev_row = (Coin*)lodepng_malloc(sizeof(Coin) * coinmem); - if(!coins || !prev_row) - { - lodepng_free(coins); - lodepng_free(prev_row); - return 83; /*alloc fail*/ - } - init_coins(coins, coinmem); - init_coins(prev_row, coinmem); - - /*first row, lowest denominator*/ - error = append_symbol_coins(coins, frequencies, numcodes, sum); - numcoins = numpresent; - qsort(coins, numcoins, sizeof(Coin), coin_compare); - if(!error) - { - unsigned numprev = 0; - for(j = 1; j <= maxbitlen && !error; ++j) /*each of the remaining rows*/ - { - unsigned tempnum; - Coin* tempcoins; - /*swap prev_row and coins, and their amounts*/ - tempcoins = prev_row; prev_row = coins; coins = tempcoins; - tempnum = numprev; numprev = numcoins; numcoins = tempnum; - - cleanup_coins(coins, numcoins); - init_coins(coins, numcoins); - - numcoins = 0; - - /*fill in the merged coins of the previous row*/ - for(i = 0; i + 1 < numprev; i += 2) - { - /*merge prev_row[i] and prev_row[i + 1] into new coin*/ - Coin* coin = &coins[numcoins++]; - coin_copy(coin, &prev_row[i]); - add_coins(coin, &prev_row[i + 1]); - } - /*fill in all the original symbols again*/ - if(j < maxbitlen) - { - error = append_symbol_coins(coins + numcoins, frequencies, numcodes, sum); - numcoins += numpresent; - } - qsort(coins, numcoins, sizeof(Coin), coin_compare); - } - } - - if(!error) - { - /*calculate the lengths of each symbol, as the amount of times a coin of each symbol is used*/ - for(i = 0; i + 1 < numpresent; ++i) - { - Coin* coin = &coins[i]; - for(j = 0; j < coin->symbols.size; ++j) ++lengths[coin->symbols.data[j]]; - } - } - - cleanup_coins(coins, coinmem); - lodepng_free(coins); - cleanup_coins(prev_row, coinmem); - lodepng_free(prev_row); - } - - return error; -} - -/*Create the Huffman tree given the symbol frequencies*/ -static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, - size_t mincodes, size_t numcodes, unsigned maxbitlen) -{ - unsigned error = 0; - while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/ - tree->maxbitlen = maxbitlen; - tree->numcodes = (unsigned)numcodes; /*number of symbols*/ - tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned)); - if(!tree->lengths) return 83; /*alloc fail*/ - /*initialize all lengths to 0*/ - memset(tree->lengths, 0, numcodes * sizeof(unsigned)); - - error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); - if(!error) error = HuffmanTree_makeFromLengths2(tree); - return error; -} - -static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) -{ - return tree->tree1d[index]; -} - -static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) -{ - return tree->lengths[index]; -} -#endif /*LODEPNG_COMPILE_ENCODER*/ - -/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/ -static unsigned generateFixedLitLenTree(HuffmanTree* tree) -{ - unsigned i, error = 0; - unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); - if(!bitlen) return 83; /*alloc fail*/ - - /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/ - for(i = 0; i <= 143; ++i) bitlen[i] = 8; - for(i = 144; i <= 255; ++i) bitlen[i] = 9; - for(i = 256; i <= 279; ++i) bitlen[i] = 7; - for(i = 280; i <= 287; ++i) bitlen[i] = 8; - - error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15); - - lodepng_free(bitlen); - return error; -} - -/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/ -static unsigned generateFixedDistanceTree(HuffmanTree* tree) -{ - unsigned i, error = 0; - unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); - if(!bitlen) return 83; /*alloc fail*/ - - /*there are 32 distance codes, but 30-31 are unused*/ - for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5; - error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15); - - lodepng_free(bitlen); - return error; -} - -#ifdef LODEPNG_COMPILE_DECODER - -/* -returns the code, or (unsigned)(-1) if error happened -inbitlength is the length of the complete buffer, in bits (so its byte length times 8) -*/ -static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp, - const HuffmanTree* codetree, size_t inbitlength) -{ - unsigned treepos = 0, ct; - for(;;) - { - if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/ - /* - decode the symbol from the tree. The "readBitFromStream" code is inlined in - the expression below because this is the biggest bottleneck while decoding - */ - ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)]; - ++(*bp); - if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/ - else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/ - - if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/ - } -} -#endif /*LODEPNG_COMPILE_DECODER*/ - -#ifdef LODEPNG_COMPILE_DECODER - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / Inflator (Decompressor) / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -/*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/ -static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) -{ - /*TODO: check for out of memory errors*/ - generateFixedLitLenTree(tree_ll); - generateFixedDistanceTree(tree_d); -} - -/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/ -static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, - const unsigned char* in, size_t* bp, size_t inlength) -{ - /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/ - unsigned error = 0; - unsigned n, HLIT, HDIST, HCLEN, i; - size_t inbitlength = inlength * 8; - - /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/ - unsigned* bitlen_ll = 0; /*lit,len code lengths*/ - unsigned* bitlen_d = 0; /*dist code lengths*/ - /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/ - unsigned* bitlen_cl = 0; - HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/ - - if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/ - - /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/ - HLIT = readBitsFromStream(bp, in, 5) + 257; - /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/ - HDIST = readBitsFromStream(bp, in, 5) + 1; - /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/ - HCLEN = readBitsFromStream(bp, in, 4) + 4; - - if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/ - - HuffmanTree_init(&tree_cl); - - while(!error) - { - /*read the code length codes out of 3 * (amount of code length codes) bits*/ - - bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); - if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/); - - for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i) - { - if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3); - else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/ - } - - error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7); - if(error) break; - - /*now we can use this tree to read the lengths for the tree that this function will return*/ - bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); - bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); - if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/); - for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0; - for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0; - - /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/ - i = 0; - while(i < HLIT + HDIST) - { - unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength); - if(code <= 15) /*a length code*/ - { - if(i < HLIT) bitlen_ll[i] = code; - else bitlen_d[i - HLIT] = code; - ++i; - } - else if(code == 16) /*repeat previous*/ - { - unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/ - unsigned value; /*set value to the previous code*/ - - if (i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/ - - if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ - replength += readBitsFromStream(bp, in, 2); - - if(i < HLIT + 1) value = bitlen_ll[i - 1]; - else value = bitlen_d[i - HLIT - 1]; - /*repeat this value in the next lengths*/ - for(n = 0; n < replength; ++n) - { - if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/ - if(i < HLIT) bitlen_ll[i] = value; - else bitlen_d[i - HLIT] = value; - ++i; - } - } - else if(code == 17) /*repeat "0" 3-10 times*/ - { - unsigned replength = 3; /*read in the bits that indicate repeat length*/ - if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ - replength += readBitsFromStream(bp, in, 3); - - /*repeat this value in the next lengths*/ - for(n = 0; n < replength; ++n) - { - if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/ - - if(i < HLIT) bitlen_ll[i] = 0; - else bitlen_d[i - HLIT] = 0; - ++i; - } - } - else if(code == 18) /*repeat "0" 11-138 times*/ - { - unsigned replength = 11; /*read in the bits that indicate repeat length*/ - if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ - replength += readBitsFromStream(bp, in, 7); - - /*repeat this value in the next lengths*/ - for(n = 0; n < replength; ++n) - { - if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/ - - if(i < HLIT) bitlen_ll[i] = 0; - else bitlen_d[i - HLIT] = 0; - ++i; - } - } - else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ - { - if(code == (unsigned)(-1)) - { - /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol - (10=no endcode, 11=wrong jump outside of tree)*/ - error = (*bp) > inbitlength ? 10 : 11; - } - else error = 16; /*unexisting code, this can never happen*/ - break; - } - } - if(error) break; - - if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/ - - /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/ - error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15); - if(error) break; - error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15); - - break; /*end of error-while*/ - } - - lodepng_free(bitlen_cl); - lodepng_free(bitlen_ll); - lodepng_free(bitlen_d); - HuffmanTree_cleanup(&tree_cl); - - return error; -} - -/*inflate a block with dynamic of fixed Huffman tree*/ -static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp, - size_t* pos, size_t inlength, unsigned btype) -{ - unsigned error = 0; - HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ - HuffmanTree tree_d; /*the huffman tree for distance codes*/ - size_t inbitlength = inlength * 8; - - HuffmanTree_init(&tree_ll); - HuffmanTree_init(&tree_d); - - if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d); - else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength); - - while(!error) /*decode all symbols until end reached, breaks at end code*/ - { - /*code_ll is literal, length or end code*/ - unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength); - if(code_ll <= 255) /*literal symbol*/ - { - /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/ - if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/); - out->data[*pos] = (unsigned char)code_ll; - ++(*pos); - } - else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ - { - unsigned code_d, distance; - unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/ - size_t start, forward, backward, length; - - /*part 1: get length base*/ - length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX]; - - /*part 2: get extra bits and add the value of that to length*/ - numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX]; - if((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ - length += readBitsFromStream(bp, in, numextrabits_l); - - /*part 3: get distance code*/ - code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength); - if(code_d > 29) - { - if(code_ll == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ - { - /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol - (10=no endcode, 11=wrong jump outside of tree)*/ - error = (*bp) > inlength * 8 ? 10 : 11; - } - else error = 18; /*error: invalid distance code (30-31 are never used)*/ - break; - } - distance = DISTANCEBASE[code_d]; - - /*part 4: get extra bits from distance*/ - numextrabits_d = DISTANCEEXTRA[code_d]; - if((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ - distance += readBitsFromStream(bp, in, numextrabits_d); - - /*part 5: fill in all the out[n] values based on the length and dist*/ - start = (*pos); - if(distance > start) ERROR_BREAK(52); /*too long backward distance*/ - backward = start - distance; - - if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/); - for(forward = 0; forward < length; ++forward) - { - out->data[(*pos)] = out->data[backward]; - ++(*pos); - ++backward; - if(backward >= start) backward = start - distance; - } - } - else if(code_ll == 256) - { - break; /*end code, break the loop*/ - } - else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ - { - /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol - (10=no endcode, 11=wrong jump outside of tree)*/ - error = ((*bp) > inlength * 8) ? 10 : 11; - break; - } - } - - HuffmanTree_cleanup(&tree_ll); - HuffmanTree_cleanup(&tree_d); - - return error; -} - -static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength) -{ - size_t p; - unsigned LEN, NLEN, n, error = 0; - - /*go to first boundary of byte*/ - while(((*bp) & 0x7) != 0) ++(*bp); - p = (*bp) / 8; /*byte position*/ - - /*read LEN (2 bytes) and NLEN (2 bytes)*/ - if(p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/ - LEN = in[p] + 256u * in[p + 1]; p += 2; - NLEN = in[p] + 256u * in[p + 1]; p += 2; - - /*check if 16-bit NLEN is really the one's complement of LEN*/ - if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/ - - if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/ - - /*read the literal data: LEN bytes are now stored in the out buffer*/ - if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/ - for(n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++]; - - (*bp) = p * 8; - - return error; -} - -static unsigned lodepng_inflatev(ucvector* out, - const unsigned char* in, size_t insize, - const LodePNGDecompressSettings* settings) -{ - /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/ - size_t bp = 0; - unsigned BFINAL = 0; - size_t pos = 0; /*byte position in the out buffer*/ - unsigned error = 0; - - (void)settings; - - while(!BFINAL) - { - unsigned BTYPE; - if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/ - BFINAL = readBitFromStream(&bp, in); - BTYPE = 1u * readBitFromStream(&bp, in); - BTYPE += 2u * readBitFromStream(&bp, in); - - if(BTYPE == 3) return 20; /*error: invalid BTYPE*/ - else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/ - else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/ - - if(error) return error; - } - - return error; -} - -unsigned lodepng_inflate(unsigned char** out, size_t* outsize, - const unsigned char* in, size_t insize, - const LodePNGDecompressSettings* settings) -{ - unsigned error; - ucvector v; - ucvector_init_buffer(&v, *out, *outsize); - error = lodepng_inflatev(&v, in, insize, settings); - *out = v.data; - *outsize = v.size; - return error; -} - -static unsigned inflate(unsigned char** out, size_t* outsize, - const unsigned char* in, size_t insize, - const LodePNGDecompressSettings* settings) -{ - if(settings->custom_inflate) - { - return settings->custom_inflate(out, outsize, in, insize, settings); - } - else - { - return lodepng_inflate(out, outsize, in, insize, settings); - } -} - -#endif /*LODEPNG_COMPILE_DECODER*/ - -#ifdef LODEPNG_COMPILE_ENCODER - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / Deflator (Compressor) / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258; - -/*bitlen is the size in bits of the code*/ -static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen) -{ - addBitsToStreamReversed(bp, compressed, code, bitlen); -} - -/*search the index in the array, that has the largest value smaller than or equal to the given value, -given array must be sorted (if no value is smaller, it returns the size of the given array)*/ -static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) -{ - /*linear search implementation*/ - /*for(size_t i = 1; i < array_size; ++i) if(array[i] > value) return i - 1; - return array_size - 1;*/ - - /*binary search implementation (not that much faster) (precondition: array_size > 0)*/ - size_t left = 1; - size_t right = array_size - 1; - while(left <= right) - { - size_t mid = (left + right) / 2; - if(array[mid] <= value) left = mid + 1; /*the value to find is more to the right*/ - else if(array[mid - 1] > value) right = mid - 1; /*the value to find is more to the left*/ - else return mid - 1; - } - return array_size - 1; -} - -static void addLengthDistance(uivector* values, size_t length, size_t distance) -{ - /*values in encoded vector are those used by deflate: - 0-255: literal bytes - 256: end - 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits) - 286-287: invalid*/ - - unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length); - unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]); - unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance); - unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]); - - uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX); - uivector_push_back(values, extra_length); - uivector_push_back(values, dist_code); - uivector_push_back(values, extra_distance); -} - -/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3 -bytes as input because 3 is the minimum match length for deflate*/ -static const unsigned HASH_NUM_VALUES = 65536; -static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/ - -typedef struct Hash -{ - int* head; /*hash value to head circular pos - can be outdated if went around window*/ - /*circular pos to prev circular pos*/ - unsigned short* chain; - int* val; /*circular pos to hash value*/ - - /*TODO: do this not only for zeros but for any repeated byte. However for PNG - it's always going to be the zeros that dominate, so not important for PNG*/ - int* headz; /*similar to head, but for chainz*/ - unsigned short* chainz; /*those with same amount of zeros*/ - unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/ -} Hash; - -static unsigned hash_init(Hash* hash, unsigned windowsize) -{ - unsigned i; - hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES); - hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize); - hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); - - hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); - hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1)); - hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); - - if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) - { - return 83; /*alloc fail*/ - } - - /*initialize hash table*/ - for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1; - for(i = 0; i != windowsize; ++i) hash->val[i] = -1; - for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/ - - for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1; - for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/ - - return 0; -} - -static void hash_cleanup(Hash* hash) -{ - lodepng_free(hash->head); - lodepng_free(hash->val); - lodepng_free(hash->chain); - - lodepng_free(hash->zeros); - lodepng_free(hash->headz); - lodepng_free(hash->chainz); -} - - - -static unsigned getHash(const unsigned char* data, size_t size, size_t pos) -{ - unsigned result = 0; - if (pos + 2 < size) - { - /*A simple shift and xor hash is used. Since the data of PNGs is dominated - by zeroes due to the filters, a better hash does not have a significant - effect on speed in traversing the chain, and causes more time spend on - calculating the hash.*/ - result ^= (unsigned)(data[pos + 0] << 0u); - result ^= (unsigned)(data[pos + 1] << 4u); - result ^= (unsigned)(data[pos + 2] << 8u); - } else { - size_t amount, i; - if(pos >= size) return 0; - amount = size - pos; - for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u)); - } - return result & HASH_BIT_MASK; -} - -static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) -{ - const unsigned char* start = data + pos; - const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH; - if(end > data + size) end = data + size; - data = start; - while (data != end && *data == 0) ++data; - /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/ - return (unsigned)(data - start); -} - -/*wpos = pos & (windowsize - 1)*/ -static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) -{ - hash->val[wpos] = (int)hashval; - if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; - hash->head[hashval] = wpos; - - hash->zeros[wpos] = numzeros; - if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; - hash->headz[numzeros] = wpos; -} - -/* -LZ77-encode the data. Return value is error code. The input are raw bytes, the output -is in the form of unsigned integers with codes representing for example literal bytes, or -length/distance pairs. -It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a -sliding window (of windowsize) is used, and all past bytes in that window can be used as -the "dictionary". A brute force search through all possible distances would be slow, and -this hash technique is one out of several ways to speed this up. -*/ -static unsigned encodeLZ77(uivector* out, Hash* hash, - const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize, - unsigned minmatch, unsigned nicematch, unsigned lazymatching) -{ - size_t pos; - unsigned i, error = 0; - /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/ - unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8; - unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64; - - unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/ - unsigned numzeros = 0; - - unsigned offset; /*the offset represents the distance in LZ77 terminology*/ - unsigned length; - unsigned lazy = 0; - unsigned lazylength = 0, lazyoffset = 0; - unsigned hashval; - unsigned current_offset, current_length; - unsigned prev_offset; - const unsigned char *lastptr, *foreptr, *backptr; - unsigned hashpos; - - if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/ - if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/ - - if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH; - - for(pos = inpos; pos < insize; ++pos) - { - size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/ - unsigned chainlength = 0; - - hashval = getHash(in, insize, pos); - - if(usezeros && hashval == 0) - { - if (numzeros == 0) numzeros = countZeros(in, insize, pos); - else if (pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; - } - else - { - numzeros = 0; - } - - updateHashChain(hash, wpos, hashval, numzeros); - - /*the length and offset found for the current position*/ - length = 0; - offset = 0; - - hashpos = hash->chain[wpos]; - - lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH]; - - /*search for the longest string*/ - prev_offset = 0; - for(;;) - { - if(chainlength++ >= maxchainlength) break; - current_offset = hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize; - - if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ - prev_offset = current_offset; - if(current_offset > 0) - { - /*test the next characters*/ - foreptr = &in[pos]; - backptr = &in[pos - current_offset]; - - /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/ - if(numzeros >= 3) - { - unsigned skip = hash->zeros[hashpos]; - if(skip > numzeros) skip = numzeros; - backptr += skip; - foreptr += skip; - } - - while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ - { - ++backptr; - ++foreptr; - } - current_length = (unsigned)(foreptr - &in[pos]); - - if(current_length > length) - { - length = current_length; /*the longest length*/ - offset = current_offset; /*the offset that is related to this longest length*/ - /*jump out once a length of max length is found (speed gain). This also jumps - out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/ - if(current_length >= nicematch) break; - } - } - - if(hashpos == hash->chain[hashpos]) break; - - if(numzeros >= 3 && length > numzeros) { - hashpos = hash->chainz[hashpos]; - if(hash->zeros[hashpos] != numzeros) break; - } else { - hashpos = hash->chain[hashpos]; - /*outdated hash value, happens if particular value was not encountered in whole last window*/ - if(hash->val[hashpos] != (int)hashval) break; - } - } - - if(lazymatching) - { - if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) - { - lazy = 1; - lazylength = length; - lazyoffset = offset; - continue; /*try the next byte*/ - } - if(lazy) - { - lazy = 0; - if(pos == 0) ERROR_BREAK(81); - if(length > lazylength + 1) - { - /*push the previous character as literal*/ - if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/); - } - else - { - length = lazylength; - offset = lazyoffset; - hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/ - hash->headz[numzeros] = -1; /*idem*/ - --pos; - } - } - } - if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/); - - /*encode it as length/distance pair or literal value*/ - if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ - { - if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); - } - else if(length < minmatch || (length == 3 && offset > 4096)) - { - /*compensate for the fact that longer offsets have more extra bits, a - length of only 3 may be not worth it then*/ - if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); - } - else - { - addLengthDistance(out, length, offset); - for(i = 1; i < length; ++i) - { - ++pos; - wpos = pos & (windowsize - 1); - hashval = getHash(in, insize, pos); - if(usezeros && hashval == 0) - { - if (numzeros == 0) numzeros = countZeros(in, insize, pos); - else if (pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; - } - else - { - numzeros = 0; - } - updateHashChain(hash, wpos, hashval, numzeros); - } - } - } /*end of the loop through each character of input*/ - - return error; -} - -/* /////////////////////////////////////////////////////////////////////////// */ - -static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) -{ - /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte, - 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/ - - size_t i, j, numdeflateblocks = (datasize + 65534) / 65535; - unsigned datapos = 0; - for(i = 0; i != numdeflateblocks; ++i) - { - unsigned BFINAL, BTYPE, LEN, NLEN; - unsigned char firstbyte; - - BFINAL = (i == numdeflateblocks - 1); - BTYPE = 0; - - firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1)); - ucvector_push_back(out, firstbyte); - - LEN = 65535; - if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos; - NLEN = 65535 - LEN; - - ucvector_push_back(out, (unsigned char)(LEN % 256)); - ucvector_push_back(out, (unsigned char)(LEN / 256)); - ucvector_push_back(out, (unsigned char)(NLEN % 256)); - ucvector_push_back(out, (unsigned char)(NLEN / 256)); - - /*Decompressed data*/ - for(j = 0; j < 65535 && datapos < datasize; ++j) - { - ucvector_push_back(out, data[datapos++]); - } - } - - return 0; -} - -/* -write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees. -tree_ll: the tree for lit and len codes. -tree_d: the tree for distance codes. -*/ -static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded, - const HuffmanTree* tree_ll, const HuffmanTree* tree_d) -{ - size_t i = 0; - for(i = 0; i != lz77_encoded->size; ++i) - { - unsigned val = lz77_encoded->data[i]; - addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val)); - if(val > 256) /*for a length code, 3 more things have to be added*/ - { - unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; - unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; - unsigned length_extra_bits = lz77_encoded->data[++i]; - - unsigned distance_code = lz77_encoded->data[++i]; - - unsigned distance_index = distance_code; - unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; - unsigned distance_extra_bits = lz77_encoded->data[++i]; - - addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits); - addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code), - HuffmanTree_getLength(tree_d, distance_code)); - addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits); - } - } -} - -/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/ -static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, - const unsigned char* data, size_t datapos, size_t dataend, - const LodePNGCompressSettings* settings, unsigned final) -{ - unsigned error = 0; - - /* - A block is compressed as follows: The PNG data is lz77 encoded, resulting in - literal bytes and length/distance pairs. This is then huffman compressed with - two huffman trees. One huffman tree is used for the lit and len values ("ll"), - another huffman tree is used for the dist values ("d"). These two trees are - stored using their code lengths, and to compress even more these code lengths - are also run-length encoded and huffman compressed. This gives a huffman tree - of code lengths "cl". The code lenghts used to describe this third tree are - the code length code lengths ("clcl"). - */ - - /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/ - uivector lz77_encoded; - HuffmanTree tree_ll; /*tree for lit,len values*/ - HuffmanTree tree_d; /*tree for distance codes*/ - HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/ - uivector frequencies_ll; /*frequency of lit,len codes*/ - uivector frequencies_d; /*frequency of dist codes*/ - uivector frequencies_cl; /*frequency of code length codes*/ - uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/ - uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/ - /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl - (these are written as is in the file, it would be crazy to compress these using yet another huffman - tree that needs to be represented by yet another set of code lengths)*/ - uivector bitlen_cl; - size_t datasize = dataend - datapos; - - /* - Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies: - bitlen_lld is to tree_cl what data is to tree_ll and tree_d. - bitlen_lld_e is to bitlen_lld what lz77_encoded is to data. - bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded. - */ - - unsigned BFINAL = final; - size_t numcodes_ll, numcodes_d, i; - unsigned HLIT, HDIST, HCLEN; - - uivector_init(&lz77_encoded); - HuffmanTree_init(&tree_ll); - HuffmanTree_init(&tree_d); - HuffmanTree_init(&tree_cl); - uivector_init(&frequencies_ll); - uivector_init(&frequencies_d); - uivector_init(&frequencies_cl); - uivector_init(&bitlen_lld); - uivector_init(&bitlen_lld_e); - uivector_init(&bitlen_cl); - - /*This while loop never loops due to a break at the end, it is here to - allow breaking out of it to the cleanup phase on error conditions.*/ - while(!error) - { - if(settings->use_lz77) - { - error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, - settings->minmatch, settings->nicematch, settings->lazymatching); - if(error) break; - } - else - { - if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/); - for(i = datapos; i < dataend; ++i) lz77_encoded.data[i] = data[i]; /*no LZ77, but still will be Huffman compressed*/ - } - - if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/); - if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/); - - /*Count the frequencies of lit, len and dist codes*/ - for(i = 0; i != lz77_encoded.size; ++i) - { - unsigned symbol = lz77_encoded.data[i]; - ++frequencies_ll.data[symbol]; - if(symbol > 256) - { - unsigned dist = lz77_encoded.data[i + 2]; - ++frequencies_d.data[dist]; - i += 3; - } - } - frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/ - - /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/ - error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15); - if(error) break; - /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/ - error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15); - if(error) break; - - numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286; - numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30; - /*store the code lengths of both generated trees in bitlen_lld*/ - for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i)); - for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i)); - - /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times), - 17 (3-10 zeroes), 18 (11-138 zeroes)*/ - for(i = 0; i != (unsigned)bitlen_lld.size; ++i) - { - unsigned j = 0; /*amount of repititions*/ - while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j; - - if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ - { - ++j; /*include the first zero*/ - if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ - { - uivector_push_back(&bitlen_lld_e, 17); - uivector_push_back(&bitlen_lld_e, j - 3); - } - else /*repeat code 18 supports max 138 zeroes*/ - { - if(j > 138) j = 138; - uivector_push_back(&bitlen_lld_e, 18); - uivector_push_back(&bitlen_lld_e, j - 11); - } - i += (j - 1); - } - else if(j >= 3) /*repeat code for value other than zero*/ - { - size_t k; - unsigned num = j / 6, rest = j % 6; - uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); - for(k = 0; k < num; ++k) - { - uivector_push_back(&bitlen_lld_e, 16); - uivector_push_back(&bitlen_lld_e, 6 - 3); - } - if(rest >= 3) - { - uivector_push_back(&bitlen_lld_e, 16); - uivector_push_back(&bitlen_lld_e, rest - 3); - } - else j -= rest; - i += j; - } - else /*too short to benefit from repeat code*/ - { - uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); - } - } - - /*generate tree_cl, the huffmantree of huffmantrees*/ - - if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/); - for(i = 0; i != bitlen_lld_e.size; ++i) - { - ++frequencies_cl.data[bitlen_lld_e.data[i]]; - /*after a repeat code come the bits that specify the number of repetitions, - those don't need to be in the frequencies_cl calculation*/ - if(bitlen_lld_e.data[i] >= 16) ++i; - } - - error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data, - frequencies_cl.size, frequencies_cl.size, 7); - if(error) break; - - if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/); - for(i = 0; i != tree_cl.numcodes; ++i) - { - /*lenghts of code length tree is in the order as specified by deflate*/ - bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]); - } - while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) - { - /*remove zeros at the end, but minimum size must be 4*/ - if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/); - } - if(error) break; - - /* - Write everything into the output - - After the BFINAL and BTYPE, the dynamic block consists out of the following: - - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN - - (HCLEN+4)*3 bits code lengths of code length alphabet - - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length - alphabet, + possible repetition codes 16, 17, 18) - - HDIST + 1 code lengths of distance alphabet (encoded using the code length - alphabet, + possible repetition codes 16, 17, 18) - - compressed data - - 256 (end code) - */ - - /*Write block type*/ - addBitToStream(bp, out, BFINAL); - addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/ - addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/ - - /*write the HLIT, HDIST and HCLEN values*/ - HLIT = (unsigned)(numcodes_ll - 257); - HDIST = (unsigned)(numcodes_d - 1); - HCLEN = (unsigned)bitlen_cl.size - 4; - /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/ - while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN; - addBitsToStream(bp, out, HLIT, 5); - addBitsToStream(bp, out, HDIST, 5); - addBitsToStream(bp, out, HCLEN, 4); - - /*write the code lenghts of the code length alphabet*/ - for(i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3); - - /*write the lenghts of the lit/len AND the dist alphabet*/ - for(i = 0; i != bitlen_lld_e.size; ++i) - { - addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]), - HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i])); - /*extra bits of repeat codes*/ - if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2); - else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3); - else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7); - } - - /*write the compressed data symbols*/ - writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); - /*error: the length of the end code 256 must be larger than 0*/ - if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64); - - /*write the end code*/ - addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); - - break; /*end of error-while*/ - } - - /*cleanup*/ - uivector_cleanup(&lz77_encoded); - HuffmanTree_cleanup(&tree_ll); - HuffmanTree_cleanup(&tree_d); - HuffmanTree_cleanup(&tree_cl); - uivector_cleanup(&frequencies_ll); - uivector_cleanup(&frequencies_d); - uivector_cleanup(&frequencies_cl); - uivector_cleanup(&bitlen_lld_e); - uivector_cleanup(&bitlen_lld); - uivector_cleanup(&bitlen_cl); - - return error; -} - -static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash, - const unsigned char* data, - size_t datapos, size_t dataend, - const LodePNGCompressSettings* settings, unsigned final) -{ - HuffmanTree tree_ll; /*tree for literal values and length codes*/ - HuffmanTree tree_d; /*tree for distance codes*/ - - unsigned BFINAL = final; - unsigned error = 0; - size_t i; - - HuffmanTree_init(&tree_ll); - HuffmanTree_init(&tree_d); - - generateFixedLitLenTree(&tree_ll); - generateFixedDistanceTree(&tree_d); - - addBitToStream(bp, out, BFINAL); - addBitToStream(bp, out, 1); /*first bit of BTYPE*/ - addBitToStream(bp, out, 0); /*second bit of BTYPE*/ - - if(settings->use_lz77) /*LZ77 encoded*/ - { - uivector lz77_encoded; - uivector_init(&lz77_encoded); - error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, - settings->minmatch, settings->nicematch, settings->lazymatching); - if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); - uivector_cleanup(&lz77_encoded); - } - else /*no LZ77, but still will be Huffman compressed*/ - { - for(i = datapos; i < dataend; ++i) - { - addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i])); - } - } - /*add END code*/ - if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); - - /*cleanup*/ - HuffmanTree_cleanup(&tree_ll); - HuffmanTree_cleanup(&tree_d); - - return error; -} - -static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize, - const LodePNGCompressSettings* settings) -{ - unsigned error = 0; - size_t i, blocksize, numdeflateblocks; - size_t bp = 0; /*the bit pointer*/ - Hash hash; - - if(settings->btype > 2) return 61; - else if(settings->btype == 0) return deflateNoCompression(out, in, insize); - else if(settings->btype == 1) blocksize = insize; - else /*if(settings->btype == 2)*/ - { - blocksize = insize / 8 + 8; - if(blocksize < 65535) blocksize = 65535; - } - - numdeflateblocks = (insize + blocksize - 1) / blocksize; - if(numdeflateblocks == 0) numdeflateblocks = 1; - - error = hash_init(&hash, settings->windowsize); - if(error) return error; - - for(i = 0; i != numdeflateblocks && !error; ++i) - { - unsigned final = (i == numdeflateblocks - 1); - size_t start = i * blocksize; - size_t end = start + blocksize; - if(end > insize) end = insize; - - if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final); - else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final); - } - - hash_cleanup(&hash); - - return error; -} - -unsigned lodepng_deflate(unsigned char** out, size_t* outsize, - const unsigned char* in, size_t insize, - const LodePNGCompressSettings* settings) -{ - unsigned error; - ucvector v; - ucvector_init_buffer(&v, *out, *outsize); - error = lodepng_deflatev(&v, in, insize, settings); - *out = v.data; - *outsize = v.size; - return error; -} - -static unsigned deflate(unsigned char** out, size_t* outsize, - const unsigned char* in, size_t insize, - const LodePNGCompressSettings* settings) -{ - if(settings->custom_deflate) - { - return settings->custom_deflate(out, outsize, in, insize, settings); - } - else - { - return lodepng_deflate(out, outsize, in, insize, settings); - } -} - -#endif /*LODEPNG_COMPILE_DECODER*/ - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / Adler32 */ -/* ////////////////////////////////////////////////////////////////////////// */ - -static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) -{ - unsigned s1 = adler & 0xffff; - unsigned s2 = (adler >> 16) & 0xffff; - - while(len > 0) - { - /*at least 5550 sums can be done before the sums overflow, saving a lot of module divisions*/ - unsigned amount = len > 5550 ? 5550 : len; - len -= amount; - while(amount > 0) - { - s1 += (*data++); - s2 += s1; - --amount; - } - s1 %= 65521; - s2 %= 65521; - } - - return (s2 << 16) | s1; -} - -/*Return the adler32 of the bytes data[0..len-1]*/ -static unsigned adler32(const unsigned char* data, unsigned len) -{ - return update_adler32(1L, data, len); -} - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / Zlib / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -#ifdef LODEPNG_COMPILE_DECODER - -unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGDecompressSettings* settings) -{ - unsigned error = 0; - unsigned CM, CINFO, FDICT; - - if(insize < 2) return 53; /*error, size of zlib data too small*/ - /*read information from zlib header*/ - if((in[0] * 256 + in[1]) % 31 != 0) - { - /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/ - return 24; - } - - CM = in[0] & 15; - CINFO = (in[0] >> 4) & 15; - /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/ - FDICT = (in[1] >> 5) & 1; - /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/ - - if(CM != 8 || CINFO > 7) - { - /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/ - return 25; - } - if(FDICT != 0) - { - /*error: the specification of PNG says about the zlib stream: - "The additional flags shall not specify a preset dictionary."*/ - return 26; - } - - error = inflate(out, outsize, in + 2, insize - 2, settings); - if(error) return error; - - if(!settings->ignore_adler32) - { - unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); - unsigned checksum = adler32(*out, (unsigned)(*outsize)); - if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ - } - - return 0; /*no error*/ -} - -static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGDecompressSettings* settings) -{ - if(settings->custom_zlib) - { - return settings->custom_zlib(out, outsize, in, insize, settings); - } - else - { - return lodepng_zlib_decompress(out, outsize, in, insize, settings); - } -} - -#endif /*LODEPNG_COMPILE_DECODER*/ - -#ifdef LODEPNG_COMPILE_ENCODER - -unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGCompressSettings* settings) -{ - /*initially, *out must be NULL and outsize 0, if you just give some random *out - that's pointing to a non allocated buffer, this'll crash*/ - ucvector outv; - size_t i; - unsigned error; - unsigned char* deflatedata = 0; - size_t deflatesize = 0; - - /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/ - unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/ - unsigned FLEVEL = 0; - unsigned FDICT = 0; - unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64; - unsigned FCHECK = 31 - CMFFLG % 31; - CMFFLG += FCHECK; - - /*ucvector-controlled version of the output buffer, for dynamic array*/ - ucvector_init_buffer(&outv, *out, *outsize); - - ucvector_push_back(&outv, (unsigned char)(CMFFLG / 256)); - ucvector_push_back(&outv, (unsigned char)(CMFFLG % 256)); - - error = deflate(&deflatedata, &deflatesize, in, insize, settings); - - if(!error) - { - unsigned ADLER32 = adler32(in, (unsigned)insize); - for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]); - lodepng_free(deflatedata); - lodepng_add32bitInt(&outv, ADLER32); - } - - *out = outv.data; - *outsize = outv.size; - - return error; -} - -/* compress using the default or custom zlib function */ -static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGCompressSettings* settings) -{ - if(settings->custom_zlib) - { - return settings->custom_zlib(out, outsize, in, insize, settings); - } - else - { - return lodepng_zlib_compress(out, outsize, in, insize, settings); - } -} - -#endif /*LODEPNG_COMPILE_ENCODER*/ - -#else /*no LODEPNG_COMPILE_ZLIB*/ - -#ifdef LODEPNG_COMPILE_DECODER -static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGDecompressSettings* settings) -{ - if (!settings->custom_zlib) return 87; /*no custom zlib function provided */ - return settings->custom_zlib(out, outsize, in, insize, settings); -} -#endif /*LODEPNG_COMPILE_DECODER*/ -#ifdef LODEPNG_COMPILE_ENCODER -static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGCompressSettings* settings) -{ - if (!settings->custom_zlib) return 87; /*no custom zlib function provided */ - return settings->custom_zlib(out, outsize, in, insize, settings); -} -#endif /*LODEPNG_COMPILE_ENCODER*/ - -#endif /*LODEPNG_COMPILE_ZLIB*/ - -/* ////////////////////////////////////////////////////////////////////////// */ - -#ifdef LODEPNG_COMPILE_ENCODER - -/*this is a good tradeoff between speed and compression ratio*/ -#define DEFAULT_WINDOWSIZE 2048 - -void lodepng_compress_settings_init(LodePNGCompressSettings* settings) -{ - /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/ - settings->btype = 2; - settings->use_lz77 = 1; - settings->windowsize = DEFAULT_WINDOWSIZE; - settings->minmatch = 3; - settings->nicematch = 128; - settings->lazymatching = 1; - - settings->custom_zlib = 0; - settings->custom_deflate = 0; - settings->custom_context = 0; -} - -const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0}; - - -#endif /*LODEPNG_COMPILE_ENCODER*/ - -#ifdef LODEPNG_COMPILE_DECODER - -void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) -{ - settings->ignore_adler32 = 0; - - settings->custom_zlib = 0; - settings->custom_inflate = 0; - settings->custom_context = 0; -} - -const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0}; - -#endif /*LODEPNG_COMPILE_DECODER*/ - -/* ////////////////////////////////////////////////////////////////////////// */ -/* ////////////////////////////////////////////////////////////////////////// */ -/* // End of Zlib related code. Begin of PNG related code. // */ -/* ////////////////////////////////////////////////////////////////////////// */ -/* ////////////////////////////////////////////////////////////////////////// */ - -#ifdef LODEPNG_COMPILE_PNG - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / CRC32 / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -/* CRC polynomial: 0xedb88320 */ -static unsigned lodepng_crc32_table[256] = { - 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, - 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, - 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u, - 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u, - 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u, - 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, - 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, - 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u, - 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u, - 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u, - 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, - 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, - 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u, - 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u, - 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u, - 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, - 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, - 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u, - 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u, - 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u, - 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, - 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, - 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u, - 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u, - 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u, - 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, - 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, - 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u, - 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u, - 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u, - 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, - 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u -}; - -/*Return the CRC of the bytes buf[0..len-1].*/ -unsigned lodepng_crc32(const unsigned char* buf, size_t len) -{ - unsigned c = 0xffffffffL; - size_t n; - - for(n = 0; n < len; ++n) - { - c = lodepng_crc32_table[(c ^ buf[n]) & 0xff] ^ (c >> 8); - } - return c ^ 0xffffffffL; -} - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / Reading and writing single bits and bytes from/to stream for LodePNG / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) -{ - unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1); - ++(*bitpointer); - return result; -} - -static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) -{ - unsigned result = 0; - size_t i; - for(i = nbits - 1; i < nbits; --i) - { - result += (unsigned)readBitFromReversedStream(bitpointer, bitstream) << i; - } - return result; -} - -#ifdef LODEPNG_COMPILE_DECODER -static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) -{ - /*the current bit in bitstream must be 0 for this to work*/ - if(bit) - { - /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/ - bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7))); - } - ++(*bitpointer); -} -#endif /*LODEPNG_COMPILE_DECODER*/ - -static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) -{ - /*the current bit in bitstream may be 0 or 1 for this to work*/ - if(bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7)))); - else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7))); - ++(*bitpointer); -} - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / PNG chunks / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -unsigned lodepng_chunk_length(const unsigned char* chunk) -{ - return lodepng_read32bitInt(&chunk[0]); -} - -void lodepng_chunk_type(char type[5], const unsigned char* chunk) -{ - unsigned i; - for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i]; - type[4] = 0; /*null termination char*/ -} - -unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) -{ - if(strlen(type) != 4) return 0; - return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]); -} - -unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) -{ - return((chunk[4] & 32) != 0); -} - -unsigned char lodepng_chunk_private(const unsigned char* chunk) -{ - return((chunk[6] & 32) != 0); -} - -unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) -{ - return((chunk[7] & 32) != 0); -} - -unsigned char* lodepng_chunk_data(unsigned char* chunk) -{ - return &chunk[8]; -} - -const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) -{ - return &chunk[8]; -} - -unsigned lodepng_chunk_check_crc(const unsigned char* chunk) -{ - unsigned length = lodepng_chunk_length(chunk); - unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]); - /*the CRC is taken of the data and the 4 chunk type letters, not the length*/ - unsigned checksum = lodepng_crc32(&chunk[4], length + 4); - if(CRC != checksum) return 1; - else return 0; -} - -void lodepng_chunk_generate_crc(unsigned char* chunk) -{ - unsigned length = lodepng_chunk_length(chunk); - unsigned CRC = lodepng_crc32(&chunk[4], length + 4); - lodepng_set32bitInt(chunk + 8 + length, CRC); -} - -unsigned char* lodepng_chunk_next(unsigned char* chunk) -{ - unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; - return &chunk[total_chunk_length]; -} - -const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) -{ - unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; - return &chunk[total_chunk_length]; -} - -unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) -{ - unsigned i; - unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; - unsigned char *chunk_start, *new_buffer; - size_t new_length = (*outlength) + total_chunk_length; - if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/ - - new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); - if(!new_buffer) return 83; /*alloc fail*/ - (*out) = new_buffer; - (*outlength) = new_length; - chunk_start = &(*out)[new_length - total_chunk_length]; - - for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i]; - - return 0; -} - -unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, - const char* type, const unsigned char* data) -{ - unsigned i; - unsigned char *chunk, *new_buffer; - size_t new_length = (*outlength) + length + 12; - if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/ - new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); - if(!new_buffer) return 83; /*alloc fail*/ - (*out) = new_buffer; - (*outlength) = new_length; - chunk = &(*out)[(*outlength) - length - 12]; - - /*1: length*/ - lodepng_set32bitInt(chunk, (unsigned)length); - - /*2: chunk name (4 letters)*/ - chunk[4] = (unsigned char)type[0]; - chunk[5] = (unsigned char)type[1]; - chunk[6] = (unsigned char)type[2]; - chunk[7] = (unsigned char)type[3]; - - /*3: the data*/ - for(i = 0; i != length; ++i) chunk[8 + i] = data[i]; - - /*4: CRC (of the chunkname characters and the data)*/ - lodepng_chunk_generate_crc(chunk); - - return 0; -} - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / Color types and such / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -/*return type is a LodePNG error code*/ -static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/ -{ - switch(colortype) - { - case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/ - case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/ - case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/ - case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/ - case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/ - default: return 31; - } - return 0; /*allowed color type / bits combination*/ -} - -static unsigned getNumColorChannels(LodePNGColorType colortype) -{ - switch(colortype) - { - case 0: return 1; /*grey*/ - case 2: return 3; /*RGB*/ - case 3: return 1; /*palette*/ - case 4: return 2; /*grey + alpha*/ - case 6: return 4; /*RGBA*/ - } - return 0; /*unexisting color type*/ -} - -static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) -{ - /*bits per pixel is amount of channels * bits per channel*/ - return getNumColorChannels(colortype) * bitdepth; -} - -/* ////////////////////////////////////////////////////////////////////////// */ - -void lodepng_color_mode_init(LodePNGColorMode* info) -{ - info->key_defined = 0; - info->key_r = info->key_g = info->key_b = 0; - info->colortype = LCT_RGBA; - info->bitdepth = 8; - info->palette = 0; - info->palettesize = 0; -} - -void lodepng_color_mode_cleanup(LodePNGColorMode* info) -{ - lodepng_palette_clear(info); -} - -unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) -{ - size_t i; - lodepng_color_mode_cleanup(dest); - *dest = *source; - if(source->palette) - { - dest->palette = (unsigned char*)lodepng_malloc(1024); - if(!dest->palette && source->palettesize) return 83; /*alloc fail*/ - for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i]; - } - return 0; -} - -static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) -{ - size_t i; - if(a->colortype != b->colortype) return 0; - if(a->bitdepth != b->bitdepth) return 0; - if(a->key_defined != b->key_defined) return 0; - if(a->key_defined) - { - if(a->key_r != b->key_r) return 0; - if(a->key_g != b->key_g) return 0; - if(a->key_b != b->key_b) return 0; - } - if(a->palettesize != b->palettesize) return 0; - for(i = 0; i != a->palettesize * 4; ++i) - { - if(a->palette[i] != b->palette[i]) return 0; - } - return 1; -} - -void lodepng_palette_clear(LodePNGColorMode* info) -{ - if(info->palette) lodepng_free(info->palette); - info->palette = 0; - info->palettesize = 0; -} - -unsigned lodepng_palette_add(LodePNGColorMode* info, - unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ - unsigned char* data; - /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with - the max of 256 colors, it'll have the exact alloc size*/ - if(!info->palette) /*allocate palette if empty*/ - { - /*room for 256 colors with 4 bytes each*/ - data = (unsigned char*)lodepng_realloc(info->palette, 1024); - if(!data) return 83; /*alloc fail*/ - else info->palette = data; - } - info->palette[4 * info->palettesize + 0] = r; - info->palette[4 * info->palettesize + 1] = g; - info->palette[4 * info->palettesize + 2] = b; - info->palette[4 * info->palettesize + 3] = a; - ++info->palettesize; - return 0; -} - -unsigned lodepng_get_bpp(const LodePNGColorMode* info) -{ - /*calculate bits per pixel out of colortype and bitdepth*/ - return lodepng_get_bpp_lct(info->colortype, info->bitdepth); -} - -unsigned lodepng_get_channels(const LodePNGColorMode* info) -{ - return getNumColorChannels(info->colortype); -} - -unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) -{ - return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA; -} - -unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) -{ - return (info->colortype & 4) != 0; /*4 or 6*/ -} - -unsigned lodepng_is_palette_type(const LodePNGColorMode* info) -{ - return info->colortype == LCT_PALETTE; -} - -unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) -{ - size_t i; - for(i = 0; i != info->palettesize; ++i) - { - if(info->palette[i * 4 + 3] < 255) return 1; - } - return 0; -} - -unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) -{ - return info->key_defined - || lodepng_is_alpha_type(info) - || lodepng_has_palette_alpha(info); -} - -size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) -{ - return (w * h * lodepng_get_bpp(color) + 7) / 8; -} - -size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) -{ - return (w * h * lodepng_get_bpp_lct(colortype, bitdepth) + 7) / 8; -} - - -#ifdef LODEPNG_COMPILE_PNG -#ifdef LODEPNG_COMPILE_DECODER -/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer*/ -static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) -{ - return h * ((w * lodepng_get_bpp(color) + 7) / 8); -} -#endif /*LODEPNG_COMPILE_DECODER*/ -#endif /*LODEPNG_COMPILE_PNG*/ - -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - -static void LodePNGUnknownChunks_init(LodePNGInfo* info) -{ - unsigned i; - for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0; - for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0; -} - -static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) -{ - unsigned i; - for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]); -} - -static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) -{ - unsigned i; - - LodePNGUnknownChunks_cleanup(dest); - - for(i = 0; i != 3; ++i) - { - size_t j; - dest->unknown_chunks_size[i] = src->unknown_chunks_size[i]; - dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]); - if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/ - for(j = 0; j < src->unknown_chunks_size[i]; ++j) - { - dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j]; - } - } - - return 0; -} - -/******************************************************************************/ - -static void LodePNGText_init(LodePNGInfo* info) -{ - info->text_num = 0; - info->text_keys = NULL; - info->text_strings = NULL; -} - -static void LodePNGText_cleanup(LodePNGInfo* info) -{ - size_t i; - for(i = 0; i != info->text_num; ++i) - { - string_cleanup(&info->text_keys[i]); - string_cleanup(&info->text_strings[i]); - } - lodepng_free(info->text_keys); - lodepng_free(info->text_strings); -} - -static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) -{ - size_t i = 0; - dest->text_keys = 0; - dest->text_strings = 0; - dest->text_num = 0; - for(i = 0; i != source->text_num; ++i) - { - CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i])); - } - return 0; -} - -void lodepng_clear_text(LodePNGInfo* info) -{ - LodePNGText_cleanup(info); -} - -unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) -{ - char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1))); - char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1))); - if(!new_keys || !new_strings) - { - lodepng_free(new_keys); - lodepng_free(new_strings); - return 83; /*alloc fail*/ - } - - ++info->text_num; - info->text_keys = new_keys; - info->text_strings = new_strings; - - string_init(&info->text_keys[info->text_num - 1]); - string_set(&info->text_keys[info->text_num - 1], key); - - string_init(&info->text_strings[info->text_num - 1]); - string_set(&info->text_strings[info->text_num - 1], str); - - return 0; -} - -/******************************************************************************/ - -static void LodePNGIText_init(LodePNGInfo* info) -{ - info->itext_num = 0; - info->itext_keys = NULL; - info->itext_langtags = NULL; - info->itext_transkeys = NULL; - info->itext_strings = NULL; -} - -static void LodePNGIText_cleanup(LodePNGInfo* info) -{ - size_t i; - for(i = 0; i != info->itext_num; ++i) - { - string_cleanup(&info->itext_keys[i]); - string_cleanup(&info->itext_langtags[i]); - string_cleanup(&info->itext_transkeys[i]); - string_cleanup(&info->itext_strings[i]); - } - lodepng_free(info->itext_keys); - lodepng_free(info->itext_langtags); - lodepng_free(info->itext_transkeys); - lodepng_free(info->itext_strings); -} - -static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) -{ - size_t i = 0; - dest->itext_keys = 0; - dest->itext_langtags = 0; - dest->itext_transkeys = 0; - dest->itext_strings = 0; - dest->itext_num = 0; - for(i = 0; i != source->itext_num; ++i) - { - CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i], - source->itext_transkeys[i], source->itext_strings[i])); - } - return 0; -} - -void lodepng_clear_itext(LodePNGInfo* info) -{ - LodePNGIText_cleanup(info); -} - -unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, - const char* transkey, const char* str) -{ - char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1))); - char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1))); - char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1))); - char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1))); - if(!new_keys || !new_langtags || !new_transkeys || !new_strings) - { - lodepng_free(new_keys); - lodepng_free(new_langtags); - lodepng_free(new_transkeys); - lodepng_free(new_strings); - return 83; /*alloc fail*/ - } - - ++info->itext_num; - info->itext_keys = new_keys; - info->itext_langtags = new_langtags; - info->itext_transkeys = new_transkeys; - info->itext_strings = new_strings; - - string_init(&info->itext_keys[info->itext_num - 1]); - string_set(&info->itext_keys[info->itext_num - 1], key); - - string_init(&info->itext_langtags[info->itext_num - 1]); - string_set(&info->itext_langtags[info->itext_num - 1], langtag); - - string_init(&info->itext_transkeys[info->itext_num - 1]); - string_set(&info->itext_transkeys[info->itext_num - 1], transkey); - - string_init(&info->itext_strings[info->itext_num - 1]); - string_set(&info->itext_strings[info->itext_num - 1], str); - - return 0; -} -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - -void lodepng_info_init(LodePNGInfo* info) -{ - lodepng_color_mode_init(&info->color); - info->interlace_method = 0; - info->compression_method = 0; - info->filter_method = 0; -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - info->background_defined = 0; - info->background_r = info->background_g = info->background_b = 0; - - LodePNGText_init(info); - LodePNGIText_init(info); - - info->time_defined = 0; - info->phys_defined = 0; - - LodePNGUnknownChunks_init(info); -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ -} - -void lodepng_info_cleanup(LodePNGInfo* info) -{ - lodepng_color_mode_cleanup(&info->color); -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - LodePNGText_cleanup(info); - LodePNGIText_cleanup(info); - - LodePNGUnknownChunks_cleanup(info); -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ -} - -unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) -{ - lodepng_info_cleanup(dest); - *dest = *source; - lodepng_color_mode_init(&dest->color); - CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color)); - -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - CERROR_TRY_RETURN(LodePNGText_copy(dest, source)); - CERROR_TRY_RETURN(LodePNGIText_copy(dest, source)); - - LodePNGUnknownChunks_init(dest); - CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source)); -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - return 0; -} - -void lodepng_info_swap(LodePNGInfo* a, LodePNGInfo* b) -{ - LodePNGInfo temp = *a; - *a = *b; - *b = temp; -} - -/* ////////////////////////////////////////////////////////////////////////// */ - -/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/ -static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) -{ - unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/ - /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/ - unsigned p = index & m; - in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/ - in = in << (bits * (m - p)); - if(p == 0) out[index * bits / 8] = in; - else out[index * bits / 8] |= in; -} - -typedef struct ColorTree ColorTree; - -/* -One node of a color tree -This is the data structure used to count the number of unique colors and to get a palette -index for a color. It's like an octree, but because the alpha channel is used too, each -node has 16 instead of 8 children. -*/ -struct ColorTree -{ - ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/ - int index; /*the payload. Only has a meaningful value if this is in the last level*/ -}; - -static void color_tree_init(ColorTree* tree) -{ - int i; - for(i = 0; i != 16; ++i) tree->children[i] = 0; - tree->index = -1; -} - -static void color_tree_cleanup(ColorTree* tree) -{ - int i; - for(i = 0; i != 16; ++i) - { - if(tree->children[i]) - { - color_tree_cleanup(tree->children[i]); - lodepng_free(tree->children[i]); - } - } -} - -/*returns -1 if color not present, its index otherwise*/ -static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ - int bit = 0; - for(bit = 0; bit < 8; ++bit) - { - int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); - if(!tree->children[i]) return -1; - else tree = tree->children[i]; - } - return tree ? tree->index : -1; -} - -#ifdef LODEPNG_COMPILE_ENCODER -static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ - return color_tree_get(tree, r, g, b, a) >= 0; -} -#endif /*LODEPNG_COMPILE_ENCODER*/ - -/*color is not allowed to already exist. -Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/ -static void color_tree_add(ColorTree* tree, - unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) -{ - int bit; - for(bit = 0; bit < 8; ++bit) - { - int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); - if(!tree->children[i]) - { - tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree)); - color_tree_init(tree->children[i]); - } - tree = tree->children[i]; - } - tree->index = (int)index; -} - -/*put a pixel, given its RGBA color, into image of any color type*/ -static unsigned rgba8ToPixel(unsigned char* out, size_t i, - const LodePNGColorMode* mode, ColorTree* tree /*for palette*/, - unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ - if(mode->colortype == LCT_GREY) - { - unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; - if(mode->bitdepth == 8) out[i] = grey; - else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey; - else - { - /*take the most significant bits of grey*/ - grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1); - addColorBits(out, i, mode->bitdepth, grey); - } - } - else if(mode->colortype == LCT_RGB) - { - if(mode->bitdepth == 8) - { - out[i * 3 + 0] = r; - out[i * 3 + 1] = g; - out[i * 3 + 2] = b; - } - else - { - out[i * 6 + 0] = out[i * 6 + 1] = r; - out[i * 6 + 2] = out[i * 6 + 3] = g; - out[i * 6 + 4] = out[i * 6 + 5] = b; - } - } - else if(mode->colortype == LCT_PALETTE) - { - int index = color_tree_get(tree, r, g, b, a); - if(index < 0) return 82; /*color not in palette*/ - if(mode->bitdepth == 8) out[i] = index; - else addColorBits(out, i, mode->bitdepth, (unsigned)index); - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; - if(mode->bitdepth == 8) - { - out[i * 2 + 0] = grey; - out[i * 2 + 1] = a; - } - else if(mode->bitdepth == 16) - { - out[i * 4 + 0] = out[i * 4 + 1] = grey; - out[i * 4 + 2] = out[i * 4 + 3] = a; - } - } - else if(mode->colortype == LCT_RGBA) - { - if(mode->bitdepth == 8) - { - out[i * 4 + 0] = r; - out[i * 4 + 1] = g; - out[i * 4 + 2] = b; - out[i * 4 + 3] = a; - } - else - { - out[i * 8 + 0] = out[i * 8 + 1] = r; - out[i * 8 + 2] = out[i * 8 + 3] = g; - out[i * 8 + 4] = out[i * 8 + 5] = b; - out[i * 8 + 6] = out[i * 8 + 7] = a; - } - } - - return 0; /*no error*/ -} - -/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/ -static void rgba16ToPixel(unsigned char* out, size_t i, - const LodePNGColorMode* mode, - unsigned short r, unsigned short g, unsigned short b, unsigned short a) -{ - if(mode->colortype == LCT_GREY) - { - unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; - out[i * 2 + 0] = (grey >> 8) & 255; - out[i * 2 + 1] = grey & 255; - } - else if(mode->colortype == LCT_RGB) - { - out[i * 6 + 0] = (r >> 8) & 255; - out[i * 6 + 1] = r & 255; - out[i * 6 + 2] = (g >> 8) & 255; - out[i * 6 + 3] = g & 255; - out[i * 6 + 4] = (b >> 8) & 255; - out[i * 6 + 5] = b & 255; - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; - out[i * 4 + 0] = (grey >> 8) & 255; - out[i * 4 + 1] = grey & 255; - out[i * 4 + 2] = (a >> 8) & 255; - out[i * 4 + 3] = a & 255; - } - else if(mode->colortype == LCT_RGBA) - { - out[i * 8 + 0] = (r >> 8) & 255; - out[i * 8 + 1] = r & 255; - out[i * 8 + 2] = (g >> 8) & 255; - out[i * 8 + 3] = g & 255; - out[i * 8 + 4] = (b >> 8) & 255; - out[i * 8 + 5] = b & 255; - out[i * 8 + 6] = (a >> 8) & 255; - out[i * 8 + 7] = a & 255; - } -} - -/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/ -static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, - unsigned char* b, unsigned char* a, - const unsigned char* in, size_t i, - const LodePNGColorMode* mode) -{ - if(mode->colortype == LCT_GREY) - { - if(mode->bitdepth == 8) - { - *r = *g = *b = in[i]; - if(mode->key_defined && *r == mode->key_r) *a = 0; - else *a = 255; - } - else if(mode->bitdepth == 16) - { - *r = *g = *b = in[i * 2 + 0]; - if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; - else *a = 255; - } - else - { - unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ - size_t j = i * mode->bitdepth; - unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); - *r = *g = *b = (value * 255) / highest; - if(mode->key_defined && value == mode->key_r) *a = 0; - else *a = 255; - } - } - else if(mode->colortype == LCT_RGB) - { - if(mode->bitdepth == 8) - { - *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2]; - if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0; - else *a = 255; - } - else - { - *r = in[i * 6 + 0]; - *g = in[i * 6 + 2]; - *b = in[i * 6 + 4]; - if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r - && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g - && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; - else *a = 255; - } - } - else if(mode->colortype == LCT_PALETTE) - { - unsigned index; - if(mode->bitdepth == 8) index = in[i]; - else - { - size_t j = i * mode->bitdepth; - index = readBitsFromReversedStream(&j, in, mode->bitdepth); - } - - if(index >= mode->palettesize) - { - /*This is an error according to the PNG spec, but common PNG decoders make it black instead. - Done here too, slightly faster due to no error handling needed.*/ - *r = *g = *b = 0; - *a = 255; - } - else - { - *r = mode->palette[index * 4 + 0]; - *g = mode->palette[index * 4 + 1]; - *b = mode->palette[index * 4 + 2]; - *a = mode->palette[index * 4 + 3]; - } - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - if(mode->bitdepth == 8) - { - *r = *g = *b = in[i * 2 + 0]; - *a = in[i * 2 + 1]; - } - else - { - *r = *g = *b = in[i * 4 + 0]; - *a = in[i * 4 + 2]; - } - } - else if(mode->colortype == LCT_RGBA) - { - if(mode->bitdepth == 8) - { - *r = in[i * 4 + 0]; - *g = in[i * 4 + 1]; - *b = in[i * 4 + 2]; - *a = in[i * 4 + 3]; - } - else - { - *r = in[i * 8 + 0]; - *g = in[i * 8 + 2]; - *b = in[i * 8 + 4]; - *a = in[i * 8 + 6]; - } - } -} - -/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color -mode test cases, optimized to convert the colors much faster, when converting -to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with -enough memory, if has_alpha is true the output is RGBA. mode has the color mode -of the input buffer.*/ -static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels, - unsigned has_alpha, const unsigned char* in, - const LodePNGColorMode* mode) -{ - unsigned num_channels = has_alpha ? 4 : 3; - size_t i; - if(mode->colortype == LCT_GREY) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = buffer[1] = buffer[2] = in[i]; - if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255; - } - } - else if(mode->bitdepth == 16) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = buffer[1] = buffer[2] = in[i * 2]; - if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255; - } - } - else - { - unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ - size_t j = 0; - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); - buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; - if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255; - } - } - } - else if(mode->colortype == LCT_RGB) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = in[i * 3 + 0]; - buffer[1] = in[i * 3 + 1]; - buffer[2] = in[i * 3 + 2]; - if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r - && buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255; - } - } - else - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = in[i * 6 + 0]; - buffer[1] = in[i * 6 + 2]; - buffer[2] = in[i * 6 + 4]; - if(has_alpha) buffer[3] = mode->key_defined - && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r - && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g - && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255; - } - } - } - else if(mode->colortype == LCT_PALETTE) - { - unsigned index; - size_t j = 0; - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - if(mode->bitdepth == 8) index = in[i]; - else index = readBitsFromReversedStream(&j, in, mode->bitdepth); - - if(index >= mode->palettesize) - { - /*This is an error according to the PNG spec, but most PNG decoders make it black instead. - Done here too, slightly faster due to no error handling needed.*/ - buffer[0] = buffer[1] = buffer[2] = 0; - if(has_alpha) buffer[3] = 255; - } - else - { - buffer[0] = mode->palette[index * 4 + 0]; - buffer[1] = mode->palette[index * 4 + 1]; - buffer[2] = mode->palette[index * 4 + 2]; - if(has_alpha) buffer[3] = mode->palette[index * 4 + 3]; - } - } - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; - if(has_alpha) buffer[3] = in[i * 2 + 1]; - } - } - else - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; - if(has_alpha) buffer[3] = in[i * 4 + 2]; - } - } - } - else if(mode->colortype == LCT_RGBA) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = in[i * 4 + 0]; - buffer[1] = in[i * 4 + 1]; - buffer[2] = in[i * 4 + 2]; - if(has_alpha) buffer[3] = in[i * 4 + 3]; - } - } - else - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { - buffer[0] = in[i * 8 + 0]; - buffer[1] = in[i * 8 + 2]; - buffer[2] = in[i * 8 + 4]; - if(has_alpha) buffer[3] = in[i * 8 + 6]; - } - } - } -} - -/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with -given color type, but the given color type must be 16-bit itself.*/ -static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a, - const unsigned char* in, size_t i, const LodePNGColorMode* mode) -{ - if(mode->colortype == LCT_GREY) - { - *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1]; - if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; - else *a = 65535; - } - else if(mode->colortype == LCT_RGB) - { - *r = 256 * in[i * 6 + 0] + in[i * 6 + 1]; - *g = 256 * in[i * 6 + 2] + in[i * 6 + 3]; - *b = 256 * in[i * 6 + 4] + in[i * 6 + 5]; - if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r - && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g - && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; - else *a = 65535; - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - *r = *g = *b = 256 * in[i * 4 + 0] + in[i * 4 + 1]; - *a = 256 * in[i * 4 + 2] + in[i * 4 + 3]; - } - else if(mode->colortype == LCT_RGBA) - { - *r = 256 * in[i * 8 + 0] + in[i * 8 + 1]; - *g = 256 * in[i * 8 + 2] + in[i * 8 + 3]; - *b = 256 * in[i * 8 + 4] + in[i * 8 + 5]; - *a = 256 * in[i * 8 + 6] + in[i * 8 + 7]; - } -} - -unsigned lodepng_convert(unsigned char* out, const unsigned char* in, - LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, - unsigned w, unsigned h) -{ - size_t i; - ColorTree tree; - size_t numpixels = w * h; - - if(lodepng_color_mode_equal(mode_out, mode_in)) - { - size_t numbytes = lodepng_get_raw_size(w, h, mode_in); - for(i = 0; i != numbytes; ++i) out[i] = in[i]; - return 0; - } - - if(mode_out->colortype == LCT_PALETTE) - { - size_t palsize = 1u << mode_out->bitdepth; - if(mode_out->palettesize < palsize) palsize = mode_out->palettesize; - color_tree_init(&tree); - for(i = 0; i != palsize; ++i) - { - unsigned char* p = &mode_out->palette[i * 4]; - color_tree_add(&tree, p[0], p[1], p[2], p[3], i); - } - } - - if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) - { - for(i = 0; i != numpixels; ++i) - { - unsigned short r = 0, g = 0, b = 0, a = 0; - getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); - rgba16ToPixel(out, i, mode_out, r, g, b, a); - } - } - else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) - { - getPixelColorsRGBA8(out, numpixels, 1, in, mode_in); - } - else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) - { - getPixelColorsRGBA8(out, numpixels, 0, in, mode_in); - } - else - { - unsigned char r = 0, g = 0, b = 0, a = 0; - for(i = 0; i != numpixels; ++i) - { - getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); - rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); - } - } - - if(mode_out->colortype == LCT_PALETTE) - { - color_tree_cleanup(&tree); - } - - return 0; /*no error (this function currently never has one, but maybe OOM detection added later.)*/ -} - -#ifdef LODEPNG_COMPILE_ENCODER - -void lodepng_color_profile_init(LodePNGColorProfile* profile) -{ - profile->colored = 0; - profile->key = 0; - profile->alpha = 0; - profile->key_r = profile->key_g = profile->key_b = 0; - profile->numcolors = 0; - profile->bits = 1; -} - -/*function used for debug purposes with C++*/ -/*void printColorProfile(LodePNGColorProfile* p) -{ - std::cout << "colored: " << (int)p->colored << ", "; - std::cout << "key: " << (int)p->key << ", "; - std::cout << "key_r: " << (int)p->key_r << ", "; - std::cout << "key_g: " << (int)p->key_g << ", "; - std::cout << "key_b: " << (int)p->key_b << ", "; - std::cout << "alpha: " << (int)p->alpha << ", "; - std::cout << "numcolors: " << (int)p->numcolors << ", "; - std::cout << "bits: " << (int)p->bits << std::endl; -}*/ - -/*Returns how many bits needed to represent given value (max 8 bit)*/ -static unsigned getValueRequiredBits(unsigned char value) -{ - if(value == 0 || value == 255) return 1; - /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/ - if(value % 17 == 0) return value % 85 == 0 ? 2 : 4; - return 8; -} - -/*profile must already have been inited with mode. -It's ok to set some parameters of profile to done already.*/ -unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, - const unsigned char* in, unsigned w, unsigned h, - const LodePNGColorMode* mode) -{ - unsigned error = 0; - size_t i; - ColorTree tree; - size_t numpixels = w * h; - - unsigned colored_done = lodepng_is_greyscale_type(mode) ? 1 : 0; - unsigned alpha_done = lodepng_can_have_alpha(mode) ? 0 : 1; - unsigned numcolors_done = 0; - unsigned bpp = lodepng_get_bpp(mode); - unsigned bits_done = bpp == 1 ? 1 : 0; - unsigned maxnumcolors = 257; - unsigned sixteen = 0; - if(bpp <= 8) maxnumcolors = bpp == 1 ? 2 : (bpp == 2 ? 4 : (bpp == 4 ? 16 : 256)); - - color_tree_init(&tree); - - /*Check if the 16-bit input is truly 16-bit*/ - if(mode->bitdepth == 16) - { - unsigned short r, g, b, a; - for(i = 0; i != numpixels; ++i) - { - getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); - if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) || - (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ - { - sixteen = 1; - break; - } - } - } - - if(sixteen) - { - unsigned short r = 0, g = 0, b = 0, a = 0; - profile->bits = 16; - bits_done = numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/ - - for(i = 0; i != numpixels; ++i) - { - getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode); - - if(!colored_done && (r != g || r != b)) - { - profile->colored = 1; - colored_done = 1; - } - - if(!alpha_done) - { - unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); - if(a != 65535 && (a != 0 || (profile->key && !matchkey))) - { - profile->alpha = 1; - alpha_done = 1; - if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ - } - else if(a == 0 && !profile->alpha && !profile->key) - { - profile->key = 1; - profile->key_r = r; - profile->key_g = g; - profile->key_b = b; - } - else if(a == 65535 && profile->key && matchkey) - { - /* Color key cannot be used if an opaque pixel also has that RGB color. */ - profile->alpha = 1; - alpha_done = 1; - } - } - - if(alpha_done && numcolors_done && colored_done && bits_done) break; - } - } - else /* < 16-bit */ - { - for(i = 0; i != numpixels; ++i) - { - unsigned char r = 0, g = 0, b = 0, a = 0; - getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode); - - if(!bits_done && profile->bits < 8) - { - /*only r is checked, < 8 bits is only relevant for greyscale*/ - unsigned bits = getValueRequiredBits(r); - if(bits > profile->bits) profile->bits = bits; - } - bits_done = (profile->bits >= bpp); - - if(!colored_done && (r != g || r != b)) - { - profile->colored = 1; - colored_done = 1; - if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ - } - - if(!alpha_done) - { - unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); - if(a != 255 && (a != 0 || (profile->key && !matchkey))) - { - profile->alpha = 1; - alpha_done = 1; - if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ - } - else if(a == 0 && !profile->alpha && !profile->key) - { - profile->key = 1; - profile->key_r = r; - profile->key_g = g; - profile->key_b = b; - } - else if(a == 255 && profile->key && matchkey) - { - /* Color key cannot be used if an opaque pixel also has that RGB color. */ - profile->alpha = 1; - alpha_done = 1; - if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ - } - } - - if(!numcolors_done) - { - if(!color_tree_has(&tree, r, g, b, a)) - { - color_tree_add(&tree, r, g, b, a, profile->numcolors); - if(profile->numcolors < 256) - { - unsigned char* p = profile->palette; - unsigned n = profile->numcolors; - p[n * 4 + 0] = r; - p[n * 4 + 1] = g; - p[n * 4 + 2] = b; - p[n * 4 + 3] = a; - } - ++profile->numcolors; - numcolors_done = profile->numcolors >= maxnumcolors; - } - } - - if(alpha_done && numcolors_done && colored_done && bits_done) break; - } - - /*make the profile's key always 16-bit for consistency - repeat each byte twice*/ - profile->key_r += (profile->key_r << 8); - profile->key_g += (profile->key_g << 8); - profile->key_b += (profile->key_b << 8); - } - - color_tree_cleanup(&tree); - return error; -} - -/*Automatically chooses color type that gives smallest amount of bits in the -output image, e.g. grey if there are only greyscale pixels, palette if there -are less than 256 colors, ... -Updates values of mode with a potentially smaller color model. mode_out should -contain the user chosen color model, but will be overwritten with the new chosen one.*/ -unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, - const unsigned char* image, unsigned w, unsigned h, - const LodePNGColorMode* mode_in) -{ - LodePNGColorProfile prof; - unsigned error = 0; - unsigned i, n, palettebits, grey_ok, palette_ok; - - lodepng_color_profile_init(&prof); - error = lodepng_get_color_profile(&prof, image, w, h, mode_in); - if(error) return error; - mode_out->key_defined = 0; - - if(prof.key && w * h <= 16) { - prof.alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ - if(prof.bits < 8) prof.bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ - } - grey_ok = !prof.colored && !prof.alpha; /*grey without alpha, with potentially low bits*/ - n = prof.numcolors; - palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); - palette_ok = n <= 256 && (n * 2 < w * h) && prof.bits <= 8; - if(w * h < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ - if(grey_ok && prof.bits <= palettebits) palette_ok = 0; /*grey is less overhead*/ - - if(palette_ok) - { - unsigned char* p = prof.palette; - lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ - for(i = 0; i != prof.numcolors; ++i) - { - error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]); - if(error) break; - } - - mode_out->colortype = LCT_PALETTE; - mode_out->bitdepth = palettebits; - - if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize - && mode_in->bitdepth == mode_out->bitdepth) - { - /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/ - lodepng_color_mode_cleanup(mode_out); - lodepng_color_mode_copy(mode_out, mode_in); - } - } - else /*8-bit or 16-bit per channel*/ - { - mode_out->bitdepth = prof.bits; - mode_out->colortype = prof.alpha ? (prof.colored ? LCT_RGBA : LCT_GREY_ALPHA) - : (prof.colored ? LCT_RGB : LCT_GREY); - - if(prof.key && !prof.alpha) - { - unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/ - mode_out->key_r = prof.key_r & mask; - mode_out->key_g = prof.key_g & mask; - mode_out->key_b = prof.key_b & mask; - mode_out->key_defined = 1; - } - } - - return error; -} - -#endif /* #ifdef LODEPNG_COMPILE_ENCODER */ - -/* -Paeth predicter, used by PNG filter type 4 -The parameters are of type short, but should come from unsigned chars, the shorts -are only needed to make the paeth calculation correct. -*/ -static unsigned char paethPredictor(short a, short b, short c) -{ - short pa = abs(b - c); - short pb = abs(a - c); - short pc = abs(a + b - c - c); - - if(pc < pa && pc < pb) return (unsigned char)c; - else if(pb < pa) return (unsigned char)b; - else return (unsigned char)a; -} - -/*shared values used by multiple Adam7 related functions*/ - -static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/ -static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/ -static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/ -static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/ - -/* -Outputs various dimensions and positions in the image related to the Adam7 reduced images. -passw: output containing the width of the 7 passes -passh: output containing the height of the 7 passes -filter_passstart: output containing the index of the start and end of each - reduced image with filter bytes -padded_passstart output containing the index of the start and end of each - reduced image when without filter bytes but with padded scanlines -passstart: output containing the index of the start and end of each reduced - image without padding between scanlines, but still padding between the images -w, h: width and height of non-interlaced image -bpp: bits per pixel -"padded" is only relevant if bpp is less than 8 and a scanline or image does not - end at a full byte -*/ -static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8], - size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) -{ - /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/ - unsigned i; - - /*calculate width and height in pixels of each pass*/ - for(i = 0; i != 7; ++i) - { - passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i]; - passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i]; - if(passw[i] == 0) passh[i] = 0; - if(passh[i] == 0) passw[i] = 0; - } - - filter_passstart[0] = padded_passstart[0] = passstart[0] = 0; - for(i = 0; i != 7; ++i) - { - /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/ - filter_passstart[i + 1] = filter_passstart[i] - + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0); - /*bits padded if needed to fill full byte at end of each scanline*/ - padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8); - /*only padded at end of reduced image*/ - passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8; - } -} - -#ifdef LODEPNG_COMPILE_DECODER - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / PNG Decoder / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -/*read the information from the header and store it in the LodePNGInfo. return value is error*/ -unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, - const unsigned char* in, size_t insize) -{ - LodePNGInfo* info = &state->info_png; - if(insize == 0 || in == 0) - { - CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/ - } - if(insize < 33) - { - CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/ - } - - /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/ - lodepng_info_cleanup(info); - lodepng_info_init(info); - - if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 - || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) - { - CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/ - } - if(in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R') - { - CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ - } - - /*read the values given in the header*/ - *w = lodepng_read32bitInt(&in[16]); - *h = lodepng_read32bitInt(&in[20]); - info->color.bitdepth = in[24]; - info->color.colortype = (LodePNGColorType)in[25]; - info->compression_method = in[26]; - info->filter_method = in[27]; - info->interlace_method = in[28]; - - if(*w == 0 || *h == 0) - { - CERROR_RETURN_ERROR(state->error, 93); - } - - if(!state->decoder.ignore_crc) - { - unsigned CRC = lodepng_read32bitInt(&in[29]); - unsigned checksum = lodepng_crc32(&in[12], 17); - if(CRC != checksum) - { - CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/ - } - } - - /*error: only compression method 0 is allowed in the specification*/ - if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32); - /*error: only filter method 0 is allowed in the specification*/ - if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33); - /*error: only interlace methods 0 and 1 exist in the specification*/ - if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34); - - state->error = checkColorValidity(info->color.colortype, info->color.bitdepth); - return state->error; -} - -static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, - size_t bytewidth, unsigned char filterType, size_t length) -{ - /* - For PNG filter method 0 - unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, - the filter works byte per byte (bytewidth = 1) - precon is the previous unfiltered scanline, recon the result, scanline the current one - the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead - recon and scanline MAY be the same memory address! precon must be disjoint. - */ - - size_t i; - switch(filterType) - { - case 0: - for(i = 0; i != length; ++i) recon[i] = scanline[i]; - break; - case 1: - for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; - for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth]; - break; - case 2: - if(precon) - { - for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i]; - } - else - { - for(i = 0; i != length; ++i) recon[i] = scanline[i]; - } - break; - case 3: - if(precon) - { - for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + precon[i] / 2; - for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2); - } - else - { - for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; - for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth] / 2; - } - break; - case 4: - if(precon) - { - for(i = 0; i != bytewidth; ++i) - { - recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ - } - for(i = bytewidth; i < length; ++i) - { - recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); - } - } - else - { - for(i = 0; i != bytewidth; ++i) - { - recon[i] = scanline[i]; - } - for(i = bytewidth; i < length; ++i) - { - /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ - recon[i] = (scanline[i] + recon[i - bytewidth]); - } - } - break; - default: return 36; /*error: unexisting filter type given*/ - } - return 0; -} - -static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) -{ - /* - For PNG filter method 0 - this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times) - out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline - w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel - in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes) - */ - - unsigned y; - unsigned char* prevline = 0; - - /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ - size_t bytewidth = (bpp + 7) / 8; - size_t linebytes = (w * bpp + 7) / 8; - - for(y = 0; y < h; ++y) - { - size_t outindex = linebytes * y; - size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ - unsigned char filterType = in[inindex]; - - CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes)); - - prevline = &out[outindex]; - } - - return 0; -} - -/* -in: Adam7 interlaced image, with no padding bits between scanlines, but between - reduced images so that each reduced image starts at a byte. -out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h -bpp: bits per pixel -out has the following size in bits: w * h * bpp. -in is possibly bigger due to padding bits between reduced images. -out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation -(because that's likely a little bit faster) -NOTE: comments about padding bits are only relevant if bpp < 8 -*/ -static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) -{ - unsigned passw[7], passh[7]; - size_t filter_passstart[8], padded_passstart[8], passstart[8]; - unsigned i; - - Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - - if(bpp >= 8) - { - for(i = 0; i != 7; ++i) - { - unsigned x, y, b; - size_t bytewidth = bpp / 8; - for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { - size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth; - size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; - for(b = 0; b < bytewidth; ++b) - { - out[pixeloutstart + b] = in[pixelinstart + b]; - } - } - } - } - else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ - { - for(i = 0; i != 7; ++i) - { - unsigned x, y, b; - unsigned ilinebits = bpp * passw[i]; - unsigned olinebits = bpp * w; - size_t obp, ibp; /*bit pointers (for out and in buffer)*/ - for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { - ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp); - obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; - for(b = 0; b < bpp; ++b) - { - unsigned char bit = readBitFromReversedStream(&ibp, in); - /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/ - setBitOfReversedStream0(&obp, out, bit); - } - } - } - } -} - -static void removePaddingBits(unsigned char* out, const unsigned char* in, - size_t olinebits, size_t ilinebits, unsigned h) -{ - /* - After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need - to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers - for the Adam7 code, the color convert code and the output to the user. - in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must - have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits - also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7 - only useful if (ilinebits - olinebits) is a value in the range 1..7 - */ - unsigned y; - size_t diff = ilinebits - olinebits; - size_t ibp = 0, obp = 0; /*input and output bit pointers*/ - for(y = 0; y < h; ++y) - { - size_t x; - for(x = 0; x < olinebits; ++x) - { - unsigned char bit = readBitFromReversedStream(&ibp, in); - setBitOfReversedStream(&obp, out, bit); - } - ibp += diff; - } -} - -/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from -the IDAT chunks (with filter index bytes and possible padding bits) -return value is error*/ -static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, - unsigned w, unsigned h, const LodePNGInfo* info_png) -{ - /* - This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype. - Steps: - *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8) - *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace - NOTE: the in buffer will be overwritten with intermediate data! - */ - unsigned bpp = lodepng_get_bpp(&info_png->color); - if(bpp == 0) return 31; /*error: invalid colortype*/ - - if(info_png->interlace_method == 0) - { - if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) - { - CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); - removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h); - } - /*we can immediatly filter into the out buffer, no other steps needed*/ - else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp)); - } - else /*interlace_method is 1 (Adam7)*/ - { - unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; - unsigned i; - - Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - - for(i = 0; i != 7; ++i) - { - CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp)); - /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline, - move bytes instead of bits or move not at all*/ - if(bpp < 8) - { - /*remove padding bits in scanlines; after this there still may be padding - bits between the different reduced images: each reduced image still starts nicely at a byte*/ - removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, - ((passw[i] * bpp + 7) / 8) * 8, passh[i]); - } - } - - Adam7_deinterlace(out, in, w, h, bpp); - } - - return 0; -} - -static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) -{ - unsigned pos = 0, i; - if(color->palette) lodepng_free(color->palette); - color->palettesize = chunkLength / 3; - color->palette = (unsigned char*)lodepng_malloc(4 * color->palettesize); - if(!color->palette && color->palettesize) - { - color->palettesize = 0; - return 83; /*alloc fail*/ - } - if(color->palettesize > 256) return 38; /*error: palette too big*/ - - for(i = 0; i != color->palettesize; ++i) - { - color->palette[4 * i + 0] = data[pos++]; /*R*/ - color->palette[4 * i + 1] = data[pos++]; /*G*/ - color->palette[4 * i + 2] = data[pos++]; /*B*/ - color->palette[4 * i + 3] = 255; /*alpha*/ - } - - return 0; /* OK */ -} - -static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) -{ - unsigned i; - if(color->colortype == LCT_PALETTE) - { - /*error: more alpha values given than there are palette entries*/ - if(chunkLength > color->palettesize) return 38; - - for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i]; - } - else if(color->colortype == LCT_GREY) - { - /*error: this chunk must be 2 bytes for greyscale image*/ - if(chunkLength != 2) return 30; - - color->key_defined = 1; - color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1]; - } - else if(color->colortype == LCT_RGB) - { - /*error: this chunk must be 6 bytes for RGB image*/ - if(chunkLength != 6) return 41; - - color->key_defined = 1; - color->key_r = 256u * data[0] + data[1]; - color->key_g = 256u * data[2] + data[3]; - color->key_b = 256u * data[4] + data[5]; - } - else return 42; /*error: tRNS chunk not allowed for other color models*/ - - return 0; /* OK */ -} - - -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS -/*background color chunk (bKGD)*/ -static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ - if(info->color.colortype == LCT_PALETTE) - { - /*error: this chunk must be 1 byte for indexed color image*/ - if(chunkLength != 1) return 43; - - info->background_defined = 1; - info->background_r = info->background_g = info->background_b = data[0]; - } - else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) - { - /*error: this chunk must be 2 bytes for greyscale image*/ - if(chunkLength != 2) return 44; - - info->background_defined = 1; - info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1]; - } - else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) - { - /*error: this chunk must be 6 bytes for greyscale image*/ - if(chunkLength != 6) return 45; - - info->background_defined = 1; - info->background_r = 256u * data[0] + data[1]; - info->background_g = 256u * data[2] + data[3]; - info->background_b = 256u * data[4] + data[5]; - } - - return 0; /* OK */ -} - -/*text chunk (tEXt)*/ -static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ - unsigned error = 0; - char *key = 0, *str = 0; - unsigned i; - - while(!error) /*not really a while loop, only used to break on error*/ - { - unsigned length, string2_begin; - - length = 0; - while(length < chunkLength && data[length] != 0) ++length; - /*even though it's not allowed by the standard, no error is thrown if - there's no null termination char, if the text is empty*/ - if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ - - key = (char*)lodepng_malloc(length + 1); - if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ - - key[length] = 0; - for(i = 0; i != length; ++i) key[i] = (char)data[i]; - - string2_begin = length + 1; /*skip keyword null terminator*/ - - length = chunkLength < string2_begin ? 0 : chunkLength - string2_begin; - str = (char*)lodepng_malloc(length + 1); - if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ - - str[length] = 0; - for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i]; - - error = lodepng_add_text(info, key, str); - - break; - } - - lodepng_free(key); - lodepng_free(str); - - return error; -} - -/*compressed text chunk (zTXt)*/ -static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, - const unsigned char* data, size_t chunkLength) -{ - unsigned error = 0; - unsigned i; - - unsigned length, string2_begin; - char *key = 0; - ucvector decoded; - - ucvector_init(&decoded); - - while(!error) /*not really a while loop, only used to break on error*/ - { - for(length = 0; length < chunkLength && data[length] != 0; ++length) ; - if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ - if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ - - key = (char*)lodepng_malloc(length + 1); - if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ - - key[length] = 0; - for(i = 0; i != length; ++i) key[i] = (char)data[i]; - - if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ - - string2_begin = length + 2; - if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ - - length = chunkLength - string2_begin; - /*will fail if zlib error, e.g. if length is too small*/ - error = zlib_decompress(&decoded.data, &decoded.size, - (unsigned char*)(&data[string2_begin]), - length, zlibsettings); - if(error) break; - ucvector_push_back(&decoded, 0); - - error = lodepng_add_text(info, key, (char*)decoded.data); - - break; - } - - lodepng_free(key); - ucvector_cleanup(&decoded); - - return error; -} - -/*international text chunk (iTXt)*/ -static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, - const unsigned char* data, size_t chunkLength) -{ - unsigned error = 0; - unsigned i; - - unsigned length, begin, compressed; - char *key = 0, *langtag = 0, *transkey = 0; - ucvector decoded; - ucvector_init(&decoded); - - while(!error) /*not really a while loop, only used to break on error*/ - { - /*Quick check if the chunk length isn't too small. Even without check - it'd still fail with other error checks below if it's too short. This just gives a different error code.*/ - if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/ - - /*read the key*/ - for(length = 0; length < chunkLength && data[length] != 0; ++length) ; - if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/ - if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ - - key = (char*)lodepng_malloc(length + 1); - if(!key) CERROR_BREAK(error, 83); /*alloc fail*/ - - key[length] = 0; - for(i = 0; i != length; ++i) key[i] = (char)data[i]; - - /*read the compression method*/ - compressed = data[length + 1]; - if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ - - /*even though it's not allowed by the standard, no error is thrown if - there's no null termination char, if the text is empty for the next 3 texts*/ - - /*read the langtag*/ - begin = length + 3; - length = 0; - for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; - - langtag = (char*)lodepng_malloc(length + 1); - if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/ - - langtag[length] = 0; - for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i]; - - /*read the transkey*/ - begin += length + 1; - length = 0; - for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length; - - transkey = (char*)lodepng_malloc(length + 1); - if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/ - - transkey[length] = 0; - for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i]; - - /*read the actual text*/ - begin += length + 1; - - length = chunkLength < begin ? 0 : chunkLength - begin; - - if(compressed) - { - /*will fail if zlib error, e.g. if length is too small*/ - error = zlib_decompress(&decoded.data, &decoded.size, - (unsigned char*)(&data[begin]), - length, zlibsettings); - if(error) break; - if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size; - ucvector_push_back(&decoded, 0); - } - else - { - if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/); - - decoded.data[length] = 0; - for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i]; - } - - error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data); - - break; - } - - lodepng_free(key); - lodepng_free(langtag); - lodepng_free(transkey); - ucvector_cleanup(&decoded); - - return error; -} - -static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ - if(chunkLength != 7) return 73; /*invalid tIME chunk size*/ - - info->time_defined = 1; - info->time.year = 256u * data[0] + data[1]; - info->time.month = data[2]; - info->time.day = data[3]; - info->time.hour = data[4]; - info->time.minute = data[5]; - info->time.second = data[6]; - - return 0; /* OK */ -} - -static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ - if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/ - - info->phys_defined = 1; - info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; - info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; - info->phys_unit = data[8]; - - return 0; /* OK */ -} -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - -/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/ -static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, - LodePNGState* state, - const unsigned char* in, size_t insize) -{ - unsigned char IEND = 0; - const unsigned char* chunk; - size_t i; - ucvector idat; /*the data from idat chunks*/ - ucvector scanlines; - size_t predict; - size_t numpixels; - - /*for unknown chunk order*/ - unsigned unknown = 0; -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/ -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - - /*provide some proper output values if error will happen*/ - *out = 0; - - state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ - if(state->error) return; - - numpixels = *w * *h; - - /*multiplication overflow*/ - if(*h != 0 && numpixels / *h != *w) CERROR_RETURN(state->error, 92); - /*multiplication overflow possible further below. Allows up to 2^31-1 pixel - bytes with 16-bit RGBA, the rest is room for filter bytes.*/ - if(numpixels > 268435455) CERROR_RETURN(state->error, 92); - - ucvector_init(&idat); - chunk = &in[33]; /*first byte of the first chunk after the header*/ - - /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. - IDAT data is put at the start of the in buffer*/ - while(!IEND && !state->error) - { - unsigned chunkLength; - const unsigned char* data; /*the data in the chunk*/ - - /*error: size of the in buffer too small to contain next chunk*/ - if((size_t)((chunk - in) + 12) > insize || chunk < in) CERROR_BREAK(state->error, 30); - - /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/ - chunkLength = lodepng_chunk_length(chunk); - /*error: chunk length larger than the max PNG chunk size*/ - if(chunkLength > 2147483647) CERROR_BREAK(state->error, 63); - - if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) - { - CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/ - } - - data = lodepng_chunk_data_const(chunk); - - /*IDAT chunk, containing compressed image data*/ - if(lodepng_chunk_type_equals(chunk, "IDAT")) - { - size_t oldsize = idat.size; - if(!ucvector_resize(&idat, oldsize + chunkLength)) CERROR_BREAK(state->error, 83 /*alloc fail*/); - for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i]; -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - critical_pos = 3; -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - } - /*IEND chunk*/ - else if(lodepng_chunk_type_equals(chunk, "IEND")) - { - IEND = 1; - } - /*palette chunk (PLTE)*/ - else if(lodepng_chunk_type_equals(chunk, "PLTE")) - { - state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength); - if(state->error) break; -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - critical_pos = 2; -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - } - /*palette transparency chunk (tRNS)*/ - else if(lodepng_chunk_type_equals(chunk, "tRNS")) - { - state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength); - if(state->error) break; - } -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*background color chunk (bKGD)*/ - else if(lodepng_chunk_type_equals(chunk, "bKGD")) - { - state->error = readChunk_bKGD(&state->info_png, data, chunkLength); - if(state->error) break; - } - /*text chunk (tEXt)*/ - else if(lodepng_chunk_type_equals(chunk, "tEXt")) - { - if(state->decoder.read_text_chunks) - { - state->error = readChunk_tEXt(&state->info_png, data, chunkLength); - if(state->error) break; - } - } - /*compressed text chunk (zTXt)*/ - else if(lodepng_chunk_type_equals(chunk, "zTXt")) - { - if(state->decoder.read_text_chunks) - { - state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); - if(state->error) break; - } - } - /*international text chunk (iTXt)*/ - else if(lodepng_chunk_type_equals(chunk, "iTXt")) - { - if(state->decoder.read_text_chunks) - { - state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); - if(state->error) break; - } - } - else if(lodepng_chunk_type_equals(chunk, "tIME")) - { - state->error = readChunk_tIME(&state->info_png, data, chunkLength); - if(state->error) break; - } - else if(lodepng_chunk_type_equals(chunk, "pHYs")) - { - state->error = readChunk_pHYs(&state->info_png, data, chunkLength); - if(state->error) break; - } -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - else /*it's not an implemented chunk type, so ignore it: skip over the data*/ - { - /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ - if(!lodepng_chunk_ancillary(chunk)) CERROR_BREAK(state->error, 69); - - unknown = 1; -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - if(state->decoder.remember_unknown_chunks) - { - state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1], - &state->info_png.unknown_chunks_size[critical_pos - 1], chunk); - if(state->error) break; - } -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - } - - if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ - { - if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/ - } - - if(!IEND) chunk = lodepng_chunk_next_const(chunk); - } - - ucvector_init(&scanlines); - /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation. - If the decompressed size does not match the prediction, the image must be corrupt.*/ - if(state->info_png.interlace_method == 0) - { - /*The extra *h is added because this are the filter bytes every scanline starts with*/ - predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color) + *h; - } - else - { - /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/ - const LodePNGColorMode* color = &state->info_png.color; - predict = 0; - predict += lodepng_get_raw_size_idat((*w + 7) / 8, (*h + 7) / 8, color) + (*h + 7) / 8; - if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) / 8, (*h + 7) / 8, color) + (*h + 7) / 8; - predict += lodepng_get_raw_size_idat((*w + 3) / 4, (*h + 3) / 8, color) + (*h + 3) / 8; - if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) / 4, (*h + 3) / 4, color) + (*h + 3) / 4; - predict += lodepng_get_raw_size_idat((*w + 1) / 2, (*h + 1) / 4, color) + (*h + 1) / 4; - if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) / 2, (*h + 1) / 2, color) + (*h + 1) / 2; - predict += lodepng_get_raw_size_idat((*w + 0) / 1, (*h + 0) / 2, color) + (*h + 0) / 2; - } - if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/ - if(!state->error) - { - state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data, - idat.size, &state->decoder.zlibsettings); - if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/ - } - ucvector_cleanup(&idat); - - if(!state->error) - { - size_t outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color); - ucvector outv; - ucvector_init(&outv); - if(!ucvector_resizev(&outv, outsize, 0)) state->error = 83; /*alloc fail*/ - if(!state->error) state->error = postProcessScanlines(outv.data, scanlines.data, *w, *h, &state->info_png); - *out = outv.data; - } - ucvector_cleanup(&scanlines); -} - -unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, - LodePNGState* state, - const unsigned char* in, size_t insize) -{ - *out = 0; - decodeGeneric(out, w, h, state, in, insize); - if(state->error) return state->error; - if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) - { - /*same color type, no copying or converting of data needed*/ - /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype - the raw image has to the end user*/ - if(!state->decoder.color_convert) - { - state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color); - if(state->error) return state->error; - } - } - else - { - /*color conversion needed; sort of copy of the data*/ - unsigned char* data = *out; - size_t outsize; - - /*TODO: check if this works according to the statement in the documentation: "The converter can convert - from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/ - if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) - && !(state->info_raw.bitdepth == 8)) - { - return 56; /*unsupported color mode conversion*/ - } - - outsize = lodepng_get_raw_size(*w, *h, &state->info_raw); - *out = (unsigned char*)lodepng_malloc(outsize); - if(!(*out)) - { - state->error = 83; /*alloc fail*/ - } - else state->error = lodepng_convert(*out, data, &state->info_raw, - &state->info_png.color, *w, *h); - lodepng_free(data); - } - return state->error; -} - -unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, - size_t insize, LodePNGColorType colortype, unsigned bitdepth) -{ - unsigned error; - LodePNGState state; - lodepng_state_init(&state); - state.info_raw.colortype = colortype; - state.info_raw.bitdepth = bitdepth; - error = lodepng_decode(out, w, h, &state, in, insize); - lodepng_state_cleanup(&state); - return error; -} - -unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) -{ - return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8); -} - -unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) -{ - return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8); -} - -#ifdef LODEPNG_COMPILE_DISK -unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, - LodePNGColorType colortype, unsigned bitdepth) -{ - unsigned char* buffer; - size_t buffersize; - unsigned error; - error = lodepng_load_file(&buffer, &buffersize, filename); - if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth); - lodepng_free(buffer); - return error; -} - -unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) -{ - return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8); -} - -unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) -{ - return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8); -} -#endif /*LODEPNG_COMPILE_DISK*/ - -void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) -{ - settings->color_convert = 1; -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - settings->read_text_chunks = 1; - settings->remember_unknown_chunks = 0; -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - settings->ignore_crc = 0; - lodepng_decompress_settings_init(&settings->zlibsettings); -} - -#endif /*LODEPNG_COMPILE_DECODER*/ - -#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) - -void lodepng_state_init(LodePNGState* state) -{ -#ifdef LODEPNG_COMPILE_DECODER - lodepng_decoder_settings_init(&state->decoder); -#endif /*LODEPNG_COMPILE_DECODER*/ -#ifdef LODEPNG_COMPILE_ENCODER - lodepng_encoder_settings_init(&state->encoder); -#endif /*LODEPNG_COMPILE_ENCODER*/ - lodepng_color_mode_init(&state->info_raw); - lodepng_info_init(&state->info_png); - state->error = 1; -} - -void lodepng_state_cleanup(LodePNGState* state) -{ - lodepng_color_mode_cleanup(&state->info_raw); - lodepng_info_cleanup(&state->info_png); -} - -void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) -{ - lodepng_state_cleanup(dest); - *dest = *source; - lodepng_color_mode_init(&dest->info_raw); - lodepng_info_init(&dest->info_png); - dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return; - dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return; -} - -#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ - -#ifdef LODEPNG_COMPILE_ENCODER - -/* ////////////////////////////////////////////////////////////////////////// */ -/* / PNG Encoder / */ -/* ////////////////////////////////////////////////////////////////////////// */ - -/*chunkName must be string of 4 characters*/ -static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length) -{ - CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data)); - out->allocsize = out->size; /*fix the allocsize again*/ - return 0; -} - -static void writeSignature(ucvector* out) -{ - /*8 bytes PNG signature, aka the magic bytes*/ - ucvector_push_back(out, 137); - ucvector_push_back(out, 80); - ucvector_push_back(out, 78); - ucvector_push_back(out, 71); - ucvector_push_back(out, 13); - ucvector_push_back(out, 10); - ucvector_push_back(out, 26); - ucvector_push_back(out, 10); -} - -static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) -{ - unsigned error = 0; - ucvector header; - ucvector_init(&header); - - lodepng_add32bitInt(&header, w); /*width*/ - lodepng_add32bitInt(&header, h); /*height*/ - ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/ - ucvector_push_back(&header, (unsigned char)colortype); /*color type*/ - ucvector_push_back(&header, 0); /*compression method*/ - ucvector_push_back(&header, 0); /*filter method*/ - ucvector_push_back(&header, interlace_method); /*interlace method*/ - - error = addChunk(out, "IHDR", header.data, header.size); - ucvector_cleanup(&header); - - return error; -} - -static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) -{ - unsigned error = 0; - size_t i; - ucvector PLTE; - ucvector_init(&PLTE); - for(i = 0; i != info->palettesize * 4; ++i) - { - /*add all channels except alpha channel*/ - if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]); - } - error = addChunk(out, "PLTE", PLTE.data, PLTE.size); - ucvector_cleanup(&PLTE); - - return error; -} - -static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) -{ - unsigned error = 0; - size_t i; - ucvector tRNS; - ucvector_init(&tRNS); - if(info->colortype == LCT_PALETTE) - { - size_t amount = info->palettesize; - /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/ - for(i = info->palettesize; i != 0; --i) - { - if(info->palette[4 * (i - 1) + 3] == 255) --amount; - else break; - } - /*add only alpha channel*/ - for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]); - } - else if(info->colortype == LCT_GREY) - { - if(info->key_defined) - { - ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256)); - ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256)); - } - } - else if(info->colortype == LCT_RGB) - { - if(info->key_defined) - { - ucvector_push_back(&tRNS, (unsigned char)(info->key_r / 256)); - ucvector_push_back(&tRNS, (unsigned char)(info->key_r % 256)); - ucvector_push_back(&tRNS, (unsigned char)(info->key_g / 256)); - ucvector_push_back(&tRNS, (unsigned char)(info->key_g % 256)); - ucvector_push_back(&tRNS, (unsigned char)(info->key_b / 256)); - ucvector_push_back(&tRNS, (unsigned char)(info->key_b % 256)); - } - } - - error = addChunk(out, "tRNS", tRNS.data, tRNS.size); - ucvector_cleanup(&tRNS); - - return error; -} - -static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize, - LodePNGCompressSettings* zlibsettings) -{ - ucvector zlibdata; - unsigned error = 0; - - /*compress with the Zlib compressor*/ - ucvector_init(&zlibdata); - error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings); - if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size); - ucvector_cleanup(&zlibdata); - - return error; -} - -static unsigned addChunk_IEND(ucvector* out) -{ - unsigned error = 0; - error = addChunk(out, "IEND", 0, 0); - return error; -} - -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - -static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) -{ - unsigned error = 0; - size_t i; - ucvector text; - ucvector_init(&text); - for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]); - if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ - ucvector_push_back(&text, 0); /*0 termination char*/ - for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]); - error = addChunk(out, "tEXt", text.data, text.size); - ucvector_cleanup(&text); - - return error; -} - -static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring, - LodePNGCompressSettings* zlibsettings) -{ - unsigned error = 0; - ucvector data, compressed; - size_t i, textsize = strlen(textstring); - - ucvector_init(&data); - ucvector_init(&compressed); - for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]); - if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ - ucvector_push_back(&data, 0); /*0 termination char*/ - ucvector_push_back(&data, 0); /*compression method: 0*/ - - error = zlib_compress(&compressed.data, &compressed.size, - (unsigned char*)textstring, textsize, zlibsettings); - if(!error) - { - for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]); - error = addChunk(out, "zTXt", data.data, data.size); - } - - ucvector_cleanup(&compressed); - ucvector_cleanup(&data); - return error; -} - -static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag, - const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) -{ - unsigned error = 0; - ucvector data; - size_t i, textsize = strlen(textstring); - - ucvector_init(&data); - - for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]); - if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/ - ucvector_push_back(&data, 0); /*null termination char*/ - ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/ - ucvector_push_back(&data, 0); /*compression method*/ - for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]); - ucvector_push_back(&data, 0); /*null termination char*/ - for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]); - ucvector_push_back(&data, 0); /*null termination char*/ - - if(compressed) - { - ucvector compressed_data; - ucvector_init(&compressed_data); - error = zlib_compress(&compressed_data.data, &compressed_data.size, - (unsigned char*)textstring, textsize, zlibsettings); - if(!error) - { - for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]); - } - ucvector_cleanup(&compressed_data); - } - else /*not compressed*/ - { - for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]); - } - - if(!error) error = addChunk(out, "iTXt", data.data, data.size); - ucvector_cleanup(&data); - return error; -} - -static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) -{ - unsigned error = 0; - ucvector bKGD; - ucvector_init(&bKGD); - if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) - { - ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256)); - ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); - } - else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) - { - ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256)); - ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); - ucvector_push_back(&bKGD, (unsigned char)(info->background_g / 256)); - ucvector_push_back(&bKGD, (unsigned char)(info->background_g % 256)); - ucvector_push_back(&bKGD, (unsigned char)(info->background_b / 256)); - ucvector_push_back(&bKGD, (unsigned char)(info->background_b % 256)); - } - else if(info->color.colortype == LCT_PALETTE) - { - ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); /*palette index*/ - } - - error = addChunk(out, "bKGD", bKGD.data, bKGD.size); - ucvector_cleanup(&bKGD); - - return error; -} - -static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) -{ - unsigned error = 0; - unsigned char* data = (unsigned char*)lodepng_malloc(7); - if(!data) return 83; /*alloc fail*/ - data[0] = (unsigned char)(time->year / 256); - data[1] = (unsigned char)(time->year % 256); - data[2] = (unsigned char)time->month; - data[3] = (unsigned char)time->day; - data[4] = (unsigned char)time->hour; - data[5] = (unsigned char)time->minute; - data[6] = (unsigned char)time->second; - error = addChunk(out, "tIME", data, 7); - lodepng_free(data); - return error; -} - -static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) -{ - unsigned error = 0; - ucvector data; - ucvector_init(&data); - - lodepng_add32bitInt(&data, info->phys_x); - lodepng_add32bitInt(&data, info->phys_y); - ucvector_push_back(&data, info->phys_unit); - - error = addChunk(out, "pHYs", data.data, data.size); - ucvector_cleanup(&data); - - return error; -} - -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - -static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline, - size_t length, size_t bytewidth, unsigned char filterType) -{ - size_t i; - switch(filterType) - { - case 0: /*None*/ - for(i = 0; i != length; ++i) out[i] = scanline[i]; - break; - case 1: /*Sub*/ - for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; - for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth]; - break; - case 2: /*Up*/ - if(prevline) - { - for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i]; - } - else - { - for(i = 0; i != length; ++i) out[i] = scanline[i]; - } - break; - case 3: /*Average*/ - if(prevline) - { - for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - prevline[i] / 2; - for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) / 2); - } - else - { - for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; - for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth] / 2; - } - break; - case 4: /*Paeth*/ - if(prevline) - { - /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/ - for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]); - for(i = bytewidth; i < length; ++i) - { - out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth])); - } - } - else - { - for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; - /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/ - for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]); - } - break; - default: return; /*unexisting filter type given*/ - } -} - -/* log2 approximation. A slight bit faster than std::log. */ -static float flog2(float f) -{ - float result = 0; - while(f > 32) { result += 4; f /= 16; } - while(f > 2) { ++result; f /= 2; } - return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f); -} - -static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, - const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) -{ - /* - For PNG filter method 0 - out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are - the scanlines with 1 extra byte per scanline - */ - - unsigned bpp = lodepng_get_bpp(info); - /*the width of a scanline in bytes, not including the filter type*/ - size_t linebytes = (w * bpp + 7) / 8; - /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ - size_t bytewidth = (bpp + 7) / 8; - const unsigned char* prevline = 0; - unsigned x, y; - unsigned error = 0; - LodePNGFilterStrategy strategy = settings->filter_strategy; - - /* - There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard: - * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e. - use fixed filtering, with the filter None). - * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is - not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply - all five filters and select the filter that produces the smallest sum of absolute values per row. - This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true. - - If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed, - but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum - heuristic is used. - */ - if(settings->filter_palette_zero && - (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO; - - if(bpp == 0) return 31; /*error: invalid color type*/ - - if(strategy == LFS_ZERO) - { - for(y = 0; y != h; ++y) - { - size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ - size_t inindex = linebytes * y; - out[outindex] = 0; /*filter type byte*/ - filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0); - prevline = &in[inindex]; - } - } - else if(strategy == LFS_MINSUM) - { - /*adaptive filtering*/ - size_t sum[5]; - ucvector attempt[5]; /*five filtering attempts, one for each filter type*/ - size_t smallest = 0; - unsigned char type, bestType = 0; - - for(type = 0; type != 5; ++type) - { - ucvector_init(&attempt[type]); - if(!ucvector_resize(&attempt[type], linebytes)) return 83; /*alloc fail*/ - } - - if(!error) - { - for(y = 0; y != h; ++y) - { - /*try the 5 filter types*/ - for(type = 0; type != 5; ++type) - { - filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type); - - /*calculate the sum of the result*/ - sum[type] = 0; - if(type == 0) - { - for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type].data[x]); - } - else - { - for(x = 0; x != linebytes; ++x) - { - /*For differences, each byte should be treated as signed, values above 127 are negative - (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there. - This means filtertype 0 is almost never chosen, but that is justified.*/ - unsigned char s = attempt[type].data[x]; - sum[type] += s < 128 ? s : (255U - s); - } - } - - /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ - if(type == 0 || sum[type] < smallest) - { - bestType = type; - smallest = sum[type]; - } - } - - prevline = &in[y * linebytes]; - - /*now fill the out values*/ - out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ - for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x]; - } - } - - for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]); - } - else if(strategy == LFS_ENTROPY) - { - float sum[5]; - ucvector attempt[5]; /*five filtering attempts, one for each filter type*/ - float smallest = 0; - unsigned type, bestType = 0; - unsigned count[256]; - - for(type = 0; type != 5; ++type) - { - ucvector_init(&attempt[type]); - if(!ucvector_resize(&attempt[type], linebytes)) return 83; /*alloc fail*/ - } - - for(y = 0; y != h; ++y) - { - /*try the 5 filter types*/ - for(type = 0; type != 5; ++type) - { - filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type); - for(x = 0; x != 256; ++x) count[x] = 0; - for(x = 0; x != linebytes; ++x) ++count[attempt[type].data[x]]; - ++count[type]; /*the filter type itself is part of the scanline*/ - sum[type] = 0; - for(x = 0; x != 256; ++x) - { - float p = count[x] / (float)(linebytes + 1); - sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p; - } - /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ - if(type == 0 || sum[type] < smallest) - { - bestType = type; - smallest = sum[type]; - } - } - - prevline = &in[y * linebytes]; - - /*now fill the out values*/ - out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ - for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x]; - } - - for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]); - } - else if(strategy == LFS_PREDEFINED) - { - for(y = 0; y != h; ++y) - { - size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ - size_t inindex = linebytes * y; - unsigned char type = settings->predefined_filters[y]; - out[outindex] = type; /*filter type byte*/ - filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); - prevline = &in[inindex]; - } - } - else if(strategy == LFS_BRUTE_FORCE) - { - /*brute force filter chooser. - deflate the scanline after every filter attempt to see which one deflates best. - This is very slow and gives only slightly smaller, sometimes even larger, result*/ - size_t size[5]; - ucvector attempt[5]; /*five filtering attempts, one for each filter type*/ - size_t smallest = 0; - unsigned type = 0, bestType = 0; - unsigned char* dummy; - LodePNGCompressSettings zlibsettings = settings->zlibsettings; - /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose, - to simulate the true case where the tree is the same for the whole image. Sometimes it gives - better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare - cases better compression. It does make this a bit less slow, so it's worth doing this.*/ - zlibsettings.btype = 1; - /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG - images only, so disable it*/ - zlibsettings.custom_zlib = 0; - zlibsettings.custom_deflate = 0; - for(type = 0; type != 5; ++type) - { - ucvector_init(&attempt[type]); - ucvector_resize(&attempt[type], linebytes); /*todo: give error if resize failed*/ - } - for(y = 0; y != h; ++y) /*try the 5 filter types*/ - { - for(type = 0; type != 5; ++type) - { - unsigned testsize = attempt[type].size; - /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ - - filterScanline(attempt[type].data, &in[y * linebytes], prevline, linebytes, bytewidth, type); - size[type] = 0; - dummy = 0; - zlib_compress(&dummy, &size[type], attempt[type].data, testsize, &zlibsettings); - lodepng_free(dummy); - /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/ - if(type == 0 || size[type] < smallest) - { - bestType = type; - smallest = size[type]; - } - } - prevline = &in[y * linebytes]; - out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ - for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType].data[x]; - } - for(type = 0; type != 5; ++type) ucvector_cleanup(&attempt[type]); - } - else return 88; /* unknown filter strategy */ - - return error; -} - -static void addPaddingBits(unsigned char* out, const unsigned char* in, - size_t olinebits, size_t ilinebits, unsigned h) -{ - /*The opposite of the removePaddingBits function - olinebits must be >= ilinebits*/ - unsigned y; - size_t diff = olinebits - ilinebits; - size_t obp = 0, ibp = 0; /*bit pointers*/ - for(y = 0; y != h; ++y) - { - size_t x; - for(x = 0; x < ilinebits; ++x) - { - unsigned char bit = readBitFromReversedStream(&ibp, in); - setBitOfReversedStream(&obp, out, bit); - } - /*obp += diff; --> no, fill in some value in the padding bits too, to avoid - "Use of uninitialised value of size ###" warning from valgrind*/ - for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0); - } -} - -/* -in: non-interlaced image with size w*h -out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with - no padding bits between scanlines, but between reduced images so that each - reduced image starts at a byte. -bpp: bits per pixel -there are no padding bits, not between scanlines, not between reduced images -in has the following size in bits: w * h * bpp. -out is possibly bigger due to padding bits between reduced images -NOTE: comments about padding bits are only relevant if bpp < 8 -*/ -static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) -{ - unsigned passw[7], passh[7]; - size_t filter_passstart[8], padded_passstart[8], passstart[8]; - unsigned i; - - Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - - if(bpp >= 8) - { - for(i = 0; i != 7; ++i) - { - unsigned x, y, b; - size_t bytewidth = bpp / 8; - for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { - size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; - size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth; - for(b = 0; b < bytewidth; ++b) - { - out[pixeloutstart + b] = in[pixelinstart + b]; - } - } - } - } - else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ - { - for(i = 0; i != 7; ++i) - { - unsigned x, y, b; - unsigned ilinebits = bpp * passw[i]; - unsigned olinebits = bpp * w; - size_t obp, ibp; /*bit pointers (for out and in buffer)*/ - for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { - ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; - obp = (8 * passstart[i]) + (y * ilinebits + x * bpp); - for(b = 0; b < bpp; ++b) - { - unsigned char bit = readBitFromReversedStream(&ibp, in); - setBitOfReversedStream(&obp, out, bit); - } - } - } - } -} - -/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image. -return value is error**/ -static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in, - unsigned w, unsigned h, - const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) -{ - /* - This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps: - *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter - *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter - */ - unsigned bpp = lodepng_get_bpp(&info_png->color); - unsigned error = 0; - - if(info_png->interlace_method == 0) - { - *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/ - *out = (unsigned char*)lodepng_malloc(*outsize); - if(!(*out) && (*outsize)) error = 83; /*alloc fail*/ - - if(!error) - { - /*non multiple of 8 bits per scanline, padding bits needed per scanline*/ - if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) - { - unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7) / 8)); - if(!padded) error = 83; /*alloc fail*/ - if(!error) - { - addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h); - error = filter(*out, padded, w, h, &info_png->color, settings); - } - lodepng_free(padded); - } - else - { - /*we can immediatly filter into the out buffer, no other steps needed*/ - error = filter(*out, in, w, h, &info_png->color, settings); - } - } - } - else /*interlace_method is 1 (Adam7)*/ - { - unsigned passw[7], passh[7]; - size_t filter_passstart[8], padded_passstart[8], passstart[8]; - unsigned char* adam7; - - Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - - *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/ - *out = (unsigned char*)lodepng_malloc(*outsize); - if(!(*out)) error = 83; /*alloc fail*/ - - adam7 = (unsigned char*)lodepng_malloc(passstart[7]); - if(!adam7 && passstart[7]) error = 83; /*alloc fail*/ - - if(!error) - { - unsigned i; - - Adam7_interlace(adam7, in, w, h, bpp); - for(i = 0; i != 7; ++i) - { - if(bpp < 8) - { - unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]); - if(!padded) ERROR_BREAK(83); /*alloc fail*/ - addPaddingBits(padded, &adam7[passstart[i]], - ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]); - error = filter(&(*out)[filter_passstart[i]], padded, - passw[i], passh[i], &info_png->color, settings); - lodepng_free(padded); - } - else - { - error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]], - passw[i], passh[i], &info_png->color, settings); - } - - if(error) break; - } - } - - lodepng_free(adam7); - } - - return error; -} - -/* -palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA... -returns 0 if the palette is opaque, -returns 1 if the palette has a single color with alpha 0 ==> color key -returns 2 if the palette is semi-translucent. -*/ -static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) -{ - size_t i; - unsigned key = 0; - unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/ - for(i = 0; i != palettesize; ++i) - { - if(!key && palette[4 * i + 3] == 0) - { - r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2]; - key = 1; - i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/ - } - else if(palette[4 * i + 3] != 255) return 2; - /*when key, no opaque RGB may have key's RGB*/ - else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2; - } - return key; -} - -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS -static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) -{ - unsigned char* inchunk = data; - while((size_t)(inchunk - data) < datasize) - { - CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk)); - out->allocsize = out->size; /*fix the allocsize again*/ - inchunk = lodepng_chunk_next(inchunk); - } - return 0; -} -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - -unsigned lodepng_encode(unsigned char** out, size_t* outsize, - const unsigned char* image, unsigned w, unsigned h, - LodePNGState* state) -{ - LodePNGInfo info; - ucvector outv; - unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/ - size_t datasize = 0; - - /*provide some proper output values if error will happen*/ - *out = 0; - *outsize = 0; - state->error = 0; - - lodepng_info_init(&info); - lodepng_info_copy(&info, &state->info_png); - - if((info.color.colortype == LCT_PALETTE || state->encoder.force_palette) - && (info.color.palettesize == 0 || info.color.palettesize > 256)) - { - state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/ - return state->error; - } - - if(state->encoder.auto_convert) - { - state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw); - } - if(state->error) return state->error; - - if(state->encoder.zlibsettings.btype > 2) - { - CERROR_RETURN_ERROR(state->error, 61); /*error: unexisting btype*/ - } - if(state->info_png.interlace_method > 1) - { - CERROR_RETURN_ERROR(state->error, 71); /*error: unexisting interlace mode*/ - } - - state->error = checkColorValidity(info.color.colortype, info.color.bitdepth); - if(state->error) return state->error; /*error: unexisting color type given*/ - state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); - if(state->error) return state->error; /*error: unexisting color type given*/ - - if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) - { - unsigned char* converted; - size_t size = (w * h * lodepng_get_bpp(&info.color) + 7) / 8; - - converted = (unsigned char*)lodepng_malloc(size); - if(!converted && size) state->error = 83; /*alloc fail*/ - if(!state->error) - { - state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); - } - if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); - lodepng_free(converted); - } - else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); - - ucvector_init(&outv); - while(!state->error) /*while only executed once, to break on error*/ - { -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - size_t i; -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - /*write signature and chunks*/ - writeSignature(&outv); - /*IHDR*/ - addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*unknown chunks between IHDR and PLTE*/ - if(info.unknown_chunks_data[0]) - { - state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]); - if(state->error) break; - } -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - /*PLTE*/ - if(info.color.colortype == LCT_PALETTE) - { - addChunk_PLTE(&outv, &info.color); - } - if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) - { - addChunk_PLTE(&outv, &info.color); - } - /*tRNS*/ - if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) - { - addChunk_tRNS(&outv, &info.color); - } - if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) - { - addChunk_tRNS(&outv, &info.color); - } -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*bKGD (must come between PLTE and the IDAt chunks*/ - if(info.background_defined) addChunk_bKGD(&outv, &info); - /*pHYs (must come before the IDAT chunks)*/ - if(info.phys_defined) addChunk_pHYs(&outv, &info); - - /*unknown chunks between PLTE and IDAT*/ - if(info.unknown_chunks_data[1]) - { - state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]); - if(state->error) break; - } -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - /*IDAT (multiple IDAT chunks must be consecutive)*/ - state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings); - if(state->error) break; -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*tIME*/ - if(info.time_defined) addChunk_tIME(&outv, &info.time); - /*tEXt and/or zTXt*/ - for(i = 0; i != info.text_num; ++i) - { - if(strlen(info.text_keys[i]) > 79) - { - state->error = 66; /*text chunk too large*/ - break; - } - if(strlen(info.text_keys[i]) < 1) - { - state->error = 67; /*text chunk too small*/ - break; - } - if(state->encoder.text_compression) - { - addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); - } - else - { - addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); - } - } - /*LodePNG version id in text chunk*/ - if(state->encoder.add_id) - { - unsigned alread_added_id_text = 0; - for(i = 0; i != info.text_num; ++i) - { - if(!strcmp(info.text_keys[i], "LodePNG")) - { - alread_added_id_text = 1; - break; - } - } - if(alread_added_id_text == 0) - { - addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ - } - } - /*iTXt*/ - for(i = 0; i != info.itext_num; ++i) - { - if(strlen(info.itext_keys[i]) > 79) - { - state->error = 66; /*text chunk too large*/ - break; - } - if(strlen(info.itext_keys[i]) < 1) - { - state->error = 67; /*text chunk too small*/ - break; - } - addChunk_iTXt(&outv, state->encoder.text_compression, - info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i], - &state->encoder.zlibsettings); - } - - /*unknown chunks between IDAT and IEND*/ - if(info.unknown_chunks_data[2]) - { - state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]); - if(state->error) break; - } -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - addChunk_IEND(&outv); - - break; /*this isn't really a while loop; no error happened so break out now!*/ - } - - lodepng_info_cleanup(&info); - lodepng_free(data); - /*instead of cleaning the vector up, give it to the output*/ - *out = outv.data; - *outsize = outv.size; - - return state->error; -} - -unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, - unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) -{ - unsigned error; - LodePNGState state; - lodepng_state_init(&state); - state.info_raw.colortype = colortype; - state.info_raw.bitdepth = bitdepth; - state.info_png.color.colortype = colortype; - state.info_png.color.bitdepth = bitdepth; - lodepng_encode(out, outsize, image, w, h, &state); - error = state.error; - lodepng_state_cleanup(&state); - return error; -} - -unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) -{ - return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8); -} - -unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) -{ - return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8); -} - -#ifdef LODEPNG_COMPILE_DISK -unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth) -{ - unsigned char* buffer; - size_t buffersize; - unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth); - if(!error) error = lodepng_save_file(buffer, buffersize, filename); - lodepng_free(buffer); - return error; -} - -unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) -{ - return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8); -} - -unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) -{ - return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8); -} -#endif /*LODEPNG_COMPILE_DISK*/ - -void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) -{ - lodepng_compress_settings_init(&settings->zlibsettings); - settings->filter_palette_zero = 1; - settings->filter_strategy = LFS_MINSUM; - settings->auto_convert = 1; - settings->force_palette = 0; - settings->predefined_filters = 0; -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - settings->add_id = 0; - settings->text_compression = 1; -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ -} - -#endif /*LODEPNG_COMPILE_ENCODER*/ -#endif /*LODEPNG_COMPILE_PNG*/ - -#ifdef LODEPNG_COMPILE_ERROR_TEXT -/* -This returns the description of a numerical error code in English. This is also -the documentation of all the error codes. -*/ -const char* lodepng_error_text(unsigned code) -{ - switch(code) - { - case 0: return "no error, everything went ok"; - case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/ - case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/ - case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/ - case 13: return "problem while processing dynamic deflate block"; - case 14: return "problem while processing dynamic deflate block"; - case 15: return "problem while processing dynamic deflate block"; - case 16: return "unexisting code while processing dynamic deflate block"; - case 17: return "end of out buffer memory reached while inflating"; - case 18: return "invalid distance code while inflating"; - case 19: return "end of out buffer memory reached while inflating"; - case 20: return "invalid deflate block BTYPE encountered while decoding"; - case 21: return "NLEN is not ones complement of LEN in a deflate block"; - /*end of out buffer memory reached while inflating: - This can happen if the inflated deflate data is longer than the amount of bytes required to fill up - all the pixels of the image, given the color depth and image dimensions. Something that doesn't - happen in a normal, well encoded, PNG image.*/ - case 22: return "end of out buffer memory reached while inflating"; - case 23: return "end of in buffer memory reached while inflating"; - case 24: return "invalid FCHECK in zlib header"; - case 25: return "invalid compression method in zlib header"; - case 26: return "FDICT encountered in zlib header while it's not used for PNG"; - case 27: return "PNG file is smaller than a PNG header"; - /*Checks the magic file header, the first 8 bytes of the PNG file*/ - case 28: return "incorrect PNG signature, it's no PNG or corrupted"; - case 29: return "first chunk is not the header chunk"; - case 30: return "chunk length too large, chunk broken off at end of file"; - case 31: return "illegal PNG color type or bpp"; - case 32: return "illegal PNG compression method"; - case 33: return "illegal PNG filter method"; - case 34: return "illegal PNG interlace method"; - case 35: return "chunk length of a chunk is too large or the chunk too small"; - case 36: return "illegal PNG filter type encountered"; - case 37: return "illegal bit depth for this color type given"; - case 38: return "the palette is too big"; /*more than 256 colors*/ - case 39: return "more palette alpha values given in tRNS chunk than there are colors in the palette"; - case 40: return "tRNS chunk has wrong size for greyscale image"; - case 41: return "tRNS chunk has wrong size for RGB image"; - case 42: return "tRNS chunk appeared while it was not allowed for this color type"; - case 43: return "bKGD chunk has wrong size for palette image"; - case 44: return "bKGD chunk has wrong size for greyscale image"; - case 45: return "bKGD chunk has wrong size for RGB image"; - /*the input data is empty, maybe a PNG file doesn't exist or is in the wrong path*/ - case 48: return "empty input or file doesn't exist"; - case 49: return "jumped past memory while generating dynamic huffman tree"; - case 50: return "jumped past memory while generating dynamic huffman tree"; - case 51: return "jumped past memory while inflating huffman block"; - case 52: return "jumped past memory while inflating"; - case 53: return "size of zlib data too small"; - case 54: return "repeat symbol in tree while there was no value symbol yet"; - /*jumped past tree while generating huffman tree, this could be when the - tree will have more leaves than symbols after generating it out of the - given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/ - case 55: return "jumped past tree while generating huffman tree"; - case 56: return "given output image colortype or bitdepth not supported for color conversion"; - case 57: return "invalid CRC encountered (checking CRC can be disabled)"; - case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)"; - case 59: return "requested color conversion not supported"; - case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)"; - case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)"; - /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/ - case 62: return "conversion from color to greyscale not supported"; - case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/ - /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/ - case 64: return "the length of the END symbol 256 in the Huffman tree is 0"; - case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes"; - case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte"; - case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors"; - case 69: return "unknown chunk type with 'critical' flag encountered by the decoder"; - case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)"; - case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)"; - case 73: return "invalid tIME chunk size"; - case 74: return "invalid pHYs chunk size"; - /*length could be wrong, or data chopped off*/ - case 75: return "no null termination char found while decoding text chunk"; - case 76: return "iTXt chunk too short to contain required bytes"; - case 77: return "integer overflow in buffer size"; - case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/ - case 79: return "failed to open file for writing"; - case 80: return "tried creating a tree of 0 symbols"; - case 81: return "lazy matching at pos 0 is impossible"; - case 82: return "color conversion to palette requested while a color isn't in palette"; - case 83: return "memory allocation failed"; - case 84: return "given image too small to contain all pixels to be encoded"; - case 86: return "impossible offset in lz77 encoding (internal bug)"; - case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined"; - case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy"; - case 89: return "text chunk keyword too short or long: must have size 1-79"; - /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ - case 90: return "windowsize must be a power of two"; - case 91: return "invalid decompressed idat size"; - case 92: return "too many pixels, not supported"; - case 93: return "zero width or height is invalid"; - } - return "unknown error code"; -} -#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ - -/* ////////////////////////////////////////////////////////////////////////// */ -/* ////////////////////////////////////////////////////////////////////////// */ -/* // C++ Wrapper // */ -/* ////////////////////////////////////////////////////////////////////////// */ -/* ////////////////////////////////////////////////////////////////////////// */ - -#ifdef LODEPNG_COMPILE_CPP -namespace lodepng -{ - -#ifdef LODEPNG_COMPILE_DISK -void load_file(std::vector& buffer, const std::string& filename) -{ - std::ifstream file(filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate); - - /*get filesize*/ - std::streamsize size = 0; - if(file.seekg(0, std::ios::end).good()) size = file.tellg(); - if(file.seekg(0, std::ios::beg).good()) size -= file.tellg(); - - /*read contents of the file into the vector*/ - buffer.resize(size_t(size)); - if(size > 0) file.read((char*)(&buffer[0]), size); -} - -/*write given buffer to the file, overwriting the file, it doesn't append to it.*/ -void save_file(const std::vector& buffer, const std::string& filename) -{ - std::ofstream file(filename.c_str(), std::ios::out|std::ios::binary); - file.write(buffer.empty() ? 0 : (char*)&buffer[0], std::streamsize(buffer.size())); -} -#endif //LODEPNG_COMPILE_DISK - -#ifdef LODEPNG_COMPILE_ZLIB -#ifdef LODEPNG_COMPILE_DECODER -unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, - const LodePNGDecompressSettings& settings) -{ - unsigned char* buffer = 0; - size_t buffersize = 0; - unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings); - if(buffer) - { - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - lodepng_free(buffer); - } - return error; -} - -unsigned decompress(std::vector& out, const std::vector& in, - const LodePNGDecompressSettings& settings) -{ - return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings); -} -#endif //LODEPNG_COMPILE_DECODER - -#ifdef LODEPNG_COMPILE_ENCODER -unsigned compress(std::vector& out, const unsigned char* in, size_t insize, - const LodePNGCompressSettings& settings) -{ - unsigned char* buffer = 0; - size_t buffersize = 0; - unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings); - if(buffer) - { - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - lodepng_free(buffer); - } - return error; -} - -unsigned compress(std::vector& out, const std::vector& in, - const LodePNGCompressSettings& settings) -{ - return compress(out, in.empty() ? 0 : &in[0], in.size(), settings); -} -#endif //LODEPNG_COMPILE_ENCODER -#endif //LODEPNG_COMPILE_ZLIB - - -#ifdef LODEPNG_COMPILE_PNG - -State::State() -{ - lodepng_state_init(this); -} - -State::State(const State& other) -{ - lodepng_state_init(this); - lodepng_state_copy(this, &other); -} - -State::~State() -{ - lodepng_state_cleanup(this); -} - -State& State::operator=(const State& other) -{ - lodepng_state_copy(this, &other); - return *this; -} - -#ifdef LODEPNG_COMPILE_DECODER - -unsigned decode(std::vector& out, unsigned& w, unsigned& h, const unsigned char* in, - size_t insize, LodePNGColorType colortype, unsigned bitdepth) -{ - unsigned char* buffer; - unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth); - if(buffer && !error) - { - State state; - state.info_raw.colortype = colortype; - state.info_raw.bitdepth = bitdepth; - size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - lodepng_free(buffer); - } - return error; -} - -unsigned decode(std::vector& out, unsigned& w, unsigned& h, - const std::vector& in, LodePNGColorType colortype, unsigned bitdepth) -{ - return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth); -} - -unsigned decode(std::vector& out, unsigned& w, unsigned& h, - State& state, - const unsigned char* in, size_t insize) -{ - unsigned char* buffer = NULL; - unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize); - if(buffer && !error) - { - size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - } - lodepng_free(buffer); - return error; -} - -unsigned decode(std::vector& out, unsigned& w, unsigned& h, - State& state, - const std::vector& in) -{ - return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size()); -} - -#ifdef LODEPNG_COMPILE_DISK -unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::string& filename, - LodePNGColorType colortype, unsigned bitdepth) -{ - std::vector buffer; - load_file(buffer, filename); - return decode(out, w, h, buffer, colortype, bitdepth); -} -#endif //LODEPNG_COMPILE_DECODER -#endif //LODEPNG_COMPILE_DISK - -#ifdef LODEPNG_COMPILE_ENCODER -unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth) -{ - unsigned char* buffer; - size_t buffersize; - unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth); - if(buffer) - { - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - lodepng_free(buffer); - } - return error; -} - -unsigned encode(std::vector& out, - const std::vector& in, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth) -{ - if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; - return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); -} - -unsigned encode(std::vector& out, - const unsigned char* in, unsigned w, unsigned h, - State& state) -{ - unsigned char* buffer; - size_t buffersize; - unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state); - if(buffer) - { - out.insert(out.end(), &buffer[0], &buffer[buffersize]); - lodepng_free(buffer); - } - return error; -} - -unsigned encode(std::vector& out, - const std::vector& in, unsigned w, unsigned h, - State& state) -{ - if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84; - return encode(out, in.empty() ? 0 : &in[0], w, h, state); -} - -#ifdef LODEPNG_COMPILE_DISK -unsigned encode(const std::string& filename, - const unsigned char* in, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth) -{ - std::vector buffer; - unsigned error = encode(buffer, in, w, h, colortype, bitdepth); - if(!error) save_file(buffer, filename); - return error; -} - -unsigned encode(const std::string& filename, - const std::vector& in, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth) -{ - if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; - return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); -} -#endif //LODEPNG_COMPILE_DISK -#endif //LODEPNG_COMPILE_ENCODER -#endif //LODEPNG_COMPILE_PNG -} //namespace lodepng -#endif /*LODEPNG_COMPILE_CPP*/ diff -Nru nestopia-1.48/source/unix/png.h nestopia-1.49/source/unix/png.h --- nestopia-1.48/source/unix/png.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/png.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,1708 +0,0 @@ -/* -LodePNG version 20141130 - -Copyright (c) 2005-2014 Lode Vandevenne - -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 LODEPNG_H -#define LODEPNG_H - -#include /*for size_t*/ - -#ifdef __cplusplus -#include -#include -#endif /*__cplusplus*/ - -#define LODEPNG_VERSION_STRING "20141130" - -/* -The following #defines are used to create code sections. They can be disabled -to disable code sections, which can give faster compile time and smaller binary. -The "NO_COMPILE" defines are designed to be used to pass as defines to the -compiler command to disable them without modifying this header, e.g. --DLODEPNG_NO_COMPILE_ZLIB for gcc. -*/ -/*deflate & zlib. If disabled, you must specify alternative zlib functions in -the custom_zlib field of the compress and decompress settings*/ -#ifndef LODEPNG_NO_COMPILE_ZLIB -#define LODEPNG_COMPILE_ZLIB -#endif -/*png encoder and png decoder*/ -#ifndef LODEPNG_NO_COMPILE_PNG -#define LODEPNG_COMPILE_PNG -#endif -/*deflate&zlib decoder and png decoder*/ -#ifndef LODEPNG_NO_COMPILE_DECODER -#define LODEPNG_COMPILE_DECODER -#endif -/*deflate&zlib encoder and png encoder*/ -#ifndef LODEPNG_NO_COMPILE_ENCODER -#define LODEPNG_COMPILE_ENCODER -#endif -/*the optional built in harddisk file loading and saving functions*/ -#ifndef LODEPNG_NO_COMPILE_DISK -#define LODEPNG_COMPILE_DISK -#endif -/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/ -#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS -#define LODEPNG_COMPILE_ANCILLARY_CHUNKS -#endif -/*ability to convert error numerical codes to English text string*/ -#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT -#define LODEPNG_COMPILE_ERROR_TEXT -#endif -/*Compile the default allocators (C's free, malloc and realloc). If you disable this, -you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your -source files with custom allocators.*/ -#ifndef LODEPNG_NO_COMPILE_ALLOCATORS -#define LODEPNG_COMPILE_ALLOCATORS -#endif -/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/ -#ifdef __cplusplus -#ifndef LODEPNG_NO_COMPILE_CPP -#define LODEPNG_COMPILE_CPP -#endif -#endif - -#ifdef LODEPNG_COMPILE_PNG -/*The PNG color types (also used for raw).*/ -typedef enum LodePNGColorType -{ - LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/ - LCT_RGB = 2, /*RGB: 8,16 bit*/ - LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ - LCT_GREY_ALPHA = 4, /*greyscale with alpha: 8,16 bit*/ - LCT_RGBA = 6 /*RGB with alpha: 8,16 bit*/ -} LodePNGColorType; - -#ifdef LODEPNG_COMPILE_DECODER -/* -Converts PNG data in memory to raw pixel data. -out: Output parameter. Pointer to buffer that will contain the raw pixel data. - After decoding, its size is w * h * (bytes per pixel) bytes larger than - initially. Bytes per pixel depends on colortype and bitdepth. - Must be freed after usage with free(*out). - Note: for 16-bit per channel colors, uses big endian format like PNG does. -w: Output parameter. Pointer to width of pixel data. -h: Output parameter. Pointer to height of pixel data. -in: Memory buffer with the PNG file. -insize: size of the in buffer. -colortype: the desired color type for the raw output image. See explanation on PNG color types. -bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types. -Return value: LodePNG error code (0 means no error). -*/ -unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, - const unsigned char* in, size_t insize, - LodePNGColorType colortype, unsigned bitdepth); - -/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/ -unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, - const unsigned char* in, size_t insize); - -/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/ -unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, - const unsigned char* in, size_t insize); - -#ifdef LODEPNG_COMPILE_DISK -/* -Load PNG from disk, from file with given name. -Same as the other decode functions, but instead takes a filename as input. -*/ -unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, - const char* filename, - LodePNGColorType colortype, unsigned bitdepth); - -/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/ -unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, - const char* filename); - -/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/ -unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, - const char* filename); -#endif /*LODEPNG_COMPILE_DISK*/ -#endif /*LODEPNG_COMPILE_DECODER*/ - - -#ifdef LODEPNG_COMPILE_ENCODER -/* -Converts raw pixel data into a PNG image in memory. The colortype and bitdepth - of the output PNG image cannot be chosen, they are automatically determined - by the colortype, bitdepth and content of the input pixel data. - Note: for 16-bit per channel colors, needs big endian format like PNG does. -out: Output parameter. Pointer to buffer that will contain the PNG image data. - Must be freed after usage with free(*out). -outsize: Output parameter. Pointer to the size in bytes of the out buffer. -image: The raw pixel data to encode. The size of this buffer should be - w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth. -w: width of the raw pixel data in pixels. -h: height of the raw pixel data in pixels. -colortype: the color type of the raw input image. See explanation on PNG color types. -bitdepth: the bit depth of the raw input image. See explanation on PNG color types. -Return value: LodePNG error code (0 means no error). -*/ -unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, - const unsigned char* image, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth); - -/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/ -unsigned lodepng_encode32(unsigned char** out, size_t* outsize, - const unsigned char* image, unsigned w, unsigned h); - -/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/ -unsigned lodepng_encode24(unsigned char** out, size_t* outsize, - const unsigned char* image, unsigned w, unsigned h); - -#ifdef LODEPNG_COMPILE_DISK -/* -Converts raw pixel data into a PNG file on disk. -Same as the other encode functions, but instead takes a filename as output. -NOTE: This overwrites existing files without warning! -*/ -unsigned lodepng_encode_file(const char* filename, - const unsigned char* image, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth); - -/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/ -unsigned lodepng_encode32_file(const char* filename, - const unsigned char* image, unsigned w, unsigned h); - -/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/ -unsigned lodepng_encode24_file(const char* filename, - const unsigned char* image, unsigned w, unsigned h); -#endif /*LODEPNG_COMPILE_DISK*/ -#endif /*LODEPNG_COMPILE_ENCODER*/ - - -#ifdef LODEPNG_COMPILE_CPP -namespace lodepng -{ -#ifdef LODEPNG_COMPILE_DECODER -/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype -is the format to output the pixels to. Default is RGBA 8-bit per channel.*/ -unsigned decode(std::vector& out, unsigned& w, unsigned& h, - const unsigned char* in, size_t insize, - LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); -unsigned decode(std::vector& out, unsigned& w, unsigned& h, - const std::vector& in, - LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); -#ifdef LODEPNG_COMPILE_DISK -/* -Converts PNG file from disk to raw pixel data in memory. -Same as the other decode functions, but instead takes a filename as input. -*/ -unsigned decode(std::vector& out, unsigned& w, unsigned& h, - const std::string& filename, - LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); -#endif //LODEPNG_COMPILE_DISK -#endif //LODEPNG_COMPILE_DECODER - -#ifdef LODEPNG_COMPILE_ENCODER -/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype -is that of the raw input data. The output PNG color type will be auto chosen.*/ -unsigned encode(std::vector& out, - const unsigned char* in, unsigned w, unsigned h, - LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); -unsigned encode(std::vector& out, - const std::vector& in, unsigned w, unsigned h, - LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); -#ifdef LODEPNG_COMPILE_DISK -/* -Converts 32-bit RGBA raw pixel data into a PNG file on disk. -Same as the other encode functions, but instead takes a filename as output. -NOTE: This overwrites existing files without warning! -*/ -unsigned encode(const std::string& filename, - const unsigned char* in, unsigned w, unsigned h, - LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); -unsigned encode(const std::string& filename, - const std::vector& in, unsigned w, unsigned h, - LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); -#endif //LODEPNG_COMPILE_DISK -#endif //LODEPNG_COMPILE_ENCODER -} //namespace lodepng -#endif /*LODEPNG_COMPILE_CPP*/ -#endif /*LODEPNG_COMPILE_PNG*/ - -#ifdef LODEPNG_COMPILE_ERROR_TEXT -/*Returns an English description of the numerical error code.*/ -const char* lodepng_error_text(unsigned code); -#endif /*LODEPNG_COMPILE_ERROR_TEXT*/ - -#ifdef LODEPNG_COMPILE_DECODER -/*Settings for zlib decompression*/ -typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; -struct LodePNGDecompressSettings -{ - unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ - - /*use custom zlib decoder instead of built in one (default: null)*/ - unsigned (*custom_zlib)(unsigned char**, size_t*, - const unsigned char*, size_t, - const LodePNGDecompressSettings*); - /*use custom deflate decoder instead of built in one (default: null) - if custom_zlib is used, custom_deflate is ignored since only the built in - zlib function will call custom_deflate*/ - unsigned (*custom_inflate)(unsigned char**, size_t*, - const unsigned char*, size_t, - const LodePNGDecompressSettings*); - - const void* custom_context; /*optional custom settings for custom functions*/ -}; - -extern const LodePNGDecompressSettings lodepng_default_decompress_settings; -void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings); -#endif /*LODEPNG_COMPILE_DECODER*/ - -#ifdef LODEPNG_COMPILE_ENCODER -/* -Settings for zlib compression. Tweaking these settings tweaks the balance -between speed and compression ratio. -*/ -typedef struct LodePNGCompressSettings LodePNGCompressSettings; -struct LodePNGCompressSettings /*deflate = compress*/ -{ - /*LZ77 related settings*/ - unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ - unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ - unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/ - unsigned minmatch; /*mininum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/ - unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/ - unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ - - /*use custom zlib encoder instead of built in one (default: null)*/ - unsigned (*custom_zlib)(unsigned char**, size_t*, - const unsigned char*, size_t, - const LodePNGCompressSettings*); - /*use custom deflate encoder instead of built in one (default: null) - if custom_zlib is used, custom_deflate is ignored since only the built in - zlib function will call custom_deflate*/ - unsigned (*custom_deflate)(unsigned char**, size_t*, - const unsigned char*, size_t, - const LodePNGCompressSettings*); - - const void* custom_context; /*optional custom settings for custom functions*/ -}; - -extern const LodePNGCompressSettings lodepng_default_compress_settings; -void lodepng_compress_settings_init(LodePNGCompressSettings* settings); -#endif /*LODEPNG_COMPILE_ENCODER*/ - -#ifdef LODEPNG_COMPILE_PNG -/* -Color mode of an image. Contains all information required to decode the pixel -bits to RGBA colors. This information is the same as used in the PNG file -format, and is used both for PNG and raw image data in LodePNG. -*/ -typedef struct LodePNGColorMode -{ - /*header (IHDR)*/ - LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ - unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ - - /* - palette (PLTE and tRNS) - - Dynamically allocated with the colors of the palette, including alpha. - When encoding a PNG, to store your colors in the palette of the LodePNGColorMode, first use - lodepng_palette_clear, then for each color use lodepng_palette_add. - If you encode an image without alpha with palette, don't forget to put value 255 in each A byte of the palette. - - When decoding, by default you can ignore this palette, since LodePNG already - fills the palette colors in the pixels of the raw RGBA output. - - The palette is only supported for color type 3. - */ - unsigned char* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/ - size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/ - - /* - transparent color key (tRNS) - - This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit. - For greyscale PNGs, r, g and b will all 3 be set to the same. - - When decoding, by default you can ignore this information, since LodePNG sets - pixels with this key to transparent already in the raw RGBA output. - - The color key is only supported for color types 0 and 2. - */ - unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/ - unsigned key_r; /*red/greyscale component of color key*/ - unsigned key_g; /*green component of color key*/ - unsigned key_b; /*blue component of color key*/ -} LodePNGColorMode; - -/*init, cleanup and copy functions to use with this struct*/ -void lodepng_color_mode_init(LodePNGColorMode* info); -void lodepng_color_mode_cleanup(LodePNGColorMode* info); -/*return value is error code (0 means no error)*/ -unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source); - -void lodepng_palette_clear(LodePNGColorMode* info); -/*add 1 color to the palette*/ -unsigned lodepng_palette_add(LodePNGColorMode* info, - unsigned char r, unsigned char g, unsigned char b, unsigned char a); - -/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/ -unsigned lodepng_get_bpp(const LodePNGColorMode* info); -/*get the amount of color channels used, based on colortype in the struct. -If a palette is used, it counts as 1 channel.*/ -unsigned lodepng_get_channels(const LodePNGColorMode* info); -/*is it a greyscale type? (only colortype 0 or 4)*/ -unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info); -/*has it got an alpha channel? (only colortype 2 or 6)*/ -unsigned lodepng_is_alpha_type(const LodePNGColorMode* info); -/*has it got a palette? (only colortype 3)*/ -unsigned lodepng_is_palette_type(const LodePNGColorMode* info); -/*only returns true if there is a palette and there is a value in the palette with alpha < 255. -Loops through the palette to check this.*/ -unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info); -/* -Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image. -Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels). -Returns false if the image can only have opaque pixels. -In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values, -or if "key_defined" is true. -*/ -unsigned lodepng_can_have_alpha(const LodePNGColorMode* info); -/*Returns the byte size of a raw image buffer with given width, height and color mode*/ -size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color); - -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS -/*The information of a Time chunk in PNG.*/ -typedef struct LodePNGTime -{ - unsigned year; /*2 bytes used (0-65535)*/ - unsigned month; /*1-12*/ - unsigned day; /*1-31*/ - unsigned hour; /*0-23*/ - unsigned minute; /*0-59*/ - unsigned second; /*0-60 (to allow for leap seconds)*/ -} LodePNGTime; -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - -/*Information about the PNG image, except pixels, width and height.*/ -typedef struct LodePNGInfo -{ - /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ - unsigned compression_method;/*compression method of the original file. Always 0.*/ - unsigned filter_method; /*filter method of the original file*/ - unsigned interlace_method; /*interlace method of the original file*/ - LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ - -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /* - suggested background color chunk (bKGD) - This color uses the same color mode as the PNG (except alpha channel), which can be 1-bit to 16-bit. - - For greyscale PNGs, r, g and b will all 3 be set to the same. When encoding - the encoder writes the red one. For palette PNGs: When decoding, the RGB value - will be stored, not a palette index. But when encoding, specify the index of - the palette in background_r, the other two are then ignored. - - The decoder does not use this background color to edit the color of pixels. - */ - unsigned background_defined; /*is a suggested background color given?*/ - unsigned background_r; /*red component of suggested background color*/ - unsigned background_g; /*green component of suggested background color*/ - unsigned background_b; /*blue component of suggested background color*/ - - /* - non-international text chunks (tEXt and zTXt) - - The char** arrays each contain num strings. The actual messages are in - text_strings, while text_keys are keywords that give a short description what - the actual text represents, e.g. Title, Author, Description, or anything else. - - A keyword is minimum 1 character and maximum 79 characters long. It's - discouraged to use a single line length longer than 79 characters for texts. - - Don't allocate these text buffers yourself. Use the init/cleanup functions - correctly and use lodepng_add_text and lodepng_clear_text. - */ - size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ - char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ - char** text_strings; /*the actual text*/ - - /* - international text chunks (iTXt) - Similar to the non-international text chunks, but with additional strings - "langtags" and "transkeys". - */ - size_t itext_num; /*the amount of international texts in this PNG*/ - char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ - char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ - char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ - char** itext_strings; /*the actual international text - UTF-8 string*/ - - /*time chunk (tIME)*/ - unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ - LodePNGTime time; - - /*phys chunk (pHYs)*/ - unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/ - unsigned phys_x; /*pixels per unit in x direction*/ - unsigned phys_y; /*pixels per unit in y direction*/ - unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/ - - /* - unknown chunks - There are 3 buffers, one for each position in the PNG where unknown chunks can appear - each buffer contains all unknown chunks for that position consecutively - The 3 buffers are the unknown chunks between certain critical chunks: - 0: IHDR-PLTE, 1: PLTE-IDAT, 2: IDAT-IEND - Do not allocate or traverse this data yourself. Use the chunk traversing functions declared - later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. - */ - unsigned char* unknown_chunks_data[3]; - size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ -} LodePNGInfo; - -/*init, cleanup and copy functions to use with this struct*/ -void lodepng_info_init(LodePNGInfo* info); -void lodepng_info_cleanup(LodePNGInfo* info); -/*return value is error code (0 means no error)*/ -unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source); - -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS -void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ -unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/ - -void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/ -unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, - const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/ -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - -/* -Converts raw buffer from one color type to another color type, based on -LodePNGColorMode structs to describe the input and output color type. -See the reference manual at the end of this header file to see which color conversions are supported. -return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported) -The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel -of the output color type (lodepng_get_bpp). -For < 8 bpp images, there should not be padding bits at the end of scanlines. -For 16-bit per channel colors, uses big endian format like PNG does. -Return value is LodePNG error code -*/ -unsigned lodepng_convert(unsigned char* out, const unsigned char* in, - LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, - unsigned w, unsigned h); - -#ifdef LODEPNG_COMPILE_DECODER -/* -Settings for the decoder. This contains settings for the PNG and the Zlib -decoder, but not the Info settings from the Info structs. -*/ -typedef struct LodePNGDecoderSettings -{ - LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ - - unsigned ignore_crc; /*ignore CRC checksums*/ - - unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ - -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/ - /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/ - unsigned remember_unknown_chunks; -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ -} LodePNGDecoderSettings; - -void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); -#endif /*LODEPNG_COMPILE_DECODER*/ - -#ifdef LODEPNG_COMPILE_ENCODER -/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/ -typedef enum LodePNGFilterStrategy -{ - /*every filter at zero*/ - LFS_ZERO, - /*Use filter that gives minumum sum, as described in the official PNG filter heuristic.*/ - LFS_MINSUM, - /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending - on the image, this is better or worse than minsum.*/ - LFS_ENTROPY, - /* - Brute-force-search PNG filters by compressing each filter for each scanline. - Experimental, very slow, and only rarely gives better compression than MINSUM. - */ - LFS_BRUTE_FORCE, - /*use predefined_filters buffer: you specify the filter type for each scanline*/ - LFS_PREDEFINED -} LodePNGFilterStrategy; - -/*Gives characteristics about the colors of the image, which helps decide which color model to use for encoding. -Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms.*/ -typedef struct LodePNGColorProfile -{ - unsigned colored; /*not greyscale*/ - unsigned key; /*if true, image is not opaque. Only if true and alpha is false, color key is possible.*/ - unsigned short key_r; /*these values are always in 16-bit bitdepth in the profile*/ - unsigned short key_g; - unsigned short key_b; - unsigned alpha; /*alpha channel or alpha palette required*/ - unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/ - unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/ - unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/ -} LodePNGColorProfile; - -void lodepng_color_profile_init(LodePNGColorProfile* profile); - -/*Get a LodePNGColorProfile of the image.*/ -unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, - const unsigned char* image, unsigned w, unsigned h, - const LodePNGColorMode* mode_in); -/*The function LodePNG uses internally to decide the PNG color with auto_convert. -Chooses an optimal color model, e.g. grey if only grey pixels, palette if < 256 colors, ...*/ -unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, - const unsigned char* image, unsigned w, unsigned h, - const LodePNGColorMode* mode_in); - -/*Settings for the encoder.*/ -typedef struct LodePNGEncoderSettings -{ - LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ - - unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ - - /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than - 8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to - completely follow the official PNG heuristic, filter_palette_zero must be true and - filter_strategy must be LFS_MINSUM*/ - unsigned filter_palette_zero; - /*Which filter strategy to use when not using zeroes due to filter_palette_zero. - Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/ - LodePNGFilterStrategy filter_strategy; - /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with - the same length as the amount of scanlines in the image, and each value must <= 5. You - have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero - must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ - const unsigned char* predefined_filters; - - /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). - If colortype is 3, PLTE is _always_ created.*/ - unsigned force_palette; -#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*add LodePNG identifier and version as a text chunk, for debugging*/ - unsigned add_id; - /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/ - unsigned text_compression; -#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ -} LodePNGEncoderSettings; - -void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); -#endif /*LODEPNG_COMPILE_ENCODER*/ - - -#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) -/*The settings, state and information for extended encoding and decoding.*/ -typedef struct LodePNGState -{ -#ifdef LODEPNG_COMPILE_DECODER - LodePNGDecoderSettings decoder; /*the decoding settings*/ -#endif /*LODEPNG_COMPILE_DECODER*/ -#ifdef LODEPNG_COMPILE_ENCODER - LodePNGEncoderSettings encoder; /*the encoding settings*/ -#endif /*LODEPNG_COMPILE_ENCODER*/ - LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/ - LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/ - unsigned error; -#ifdef LODEPNG_COMPILE_CPP - //For the lodepng::State subclass. - virtual ~LodePNGState(){} -#endif -} LodePNGState; - -/*init, cleanup and copy functions to use with this struct*/ -void lodepng_state_init(LodePNGState* state); -void lodepng_state_cleanup(LodePNGState* state); -void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source); -#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ - -#ifdef LODEPNG_COMPILE_DECODER -/* -Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and -getting much more information about the PNG image and color mode. -*/ -unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, - LodePNGState* state, - const unsigned char* in, size_t insize); - -/* -Read the PNG header, but not the actual data. This returns only the information -that is in the header chunk of the PNG, such as width, height and color type. The -information is placed in the info_png field of the LodePNGState. -*/ -unsigned lodepng_inspect(unsigned* w, unsigned* h, - LodePNGState* state, - const unsigned char* in, size_t insize); -#endif /*LODEPNG_COMPILE_DECODER*/ - - -#ifdef LODEPNG_COMPILE_ENCODER -/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/ -unsigned lodepng_encode(unsigned char** out, size_t* outsize, - const unsigned char* image, unsigned w, unsigned h, - LodePNGState* state); -#endif /*LODEPNG_COMPILE_ENCODER*/ - -/* -The lodepng_chunk functions are normally not needed, except to traverse the -unknown chunks stored in the LodePNGInfo struct, or add new ones to it. -It also allows traversing the chunks of an encoded PNG file yourself. - -PNG standard chunk naming conventions: -First byte: uppercase = critical, lowercase = ancillary -Second byte: uppercase = public, lowercase = private -Third byte: must be uppercase -Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy -*/ - -/* -Gets the length of the data of the chunk. Total chunk length has 12 bytes more. -There must be at least 4 bytes to read from. If the result value is too large, -it may be corrupt data. -*/ -unsigned lodepng_chunk_length(const unsigned char* chunk); - -/*puts the 4-byte type in null terminated string*/ -void lodepng_chunk_type(char type[5], const unsigned char* chunk); - -/*check if the type is the given type*/ -unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type); - -/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/ -unsigned char lodepng_chunk_ancillary(const unsigned char* chunk); - -/*0: public, 1: private (see PNG standard)*/ -unsigned char lodepng_chunk_private(const unsigned char* chunk); - -/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/ -unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk); - -/*get pointer to the data of the chunk, where the input points to the header of the chunk*/ -unsigned char* lodepng_chunk_data(unsigned char* chunk); -const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk); - -/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/ -unsigned lodepng_chunk_check_crc(const unsigned char* chunk); - -/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/ -void lodepng_chunk_generate_crc(unsigned char* chunk); - -/*iterate to next chunks. don't use on IEND chunk, as there is no next chunk then*/ -unsigned char* lodepng_chunk_next(unsigned char* chunk); -const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk); - -/* -Appends chunk to the data in out. The given chunk should already have its chunk header. -The out variable and outlength are updated to reflect the new reallocated buffer. -Returns error code (0 if it went ok) -*/ -unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk); - -/* -Appends new chunk to out. The chunk to append is given by giving its length, type -and data separately. The type is a 4-letter string. -The out variable and outlength are updated to reflect the new reallocated buffer. -Returne error code (0 if it went ok) -*/ -unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, - const char* type, const unsigned char* data); - - -/*Calculate CRC32 of buffer*/ -unsigned lodepng_crc32(const unsigned char* buf, size_t len); -#endif /*LODEPNG_COMPILE_PNG*/ - - -#ifdef LODEPNG_COMPILE_ZLIB -/* -This zlib part can be used independently to zlib compress and decompress a -buffer. It cannot be used to create gzip files however, and it only supports the -part of zlib that is required for PNG, it does not support dictionaries. -*/ - -#ifdef LODEPNG_COMPILE_DECODER -/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/ -unsigned lodepng_inflate(unsigned char** out, size_t* outsize, - const unsigned char* in, size_t insize, - const LodePNGDecompressSettings* settings); - -/* -Decompresses Zlib data. Reallocates the out buffer and appends the data. The -data must be according to the zlib specification. -Either, *out must be NULL and *outsize must be 0, or, *out must be a valid -buffer and *outsize its size in bytes. out must be freed by user after usage. -*/ -unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, - const unsigned char* in, size_t insize, - const LodePNGDecompressSettings* settings); -#endif /*LODEPNG_COMPILE_DECODER*/ - -#ifdef LODEPNG_COMPILE_ENCODER -/* -Compresses data with Zlib. Reallocates the out buffer and appends the data. -Zlib adds a small header and trailer around the deflate data. -The data is output in the format of the zlib specification. -Either, *out must be NULL and *outsize must be 0, or, *out must be a valid -buffer and *outsize its size in bytes. out must be freed by user after usage. -*/ -unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, - const unsigned char* in, size_t insize, - const LodePNGCompressSettings* settings); - -/* -Find length-limited Huffman code for given frequencies. This function is in the -public interface only for tests, it's used internally by lodepng_deflate. -*/ -unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, - size_t numcodes, unsigned maxbitlen); - -/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/ -unsigned lodepng_deflate(unsigned char** out, size_t* outsize, - const unsigned char* in, size_t insize, - const LodePNGCompressSettings* settings); - -#endif /*LODEPNG_COMPILE_ENCODER*/ -#endif /*LODEPNG_COMPILE_ZLIB*/ - -#ifdef LODEPNG_COMPILE_DISK -/* -Load a file from disk into buffer. The function allocates the out buffer, and -after usage you should free it. -out: output parameter, contains pointer to loaded buffer. -outsize: output parameter, size of the allocated out buffer -filename: the path to the file to load -return value: error code (0 means ok) -*/ -unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename); - -/* -Save a file from buffer to disk. Warning, if it exists, this function overwrites -the file without warning! -buffer: the buffer to write -buffersize: size of the buffer to write -filename: the path to the file to save to -return value: error code (0 means ok) -*/ -unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename); -#endif /*LODEPNG_COMPILE_DISK*/ - -#ifdef LODEPNG_COMPILE_CPP -//The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. -namespace lodepng -{ -#ifdef LODEPNG_COMPILE_PNG -class State : public LodePNGState -{ - public: - State(); - State(const State& other); - virtual ~State(); - State& operator=(const State& other); -}; - -#ifdef LODEPNG_COMPILE_DECODER -//Same as other lodepng::decode, but using a State for more settings and information. -unsigned decode(std::vector& out, unsigned& w, unsigned& h, - State& state, - const unsigned char* in, size_t insize); -unsigned decode(std::vector& out, unsigned& w, unsigned& h, - State& state, - const std::vector& in); -#endif /*LODEPNG_COMPILE_DECODER*/ - -#ifdef LODEPNG_COMPILE_ENCODER -//Same as other lodepng::encode, but using a State for more settings and information. -unsigned encode(std::vector& out, - const unsigned char* in, unsigned w, unsigned h, - State& state); -unsigned encode(std::vector& out, - const std::vector& in, unsigned w, unsigned h, - State& state); -#endif /*LODEPNG_COMPILE_ENCODER*/ - -#ifdef LODEPNG_COMPILE_DISK -/* -Load a file from disk into an std::vector. If the vector is empty, then either -the file doesn't exist or is an empty file. -*/ -void load_file(std::vector& buffer, const std::string& filename); - -/* -Save the binary data in an std::vector to a file on disk. The file is overwritten -without warning. -*/ -void save_file(const std::vector& buffer, const std::string& filename); -#endif //LODEPNG_COMPILE_DISK -#endif //LODEPNG_COMPILE_PNG - -#ifdef LODEPNG_COMPILE_ZLIB -#ifdef LODEPNG_COMPILE_DECODER -//Zlib-decompress an unsigned char buffer -unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, - const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); - -//Zlib-decompress an std::vector -unsigned decompress(std::vector& out, const std::vector& in, - const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); -#endif //LODEPNG_COMPILE_DECODER - -#ifdef LODEPNG_COMPILE_ENCODER -//Zlib-compress an unsigned char buffer -unsigned compress(std::vector& out, const unsigned char* in, size_t insize, - const LodePNGCompressSettings& settings = lodepng_default_compress_settings); - -//Zlib-compress an std::vector -unsigned compress(std::vector& out, const std::vector& in, - const LodePNGCompressSettings& settings = lodepng_default_compress_settings); -#endif //LODEPNG_COMPILE_ENCODER -#endif //LODEPNG_COMPILE_ZLIB -} //namespace lodepng -#endif /*LODEPNG_COMPILE_CPP*/ - -/* -TODO: -[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often -[.] check compatibility with vareous compilers - done but needs to be redone for every newer version -[X] converting color to 16-bit per channel types -[ ] read all public PNG chunk types (but never let the color profile and gamma ones touch RGB values) -[ ] make sure encoder generates no chunks with size > (2^31)-1 -[ ] partial decoding (stream processing) -[X] let the "isFullyOpaque" function check color keys and transparent palettes too -[X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl" -[ ] don't stop decoding on errors like 69, 57, 58 (make warnings) -[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes -[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ... -*/ - -#endif /*LODEPNG_H inclusion guard*/ - -/* -LodePNG Documentation ---------------------- - -0. table of contents --------------------- - - 1. about - 1.1. supported features - 1.2. features not supported - 2. C and C++ version - 3. security - 4. decoding - 5. encoding - 6. color conversions - 6.1. PNG color types - 6.2. color conversions - 6.3. padding bits - 6.4. A note about 16-bits per channel and endianness - 7. error values - 8. chunks and PNG editing - 9. compiler support - 10. examples - 10.1. decoder C++ example - 10.2. decoder C example - 11. changes - 12. contact information - - -1. about --------- - -PNG is a file format to store raster images losslessly with good compression, -supporting different color types and alpha channel. - -LodePNG is a PNG codec according to the Portable Network Graphics (PNG) -Specification (Second Edition) - W3C Recommendation 10 November 2003. - -The specifications used are: - -*) Portable Network Graphics (PNG) Specification (Second Edition): - http://www.w3.org/TR/2003/REC-PNG-20031110 -*) RFC 1950 ZLIB Compressed Data Format version 3.3: - http://www.gzip.org/zlib/rfc-zlib.html -*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3: - http://www.gzip.org/zlib/rfc-deflate.html - -The most recent version of LodePNG can currently be found at -http://lodev.org/lodepng/ - -LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds -extra functionality. - -LodePNG exists out of two files: --lodepng.h: the header file for both C and C++ --lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage - -If you want to start using LodePNG right away without reading this doc, get the -examples from the LodePNG website to see how to use it in code, or check the -smaller examples in chapter 13 here. - -LodePNG is simple but only supports the basic requirements. To achieve -simplicity, the following design choices were made: There are no dependencies -on any external library. There are functions to decode and encode a PNG with -a single function call, and extended versions of these functions taking a -LodePNGState struct allowing to specify or get more information. By default -the colors of the raw image are always RGB or RGBA, no matter what color type -the PNG file uses. To read and write files, there are simple functions to -convert the files to/from buffers in memory. - -This all makes LodePNG suitable for loading textures in games, demos and small -programs, ... It's less suitable for full fledged image editors, loading PNGs -over network (it requires all the image data to be available before decoding can -begin), life-critical systems, ... - -1.1. supported features ------------------------ - -The following features are supported by the decoder: - -*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image, - or the same color type as the PNG -*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image -*) Adam7 interlace and deinterlace for any color type -*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk -*) support for alpha channels, including RGBA color model, translucent palettes and color keying -*) zlib decompression (inflate) -*) zlib compression (deflate) -*) CRC32 and ADLER32 checksums -*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks. -*) the following chunks are supported (generated/interpreted) by both encoder and decoder: - IHDR: header information - PLTE: color palette - IDAT: pixel data - IEND: the final chunk - tRNS: transparency for palettized images - tEXt: textual information - zTXt: compressed textual information - iTXt: international textual information - bKGD: suggested background color - pHYs: physical dimensions - tIME: modification time - -1.2. features not supported ---------------------------- - -The following features are _not_ supported: - -*) some features needed to make a conformant PNG-Editor might be still missing. -*) partial loading/stream processing. All data must be available and is processed in one call. -*) The following public chunks are not supported but treated as unknown chunks by LodePNG - cHRM, gAMA, iCCP, sRGB, sBIT, hIST, sPLT - Some of these are not supported on purpose: LodePNG wants to provide the RGB values - stored in the pixels, not values modified by system dependent gamma or color models. - - -2. C and C++ version --------------------- - -The C version uses buffers allocated with alloc that you need to free() -yourself. You need to use init and cleanup functions for each struct whenever -using a struct from the C version to avoid exploits and memory leaks. - -The C++ version has extra functions with std::vectors in the interface and the -lodepng::State class which is a LodePNGState with constructor and destructor. - -These files work without modification for both C and C++ compilers because all -the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers -ignore it, and the C code is made to compile both with strict ISO C90 and C++. - -To use the C++ version, you need to rename the source file to lodepng.cpp -(instead of lodepng.c), and compile it with a C++ compiler. - -To use the C version, you need to rename the source file to lodepng.c (instead -of lodepng.cpp), and compile it with a C compiler. - - -3. Security ------------ - -Even if carefully designed, it's always possible that LodePNG contains possible -exploits. If you discover one, please let me know, and it will be fixed. - -When using LodePNG, care has to be taken with the C version of LodePNG, as well -as the C-style structs when working with C++. The following conventions are used -for all C-style structs: - --if a struct has a corresponding init function, always call the init function when making a new one --if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks --if a struct has a corresponding copy function, use the copy function instead of "=". - The destination must also be inited already. - - -4. Decoding ------------ - -Decoding converts a PNG compressed image to a raw pixel buffer. - -Most documentation on using the decoder is at its declarations in the header -above. For C, simple decoding can be done with functions such as -lodepng_decode32, and more advanced decoding can be done with the struct -LodePNGState and lodepng_decode. For C++, all decoding can be done with the -various lodepng::decode functions, and lodepng::State can be used for advanced -features. - -When using the LodePNGState, it uses the following fields for decoding: -*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here -*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get -*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use - -LodePNGInfo info_png --------------------- - -After decoding, this contains extra information of the PNG image, except the actual -pixels, width and height because these are already gotten directly from the decoder -functions. - -It contains for example the original color type of the PNG image, text comments, -suggested background color, etc... More details about the LodePNGInfo struct are -at its declaration documentation. - -LodePNGColorMode info_raw -------------------------- - -When decoding, here you can specify which color type you want -the resulting raw image to be. If this is different from the colortype of the -PNG, then the decoder will automatically convert the result. This conversion -always works, except if you want it to convert a color PNG to greyscale or to -a palette with missing colors. - -By default, 32-bit color is used for the result. - -LodePNGDecoderSettings decoder ------------------------------- - -The settings can be used to ignore the errors created by invalid CRC and Adler32 -chunks, and to disable the decoding of tEXt chunks. - -There's also a setting color_convert, true by default. If false, no conversion -is done, the resulting data will be as it was in the PNG (after decompression) -and you'll have to puzzle the colors of the pixels together yourself using the -color type information in the LodePNGInfo. - - -5. Encoding ------------ - -Encoding converts a raw pixel buffer to a PNG compressed image. - -Most documentation on using the encoder is at its declarations in the header -above. For C, simple encoding can be done with functions such as -lodepng_encode32, and more advanced decoding can be done with the struct -LodePNGState and lodepng_encode. For C++, all encoding can be done with the -various lodepng::encode functions, and lodepng::State can be used for advanced -features. - -Like the decoder, the encoder can also give errors. However it gives less errors -since the encoder input is trusted, the decoder input (a PNG image that could -be forged by anyone) is not trusted. - -When using the LodePNGState, it uses the following fields for encoding: -*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be. -*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has -*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use - -LodePNGInfo info_png --------------------- - -When encoding, you use this the opposite way as when decoding: for encoding, -you fill in the values you want the PNG to have before encoding. By default it's -not needed to specify a color type for the PNG since it's automatically chosen, -but it's possible to choose it yourself given the right settings. - -The encoder will not always exactly match the LodePNGInfo struct you give, -it tries as close as possible. Some things are ignored by the encoder. The -encoder uses, for example, the following settings from it when applicable: -colortype and bitdepth, text chunks, time chunk, the color key, the palette, the -background color, the interlace method, unknown chunks, ... - -When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk. -If the palette contains any colors for which the alpha channel is not 255 (so -there are translucent colors in the palette), it'll add a tRNS chunk. - -LodePNGColorMode info_raw -------------------------- - -You specify the color type of the raw image that you give to the input here, -including a possible transparent color key and palette you happen to be using in -your raw image data. - -By default, 32-bit color is assumed, meaning your input has to be in RGBA -format with 4 bytes (unsigned chars) per pixel. - -LodePNGEncoderSettings encoder ------------------------------- - -The following settings are supported (some are in sub-structs): -*) auto_convert: when this option is enabled, the encoder will -automatically choose the smallest possible color mode (including color key) that -can encode the colors of all pixels without information loss. -*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree, - 2 = dynamic huffman tree (best compression). Should be 2 for proper - compression. -*) use_lz77: whether or not to use LZ77 for compressed block types. Should be - true for proper compression. -*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value - 2048 by default, but can be set to 32768 for better, but slow, compression. -*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE - chunk if force_palette is true. This can used as suggested palette to convert - to by viewers that don't support more than 256 colors (if those still exist) -*) add_id: add text chunk "Encoder: LodePNG " to the image. -*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks. - zTXt chunks use zlib compression on the text. This gives a smaller result on - large texts but a larger result on small texts (such as a single program name). - It's all tEXt or all zTXt though, there's no separate setting per text yet. - - -6. color conversions --------------------- - -An important thing to note about LodePNG, is that the color type of the PNG, and -the color type of the raw image, are completely independent. By default, when -you decode a PNG, you get the result as a raw image in the color type you want, -no matter whether the PNG was encoded with a palette, greyscale or RGBA color. -And if you encode an image, by default LodePNG will automatically choose the PNG -color type that gives good compression based on the values of colors and amount -of colors in the image. It can be configured to let you control it instead as -well, though. - -To be able to do this, LodePNG does conversions from one color mode to another. -It can convert from almost any color type to any other color type, except the -following conversions: RGB to greyscale is not supported, and converting to a -palette when the palette doesn't have a required color is not supported. This is -not supported on purpose: this is information loss which requires a color -reduction algorithm that is beyong the scope of a PNG encoder (yes, RGB to grey -is easy, but there are multiple ways if you want to give some channels more -weight). - -By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB -color, no matter what color type the PNG has. And by default when encoding, -LodePNG automatically picks the best color model for the output PNG, and expects -the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control -the color format of the images yourself, you can skip this chapter. - -6.1. PNG color types --------------------- - -A PNG image can have many color types, ranging from 1-bit color to 64-bit color, -as well as palettized color modes. After the zlib decompression and unfiltering -in the PNG image is done, the raw pixel data will have that color type and thus -a certain amount of bits per pixel. If you want the output raw image after -decoding to have another color type, a conversion is done by LodePNG. - -The PNG specification gives the following color types: - -0: greyscale, bit depths 1, 2, 4, 8, 16 -2: RGB, bit depths 8 and 16 -3: palette, bit depths 1, 2, 4 and 8 -4: greyscale with alpha, bit depths 8 and 16 -6: RGBA, bit depths 8 and 16 - -Bit depth is the amount of bits per pixel per color channel. So the total amount -of bits per pixel is: amount of channels * bitdepth. - -6.2. color conversions ----------------------- - -As explained in the sections about the encoder and decoder, you can specify -color types and bit depths in info_png and info_raw to change the default -behaviour. - -If, when decoding, you want the raw image to be something else than the default, -you need to set the color type and bit depth you want in the LodePNGColorMode, -or the parameters colortype and bitdepth of the simple decoding function. - -If, when encoding, you use another color type than the default in the raw input -image, you need to specify its color type and bit depth in the LodePNGColorMode -of the raw image, or use the parameters colortype and bitdepth of the simple -encoding function. - -If, when encoding, you don't want LodePNG to choose the output PNG color type -but control it yourself, you need to set auto_convert in the encoder settings -to false, and specify the color type you want in the LodePNGInfo of the -encoder (including palette: it can generate a palette if auto_convert is true, -otherwise not). - -If the input and output color type differ (whether user chosen or auto chosen), -LodePNG will do a color conversion, which follows the rules below, and may -sometimes result in an error. - -To avoid some confusion: --the decoder converts from PNG to raw image --the encoder converts from raw image to PNG --the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image --the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG --when encoding, the color type in LodePNGInfo is ignored if auto_convert - is enabled, it is automatically generated instead --when decoding, the color type in LodePNGInfo is set by the decoder to that of the original - PNG image, but it can be ignored since the raw image has the color type you requested instead --if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion - between the color types is done if the color types are supported. If it is not - supported, an error is returned. If the types are the same, no conversion is done. --even though some conversions aren't supported, LodePNG supports loading PNGs from any - colortype and saving PNGs to any colortype, sometimes it just requires preparing - the raw image correctly before encoding. --both encoder and decoder use the same color converter. - -Non supported color conversions: --color to greyscale: no error is thrown, but the result will look ugly because -only the red channel is taken --anything to palette when that palette does not have that color in it: in this -case an error is thrown - -Supported color conversions: --anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA --any grey or grey+alpha, to grey or grey+alpha --anything to a palette, as long as the palette has the requested colors in it --removing alpha channel --higher to smaller bitdepth, and vice versa - -If you want no color conversion to be done (e.g. for speed or control): --In the encoder, you can make it save a PNG with any color type by giving the -raw color mode and LodePNGInfo the same color mode, and setting auto_convert to -false. --In the decoder, you can make it store the pixel data in the same color type -as the PNG has, by setting the color_convert setting to false. Settings in -info_raw are then ignored. - -The function lodepng_convert does the color conversion. It is available in the -interface but normally isn't needed since the encoder and decoder already call -it. - -6.3. padding bits ------------------ - -In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines -have a bit amount that isn't a multiple of 8, then padding bits are used so that each -scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output. -The raw input image you give to the encoder, and the raw output image you get from the decoder -will NOT have these padding bits, e.g. in the case of a 1-bit image with a width -of 7 pixels, the first pixel of the second scanline will the the 8th bit of the first byte, -not the first bit of a new byte. - -6.4. A note about 16-bits per channel and endianness ----------------------------------------------------- - -LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like -for any other color format. The 16-bit values are stored in big endian (most -significant byte first) in these arrays. This is the opposite order of the -little endian used by x86 CPU's. - -LodePNG always uses big endian because the PNG file format does so internally. -Conversions to other formats than PNG uses internally are not supported by -LodePNG on purpose, there are myriads of formats, including endianness of 16-bit -colors, the order in which you store R, G, B and A, and so on. Supporting and -converting to/from all that is outside the scope of LodePNG. - -This may mean that, depending on your use case, you may want to convert the big -endian output of LodePNG to little endian with a for loop. This is certainly not -always needed, many applications and libraries support big endian 16-bit colors -anyway, but it means you cannot simply cast the unsigned char* buffer to an -unsigned short* buffer on x86 CPUs. - - -7. error values ---------------- - -All functions in LodePNG that return an error code, return 0 if everything went -OK, or a non-zero code if there was an error. - -The meaning of the LodePNG error values can be retrieved with the function -lodepng_error_text: given the numerical error code, it returns a description -of the error in English as a string. - -Check the implementation of lodepng_error_text to see the meaning of each code. - - -8. chunks and PNG editing -------------------------- - -If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG -editor that should follow the rules about handling of unknown chunks, or if your -program is able to read other types of chunks than the ones handled by LodePNG, -then that's possible with the chunk functions of LodePNG. - -A PNG chunk has the following layout: - -4 bytes length -4 bytes type name -length bytes data -4 bytes CRC - -8.1. iterating through chunks ------------------------------ - -If you have a buffer containing the PNG image data, then the first chunk (the -IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the -signature of the PNG and are not part of a chunk. But if you start at byte 8 -then you have a chunk, and can check the following things of it. - -NOTE: none of these functions check for memory buffer boundaries. To avoid -exploits, always make sure the buffer contains all the data of the chunks. -When using lodepng_chunk_next, make sure the returned value is within the -allocated memory. - -unsigned lodepng_chunk_length(const unsigned char* chunk): - -Get the length of the chunk's data. The total chunk length is this length + 12. - -void lodepng_chunk_type(char type[5], const unsigned char* chunk): -unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type): - -Get the type of the chunk or compare if it's a certain type - -unsigned char lodepng_chunk_critical(const unsigned char* chunk): -unsigned char lodepng_chunk_private(const unsigned char* chunk): -unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk): - -Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are). -Check if the chunk is private (public chunks are part of the standard, private ones not). -Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical -chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your -program doesn't handle that type of unknown chunk. - -unsigned char* lodepng_chunk_data(unsigned char* chunk): -const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk): - -Get a pointer to the start of the data of the chunk. - -unsigned lodepng_chunk_check_crc(const unsigned char* chunk): -void lodepng_chunk_generate_crc(unsigned char* chunk): - -Check if the crc is correct or generate a correct one. - -unsigned char* lodepng_chunk_next(unsigned char* chunk): -const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk): - -Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these -functions do no boundary checking of the allocated data whatsoever, so make sure there is enough -data available in the buffer to be able to go to the next chunk. - -unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk): -unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, - const char* type, const unsigned char* data): - -These functions are used to create new chunks that are appended to the data in *out that has -length *outlength. The append function appends an existing chunk to the new data. The create -function creates a new chunk with the given parameters and appends it. Type is the 4-letter -name of the chunk. - -8.2. chunks in info_png ------------------------ - -The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3 -buffers (each with size) to contain 3 types of unknown chunks: -the ones that come before the PLTE chunk, the ones that come between the PLTE -and the IDAT chunks, and the ones that come after the IDAT chunks. -It's necessary to make the distionction between these 3 cases because the PNG -standard forces to keep the ordering of unknown chunks compared to the critical -chunks, but does not force any other ordering rules. - -info_png.unknown_chunks_data[0] is the chunks before PLTE -info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT -info_png.unknown_chunks_data[2] is the chunks after IDAT - -The chunks in these 3 buffers can be iterated through and read by using the same -way described in the previous subchapter. - -When using the decoder to decode a PNG, you can make it store all unknown chunks -if you set the option settings.remember_unknown_chunks to 1. By default, this -option is off (0). - -The encoder will always encode unknown chunks that are stored in the info_png. -If you need it to add a particular chunk that isn't known by LodePNG, you can -use lodepng_chunk_append or lodepng_chunk_create to the chunk data in -info_png.unknown_chunks_data[x]. - -Chunks that are known by LodePNG should not be added in that way. E.g. to make -LodePNG add a bKGD chunk, set background_defined to true and add the correct -parameters there instead. - - -9. compiler support -------------------- - -No libraries other than the current standard C library are needed to compile -LodePNG. For the C++ version, only the standard C++ library is needed on top. -Add the files lodepng.c(pp) and lodepng.h to your project, include -lodepng.h where needed, and your program can read/write PNG files. - -It is compatible with C90 and up, and C++03 and up. - -If performance is important, use optimization when compiling! For both the -encoder and decoder, this makes a large difference. - -Make sure that LodePNG is compiled with the same compiler of the same version -and with the same settings as the rest of the program, or the interfaces with -std::vectors and std::strings in C++ can be incompatible. - -CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets. - -*) gcc and g++ - -LodePNG is developed in gcc so this compiler is natively supported. It gives no -warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++ -version 4.7.1 on Linux, 32-bit and 64-bit. - -*) Clang - -Fully supported and warning-free. - -*) Mingw - -The Mingw compiler (a port of gcc for Windows) should be fully supported by -LodePNG. - -*) Visual Studio and Visual C++ Express Edition - -LodePNG should be warning-free with warning level W4. Two warnings were disabled -with pragmas though: warning 4244 about implicit conversions, and warning 4996 -where it wants to use a non-standard function fopen_s instead of the standard C -fopen. - -Visual Studio may want "stdafx.h" files to be included in each source file and -give an error "unexpected end of file while looking for precompiled header". -This is not standard C++ and will not be added to the stock LodePNG. You can -disable it for lodepng.cpp only by right clicking it, Properties, C/C++, -Precompiled Headers, and set it to Not Using Precompiled Headers there. - -NOTE: Modern versions of VS should be fully supported, but old versions, e.g. -VS6, are not guaranteed to work. - -*) Compilers on Macintosh - -LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for -C and C++. - -*) Other Compilers - -If you encounter problems on any compilers, feel free to let me know and I may -try to fix it if the compiler is modern and standards complient. - - -10. examples ------------- - -This decoder example shows the most basic usage of LodePNG. More complex -examples can be found on the LodePNG website. - -10.1. decoder C++ example -------------------------- - -#include "lodepng.h" -#include - -int main(int argc, char *argv[]) -{ - const char* filename = argc > 1 ? argv[1] : "test.png"; - - //load and decode - std::vector image; - unsigned width, height; - unsigned error = lodepng::decode(image, width, height, filename); - - //if there's an error, display it - if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; - - //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... -} - -10.2. decoder C example ------------------------ - -#include "lodepng.h" - -int main(int argc, char *argv[]) -{ - unsigned error; - unsigned char* image; - size_t width, height; - const char* filename = argc > 1 ? argv[1] : "test.png"; - - error = lodepng_decode32_file(&image, &width, &height, filename); - - if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error)); - - / * use image here * / - - free(image); - return 0; -} - - -11. changes ------------ - -The version number of LodePNG is the date of the change given in the format -yyyymmdd. - -Some changes aren't backwards compatible. Those are indicated with a (!) -symbol. - -*) 23 aug 2014: Reduced needless memory usage of decoder. -*) 28 jun 2014: Removed fix_png setting, always support palette OOB for - simplicity. Made ColorProfile public. -*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization. -*) 22 dec 2013: Power of two windowsize required for optimization. -*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key. -*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png). -*) 11 mar 2013 (!): Bugfix with custom free. Changed from "my" to "lodepng_" - prefix for the custom allocators and made it possible with a new #define to - use custom ones in your project without needing to change lodepng's code. -*) 28 jan 2013: Bugfix with color key. -*) 27 okt 2012: Tweaks in text chunk keyword length error handling. -*) 8 okt 2012 (!): Added new filter strategy (entropy) and new auto color mode. - (no palette). Better deflate tree encoding. New compression tweak settings. - Faster color conversions while decoding. Some internal cleanups. -*) 23 sep 2012: Reduced warnings in Visual Studio a little bit. -*) 1 sep 2012 (!): Removed #define's for giving custom (de)compression functions - and made it work with function pointers instead. -*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc - and free functions and toggle #defines from compiler flags. Small fixes. -*) 6 may 2012 (!): Made plugging in custom zlib/deflate functions more flexible. -*) 22 apr 2012 (!): Made interface more consistent, renaming a lot. Removed - redundant C++ codec classes. Reduced amount of structs. Everything changed, - but it is cleaner now imho and functionality remains the same. Also fixed - several bugs and shrinked the implementation code. Made new samples. -*) 6 nov 2011 (!): By default, the encoder now automatically chooses the best - PNG color model and bit depth, based on the amount and type of colors of the - raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color. -*) 9 okt 2011: simpler hash chain implementation for the encoder. -*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching. -*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking. - A bug with the PNG filtertype heuristic was fixed, so that it chooses much - better ones (it's quite significant). A setting to do an experimental, slow, - brute force search for PNG filter types is added. -*) 17 aug 2011 (!): changed some C zlib related function names. -*) 16 aug 2011: made the code less wide (max 120 characters per line). -*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors. -*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled. -*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman - to optimize long sequences of zeros. -*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and - LodePNG_InfoColor_canHaveAlpha functions for convenience. -*) 7 nov 2010: added LodePNG_error_text function to get error code description. -*) 30 okt 2010: made decoding slightly faster -*) 26 okt 2010: (!) changed some C function and struct names (more consistent). - Reorganized the documentation and the declaration order in the header. -*) 08 aug 2010: only changed some comments and external samples. -*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version. -*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers. -*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could - read by ignoring the problem but windows apps couldn't. -*) 06 jun 2008: added more error checks for out of memory cases. -*) 26 apr 2008: added a few more checks here and there to ensure more safety. -*) 06 mar 2008: crash with encoding of strings fixed -*) 02 feb 2008: support for international text chunks added (iTXt) -*) 23 jan 2008: small cleanups, and #defines to divide code in sections -*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor. -*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder. -*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added - Also vareous fixes, such as in the deflate and the padding bits code. -*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved - filtering code of encoder. -*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A - C++ wrapper around this provides an interface almost identical to before. - Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code - are together in these files but it works both for C and C++ compilers. -*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks -*) 30 aug 2007: bug fixed which makes this Borland C++ compatible -*) 09 aug 2007: some VS2005 warnings removed again -*) 21 jul 2007: deflate code placed in new namespace separate from zlib code -*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images -*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing - invalid std::vector element [0] fixed, and level 3 and 4 warnings removed -*) 02 jun 2007: made the encoder add a tag with version by default -*) 27 may 2007: zlib and png code separated (but still in the same file), - simple encoder/decoder functions added for more simple usage cases -*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69), - moved some examples from here to lodepng_examples.cpp -*) 12 may 2007: palette decoding bug fixed -*) 24 apr 2007: changed the license from BSD to the zlib license -*) 11 mar 2007: very simple addition: ability to encode bKGD chunks. -*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding - palettized PNG images. Plus little interface change with palette and texts. -*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes. - Fixed a bug where the end code of a block had length 0 in the Huffman tree. -*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented - and supported by the encoder, resulting in smaller PNGs at the output. -*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone. -*) 24 jan 2007: gave encoder an error interface. Added color conversion from any - greyscale type to 8-bit greyscale with or without alpha. -*) 21 jan 2007: (!) Totally changed the interface. It allows more color types - to convert to and is more uniform. See the manual for how it works now. -*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days: - encode/decode custom tEXt chunks, separate classes for zlib & deflate, and - at last made the decoder give errors for incorrect Adler32 or Crc. -*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel. -*) 29 dec 2006: Added support for encoding images without alpha channel, and - cleaned out code as well as making certain parts faster. -*) 28 dec 2006: Added "Settings" to the encoder. -*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now. - Removed some code duplication in the decoder. Fixed little bug in an example. -*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter. - Fixed a bug of the decoder with 16-bit per color. -*) 15 okt 2006: Changed documentation structure -*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the - given image buffer, however for now it's not compressed. -*) 08 sep 2006: (!) Changed to interface with a Decoder class -*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different - way. Renamed decodePNG to decodePNGGeneric. -*) 29 jul 2006: (!) Changed the interface: image info is now returned as a - struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy. -*) 28 jul 2006: Cleaned the code and added new error checks. - Corrected terminology "deflate" into "inflate". -*) 23 jun 2006: Added SDL example in the documentation in the header, this - example allows easy debugging by displaying the PNG and its transparency. -*) 22 jun 2006: (!) Changed way to obtain error value. Added - loadFile function for convenience. Made decodePNG32 faster. -*) 21 jun 2006: (!) Changed type of info vector to unsigned. - Changed position of palette in info vector. Fixed an important bug that - happened on PNGs with an uncompressed block. -*) 16 jun 2006: Internally changed unsigned into unsigned where - needed, and performed some optimizations. -*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them - in LodePNG namespace. Changed the order of the parameters. Rewrote the - documentation in the header. Renamed files to lodepng.cpp and lodepng.h -*) 22 apr 2006: Optimized and improved some code -*) 07 sep 2005: (!) Changed to std::vector interface -*) 12 aug 2005: Initial release (C++, decoder only) - - -12. contact information ------------------------ - -Feel free to contact me with suggestions, problems, comments, ... concerning -LodePNG. If you encounter a PNG image that doesn't work properly with this -decoder, feel free to send it and I'll use it to find and fix the problem. - -My email address is (puzzle the account and domain together with an @ symbol): -Domain: gmail dot com. -Account: lode dot vandevenne. - - -Copyright (c) 2005-2014 Lode Vandevenne -*/ diff -Nru nestopia-1.48/source/unix/video.cpp nestopia-1.49/source/unix/video.cpp --- nestopia-1.48/source/unix/video.cpp 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/video.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,884 +0,0 @@ -/* - * Nestopia UE - * - * Copyright (C) 2007-2008 R. Belmont - * Copyright (C) 2012-2017 R. Danbrook - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. - * - */ - -#include -#include -#include - -#include "core/api/NstApiEmulator.hpp" -#include "core/api/NstApiInput.hpp" -#include "core/api/NstApiVideo.hpp" -#include "core/api/NstApiNsf.hpp" - -#include "main.h" -#include "audio.h" -#include "video.h" -#include "config.h" -#include "cursor.h" -#include "font.h" -#include "png.h" - -#ifdef _GTK -#include "gtkui/gtkui.h" -#ifndef _APPLE -#define _EMBED -#endif -extern GtkWidget *drawingarea; -#endif - -using namespace Nes::Api; - -int drawtext = 0; -char textbuf[32]; - -bool drawtime = false; -char timebuf[6]; - -int overscan_offset, overscan_height; - -static uint32_t videobuf[VIDBUF_MAXSIZE]; // Maximum possible internal size - -SDL_Window *sdlwindow; -SDL_GLContext glcontext; -SDL_DisplayMode displaymode; - -Video::RenderState::Filter filter; -Video::RenderState renderstate; - -dimensions_t basesize, rendersize; - -extern void *custompalette; - -extern bool playing, nst_nsf, nst_pal; -extern settings_t conf; -extern nstpaths_t nstpaths; -extern Emulator emulator; - -// Shader sources -const GLchar* vshader_src = - "#version 150 core\n" - "in vec2 position;" - "in vec2 texcoord;" - "out vec2 outcoord;" - "void main() {" - " outcoord = texcoord;" - " gl_Position = vec4(position, 0.0, 1.0);" - "}"; - -const GLchar* fshader_src = - "#version 150 core\n" - "in vec2 outcoord;" - "out vec4 fragcolor;" - "uniform sampler2D nestex;" - "void main() {" - " fragcolor = texture(nestex, outcoord);" - "}"; - -GLuint vao; -GLuint vbo; -GLuint vshader; -GLuint fshader; -GLuint gl_shader_prog = 0; -GLuint gl_texture_id = 0; - -void ogl_init() { - // Initialize OpenGL - - float vertices[] = { - -1.0f, -1.0f, // Vertex 1 (X, Y) - -1.0f, 1.0f, // Vertex 2 (X, Y) - 1.0f, -1.0f, // Vertex 3 (X, Y) - 1.0f, 1.0f, // Vertex 4 (X, Y) - 0.0, 1.0, // Texture 1 (X, Y) - 0.0, 0.0, // Texture 2 (X, Y) - 1.0, 1.0, // Texture 3 (X, Y) - 1.0, 0.0 // Texture 4 (X, Y) - }; - - GLint status; - - glGenVertexArrays(1, &vao); - glBindVertexArray(vao); - - glGenBuffers(1, &vbo); - glBindBuffer(GL_ARRAY_BUFFER, vbo); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - - vshader = glCreateShader(GL_VERTEX_SHADER); - glShaderSource(vshader, 1, &vshader_src, NULL); - glCompileShader(vshader); - - glGetShaderiv(vshader, GL_COMPILE_STATUS, &status); - if (status == GL_FALSE) { fprintf(stderr, "Failed to compile vertex shader\n"); } - - fshader = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(fshader, 1, &fshader_src, NULL); - glCompileShader(fshader); - - glGetShaderiv(fshader, GL_COMPILE_STATUS, &status); - if (status == GL_FALSE) { fprintf(stderr, "Failed to compile fragment shader\n"); } - - GLuint gl_shader_prog = glCreateProgram(); - glAttachShader(gl_shader_prog, vshader); - glAttachShader(gl_shader_prog, fshader); - - glLinkProgram(gl_shader_prog); - - glValidateProgram(gl_shader_prog); - glGetProgramiv(gl_shader_prog, GL_LINK_STATUS, &status); - if (status == GL_FALSE) { fprintf(stderr, "Failed to link shader program\n"); } - - glUseProgram(gl_shader_prog); - - GLint posAttrib = glGetAttribLocation(gl_shader_prog, "position"); - glEnableVertexAttribArray(posAttrib); - glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0); - - GLint texAttrib = glGetAttribLocation(gl_shader_prog, "texcoord"); - glEnableVertexAttribArray(texAttrib); - glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 0, (void*)(8 * sizeof(GLfloat))); - - glGenTextures(1, &gl_texture_id); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, gl_texture_id); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, conf.video_linear_filter ? GL_LINEAR : GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - - conf.video_fullscreen ? - glViewport(displaymode.w / 2.0f - rendersize.w / 2.0f, 0, rendersize.w, rendersize.h) : - glViewport(0, 0, rendersize.w, rendersize.h); - - glUniform1i(glGetUniformLocation(gl_shader_prog, "nestex"), 0); -} - -void ogl_deinit() { - // Deinitialize OpenGL - if (gl_texture_id) { glDeleteTextures(1, &gl_texture_id); } - if (gl_shader_prog) { glDeleteProgram(gl_shader_prog); } - if (vshader) { glDeleteShader(vshader); } - if (fshader) { glDeleteShader(fshader); } - if (vao) { glDeleteVertexArrays(1, &vao); } - if (vbo) { glDeleteBuffers(1, &vbo); } -} - -void ogl_render() { - // Render the scene - glTexImage2D(GL_TEXTURE_2D, - 0, - GL_RGBA, - basesize.w, - overscan_height, - 0, - GL_BGRA, - GL_UNSIGNED_BYTE, - videobuf + overscan_offset); - - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - - video_swapbuffers(); -} - -void video_init() { - // Initialize video - ogl_deinit(); - - video_set_dimensions(); - video_set_filter(); - - ogl_init(); - - if (nst_nsf) { video_clear_buffer(); video_disp_nsf(); } - - video_set_cursor(); -} - -void video_toggle_fullscreen() { - // Toggle between fullscreen and window mode - if (!playing) { return; } - - conf.video_fullscreen ^= 1; - - if (conf.misc_disable_gui) { - Uint32 flags; - if (conf.video_fullscreen) { - flags = SDL_WINDOW_FULLSCREEN_DESKTOP; - } - else { flags = 0; } - SDL_SetWindowFullscreen(sdlwindow, flags); - SDL_SetWindowSize(sdlwindow, rendersize.w, rendersize.h); - } - #ifdef _EMBED - else { gtkui_toggle_fullscreen(); } - #endif - video_set_cursor(); - video_init(); -} - -void video_toggle_filter() { - conf.video_filter++; - - // Intentionally leaving out scalex - if (conf.video_filter > 4) { conf.video_filter = 0; } - - // The scalex filter only allows 3x scale and crashes otherwise - if (conf.video_filter == 5 && conf.video_scale_factor == 4) { - conf.video_scale_factor = 3; - } - - video_init(); -} - -void video_toggle_filterupdate() { - // Clear the filter update flag - Video video(emulator); - video.ClearFilterUpdateFlag(); -} - -void video_toggle_scalefactor() { - // Toggle video scale factor - conf.video_scale_factor++; - if (conf.video_scale_factor > 4) { conf.video_scale_factor = 1; } - - // The scalex filter only allows 3x scale and crashes otherwise - if (conf.video_filter == 5 && conf.video_scale_factor == 4) { - conf.video_scale_factor = 1; - } - - video_init(); -} - -void video_create_standalone() { - // Create a standalone SDL window - int displayindex; - - Uint32 windowflags = SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE; - - if (conf.video_fullscreen) { - SDL_ShowCursor(0); - windowflags |= SDL_WINDOW_FULLSCREEN_DESKTOP; - } - - sdlwindow = SDL_CreateWindow( - nstpaths.gamename, // window title - SDL_WINDOWPOS_UNDEFINED, // initial x position - SDL_WINDOWPOS_UNDEFINED, // initial y position - rendersize.w, // width, in pixels - rendersize.h, // height, in pixels - windowflags); - - if(sdlwindow == NULL) { - fprintf(stderr, "Could not create window: %s\n", SDL_GetError()); - } - - displayindex = SDL_GetWindowDisplayIndex(sdlwindow); - SDL_GetDesktopDisplayMode(displayindex, &displaymode); - //printf("w: %d\th: %d\n", displaymode.w, displaymode.h); - //printf("Window Flags: %x\n", SDL_GetWindowFlags(sdlwindow)); - - SDL_GL_MakeCurrent(sdlwindow, glcontext); - SDL_GL_SetSwapInterval(conf.timing_vsync); -} - -void video_create_embedded() { - // Create an embedded SDL window - #ifdef _EMBED - GdkDisplayManager *displaymanager = gdk_display_manager_get(); - GdkDisplay *display = gdk_display_manager_get_default_display(displaymanager); - - sdlwindow = SDL_CreateWindowFrom((void*)GDK_WINDOW_XID(gtk_widget_get_window(drawingarea))); - - int displayindex = SDL_GetWindowDisplayIndex(sdlwindow); - SDL_GetDesktopDisplayMode(displayindex, &displaymode); - - sdlwindow->flags |= SDL_WINDOW_OPENGL; - SDL_GL_LoadLibrary(NULL); - if (nst_nsf) { video_disp_nsf(); } - #endif -} - -void video_create() { - // Create the necessary window(s) - - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); - - #ifdef _EMBED - if (conf.misc_disable_gui) { - video_create_standalone(); - } - else { - video_create_embedded(); - } - glcontext = SDL_GL_CreateContext(sdlwindow); - #else - video_create_standalone(); - glcontext = SDL_GL_CreateContext(sdlwindow); - #endif - - if(glcontext == NULL) { - fprintf(stderr, "Could not create glcontext: %s\n", SDL_GetError()); - } - - fprintf(stderr, "OpenGL: %s\n", glGetString(GL_VERSION)); -} - -void video_swapbuffers() { - // Swap Buffers - SDL_GL_SwapWindow(sdlwindow); -} - -void video_destroy() { - // Destroy the video window - SDL_DestroyWindow(sdlwindow); -} - -void video_set_filter() { - // Set the filter - Video video(emulator); - int scalefactor = conf.video_scale_factor; - - switch(conf.video_filter) { - case 0: // None - filter = Video::RenderState::FILTER_NONE; - break; - - case 1: // NTSC - filter = Video::RenderState::FILTER_NTSC; - break; - - case 2: // xBR - switch (scalefactor) { - case 2: - filter = Video::RenderState::FILTER_2XBR; - break; - - case 3: - filter = Video::RenderState::FILTER_3XBR; - break; - - case 4: - filter = Video::RenderState::FILTER_4XBR; - break; - - default: - filter = Video::RenderState::FILTER_NONE; - break; - } - break; - - case 3: // scale HQx - switch (scalefactor) { - case 2: - filter = Video::RenderState::FILTER_HQ2X; - break; - - case 3: - filter = Video::RenderState::FILTER_HQ3X; - break; - - case 4: - filter = Video::RenderState::FILTER_HQ4X; - break; - - default: - filter = Video::RenderState::FILTER_NONE; - break; - } - break; - - case 4: // 2xSaI - filter = Video::RenderState::FILTER_2XSAI; - break; - - case 5: // scale x - switch (scalefactor) { - case 2: - filter = Video::RenderState::FILTER_SCALE2X; - break; - - case 3: - filter = Video::RenderState::FILTER_SCALE3X; - break; - - default: - filter = Video::RenderState::FILTER_NONE; - break; - } - break; - break; - } - - // Set the sprite limit: false = enable sprite limit, true = disable sprite limit - video.EnableUnlimSprites(conf.video_unlimited_sprites ? true : false); - - // Set Palette options - switch (conf.video_palette_mode) { - case 0: // YUV - video.GetPalette().SetMode(Video::Palette::MODE_YUV); - break; - - case 1: // RGB - video.GetPalette().SetMode(Video::Palette::MODE_RGB); - break; - - case 2: // Custom - video.GetPalette().SetMode(Video::Palette::MODE_CUSTOM); - video.GetPalette().SetCustom((const unsigned char (*)[3])custompalette, Video::Palette::EXT_PALETTE); - break; - - default: break; - } - - // Set YUV Decoder/Picture options - if (video.GetPalette().GetMode() == Video::Palette::MODE_YUV) { - switch (conf.video_decoder) { - case 0: // Consumer - video.SetDecoder(Video::DECODER_CONSUMER); - break; - - case 1: // Canonical - video.SetDecoder(Video::DECODER_CANONICAL); - break; - - case 2: // Alternative (Canonical with yellow boost) - video.SetDecoder(Video::DECODER_ALTERNATIVE); - break; - - default: break; - } - } - - video.SetBrightness(conf.video_brightness); - video.SetSaturation(conf.video_saturation); - video.SetContrast(conf.video_contrast); - video.SetHue(conf.video_hue); - - // Set NTSC options - if (conf.video_filter == 1) { - switch (conf.video_ntsc_mode) { - case 0: // Composite - video.SetSaturation(Video::DEFAULT_SATURATION_COMP); - video.SetSharpness(Video::DEFAULT_SHARPNESS_COMP); - video.SetColorResolution(Video::DEFAULT_COLOR_RESOLUTION_COMP); - video.SetColorBleed(Video::DEFAULT_COLOR_BLEED_COMP); - video.SetColorArtifacts(Video::DEFAULT_COLOR_ARTIFACTS_COMP); - video.SetColorFringing(Video::DEFAULT_COLOR_FRINGING_COMP); - break; - - case 1: // S-Video - video.SetSaturation(Video::DEFAULT_SATURATION_SVIDEO); - video.SetSharpness(Video::DEFAULT_SHARPNESS_SVIDEO); - video.SetColorResolution(Video::DEFAULT_COLOR_RESOLUTION_SVIDEO); - video.SetColorBleed(Video::DEFAULT_COLOR_BLEED_SVIDEO); - video.SetColorArtifacts(Video::DEFAULT_COLOR_ARTIFACTS_SVIDEO); - video.SetColorFringing(Video::DEFAULT_COLOR_FRINGING_SVIDEO); - break; - - case 2: // RGB - video.SetSaturation(Video::DEFAULT_SATURATION_RGB); - video.SetSharpness(Video::DEFAULT_SHARPNESS_RGB); - video.SetColorResolution(Video::DEFAULT_COLOR_RESOLUTION_RGB); - video.SetColorBleed(Video::DEFAULT_COLOR_BLEED_RGB); - video.SetColorArtifacts(Video::DEFAULT_COLOR_ARTIFACTS_RGB); - video.SetColorFringing(Video::DEFAULT_COLOR_FRINGING_RGB); - break; - - case 3: // Monochrome - video.SetSaturation(Video::DEFAULT_SATURATION_MONO); - video.SetSharpness(Video::DEFAULT_SHARPNESS_MONO); - video.SetColorResolution(Video::DEFAULT_COLOR_RESOLUTION_MONO); - video.SetColorBleed(Video::DEFAULT_COLOR_BLEED_MONO); - video.SetColorArtifacts(Video::DEFAULT_COLOR_ARTIFACTS_MONO); - video.SetColorFringing(Video::DEFAULT_COLOR_FRINGING_MONO); - break; - - case 4: // Custom - video.SetSaturation(conf.video_saturation); - video.SetSharpness(conf.video_ntsc_sharpness); - video.SetColorResolution(conf.video_ntsc_resolution); - video.SetColorBleed(conf.video_ntsc_bleed); - video.SetColorArtifacts(conf.video_ntsc_artifacts); - video.SetColorFringing(conf.video_ntsc_fringing); - break; - - default: break; - } - } - - // Set xBR options - if (conf.video_filter == 2) { - video.SetCornerRounding(conf.video_xbr_corner_rounding); - video.SetBlend(conf.video_xbr_pixel_blending); - } - - // Set up the render state parameters - renderstate.filter = filter; - renderstate.width = basesize.w; - renderstate.height = basesize.h; - renderstate.bits.count = 32; - - #if SDL_BYTEORDER == SDL_BIG_ENDIAN - renderstate.bits.mask.r = 0x000000ff; - renderstate.bits.mask.g = 0xff000000; - renderstate.bits.mask.b = 0x00ff0000; - #else - renderstate.bits.mask.r = 0x00ff0000; - renderstate.bits.mask.g = 0x0000ff00; - renderstate.bits.mask.b = 0x000000ff; - #endif - - if (NES_FAILED(video.SetRenderState(renderstate))) { - fprintf(stderr, "Nestopia core rejected render state\n"); - exit(1); - } -} - -void video_set_dimensions() { - // Set up the video dimensions - int scalefactor = conf.video_scale_factor; - int tvwidth = nst_pal ? PAL_TV_WIDTH : TV_WIDTH; - - switch(conf.video_filter) { - case 0: // None - basesize.w = Video::Output::WIDTH; - basesize.h = Video::Output::HEIGHT; - conf.video_tv_aspect == true ? rendersize.w = tvwidth * scalefactor : rendersize.w = basesize.w * scalefactor; - rendersize.h = basesize.h * scalefactor; - overscan_offset = basesize.w * OVERSCAN_TOP; - overscan_height = basesize.h - OVERSCAN_TOP - OVERSCAN_BOTTOM; - break; - - case 1: // NTSC - basesize.w = Video::Output::NTSC_WIDTH; - rendersize.w = (basesize.w / 2) * scalefactor; - basesize.h = Video::Output::HEIGHT; - rendersize.h = basesize.h * scalefactor; - overscan_offset = basesize.w * OVERSCAN_TOP; - overscan_height = basesize.h - OVERSCAN_TOP - OVERSCAN_BOTTOM; - break; - - case 2: // xBR - case 3: // HqX - case 5: // ScaleX - if (conf.video_filter == 5 && scalefactor == 4) { - fprintf(stderr, "error: ScaleX filter cannot scale to 4x\n"); - conf.video_scale_factor = scalefactor = 3; - } - - basesize.w = Video::Output::WIDTH * scalefactor; - basesize.h = Video::Output::HEIGHT * scalefactor; - conf.video_tv_aspect == true ? rendersize.w = tvwidth * scalefactor : rendersize.w = basesize.w; - rendersize.h = basesize.h; - overscan_offset = basesize.w * OVERSCAN_TOP * scalefactor; - overscan_height = basesize.h - (OVERSCAN_TOP + OVERSCAN_BOTTOM) * scalefactor; - break; - - case 4: // 2xSaI - basesize.w = Video::Output::WIDTH * 2; - basesize.h = Video::Output::HEIGHT * 2; - conf.video_tv_aspect == true ? rendersize.w = tvwidth * scalefactor : rendersize.w = Video::Output::WIDTH * scalefactor; - rendersize.h = Video::Output::HEIGHT * scalefactor; - overscan_offset = basesize.w * OVERSCAN_TOP * 2; - overscan_height = basesize.h - (OVERSCAN_TOP + OVERSCAN_BOTTOM) * 2; - break; - } - - if (!conf.video_unmask_overscan) { - rendersize.h -= (OVERSCAN_TOP + OVERSCAN_BOTTOM) * scalefactor; - } - else { overscan_offset = 0; overscan_height = basesize.h; } - - // Calculate the aspect from the height because it's smaller - float aspect = (float)displaymode.h / (float)rendersize.h; - - if (!conf.video_stretch_aspect && conf.video_fullscreen && sdlwindow) { - rendersize.h *= aspect; - rendersize.w *= aspect; - } - else if (conf.video_fullscreen && sdlwindow) { - rendersize.h = displaymode.h; - rendersize.w = displaymode.w; - } - - #ifdef _EMBED - if (conf.misc_disable_gui) { SDL_SetWindowSize(sdlwindow, rendersize.w, rendersize.h); } - else { gtkui_resize(); } - #else - SDL_SetWindowSize(sdlwindow, rendersize.w, rendersize.h); - #endif -} - -void video_set_cursor() { - // Set the cursor to what it needs to be - int cursor; - bool special; - - if (conf.misc_disable_cursor) { SDL_ShowCursor(false); } - else { - if (Input(emulator).GetConnectedController(0) == Input::ZAPPER || - Input(emulator).GetConnectedController(1) == Input::ZAPPER) { - special = true; - SDL_ShowCursor(true); // Must be set true to be modified if special - cursor_set_special(Input::ZAPPER); - } - else { - special = false; - cursor_set_default(); - } - - if (conf.video_fullscreen) { cursor = special; } - else { cursor = true; } - - SDL_ShowCursor(cursor); - } -} - -void video_set_title(const char *title) { - // Set the window title - SDL_SetWindowTitle(sdlwindow, title); -} - -long video_lock_screen(void*& ptr) { - ptr = videobuf; - return basesize.w * 4; -} - -void video_unlock_screen(void*) { - - int wscale = renderstate.width / 256; - int hscale = renderstate.height / 240; - - if (drawtext) { - //video_text_draw(textbuf, 8 * wscale, 16 * hscale); // Top - video_text_draw(textbuf, 8 * wscale, 218 * hscale); // Bottom - drawtext--; - } - - if (drawtime) { - video_text_draw(timebuf, 208 * wscale, 218 * hscale); - } - - ogl_render(); -} - -void video_screenshot_flip(unsigned char *pixels, int width, int height, int bytes) { - // Flip the pixels - int rowsize = width * bytes; - unsigned char *row = (unsigned char*)malloc(rowsize); - unsigned char *low = pixels; - unsigned char *high = &pixels[(height - 1) * rowsize]; - - for (; low < high; low += rowsize, high -= rowsize) { - memcpy(row, low, rowsize); - memcpy(low, high, rowsize); - memcpy(high, row, rowsize); - } - free(row); -} - -void video_screenshot(const char* filename) { - // Take a screenshot in .png format - unsigned char *pixels; - pixels = (unsigned char*)malloc(sizeof(unsigned char) * rendersize.w * rendersize.h * 4); - - // Read the pixels and flip them vertically - glReadPixels(0, 0, rendersize.w, rendersize.h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - video_screenshot_flip(pixels, rendersize.w, rendersize.h, 4); - - if (filename == NULL) { - // Set the filename - char sshotpath[512]; - snprintf(sshotpath, sizeof(sshotpath), "%sscreenshots/%s-%ld-%d.png", nstpaths.nstdir, nstpaths.gamename, time(NULL), rand() % 899 + 100); - - // Save the file - lodepng_encode32_file(sshotpath, (const unsigned char*)pixels, rendersize.w, rendersize.h); - fprintf(stderr, "Screenshot: %s\n", sshotpath); - } - else { - lodepng_encode32_file(filename, (const unsigned char*)pixels, rendersize.w, rendersize.h); - } - - free(pixels); -} - -void video_clear_buffer() { - // Write black to the video buffer - memset(videobuf, 0x00000000, VIDBUF_MAXSIZE); -} - -void video_disp_nsf() { - // Display NSF text - Nsf nsf(emulator); - - int wscale = renderstate.width / 256; - int hscale = renderstate.height / 240; - - video_text_draw(nsf.GetName(), 4 * wscale, 16 * hscale); - video_text_draw(nsf.GetArtist(), 4 * wscale, 28 * hscale); - video_text_draw(nsf.GetCopyright(), 4 * wscale, 40 * hscale); - - char currentsong[10]; - snprintf(currentsong, sizeof(currentsong), "%d / %d", nsf.GetCurrentSong() +1, nsf.GetNumSongs()); - video_text_draw(currentsong, 4 * wscale, 52 * hscale); - - ogl_render(); -} - -void video_text_draw(const char *text, int xpos, int ypos) { - // Draw text on screen - uint32_t w = 0xc0c0c0c0; - uint32_t b = 0x00000000; - - int numchars = strlen(text); - - int letterypos; - int letterxpos; - int letternum = 0; - - for (int tpos = 0; tpos < (8 * numchars); tpos+=8) { - video_text_match(text, &letterxpos, &letterypos, letternum); - for (int row = 0; row < 8; row++) { // Draw Rows - for (int col = 0; col < 8; col++) { // Draw Columns - switch (nesfont[row + letterypos][col + letterxpos]) { - case '.': - videobuf[xpos + ((ypos + row) * renderstate.width) + (col + tpos)] = w; - break; - - case '+': - videobuf[xpos + ((ypos + row) * renderstate.width) + (col + tpos)] = b; - break; - - default: break; - } - } - } - letternum++; - } -} - -void video_text_match(const char *text, int *xpos, int *ypos, int strpos) { - // Match letters to draw on screen - switch (text[strpos]) { - case ' ': *xpos = 0; *ypos = 0; break; - case '!': *xpos = 8; *ypos = 0; break; - case '"': *xpos = 16; *ypos = 0; break; - case '#': *xpos = 24; *ypos = 0; break; - case '$': *xpos = 32; *ypos = 0; break; - case '%': *xpos = 40; *ypos = 0; break; - case '&': *xpos = 48; *ypos = 0; break; - case '\'': *xpos = 56; *ypos = 0; break; - case '(': *xpos = 64; *ypos = 0; break; - case ')': *xpos = 72; *ypos = 0; break; - case '*': *xpos = 80; *ypos = 0; break; - case '+': *xpos = 88; *ypos = 0; break; - case ',': *xpos = 96; *ypos = 0; break; - case '-': *xpos = 104; *ypos = 0; break; - case '.': *xpos = 112; *ypos = 0; break; - case '/': *xpos = 120; *ypos = 0; break; - case '0': *xpos = 0; *ypos = 8; break; - case '1': *xpos = 8; *ypos = 8; break; - case '2': *xpos = 16; *ypos = 8; break; - case '3': *xpos = 24; *ypos = 8; break; - case '4': *xpos = 32; *ypos = 8; break; - case '5': *xpos = 40; *ypos = 8; break; - case '6': *xpos = 48; *ypos = 8; break; - case '7': *xpos = 56; *ypos = 8; break; - case '8': *xpos = 64; *ypos = 8; break; - case '9': *xpos = 72; *ypos = 8; break; - case ':': *xpos = 80; *ypos = 8; break; - case ';': *xpos = 88; *ypos = 8; break; - case '<': *xpos = 96; *ypos = 8; break; - case '=': *xpos = 104; *ypos = 8; break; - case '>': *xpos = 112; *ypos = 8; break; - case '?': *xpos = 120; *ypos = 8; break; - case '@': *xpos = 0; *ypos = 16; break; - case 'A': *xpos = 8; *ypos = 16; break; - case 'B': *xpos = 16; *ypos = 16; break; - case 'C': *xpos = 24; *ypos = 16; break; - case 'D': *xpos = 32; *ypos = 16; break; - case 'E': *xpos = 40; *ypos = 16; break; - case 'F': *xpos = 48; *ypos = 16; break; - case 'G': *xpos = 56; *ypos = 16; break; - case 'H': *xpos = 64; *ypos = 16; break; - case 'I': *xpos = 72; *ypos = 16; break; - case 'J': *xpos = 80; *ypos = 16; break; - case 'K': *xpos = 88; *ypos = 16; break; - case 'L': *xpos = 96; *ypos = 16; break; - case 'M': *xpos = 104; *ypos = 16; break; - case 'N': *xpos = 112; *ypos = 16; break; - case 'O': *xpos = 120; *ypos = 16; break; - case 'P': *xpos = 0; *ypos = 24; break; - case 'Q': *xpos = 8; *ypos = 24; break; - case 'R': *xpos = 16; *ypos = 24; break; - case 'S': *xpos = 24; *ypos = 24; break; - case 'T': *xpos = 32; *ypos = 24; break; - case 'U': *xpos = 40; *ypos = 24; break; - case 'V': *xpos = 48; *ypos = 24; break; - case 'W': *xpos = 56; *ypos = 24; break; - case 'X': *xpos = 64; *ypos = 24; break; - case 'Y': *xpos = 72; *ypos = 24; break; - case 'Z': *xpos = 80; *ypos = 24; break; - case '[': *xpos = 88; *ypos = 24; break; - case '\\': *xpos = 96; *ypos = 24; break; - case ']': *xpos = 104; *ypos = 24; break; - case '^': *xpos = 112; *ypos = 24; break; - case '_': *xpos = 120; *ypos = 24; break; - case '`': *xpos = 0; *ypos = 32; break; - case 'a': *xpos = 8; *ypos = 32; break; - case 'b': *xpos = 16; *ypos = 32; break; - case 'c': *xpos = 24; *ypos = 32; break; - case 'd': *xpos = 32; *ypos = 32; break; - case 'e': *xpos = 40; *ypos = 32; break; - case 'f': *xpos = 48; *ypos = 32; break; - case 'g': *xpos = 56; *ypos = 32; break; - case 'h': *xpos = 64; *ypos = 32; break; - case 'i': *xpos = 72; *ypos = 32; break; - case 'j': *xpos = 80; *ypos = 32; break; - case 'k': *xpos = 88; *ypos = 32; break; - case 'l': *xpos = 96; *ypos = 32; break; - case 'm': *xpos = 104; *ypos = 32; break; - case 'n': *xpos = 112; *ypos = 32; break; - case 'o': *xpos = 120; *ypos = 32; break; - case 'p': *xpos = 0; *ypos = 40; break; - case 'q': *xpos = 8; *ypos = 40; break; - case 'r': *xpos = 16; *ypos = 40; break; - case 's': *xpos = 24; *ypos = 40; break; - case 't': *xpos = 32; *ypos = 40; break; - case 'u': *xpos = 40; *ypos = 40; break; - case 'v': *xpos = 48; *ypos = 40; break; - case 'w': *xpos = 56; *ypos = 40; break; - case 'x': *xpos = 64; *ypos = 40; break; - case 'y': *xpos = 72; *ypos = 40; break; - case 'z': *xpos = 80; *ypos = 40; break; - case '{': *xpos = 88; *ypos = 40; break; - case '|': *xpos = 96; *ypos = 40; break; - case '}': *xpos = 104; *ypos = 40; break; - case '~': *xpos = 112; *ypos = 40; break; - //case ' ': *xpos = 120; *ypos = 40; break; // Triangle - default: *xpos = 0; *ypos = 0; break; - } -} diff -Nru nestopia-1.48/source/unix/video.h nestopia-1.49/source/unix/video.h --- nestopia-1.48/source/unix/video.h 2017-09-03 20:32:25.000000000 +0000 +++ nestopia-1.49/source/unix/video.h 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -#ifndef _VIDEO_H_ -#define _VIDEO_H_ - -#define TV_WIDTH 292 -#define PAL_TV_WIDTH 320 -#define OVERSCAN_LEFT 0 -#define OVERSCAN_RIGHT 0 -#define OVERSCAN_BOTTOM 8 -#define OVERSCAN_TOP 8 - -#define VIDBUF_MAXSIZE 31457280 - -#include -#include -#include -#include -#ifdef _APPLE -#include -#endif - -// This is part of an elaborate hack to embed the SDL window -struct SDL_Window { - const void *magic; - Uint32 id; - char *title; - SDL_Surface *icon; - int x, y; - int w, h; - int min_w, min_h; - int max_w, max_h; - Uint32 flags; -}; -typedef struct SDL_Window SDL_Window; -// - -typedef struct { - int w; - int h; -} dimensions_t; - -void ogl_init(); -void ogl_deinit(); -void ogl_render(); - -void video_init(); -void video_create_standalone(); -void video_create_embedded(); -void video_create(); -void video_swapbuffers(); -void video_destroy(); -void video_toggle_fullscreen(); -void video_toggle_filter(); -void video_toggle_filterupdate(); -void video_toggle_scalefactor(); -void video_set_filter(); -void video_set_dimensions(); -void video_set_cursor(); -void video_set_title(const char *title); - -long video_lock_screen(void*& ptr); -void video_unlock_screen(void*); -void video_screenshot(const char* filename); -void video_clear_buffer(); -void video_disp_nsf(); -void video_text_draw(const char *text, int xpos, int ypos); -void video_text_match(const char *text, int *xpos, int *ypos, int strpos); - -#endif diff -Nru nestopia-1.48/.travis.yml nestopia-1.49/.travis.yml --- nestopia-1.48/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ nestopia-1.49/.travis.yml 2018-06-24 23:26:58.000000000 +0000 @@ -0,0 +1,36 @@ +language: generic +os: linux +dist: trusty +sudo: required +addons: + apt: + packages: + - g++-7 + sources: + - ubuntu-toolchain-r-test +env: + global: + - CORE=nestopia + - COMPILER_NAME=gcc CXX=g++-7 CC=gcc-7 + matrix: + - PLATFORM=3ds + - PLATFORM=linux_x64 + - PLATFORM=ngc + - PLATFORM=wii + - PLATFORM=wiiu +before_script: + - pwd + - mkdir -p ~/bin + - ln -s /usr/bin/gcc-7 ~/bin/gcc + - ln -s /usr/bin/g++-7 ~/bin/g++ + - ln -s /usr/bin/cpp-7 ~/bin/cpp + - export PATH=~/bin:$PATH + - ls -l ~/bin + - echo $PATH + - g++-7 --version + - g++ --version +script: + - cd ~/ + - git clone --depth=50 https://github.com/libretro/libretro-super + - cd libretro-super/travis + - ./build.sh