pax_global_header00006660000000000000000000000064152515502250014514gustar00rootroot0000000000000052 comment=0ca6377fa9cf181cba7884c0512b9d73cd405a5b qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/000077500000000000000000000000001525155022500201555ustar00rootroot00000000000000qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/.gitignore000066400000000000000000000000121525155022500221360ustar00rootroot00000000000000build *.o qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/CMakeLists.txt000066400000000000000000001054531525155022500227250ustar00rootroot00000000000000# 3.19 for COMMAND_ERROR_IS_FATAL; 3.31 opts in to CMP0177, which quiets # install() about the prefix-root destinations below. cmake_minimum_required(VERSION 3.19...3.31) # Override the compiler on a fresh build directory: # CXX=clang++ cmake -B build -DQTEA_CORE_DIR=... project(qtea LANGUAGES CXX) message(STATUS "qtea: compiler = ${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION} (${CMAKE_CXX_COMPILER})") # OBJCXX is detected independently of CXX; a mixed pair gives objects LTO # cannot combine, so pin it unless asked otherwise. if(APPLE) if(NOT DEFINED CMAKE_OBJCXX_COMPILER AND NOT DEFINED ENV{OBJCXX}) set(CMAKE_OBJCXX_COMPILER "${CMAKE_CXX_COMPILER}") endif() enable_language(OBJCXX) endif() # The core's static build output directory: jg-static.mk and lib-jg.a. set(QTEA_CORE_DIR "" CACHE PATH "Path to the core's static build directory (contains jg-static.mk and lib-jg.a)") if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build type: Debug, Release, RelWithDebInfo, MinSizeRel" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "RelWithDebInfo" "MinSizeRel") endif() message(STATUS "qtea: build type = ${CMAKE_BUILD_TYPE}") # The core must be built with the same sanitizer to be covered. set(QTEA_SANITIZE "" CACHE STRING "Sanitizers to enable, comma-separated (e.g. address, address,undefined, thread)") # QTea's own objects only; the core archive links in as built, bitcode or # not, so a bitcode core needs a linker that reads it (lld, Apple ld). option(QTEA_LTO "Enable link-time optimization" OFF) # Packaging identity, all optional; defaults come from the core. set(QTEA_APP_NAME "" CACHE STRING "Display name for the desktop entry and macOS bundle; empty keeps the one the core's .desktop declares") set(QTEA_APP_ID "" CACHE STRING "Reverse-DNS application identifier; empty means org.jgemu.") set(QTEA_CORE_VERSION "" CACHE STRING "Version of the linked core; empty means read it from the core's version.h") set(QTEA_PROJECT_LICENSE "BSD-3-Clause" CACHE STRING "SPDX expression covering the built binary. QTea is BSD-3-Clause, but the core is linked into it and not every core is") set(QTEA_RELEASE_DATE "" CACHE STRING "Release date for the AppStream metadata, YYYY-MM-DD. Empty omits the releases block, since reading the clock here would make builds unreproducible") if(NOT QTEA_CORE_DIR) message(FATAL_ERROR "QTEA_CORE_DIR is not set. Pass -DQTEA_CORE_DIR=/path/to// " "pointing at the directory that contains jg-static.mk and lib-jg.a.") endif() get_filename_component(QTEA_CORE_DIR "${QTEA_CORE_DIR}" ABSOLUTE) set(QTEA_CORE_MK "${QTEA_CORE_DIR}/jg-static.mk") if(NOT EXISTS "${QTEA_CORE_MK}") message(FATAL_ERROR "jg-static.mk not found at ${QTEA_CORE_MK}") endif() # jg-static.mk is "KEY := value" lines; five keys matter. file(STRINGS "${QTEA_CORE_MK}" QTEA_CORE_MK_LINES) set(QTEA_CORE_NAME "") set(QTEA_CORE_ICONS "") set(QTEA_CORE_ASSETS "") set(QTEA_CORE_FLAGS_STATIC "") set(QTEA_CORE_LIBS_STATIC "") foreach(line IN LISTS QTEA_CORE_MK_LINES) if(line MATCHES "^[ \t]*([A-Za-z_][A-Za-z0-9_]*)[ \t]*[:+]?=[ \t]*(.*)$") set(_key "${CMAKE_MATCH_1}") set(_val "${CMAKE_MATCH_2}") string(STRIP "${_val}" _val) if(_key STREQUAL "NAME") set(QTEA_CORE_NAME "${_val}") elseif(_key STREQUAL "ICONS") string(REGEX REPLACE "[ \t]+" ";" QTEA_CORE_ICONS "${_val}") elseif(_key STREQUAL "ASSETS") string(REGEX REPLACE "[ \t]+" ";" QTEA_CORE_ASSETS "${_val}") elseif(_key STREQUAL "FLAGS_STATIC") set(QTEA_CORE_FLAGS_STATIC "${_val}") elseif(_key STREQUAL "LIBS_STATIC") set(QTEA_CORE_LIBS_STATIC "${_val}") endif() endif() endforeach() if(NOT QTEA_CORE_NAME) message(FATAL_ERROR "NAME not defined in ${QTEA_CORE_MK}") endif() # The executable, desktop entry, icons and app ID use the core name minus # the -jg suffix some cores carry; the archive always has it. string(REGEX REPLACE "-jg$" "" QTEA_CORE_BINARY_NAME "${QTEA_CORE_NAME}") set(QTEA_CORE_ARCHIVE "${QTEA_CORE_DIR}/lib${QTEA_CORE_BINARY_NAME}-jg.a") if(NOT EXISTS "${QTEA_CORE_ARCHIVE}") message(FATAL_ERROR "Core static archive not found: ${QTEA_CORE_ARCHIVE}") endif() message(STATUS "qtea: linking against core '${QTEA_CORE_NAME}' (${QTEA_CORE_ARCHIVE})") if(QTEA_CORE_FLAGS_STATIC) message(STATUS "qtea: core FLAGS_STATIC = ${QTEA_CORE_FLAGS_STATIC}") endif() if(QTEA_CORE_LIBS_STATIC) message(STATUS "qtea: core LIBS_STATIC = ${QTEA_CORE_LIBS_STATIC}") endif() include(GNUInstallDirs) # Reads the VERSION define out of a Jolly Good version.h, QTea's or a core's. function(qtea_read_version path out) set(_version "") if(EXISTS "${path}") file(READ "${path}" _text) if(_text MATCHES "#define[ \t]+[A-Z_]*VERSION[ \t]+\"([^\"]+)\"") set(_version "${CMAKE_MATCH_1}") endif() endif() set(${out} "${_version}" PARENT_SCOPE) endfunction() qtea_read_version("${CMAKE_SOURCE_DIR}/src/version.h" QTEA_VERSION) if(NOT QTEA_VERSION) message(FATAL_ERROR "Could not read QTEA_VERSION from src/version.h") endif() message(STATUS "qtea: frontend version = ${QTEA_VERSION}") # The packaged version is the core's: the binary is the emulator. The # frontend's stays in --version and About. jg-static.mk lacks it, but every # Jolly Good project keeps a version.h above the static output directory. set(QTEA_APP_VERSION "${QTEA_CORE_VERSION}") if(NOT QTEA_APP_VERSION) get_filename_component(_qtea_core_tree "${QTEA_CORE_DIR}" DIRECTORY) foreach(_cand "${_qtea_core_tree}/version.h" "${QTEA_CORE_DIR}/version.h") if(NOT QTEA_APP_VERSION) qtea_read_version("${_cand}" QTEA_APP_VERSION) endif() endforeach() endif() if(QTEA_APP_VERSION) message(STATUS "qtea: core version = ${QTEA_APP_VERSION}") else() # Wrong, but not empty. set(QTEA_APP_VERSION "${QTEA_VERSION}") message(WARNING "qtea: no version.h found for core '${QTEA_CORE_NAME}'; " "packaging metadata will report the frontend version " "${QTEA_VERSION} instead. Set QTEA_CORE_VERSION to override.") endif() # Resolved, not cached: retargeting QTEA_CORE_DIR must not leave a stale id. if(NOT QTEA_APP_ID) set(QTEA_APP_ID "org.jgemu.${QTEA_CORE_BINARY_NAME}") endif() set(QTEA_HOMEPAGE "https://gitlab.jgemu.io") # For a Qt outside the system library path (/opt, an installer prefix). # Implicit linker directories are excluded, so a distro build gets no RPATH. set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) # Qt first: a package referencing Qt6Gui before Qt6Config.cmake has run # fails with "Unknown CMake command". 6.3 for qt_standard_project_setup. find_package(Qt6 6.3 REQUIRED COMPONENTS Core Gui Widgets OpenGL OpenGLWidgets ) qt_standard_project_setup() find_package(SDL3 REQUIRED CONFIG COMPONENTS SDL3) find_package(PkgConfig REQUIRED) # Homebrew's pkg-config searches only its own prefix; the JG API installs to # /usr/local. A non-default JG prefix goes in PKG_CONFIG_PATH instead. if(APPLE) set(ENV{PKG_CONFIG_PATH} "/usr/local/lib/pkgconfig:/usr/local/share/pkgconfig:$ENV{PKG_CONFIG_PATH}") endif() pkg_check_modules(JG REQUIRED IMPORTED_TARGET jg) pkg_check_modules(EPOXY REQUIRED IMPORTED_TARGET epoxy) pkg_check_modules(SPEEXDSP REQUIRED IMPORTED_TARGET speexdsp) if(APPLE) # Homebrew is the supported macOS toolchain; its libarchive is keg-only. # Another package manager passes -DLibArchive_INCLUDE_DIR/_LIBRARY. execute_process( COMMAND brew --prefix libarchive OUTPUT_VARIABLE LIBARCHIVE_PREFIX OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY ) set(LibArchive_INCLUDE_DIR "${LIBARCHIVE_PREFIX}/include") endif() find_package(LibArchive REQUIRED) qt_add_executable(${PROJECT_NAME} src/audiomanager.cpp src/audiomanager.h src/chtmanager.cpp src/chtmanager.h src/parson.cpp src/parson.h src/qtea_about.cpp src/qtea_about.h src/qtea_archive.cpp src/qtea_archive.h src/qtea_bios.cpp src/qtea_bios.h src/qtea_cheats.cpp src/qtea_cheats.h src/qtea_detect.cpp src/qtea_detect.h src/qtea_dipswitches.cpp src/qtea_dipswitches.h src/qtea_emulator.cpp src/qtea_emulator.h src/qtea_glarea.cpp src/qtea_main.cpp src/qtea_menu.cpp src/qtea_openmultiple.cpp src/qtea_openmultiple.h src/qtea_inputcodes.h src/qtea_parse.h src/qtea_paths.cpp src/qtea_paths.h src/qtea_settings.cpp src/qtea_settings.h src/qtea_theme.cpp src/qtea_theme.h src/qtea_window.cpp src/qtea_window.h src/ini.h src/hasher.cpp src/hasher.h src/crc32.cpp src/crc32.h src/md5.cpp src/md5.h src/inputmanager.cpp src/inputmanager.h src/jgmanager.cpp src/jgmanager.h src/lodepng.cpp src/lodepng.h src/logdriver.cpp src/logdriver.h src/setmanager.cpp src/setmanager.h src/uiadapter.cpp src/uiadapter.h src/version.h src/videomanager.cpp src/videomanager.h src/qtea_osd.cpp src/qtea_osd.h ) # CADisplayLink frame pacer (macOS 14+ behind @available) and the # application-menu name. if(APPLE) target_sources(${PROJECT_NAME} PRIVATE src/qtea_displaylink.mm src/qtea_displaylink.h src/qtea_macos.mm src/qtea_macos.h) endif() # On macOS the output name is the .app name Finder shows. if(APPLE AND QTEA_APP_NAME) set(QTEA_OUTPUT_NAME "${QTEA_APP_NAME}") else() set(QTEA_OUTPUT_NAME "${QTEA_CORE_BINARY_NAME}") endif() set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME "${QTEA_OUTPUT_NAME}" CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON POSITION_INDEPENDENT_CODE TRUE ) if(APPLE) set_target_properties(${PROJECT_NAME} PROPERTIES OBJCXX_STANDARD 17 OBJCXX_STANDARD_REQUIRED ON ) endif() # The GUI subsystem, or Windows hands the process a console window of its # own whenever Explorer starts it. if(WIN32) set_target_properties(${PROJECT_NAME} PROPERTIES WIN32_EXECUTABLE TRUE) endif() # Release has always built at -O2; say so rather than rely on flag order. string(REPLACE "-O3" "-O2" CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}") # Only what CMake's per-config flags lack. -g3 keeps macro definitions. target_compile_options(${PROJECT_NAME} PRIVATE $<$:-O0 -g3 -fno-omit-frame-pointer> $<$:-fno-omit-frame-pointer> -Wall -Wextra -Wshadow ) # Keeps this machine's paths out of debug info; gdb's `set substitute-path` # or lldb's `target.source-map` finds the sources again. Binary dir first, # so a build tree nested in the source tree matches the longer prefix. include(CheckCXXCompilerFlag) check_cxx_compiler_flag("-ffile-prefix-map=/a=/b" QTEA_HAS_FILE_PREFIX_MAP) if(QTEA_HAS_FILE_PREFIX_MAP) target_compile_options(${PROJECT_NAME} PRIVATE "-ffile-prefix-map=${CMAKE_BINARY_DIR}=." "-ffile-prefix-map=${CMAKE_SOURCE_DIR}=." ) else() message(STATUS "qtea: no -ffile-prefix-map; debug builds carry " "absolute paths") endif() if(QTEA_LTO) include(CheckIPOSupported) check_ipo_supported(RESULT _qtea_ipo_ok OUTPUT _qtea_ipo_msg LANGUAGES CXX) if(NOT _qtea_ipo_ok) message(FATAL_ERROR "qtea: QTEA_LTO is set but this toolchain cannot do " "it. Clang needs a linker with a bitcode plugin (lld, gold, or the " "Apple linker); GCC needs its matching binutils plugin.\n${_qtea_ipo_msg}") endif() set_target_properties(${PROJECT_NAME} PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE) message(STATUS "qtea: link-time optimization enabled") if(CMAKE_BUILD_TYPE STREQUAL "Debug") message(WARNING "qtea: LTO on a Debug build, which compiles at -O0 and " "leaves it almost nothing to do. Set -DCMAKE_BUILD_TYPE=Release.") endif() endif() if(QTEA_SANITIZE) message(STATUS "qtea: enabling sanitizers: ${QTEA_SANITIZE}") target_compile_options(${PROJECT_NAME} PRIVATE -fsanitize=${QTEA_SANITIZE} -fno-omit-frame-pointer) target_link_options(${PROJECT_NAME} PRIVATE -fsanitize=${QTEA_SANITIZE}) endif() target_include_directories(${PROJECT_NAME} PRIVATE src/ ) target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Core Qt6::Gui Qt6::Widgets Qt6::OpenGL Qt6::OpenGLWidgets SDL3::SDL3 PkgConfig::JG PkgConfig::EPOXY PkgConfig::SPEEXDSP LibArchive::LibArchive ) # CADisplayLink is in QuartzCore; displayLinkWithTarget:selector: is AppKit. if(APPLE) target_link_libraries(${PROJECT_NAME} PRIVATE "-framework AppKit" "-framework QuartzCore" ) endif() # The core, plus the flags and libs its jg-static.mk declares. target_link_libraries(${PROJECT_NAME} PRIVATE "${QTEA_CORE_ARCHIVE}") if(QTEA_CORE_FLAGS_STATIC) separate_arguments(_qtea_core_flags NATIVE_COMMAND "${QTEA_CORE_FLAGS_STATIC}") target_link_options(${PROJECT_NAME} PRIVATE ${_qtea_core_flags}) endif() if(QTEA_CORE_LIBS_STATIC) separate_arguments(_qtea_core_libs NATIVE_COMMAND "${QTEA_CORE_LIBS_STATIC}") target_link_libraries(${PROJECT_NAME} PRIVATE ${_qtea_core_libs}) endif() target_compile_definitions(${PROJECT_NAME} PRIVATE QTEA_CORE="${QTEA_CORE_NAME}" # For the usage text. QTEA_BINARY="${QTEA_OUTPUT_NAME}" # One of the roots qtea::paths searches. QTEA_DATAROOTDIR="${CMAKE_INSTALL_FULL_DATADIR}" ) # Flat icons/ for find_core_icon(): QTea's fallbacks, then the core's. set(QTEA_ICON_DST "${CMAKE_BINARY_DIR}/icons") file(MAKE_DIRECTORY "${QTEA_ICON_DST}") set(QTEA_FALLBACK_ICON_SRC "${CMAKE_SOURCE_DIR}/icons") if(EXISTS "${QTEA_FALLBACK_ICON_SRC}") file(GLOB QTEA_FALLBACK_ICON_FILES "${QTEA_FALLBACK_ICON_SRC}/*") file(COPY ${QTEA_FALLBACK_ICON_FILES} DESTINATION "${QTEA_ICON_DST}") message(STATUS "Copied qtea fallback icons -> ${QTEA_ICON_DST}") else() message(WARNING "qtea fallback icons not found at ${QTEA_FALLBACK_ICON_SRC}") endif() # ICONS is the list, not a glob: stray files must not leak into the install. set(QTEA_ICON_SRC "${QTEA_CORE_DIR}/icons") if(QTEA_CORE_ICONS) set(_copied 0) foreach(icon IN LISTS QTEA_CORE_ICONS) set(_icon_path "${QTEA_ICON_SRC}/${icon}") if(EXISTS "${_icon_path}") file(COPY "${_icon_path}" DESTINATION "${QTEA_ICON_DST}") math(EXPR _copied "${_copied} + 1") else() message(WARNING "Icon listed in jg-static.mk but not found: ${_icon_path}") endif() endforeach() message(STATUS "Copied ${_copied} icon(s) for core '${QTEA_CORE_NAME}' -> ${QTEA_ICON_DST}") else() message(STATUS "Core '${QTEA_CORE_NAME}' declares no ICONS in jg-static.mk") endif() # ASSETS are relative to the core's output dir, subdirectories included. set(QTEA_ASSET_SRC "${QTEA_CORE_DIR}") if(QTEA_CORE_ASSETS) set(_copied 0) foreach(asset IN LISTS QTEA_CORE_ASSETS) set(_asset_src "${QTEA_ASSET_SRC}/${asset}") get_filename_component(_asset_subdir "${asset}" DIRECTORY) set(_asset_dst_dir "${CMAKE_BINARY_DIR}/${_asset_subdir}") if(EXISTS "${_asset_src}") file(MAKE_DIRECTORY "${_asset_dst_dir}") file(COPY "${_asset_src}" DESTINATION "${_asset_dst_dir}") math(EXPR _copied "${_copied} + 1") else() message(WARNING "Asset listed in jg-static.mk but not found: ${_asset_src}") endif() endforeach() message(STATUS "Copied ${_copied} asset(s) for core '${QTEA_CORE_NAME}' -> ${CMAKE_BINARY_DIR}") endif() # The upstream licences the About dialog shows: beside the core's output # dir, or one level up where a repository keeps it. foreach(_lic "${QTEA_CORE_DIR}/LICENSES" "${QTEA_CORE_DIR}/../LICENSES") if(EXISTS "${_lic}" AND NOT QTEA_CORE_LICENSES) get_filename_component(QTEA_CORE_LICENSES "${_lic}" ABSOLUTE) endif() endforeach() if(QTEA_CORE_LICENSES) file(COPY "${QTEA_CORE_LICENSES}" DESTINATION "${CMAKE_BINARY_DIR}") message(STATUS "Copied LICENSES -> ${CMAKE_BINARY_DIR}") else() message(WARNING "LICENSES not found for core '${QTEA_CORE_NAME}'; the About dialog's " "Licenses tab will be empty.") endif() # Licences of the libraries shipped alongside the binary: beside it on # Windows, inside the bundle on macOS. Elsewhere these are system packages # carrying their own. Direct dependencies only; transitive ones are not # covered. set(QTEA_DEP_LICENSES "${CMAKE_SOURCE_DIR}/Qt-LGPL-3.0.txt" "${CMAKE_SOURCE_DIR}/Qt-GPL-3.0.txt" "${CMAKE_SOURCE_DIR}/SDL-Zlib.txt" "${CMAKE_SOURCE_DIR}/SpeexDSP-BSD-3-Clause.txt" "${CMAKE_SOURCE_DIR}/libarchive-BSD-2-Clause.txt") if(WIN32) file(COPY ${QTEA_DEP_LICENSES} DESTINATION "${CMAKE_BINARY_DIR}") endif() # The application icon set: the core's, else QTea's. if(QTEA_CORE_ICONS) set(QTEA_APP_ICON_DIR "${QTEA_ICON_SRC}") set(QTEA_APP_ICONS ${QTEA_CORE_ICONS}) else() set(QTEA_APP_ICON_DIR "${QTEA_FALLBACK_ICON_SRC}") file(GLOB QTEA_APP_ICONS RELATIVE "${QTEA_FALLBACK_ICON_SRC}" "${QTEA_FALLBACK_ICON_SRC}/*.png" "${QTEA_FALLBACK_ICON_SRC}/*.svg") endif() # Beside the binary: the first root qtea::paths searches. set(QTEA_SHADER_SRC "${CMAKE_SOURCE_DIR}/shaders") set(QTEA_SHADER_DST "${CMAKE_BINARY_DIR}/shaders") if(EXISTS "${QTEA_SHADER_SRC}") file(COPY "${QTEA_SHADER_SRC}/" DESTINATION "${QTEA_SHADER_DST}") message(STATUS "Copied shaders -> ${QTEA_SHADER_DST}") else() message(WARNING "Shaders directory not found at ${QTEA_SHADER_SRC}") endif() # --------------------------------------------------------------------------- # Application metadata # --------------------------------------------------------------------------- # The core's .desktop describes the system it emulates, which nothing here # knows, so it feeds both the desktop entry and the AppStream metadata; only # the fields naming the executable are rewritten. # Rewrite one "Key=value" line, or append it. function(qtea_desktop_set var key value) set(_text "${${var}}") if(_text MATCHES "(^|\n)${key}=") string(REGEX REPLACE "(^|\n)${key}=[^\n]*" "\\1${key}=${value}" _text "${_text}") else() string(APPEND _text "${key}=${value}\n") endif() set(${var} "${_text}" PARENT_SCOPE) endfunction() # Read one "Key=value" line; a commented-out key does not match. function(qtea_desktop_get var key out) set(_value "") if("${${var}}" MATCHES "(^|\n)${key}=([^\n]*)") set(_value "${CMAKE_MATCH_2}") endif() set(${out} "${_value}" PARENT_SCOPE) endfunction() # Ampersand first. function(qtea_xml_escape var) set(_text "${${var}}") string(REPLACE "&" "&" _text "${_text}") string(REPLACE "<" "<" _text "${_text}") string(REPLACE ">" ">" _text "${_text}") set(${var} "${_text}" PARENT_SCOPE) endfunction() # A semicolon-separated value as an AppStream element list; empty gives none. function(qtea_xml_list var wrapper item out) set(_body "") foreach(_entry IN LISTS ${var}) if(_entry) qtea_xml_escape(_entry) string(APPEND _body " <${item}>${_entry}\n") endif() endforeach() if(_body) set(_body " <${wrapper}>\n${_body} \n") endif() set(${out} "${_body}" PARENT_SCOPE) endfunction() set(QTEA_DESKTOP_SRC "") foreach(_cand "${QTEA_CORE_DIR}/${QTEA_CORE_NAME}.desktop" "${QTEA_CORE_DIR}/${QTEA_CORE_BINARY_NAME}.desktop") if(EXISTS "${_cand}" AND NOT QTEA_DESKTOP_SRC) set(QTEA_DESKTOP_SRC "${_cand}") endif() endforeach() if(QTEA_DESKTOP_SRC) file(READ "${QTEA_DESKTOP_SRC}" QTEA_DESKTOP_TEXT) message(STATUS "qtea: metadata based on ${QTEA_DESKTOP_SRC}") else() # A core without one. set(QTEA_DESKTOP_TEXT "[Desktop Entry]\nType=Application\nVersion=1.0\n\ Name=${QTEA_CORE_BINARY_NAME}\nTerminal=false\nCategories=Game;Emulator;\n\ Keywords=emulator;\n") message(STATUS "qtea: no .desktop found in ${QTEA_CORE_DIR}, " "generating a minimal one") endif() # So an appended key starts its own line. if(NOT QTEA_DESKTOP_TEXT MATCHES "\n$") string(APPEND QTEA_DESKTOP_TEXT "\n") endif() if(QTEA_APP_NAME) qtea_desktop_set(QTEA_DESKTOP_TEXT "Name" "${QTEA_APP_NAME}") endif() # Absolute, for a prefix off PATH. Icon and StartupWMClass must match the # WM_CLASS Qt derives from the executable name. qtea_desktop_set(QTEA_DESKTOP_TEXT "Exec" "${CMAKE_INSTALL_FULL_BINDIR}/${QTEA_CORE_BINARY_NAME} %f") qtea_desktop_set(QTEA_DESKTOP_TEXT "TryExec" "${CMAKE_INSTALL_FULL_BINDIR}/${QTEA_CORE_BINARY_NAME}") qtea_desktop_set(QTEA_DESKTOP_TEXT "Icon" "${QTEA_CORE_BINARY_NAME}") qtea_desktop_set(QTEA_DESKTOP_TEXT "StartupWMClass" "${QTEA_CORE_BINARY_NAME}") # The core's file says NoDisplay: in jgrf a core is a plugin. Here it is # the application. qtea_desktop_set(QTEA_DESKTOP_TEXT "NoDisplay" "false") # Shared by the desktop entry, AppStream metadata and bundles. qtea_desktop_get(QTEA_DESKTOP_TEXT "Name" QTEA_META_NAME) qtea_desktop_get(QTEA_DESKTOP_TEXT "GenericName" QTEA_META_GENERIC) qtea_desktop_get(QTEA_DESKTOP_TEXT "Comment" QTEA_META_COMMENT) qtea_desktop_get(QTEA_DESKTOP_TEXT "Categories" QTEA_META_CATEGORIES) qtea_desktop_get(QTEA_DESKTOP_TEXT "Keywords" QTEA_META_KEYWORDS) qtea_desktop_get(QTEA_DESKTOP_TEXT "MimeType" QTEA_META_MIMETYPES) if(NOT QTEA_META_NAME) set(QTEA_META_NAME "${QTEA_CORE_BINARY_NAME}") endif() # AppStream summaries take no trailing full stop. if(QTEA_META_COMMENT) set(QTEA_META_SUMMARY "${QTEA_META_COMMENT}") elseif(QTEA_META_GENERIC) set(QTEA_META_SUMMARY "${QTEA_META_GENERIC}") else() set(QTEA_META_SUMMARY "Emulator built on the QTea frontend") endif() string(REGEX REPLACE "\\.$" "" QTEA_META_SUMMARY "${QTEA_META_SUMMARY}") # --------------------------------------------------------------------------- # macOS application bundle # --------------------------------------------------------------------------- if(APPLE) # What the menu bar and Get Info show. if(QTEA_APP_NAME) set(QTEA_BUNDLE_NAME "${QTEA_APP_NAME}") else() set(QTEA_BUNDLE_NAME "${QTEA_META_NAME}") endif() if(CMAKE_OSX_DEPLOYMENT_TARGET) set(QTEA_MACOS_MIN "${CMAKE_OSX_DEPLOYMENT_TARGET}") else() set(QTEA_MACOS_MIN "11.0") endif() configure_file("${CMAKE_SOURCE_DIR}/cmake/Info.plist.in" "${CMAKE_BINARY_DIR}/Info.plist" @ONLY) set_target_properties(${PROJECT_NAME} PROPERTIES MACOSX_BUNDLE TRUE MACOSX_BUNDLE_INFO_PLIST "${CMAKE_BINARY_DIR}/Info.plist" # Built with the install RPATH so `install` never rewrites what # macdeployqt fixed up. The link paths keep an undeployed build # running; the bundle entry takes over once frameworks are copied in. BUILD_WITH_INSTALL_RPATH TRUE INSTALL_RPATH "@executable_path/../Frameworks" ) set(QTEA_ICNS_SOURCES "") foreach(icon IN LISTS QTEA_APP_ICONS) if(icon MATCHES "\\.png$" AND EXISTS "${QTEA_APP_ICON_DIR}/${icon}") list(APPEND QTEA_ICNS_SOURCES "${QTEA_APP_ICON_DIR}/${icon}") endif() endforeach() if(QTEA_ICNS_SOURCES) set(QTEA_ICNS "${CMAKE_BINARY_DIR}/${QTEA_OUTPUT_NAME}.icns") add_custom_command( OUTPUT "${QTEA_ICNS}" COMMAND "${CMAKE_COMMAND}" -P "${CMAKE_SOURCE_DIR}/cmake/make_icns.cmake" "${QTEA_ICNS}" "${CMAKE_BINARY_DIR}/qtea.iconset" ${QTEA_ICNS_SOURCES} DEPENDS ${QTEA_ICNS_SOURCES} "${CMAKE_SOURCE_DIR}/cmake/make_icns.cmake" COMMENT "Building ${QTEA_OUTPUT_NAME}.icns" VERBATIM ) # A package location makes it a resource, not a source. target_sources(${PROJECT_NAME} PRIVATE "${QTEA_ICNS}") set_source_files_properties("${QTEA_ICNS}" PROPERTIES GENERATED TRUE MACOSX_PACKAGE_LOCATION "Resources") else() message(WARNING "qtea: no icons; the bundle gets a generic one") endif() # The only root that resolves inside a bundle: Finder starts the process # in "/" and there is no /share. set(QTEA_BUNDLE_RES "$/Resources") # From the staged copies, so it cannot drift from the other installs. set(_stage COMMAND "${CMAKE_COMMAND}" -E copy_directory "${QTEA_SHADER_DST}" "${QTEA_BUNDLE_RES}/shaders" COMMAND "${CMAKE_COMMAND}" -E copy_directory "${QTEA_ICON_DST}" "${QTEA_BUNDLE_RES}/icons") list(APPEND _stage COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CMAKE_SOURCE_DIR}/LICENSE" "${QTEA_BUNDLE_RES}/LICENSE") foreach(_lic IN LISTS QTEA_DEP_LICENSES) get_filename_component(_name "${_lic}" NAME) list(APPEND _stage COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${_lic}" "${QTEA_BUNDLE_RES}/${_name}") endforeach() if(QTEA_CORE_LICENSES) list(APPEND _stage COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CMAKE_BINARY_DIR}/LICENSES" "${QTEA_BUNDLE_RES}/LICENSES") endif() foreach(asset IN LISTS QTEA_CORE_ASSETS) if(EXISTS "${QTEA_ASSET_SRC}/${asset}") get_filename_component(_asset_subdir "${asset}" DIRECTORY) list(APPEND _stage COMMAND "${CMAKE_COMMAND}" -E make_directory "${QTEA_BUNDLE_RES}/${_asset_subdir}" COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CMAKE_BINARY_DIR}/${asset}" "${QTEA_BUNDLE_RES}/${asset}") endif() endforeach() add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD ${_stage} COMMENT "Staging runtime data into the bundle" VERBATIM) # Copies Qt and the Homebrew dylibs in and rewrites their install names. get_target_property(_qtea_qmake Qt6::qmake IMPORTED_LOCATION) get_filename_component(_qtea_qt_bin "${_qtea_qmake}" DIRECTORY) find_program(QTEA_MACDEPLOYQT NAMES macdeployqt HINTS "${_qtea_qt_bin}") if(QTEA_MACDEPLOYQT) add_custom_target(bundle COMMAND "${QTEA_MACDEPLOYQT}" "$" -always-overwrite COMMENT "Copying Qt and its dependencies into the bundle" VERBATIM ) add_dependencies(bundle ${PROJECT_NAME}) else() message(STATUS "qtea: macdeployqt not found beside ${_qtea_qt_bin}; " "no 'bundle' target, the .app runs only where the libraries are " "installed") endif() endif() # --------------------------------------------------------------------------- # Windows resources # --------------------------------------------------------------------------- # MSYS2 UCRT64. The manifest sets the process code page to UTF-8, so the # narrow Win32 entry points agree with libstdc++'s handling of std::string # paths. if(WIN32) enable_language(RC) # FILEVERSION and assemblyIdentity want exactly four numeric parts. string(REGEX MATCHALL "[0-9]+" _qtea_vparts "${QTEA_APP_VERSION}") list(APPEND _qtea_vparts 0 0 0 0) list(SUBLIST _qtea_vparts 0 4 _qtea_vparts) list(JOIN _qtea_vparts "," QTEA_VERSION_RC) list(JOIN _qtea_vparts "." QTEA_VERSION_DOT4) # RC string literal escaping; a stray quote in the core's .desktop would # be a windres syntax error. set(QTEA_RC_NAME "${QTEA_META_NAME}") set(QTEA_RC_SUMMARY "${QTEA_META_SUMMARY}") foreach(_v QTEA_RC_NAME QTEA_RC_SUMMARY) string(REPLACE "\\" "\\\\" ${_v} "${${_v}}") string(REPLACE "\"" "\"\"" ${_v} "${${_v}}") endforeach() set(QTEA_WIN_MANIFEST "${CMAKE_BINARY_DIR}/${QTEA_OUTPUT_NAME}.manifest") set(QTEA_WIN_RC "${CMAKE_BINARY_DIR}/${QTEA_OUTPUT_NAME}.rc") set(QTEA_WIN_RC_DEPS "${QTEA_WIN_MANIFEST}") # The icon, built from the PNGs rather than an .ico. include("${CMAKE_SOURCE_DIR}/cmake/win32_icon.cmake") qtea_win_icon_rc(QTEA_RC_ICON _qtea_icon_deps "${QTEA_APP_ICON_DIR}" ${QTEA_APP_ICONS}) if(_qtea_icon_deps) list(APPEND QTEA_WIN_RC_DEPS ${_qtea_icon_deps}) else() message(WARNING "qtea: no usable icons for " "'${QTEA_CORE_BINARY_NAME}'; the executable and any pinned " "shortcut get a generic one") endif() configure_file("${CMAKE_SOURCE_DIR}/cmake/win32.manifest.in" "${QTEA_WIN_MANIFEST}" @ONLY) configure_file("${CMAKE_SOURCE_DIR}/cmake/win32.rc.in" "${QTEA_WIN_RC}" @ONLY) target_sources(${PROJECT_NAME} PRIVATE "${QTEA_WIN_RC}") set_source_files_properties("${QTEA_WIN_RC}" PROPERTIES OBJECT_DEPENDS "${QTEA_WIN_RC_DEPS}") endif() # --------------------------------------------------------------------------- # Install # --------------------------------------------------------------------------- if(APPLE) # The prefix is where the self-contained .app lands. if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "/Applications" CACHE PATH "Install path prefix" FORCE) endif() install(TARGETS ${PROJECT_NAME} BUNDLE DESTINATION ".") else() # Windows is a zip run in place: everything flat beside the executable, # the first root qtea::paths searches and the layout the Qt DLLs need; # saves and config join it at runtime. Elsewhere the usual bindir and a # per-core datadir, so white-label builds do not collide. if(WIN32) set(QTEA_BIN_DEST ".") set(QTEA_DATA_DEST ".") else() set(QTEA_BIN_DEST "${CMAKE_INSTALL_BINDIR}") set(QTEA_DATA_DEST "${CMAKE_INSTALL_DATADIR}/${QTEA_CORE_BINARY_NAME}") endif() install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION "${QTEA_BIN_DEST}") if(EXISTS "${QTEA_FALLBACK_ICON_SRC}") install(DIRECTORY "${QTEA_FALLBACK_ICON_SRC}/" DESTINATION "${QTEA_DATA_DEST}/icons") endif() if(QTEA_CORE_ICONS) foreach(icon IN LISTS QTEA_CORE_ICONS) set(_icon_path "${QTEA_ICON_SRC}/${icon}") if(EXISTS "${_icon_path}") install(FILES "${_icon_path}" DESTINATION "${QTEA_DATA_DEST}/icons") endif() endforeach() endif() if(QTEA_CORE_ASSETS) foreach(asset IN LISTS QTEA_CORE_ASSETS) set(_asset_src "${QTEA_ASSET_SRC}/${asset}") get_filename_component(_asset_subdir "${asset}" DIRECTORY) if(EXISTS "${_asset_src}") install(FILES "${_asset_src}" DESTINATION "${QTEA_DATA_DEST}/${_asset_subdir}") endif() endforeach() endif() if(EXISTS "${QTEA_SHADER_SRC}") install(DIRECTORY "${QTEA_SHADER_SRC}/" DESTINATION "${QTEA_DATA_DEST}/shaders") endif() # The frontend's licence beside the core's. install(FILES "${CMAKE_SOURCE_DIR}/LICENSE" DESTINATION "${QTEA_DATA_DEST}") if(WIN32) install(FILES ${QTEA_DEP_LICENSES} DESTINATION "${QTEA_DATA_DEST}") endif() if(QTEA_CORE_LICENSES) install(FILES "${QTEA_CORE_LICENSES}" DESTINATION "${QTEA_DATA_DEST}") endif() endif() # --------------------------------------------------------------------------- # Freedesktop integration # --------------------------------------------------------------------------- # NOT WIN32 too: an MSYS shell can leave UNIX set on a native Windows build. if(UNIX AND NOT APPLE AND NOT WIN32) set(QTEA_DESKTOP_OUT "${CMAKE_BINARY_DIR}/${QTEA_CORE_BINARY_NAME}.desktop") file(WRITE "${QTEA_DESKTOP_OUT}" "${QTEA_DESKTOP_TEXT}") install(FILES "${QTEA_DESKTOP_OUT}" DESTINATION "${CMAKE_INSTALL_DATADIR}/applications") # The file is named after the reverse-DNS component ID; # ties it to the desktop entry, which keeps the binary name. set(QTEA_META_XML_NAME "${QTEA_META_NAME}") set(QTEA_META_XML_SUMMARY "${QTEA_META_SUMMARY}") qtea_xml_escape(QTEA_META_XML_NAME) qtea_xml_escape(QTEA_META_XML_SUMMARY) qtea_xml_list(QTEA_META_CATEGORIES categories category QTEA_META_CATEGORIES_XML) qtea_xml_list(QTEA_META_KEYWORDS keywords keyword QTEA_META_KEYWORDS_XML) qtea_xml_list(QTEA_META_MIMETYPES provides mediatype QTEA_META_PROVIDES_XML) if(QTEA_RELEASE_DATE) set(QTEA_META_RELEASES_XML " \n \n \n") else() set(QTEA_META_RELEASES_XML "") message(STATUS "qtea: QTEA_RELEASE_DATE unset, no AppStream releases block") endif() set(QTEA_METAINFO_OUT "${CMAKE_BINARY_DIR}/${QTEA_APP_ID}.metainfo.xml") configure_file("${CMAKE_SOURCE_DIR}/cmake/metainfo.xml.in" "${QTEA_METAINFO_OUT}" @ONLY) install(FILES "${QTEA_METAINFO_OUT}" DESTINATION "${CMAKE_INSTALL_DATADIR}/metainfo") # What makes Icon= resolve: renamed to the binary and sorted into hicolor # by size. Sizes index.theme does not declare are never searched. set(QTEA_HICOLOR_SIZES 16 22 24 32 36 48 64 72 96 128 192 256 512) set(_theme_installed "") foreach(icon IN LISTS QTEA_APP_ICONS) set(_src "${QTEA_APP_ICON_DIR}/${icon}") if(NOT EXISTS "${_src}") continue() endif() get_filename_component(_stem "${icon}" NAME_WLE) get_filename_component(_ext "${icon}" LAST_EXT) if(_ext STREQUAL ".svg") install(FILES "${_src}" DESTINATION "${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps" RENAME "${QTEA_CORE_BINARY_NAME}.svg") list(APPEND _theme_installed "scalable") elseif(_ext STREQUAL ".png" AND _stem MATCHES "^(.*[^0-9])?([0-9]+)$") set(_size "${CMAKE_MATCH_2}") if("${_size}" IN_LIST QTEA_HICOLOR_SIZES) install(FILES "${_src}" DESTINATION "${CMAKE_INSTALL_DATADIR}/icons/hicolor/${_size}x${_size}/apps" RENAME "${QTEA_CORE_BINARY_NAME}.png") list(APPEND _theme_installed "${_size}") endif() endif() endforeach() if(_theme_installed) list(JOIN _theme_installed " " _theme_installed_str) message(STATUS "qtea: icon theme sizes for " "'${QTEA_CORE_BINARY_NAME}': ${_theme_installed_str}") else() message(WARNING "qtea: no usable icons for the theme; the desktop " "entry gets a generic one") endif() endif() # For the from-source install; a package manager has its own. configure_file( "${CMAKE_SOURCE_DIR}/cmake/uninstall.cmake.in" "${CMAKE_BINARY_DIR}/uninstall.cmake" @ONLY ) add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P "${CMAKE_BINARY_DIR}/uninstall.cmake" COMMENT "Removing files listed in install_manifest.txt" VERBATIM ) qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/LICENSE000066400000000000000000000027531525155022500211710ustar00rootroot00000000000000Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/Qt-GPL-3.0.txt000066400000000000000000001045131525155022500222240ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/Qt-LGPL-3.0.txt000066400000000000000000000167431525155022500223470ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/README000066400000000000000000000042121525155022500210340ustar00rootroot00000000000000The Quality Tea Frontend ------------------------ The Quality Tea Frontend is a Jolly Good API frontend which utilizes Qt6 for a classic WIMP style emulation experience. This frontend currently supports static builds only. Module support is planned for the future. Compiling --------- First, ensure you have a static JG archive built. This means a JG emulator core built with ENABLE_STATIC_JG=1. In the Jolly Good ecosystem, a core is a directory containing a module or static archive and possibly assets, not the module or static archive itself. You will also require SDL3, SpeexDSP, libarchive, and Qt6 (6.3 or newer) development libraries, and CMake 3.19 or newer. On macOS these are expected from Homebrew. Instructions: mkdir build cd build cmake .. -DQTEA_CORE_DIR=/path/to/static_jg_core/ make (or ninja on UCRT64 environments) Distributing Binaries --------------------- Qt is used under the LGPLv3. The frontend links it dynamically and ships it unmodified: the macOS bundle carries the frameworks and any Windows package must ship the DLLs, either of which the recipient may replace with their own build. The licence text and Qt version are shown by Help->About Qt. SDL3, SpeexDSP and libarchive are shipped the same way under their own licences. The emulator core's licences are in LICENSES beside the binary, shown by Help->About. You may not legally distribute binaries linked to emulator cores with legacy MAME-style licensing, such as Genesis Plus GX or PicoDrive. Copyright --------- The Quality Tea Frontend Copyright (c) 2021-2026, Jolly Good Emulation Team (BSD-3-Clause) See LICENSE AntiAliased Nearest Neighbor Fragment Shader Copyright (c) 2015 nyanpasu64 and wareya (MIT) LodePNG Copyright (c) 2005-2023 Lode Vandevenne (Zlib) See src/lodepng.h MD5 Message-Digest Algorithm (RFC 1321) Implementation Public Domain or BSD-like license without advertising clause See src/md5.h MMPX Copyright (c) Morgan McGuire and Mara Gagiu (MIT) mINI Copyright (c) 2018 Danijel Durakovic (MIT) See src/ini.h OmniScale Copyright (c) 2015-2016 Lior Halphon (MIT) parson Copyright (c) 2012-2023 Krzysztof Gabis (MIT) See src/parson.h qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/SDL-Zlib.txt000066400000000000000000000015641525155022500222440ustar00rootroot00000000000000Copyright (C) 1997-2026 Sam Lantinga 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. qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/SpeexDSP-BSD-3-Clause.txt000066400000000000000000000033551525155022500243370ustar00rootroot00000000000000Copyright 2002-2008 Xiph.org Foundation Copyright 2002-2008 Jean-Marc Valin Copyright 2005-2007 Analog Devices Inc. Copyright 2005-2008 Commonwealth Scientific and Industrial Research Organisation (CSIRO) Copyright 1993, 2002, 2006 David Rowe Copyright 2003 EpicGames Copyright 1992-1994 Jutta Degener, Carsten Bormann 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 the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``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 FOUNDATION OR CONTRIBUTORS 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. qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/cmake/000077500000000000000000000000001525155022500212355ustar00rootroot00000000000000qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/cmake/Info.plist.in000066400000000000000000000031001525155022500236040ustar00rootroot00000000000000 CFBundleDevelopmentRegion en CFBundleExecutable @QTEA_OUTPUT_NAME@ CFBundleIconFile @QTEA_OUTPUT_NAME@.icns CFBundleIdentifier @QTEA_APP_ID@ CFBundleInfoDictionaryVersion 6.0 CFBundleName @QTEA_BUNDLE_NAME@ CFBundleDisplayName @QTEA_BUNDLE_NAME@ CFBundlePackageType APPL CFBundleShortVersionString @QTEA_APP_VERSION@ CFBundleVersion @QTEA_APP_VERSION@ LSApplicationCategoryType public.app-category.games LSMinimumSystemVersion @QTEA_MACOS_MIN@ NSHumanReadableCopyright Copyright © 2021-2026 Jolly Good Emulation Team NSHighResolutionCapable NSPrincipalClass NSApplication NSSupportsAutomaticGraphicsSwitching qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/cmake/icon_size.cmake000066400000000000000000000012251525155022500242210ustar00rootroot00000000000000# The pixel size in an icon filename, under the JG .png rule. # # qtea_icon_size( ) # # is left unset when the stem carries no usable size. # # Matched against the sizes an icon can actually be, longest first, rather # than read off as the trailing digit run: a core whose name ends in digits # would otherwise absorb them, and cen64's cen6448.png reads as 6448. function(qtea_icon_size out stem) foreach(size 1024 512 256 128 64 48 32 24 16) if(stem MATCHES "${size}$") set(${out} "${size}" PARENT_SCOPE) return() endif() endforeach() unset(${out} PARENT_SCOPE) endfunction() qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/cmake/make_icns.cmake000066400000000000000000000062611525155022500241750ustar00rootroot00000000000000# Builds a macOS .icns from a set of square PNGs. # # cmake -P make_icns.cmake ... # # iconutil wants fixed member names and sizes. An exact source is copied; # the rest are resized with sips from the smallest source above the target. cmake_minimum_required(VERSION 3.16) set(OUT "${CMAKE_ARGV3}") set(WORK "${CMAKE_ARGV4}") if(NOT OUT OR NOT WORK) message(FATAL_ERROR "usage: cmake -P make_icns.cmake ...") endif() # Everything past the work directory is a source image. set(_argi 5) set(SOURCES "") while(_argi LESS CMAKE_ARGC) list(APPEND SOURCES "${CMAKE_ARGV${_argi}}") math(EXPR _argi "${_argi} + 1") endwhile() include("${CMAKE_CURRENT_LIST_DIR}/icon_size.cmake") # Index sources by the pixel size in their filename. set(SIZES "") foreach(src IN LISTS SOURCES) if(NOT EXISTS "${src}") continue() endif() get_filename_component(_stem "${src}" NAME_WLE) get_filename_component(_ext "${src}" LAST_EXT) if(NOT _ext STREQUAL ".png") continue() endif() qtea_icon_size(_size "${_stem}") if(DEFINED _size) set(SRC_${_size} "${src}") list(APPEND SIZES "${_size}") endif() endforeach() if(NOT SIZES) message(FATAL_ERROR "make_icns: no usable PNG icons among: ${SOURCES}") endif() list(REMOVE_DUPLICATES SIZES) list(SORT SIZES COMPARE NATURAL) list(GET SIZES -1 LARGEST) set(ICONSET "${WORK}") file(REMOVE_RECURSE "${ICONSET}") file(MAKE_DIRECTORY "${ICONSET}") # name:size pairs, as iconutil expects them. set(MEMBERS "icon_16x16.png:16" "icon_16x16@2x.png:32" "icon_32x32.png:32" "icon_32x32@2x.png:64" "icon_128x128.png:128" "icon_128x128@2x.png:256" "icon_256x256.png:256" "icon_256x256@2x.png:512" "icon_512x512.png:512" "icon_512x512@2x.png:1024" ) foreach(member IN LISTS MEMBERS) string(REPLACE ":" ";" _parts "${member}") list(GET _parts 0 _name) list(GET _parts 1 _want) if(DEFINED SRC_${_want}) execute_process( COMMAND "${CMAKE_COMMAND}" -E copy "${SRC_${_want}}" "${ICONSET}/${_name}" RESULT_VARIABLE _rc ) if(NOT _rc EQUAL 0) message(FATAL_ERROR "make_icns: could not copy ${SRC_${_want}}") endif() continue() endif() # Smallest source at or above the target, else the largest. set(_from "${LARGEST}") foreach(_size IN LISTS SIZES) if(NOT _size LESS _want) set(_from "${_size}") break() endif() endforeach() execute_process( COMMAND sips -z ${_want} ${_want} "${SRC_${_from}}" --out "${ICONSET}/${_name}" OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE _rc ) if(NOT _rc EQUAL 0) message(FATAL_ERROR "make_icns: sips failed resizing ${SRC_${_from}} to ${_want}px") endif() endforeach() get_filename_component(_outdir "${OUT}" DIRECTORY) file(MAKE_DIRECTORY "${_outdir}") execute_process( COMMAND iconutil -c icns "${ICONSET}" -o "${OUT}" RESULT_VARIABLE _rc ) if(NOT _rc EQUAL 0) message(FATAL_ERROR "make_icns: iconutil failed for ${ICONSET}") endif() file(REMOVE_RECURSE "${ICONSET}") qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/cmake/metainfo.xml.in000066400000000000000000000022121525155022500241630ustar00rootroot00000000000000 @QTEA_APP_ID@ @QTEA_META_XML_NAME@ @QTEA_META_XML_SUMMARY@ CC0-1.0 @QTEA_PROJECT_LICENSE@ Jolly Good Emulation Team @QTEA_CORE_BINARY_NAME@.desktop

@QTEA_META_XML_SUMMARY@.

A Jolly Good emulator core and the QTea frontend, built together into one self-contained application: OpenGL output with optional shader passes, resampled audio, gamepad support, save states, cheats and screenshots.

@QTEA_HOMEPAGE@ @QTEA_META_CATEGORIES_XML@@QTEA_META_KEYWORDS_XML@@QTEA_META_PROVIDES_XML@ @QTEA_META_RELEASES_XML@
qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/cmake/uninstall.cmake.in000066400000000000000000000016341525155022500246610ustar00rootroot00000000000000# Removes exactly what the matching install wrote. Directories are left # alone: share/applications and hicolor belong to other packages too. set(MANIFEST "@CMAKE_BINARY_DIR@/install_manifest.txt") if(NOT EXISTS "${MANIFEST}") message(FATAL_ERROR "No install manifest at ${MANIFEST}. Nothing was installed from this " "build directory, or it has been cleaned.") endif() file(STRINGS "${MANIFEST}" FILES) foreach(file IN LISTS FILES) # Honoured for the same reason install does: a packaging run never # touches the live filesystem. set(target "$ENV{DESTDIR}${file}") if(EXISTS "${target}" OR IS_SYMLINK "${target}") message(STATUS "Removing ${target}") file(REMOVE "${target}") if(EXISTS "${target}") message(WARNING "Could not remove ${target}") endif() else() message(STATUS "Already gone: ${target}") endif() endforeach() qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/cmake/win32.manifest.in000066400000000000000000000025641525155022500243430ustar00rootroot00000000000000 UTF-8 true qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/cmake/win32.rc.in000066400000000000000000000041451525155022500231360ustar00rootroot00000000000000/* Compiled by windres. Numeric resource types throughout, so this needs no headers and no include path. */ /* 1 is CREATEPROCESS_MANIFEST_RESOURCE_ID, 24 is RT_MANIFEST. */ 1 24 "@QTEA_WIN_MANIFEST@" /* The icon. windres splits an .ico into one RT_ICON (3) per image and an RT_GROUP_ICON (14) naming them, so the container is skipped: the PNGs go in as the images, and CMake writes the group by hand. A PNG payload is what an .ico holds anyway from Vista on. The shell reads the lowest group ID for the .exe and for the shortcut behind a pinned taskbar button, hence 1 here too; the manifest above is a different type, so nothing collides. GRPICONDIR is three words: reserved, type, count. Then a 14-byte GRPICONDIRENTRY each, written as five words and a dword because the four leading bytes pack in pairs: bHeight:bWidth one byte each, 0 reads as 256 bReserved:bColorCount wPlanes wBitCount dwBytesInRes the PNG's size on disk, hence the L nID which RT_ICON above this entry names */ @QTEA_RC_ICON@ /* Properties > Details. FILEVERSION and PRODUCTVERSION are four numbers; the strings beside them are free text and are what gets displayed. */ 1 VERSIONINFO FILEVERSION @QTEA_VERSION_RC@ PRODUCTVERSION @QTEA_VERSION_RC@ FILEOS 0x4L /* VOS__WINDOWS32 */ FILETYPE 0x1L /* VFT_APP */ BEGIN BLOCK "StringFileInfo" BEGIN /* 0409 is US English, 04b0 is UTF-16. */ BLOCK "040904b0" BEGIN VALUE "CompanyName", "Jolly Good Emulation Team" VALUE "FileDescription", "@QTEA_RC_SUMMARY@" VALUE "FileVersion", "@QTEA_APP_VERSION@" VALUE "InternalName", "@QTEA_OUTPUT_NAME@" VALUE "LegalCopyright", "Copyright (c) 2021-2026 Jolly Good Emulation Team" VALUE "OriginalFilename", "@QTEA_OUTPUT_NAME@.exe" VALUE "ProductName", "@QTEA_RC_NAME@" VALUE "ProductVersion", "@QTEA_APP_VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/cmake/win32_icon.cmake000066400000000000000000000047771525155022500242300ustar00rootroot00000000000000# Builds the icon statements for win32.rc.in out of a set of square PNGs. # # qtea_win_icon_rc( ...) # # takes the resource text, ready to substitute; the PNGs # it names, for the resource script's OBJECT_DEPENDS. Empty deps means # nothing was usable and is a comment. # # What is being written is documented in win32.rc.in, beside the output. include("${CMAKE_CURRENT_LIST_DIR}/icon_size.cmake") function(qtea_win_icon_rc out_rc out_deps icon_dir) set(sizes "") foreach(icon IN LISTS ARGN) if(NOT icon MATCHES "\\.png$") continue() endif() if(NOT EXISTS "${icon_dir}/${icon}") continue() endif() # The size off the filename, as the .icns build reads it. get_filename_component(stem "${icon}" NAME_WLE) qtea_icon_size(size "${stem}") if(NOT DEFINED size) continue() endif() # bWidth and bHeight are one byte each, so 256 is the ceiling. if(size GREATER 256) continue() endif() if(NOT DEFINED src_${size}) set(src_${size} "${icon_dir}/${icon}") list(APPEND sizes "${size}") endif() endforeach() if(NOT sizes) set(${out_rc} "/* No sized PNGs among the application icons. */" PARENT_SCOPE) set(${out_deps} "" PARENT_SCOPE) return() endif() # Largest last, so the directory reads in order. list(SORT sizes COMPARE NATURAL) list(LENGTH sizes count) set(images "") set(dir "") set(deps "") set(id 0) foreach(size IN LISTS sizes) math(EXPR id "${id} + 1") set(src "${src_${size}}") file(SIZE "${src}" bytes) list(APPEND deps "${src}") string(APPEND images "${id} 3 \"${src}\"\n") # bHeight:bWidth packed into one word; 0 there reads as 256. if(size EQUAL 256) set(dim "0x0000") else() math(EXPR dim "${size} * 257" OUTPUT_FORMAT HEXADECIMAL) endif() string(APPEND dir " ${dim}, 0x0000, 1, 32, ${bytes}L, ${id}, " "/* ${size}x${size} */\n") endforeach() set(rc "${images}") string(APPEND rc "\n1 14 {\n") string(APPEND rc " 0, 1, ${count},\n") string(APPEND rc "${dir}") string(APPEND rc "}\n") message(STATUS "qtea: icon resource sizes: ${sizes}") set(${out_rc} "${rc}" PARENT_SCOPE) set(${out_deps} "${deps}" PARENT_SCOPE) endfunction() qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/icons/000077500000000000000000000000001525155022500212705ustar00rootroot00000000000000qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/icons/qtea.svg000066400000000000000000000034211525155022500227430ustar00rootroot00000000000000 qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/icons/qtea1024.png000066400000000000000000001265031525155022500232460ustar00rootroot00000000000000‰PNG  IHDR+ƒ pHYs‡‡�åñetEXtSoftwarewww.inkscape.org›î< IDATxœìÝy˜¤e}ïÿ÷÷éž…·¨ˆ==ƒˆË1zTb<îe¦Æ•F�5j-öØòû= ælÈd#@ÀYÑŠ“ëZ°�ä¶*¸=*nßÜâ¶XÈíKNÉõEþ’’$I3™Y:ƒ$I³6Þˆ§à±VÉ#�AL­à¡ ûÑÝÙnÀ­ 7Ü@rcVÜP%7´’¸ar€«%oëb&I’$À@’ÔÃÆñ{$�'xpp2ý•é¯{lÿÕ=í7À/H~\I5ýu`‚Ëýjþ¦p6I’Ô§,$IÅ­jÄ>óáà*Ypd+ªàð„‡”ÎVÀmÀx$«Æ€ñÉ…üÔå’$iWYH’ºêò—Å^ó9² þðÔ„'�*�«—L%\Ap1pqNqѦýøù‘ŸÍ‰ÒÙ$IÒÜa I꜈?†!*žAò´VðÔ K(­l ø)pqMMòý%gæ¯J‡’$I½Ë@’ÔV—.�ƒ*þxfÂQÀ#Kgª‘ ~ÉVœ{èiyMé@’$©wXH’vÉêcâÑSƒ¼�GEðlà¡¥3éW�œ|7‚s‡š¹¶t I’TŽ€$iVF1p(<1‚—VÉKžDé\Ú¾€)àg­à›™|cñ?ÁH’T+’¤Z³"öŸœà¥¼(ày û”Τ]p}&çTçÜž|ëéÍÜP:“$Iê, ©]ùªØ{rŠOL±_Àƒ«d_‚yÀž™ìKE�ìN² ƒuL>à2›i±.àŽÜ‘ÁºÁŠuÙâÎ�MÜvÈY¹®û3Í%ã�8°/Xðl7îëkë ÎÉäÌ ÎjæoKRo»ô•ñ 6ñ j�½bн£b¯©d¯ öiÁ>T÷}~´X˜°ë�Í‘L¿hÁ[þ¶–`mk[óXëÑ—’Ô~R—]s|,¼k=µ’ƒ¨8¨JJ8ˆé_ v:GÀ঄nŽà†hqs+øÉ/ªàª¡EüгÕé,ê—�¬8&ààpÿÄ«ÿlhÁ·ÎÜ”|ãÈfÞQ:“ºg¼ó«ŠÇ´Z”ÉAÀ�<<§÷ö80àa óºg°6áÆ€«®ŠWµ‚«¨¸jÓ>\ëQ˜’4;R§DÄ¥ÇðØÁ–d²$a1p8ð8æÎMÕæ€«®"¹ŠŠÕÙb¬ .q3±þqé+ãA›idðjà÷q=¿îµ ø�LNY¸ž³>'7•¤ö=.UM2œ°˜ŠÇ“<8(à‘sh¶Ïf`<àÒVp ÉÏä’áSó×¥ƒIR¯²�ÚäÒWƃ'yz žNòûÀ“�½Kçê F[Á%U2?m±zY3§JÓŽ­:!æív/Lx5ðR`AéLêykVNÁ¿.næ…¥Ãhf®9>®[ÏUrDÀâ †�a`ßÒÙ:è×À�H~páÁ�ÝãB’¦YH;itE<”)žWµ8*ƒ§‡â'§ë€UÁEUÅŇœ–7”¥{�.�'3Àk"9Ø¿tÍYW|¹à”COËkJ‡Ñ½.;6ž0™<5’§OŽ ;Óõ{ÙðÓ€ 3øN$ç¹Ï…¤º²�fèšãcáo×ó?«éÐÿ°oøg⺀ó[Áù9Åù‹ÏÈ«Jª›Ë_{MÍgE'0}3 µK 8· >ûë›ùæsÎËnFªN:)ªñ1–dò‚£€g2½�Œ¶o"áBàܨ8wÑa¬r¿Iua mÇš±ÿæ)ŽŽäåÏMØ­t¦>p-Áù‘œSœwØ™ùËÒ�úÕøÒ8¢5À ‘¬ö*�Gý-àú„É>?|Z^W:O_ŠˆÑcXÌÏ!9*àYxÃß¿!8»‚¯y$¦¤~g =À%ÇÄ#ø£œ>þÌ£Ï:o<àìVrΦs�;:ïš ±Û^Áq‘œÀôô_©«¦Ω‚:lˆÿð“Õ]3Þˆ=[ð¼^É Q:SŸ[ü{À×6ÀÙž‚!©ßXHÀÏ^ûΟG#á5¸ z1wdpn$çLNrÎ’¯æÍ¥3Í«�‰‡åoN8×ö«w\Aò‰©Ýø’gºÏÜê¥ñøÖ/ÉäE[>åŸ_:SMmN88¥‚³‡š¹¹t IÚUª­‘F Geòšœ>ó|÷Ò™t?-à„‘)8ãðf^_:P/;6§Å›˜.¯–Î#mÃ�‘|‘ào‡šymé0½èÒ¥qPT¼4`ðŒÒyô;nšÿ:4ÂøhIs”€jgôØx\5Å3x p@é<š‘ðÄ3ZSœ¹äÌüUé@E�ÕØ8/&y;pTé8Ò,L#ÙâãÃgä�K‡)íÒF,®`)Ó¿†JçÑÌ\NòÏ_jæÚÒy$i6,T'E5:Æ Þ <¨JGÒNKà‡§lž ùįåí¥uËùGÅàCögÁ{™>vRšË΋äƒC#ù�ÒAºi¼¿×‚W¼ ÿ<§l 9m*øÌâf®*�G’fÂ@}m¼ÎäO"xcÂcKçQÛmÌäë§Üz ßê×#È®|Q,ظ'ðnà1¥óHí”ð£>´¨É7ûuZõx#öÌà’×ÏÆº]”ð¬t¯I½Ì@}iô¸xT´xÉŸ{–Σ®ø5É©­à ‹›yié0í0Þˆ=�ÿ�ðçÀÃJç‘:ì’„ /b¤/Nˆˆñ¥üÁk^ìQ:’:/àz’�læs‡œ•ëJ瑤²P_oÄP»€¸krm\˜É?ÝŒÌÅóœ/Yì59Ÿ·¼ wôWý¬!øÐxòåeÍœ*f¶Ö¬ˆý7Or|Àÿ.�GÅÜÉ?NNñIO´‘ÔK,ÔF—Æ“£â}ÀKqj¥îµ–à”ÖŸ]|F^V:ÌŽ\؈ÝöIÞ”Á_à�¿´:’‡ÎàŒ¹°4`õòxV+9�éSe”ΣÞ°!ƒ/dÅÉçåu¥óH’€æ´K±8à¯^Dé<êY |/’ÏÜ|+_ëµ½V�óÜÎë«ä} �(�Gê1?Mxÿp3Ï.ä�.Yì55Ÿ×eðFÜÅ_Û·)’Ï|x¨™7•#©¾,4']ÒˆÇÀ_¼>a tÍ)7fð¹ä“‹¿’·MrRT㣓Á‡pª°´] ?ª’÷õ©«�‰‡M rB$o\:�æ”»"ù|k>5]:Œ¤ú±Ðœ2z\<*¦øë€W{ã¯]´Žà_¦’O-iæÕÝ|ly¼”ädüÔPš•€oïjæÏº=öx#ž ¼#§§ùv{|õ•uÀÇ>:ÔÌß–#©>,4'\òšØc`ï!x'°{é<êS _«*þö°ÓóG�oõ±ñ¤V‹�Guz,©�µ2øÒTòþÛy}GG:)ªÑQþ(‚wÏèèXª£#ùË¡a¾Ô§_HêyêmÓÇ(-Íà£À£KÇQß»€à#‹Væ7Ú}áŸ7âƒð—­Hmuɧ,àC9ïlë•ï]¢óW8SG–ð“„w,næ÷Jg‘Ôß,Ô³ÆñÌ„�O.�EµsÁ5ùæ®î>>Þˆ=3xÉ;pöŠÔ)7&¼5|qW�¼òE±`ã^_%ïNxl»J3tf«Å»Ÿ‘W•"©?Y¨ç¬YûOLòQ൸³¿Êº„äÃãÁȬo*"b´Áñ‘|8°3ñ$=À%™¼mx$ÏŸõ _{ nä„„wo4if6´àƒÕôþ›Kç‘Ô_,Ô;î½aúÀ~¥ãHw ¸¼'/bd&k4WOšjñÿ£ù$=@rÚdð®™ìpa#vÛ+xs$ïöïB:i¦VWÁ[™ÿU:ˆ¤þa ž°zi<¾Uñ�ÀsKg‘¶c,’“†ÎàŒ­- øÙËcßùƒœDðf×ùKÅÝ•ÁG®ãß“›øÍU'ļÝnãø„ñõ® øò&xçͼ¥tIsŸ€ŠoÄü ÞOòn`~é<Ò ]œð¾áf~˜Þ%|Œã+øpÂC g“t«#yËÐH~àü£bð€ýyuS6š4c·fðöá•ùåÒA$Ím*f|iAÅ——Î"팀ïŸKx+ð´Òy$m[&Í þƒà= ‡”Î#í¤³r�†OÍ_—"in²P×�T >äÞIò×ø©¿$IÒlÜðž¡f~®tIs�À¬Yûožà Uðð<"‚‡“@°É„Ý&l„é�Z 6w7E‹›[ÁÍ$×MW¸^ëþVÃÙâ‹ G–Î"I’4g#›“7ûoÍûˆˆÕ¯à÷r€Çµ‚‡<$’‡er»g²0?¦O™šŸ°©‚uLÒâvঠn¬àú)¸~.jæo ÿ­¤¶ªu0z\<ŠÏ®Z<%ƒEÀ0ðÐ6s;pE$—gÅO"ùïÉ…ütÉ)¹¾Íãô¶éþßÉß JÇ‘$Iê7gòúá‘üfé ݶfEì?9ÁSž’°$à �¶q˜ ¸&a %øa$ 5smÇ�ºªVÀªbÞî·ó⼜äYÚü'` o?¬Z|gpç=áÔ¼µD–n]�I¾<¿tI’¤>“Ÿšÿ[Þ³µ/úÅ%�xì@ò\‚£˜>f÷ BQZc ß X94Â[;HêUµ(Æ1”Á"ye�îÐÝ~ðŸ$ßæ‚™œ5>Œ-�ç“|‰öϬ�$IÒ½~:Ç-iæå¥ƒ´Ã…�ØmŸä%¼˜à¹”»áß‘5‘|‘à Cͼ©tiGúºX}l<)[üYÂ+�ªtžYøMÀ9Œ,Xǹs±Í=ÿ¨ÜÿÞÉû™[ÿÛK’$ÍIZðÞáf~²t–�±êèØ}án<7’e ìU:Ó,lX9 ì—Fý©/ €ñ¥ñ4*>’ðìÒYÚ`-Éiœ2ÔÌ‹K‡™‰ËŽ‹ÇLMÑžR:‹$IR �pÂ\ØÀîü£bpÿ‡ðü^Kr4s|¯¨€)’Ó¢Åû;3Y:�ô@}UŒ7â÷29™àX¦w÷ì7« ¾É—zuŠÑ–)ÿ_ö+�E’$©ÆÆ*^qè鹦t�­oÄPÂë�À�¥ó´[À’�læäCÎÊu¥óHwë‹àü£bð€‡ðçÀv+�§ 6gTŸ>ìôüQé0DÄØRþ’à$œò/I’Ô î¬‚×¶2ÿ­t€‘F Güà(úó»º1áÍÃÍüZé ôA0¾4eŨïtó“|:‚Ó‡š¹¹D€U�Øg!œ]b|I’$mSfpòêäýËš9U"À¥¯ŒU›yÁ›€G—ÈPZÀÊMð–#šyKé,ª·¹[DÄø2Þžð!æøZ¡6¹.áo7mäŸ�üzÞÕ­AWí_eúÜUI’$õ €o²¢›GO�7â@à odnmè×·�¼vh$ÿ½tÕל,®|Uì½i‚Ï“,+�¥ÝšÁ?Tɧ†š¹¶“�7â +�½;9Ž$I’Ú⪀—5s¼“ƒ\v\<¦5ÉÛ ÞP“å¹³‘‘|úæ[yçsÎËÉÒaT?s®;6§Å™ÀãJgéewdò±>щ`Ç—Å; >’0ÐîkK’$©3îÈ`ù¢•ù­v_û’câ‘ 8l÷õûÌwç ²¼›32$˜cÀh#žp~â<·|l�Ýùäc¾�wõbçƒ9€O’¼©á$I’Ô]Sü墕ù‘v\ï²WÄ~S¼+‚·ú‰ÿ¬\ÕjñâÅgäe¥ƒ¨>æL0¶<Þ@òlwÖµ'-âNÌÖÎ\`¼N8xN{£I’$©ë‚ÏÜr3oÛÙ©è—¼&öÜÀŸgðN\㿳~Cð²E+ó‚ÒATs¢_'fðW¥sôƒ€UÀŸ 5ó³yÝê¥ñøVÅٸٟ$IR?9wÁ|–üå¼sƯˆˆÑ¯¬’“ÑÁlu±‘ ±he~£tõ¿ž/Æqð�Ò9úÐ7§à­KšyõŽž8º4žÓ7ÿt!—$I’º(at ^px3¯ßÑs·ü»ðÀ3º­N&–7ók¥ƒ¨¿õt0¶,N&xOéý*`CÂG÷؃ok€-;ý�{v9ž$I’º$àêªâ‡žžk¶öýÑñÐj’�&¼júéê€ ‚ã­Ì3KQÿêÙ`¼“ð—¥sÔÄ‘üéÐH~美-‹×|˜W(—$I’º$àà%CͼøžOŠj|Œ?I8xP±põ1pÌP3¿^:ˆúSO£�øÓ€Ï”ÎQ;ÁHð–áSó×£�x[ÀßUéX’$Iêšõ[¦¢Ÿ}Ù±ñ„©ÿU:T�l yþÐH~¿tõŸž+F—G#’ÓðÆ³”Û€ó€W”"I’¤"&˜^º g‚–r[Uñ¬ÃNÏÑÒAÔ_zªX½<žÕJΔÎ"I’$I¥\?O›ÉæŒÒLõ̧ì«�‰G·’¼ù—$I’Ts �€¯¯::v/�Eý£' € ±[p&3'I’$I¶Ç|¦tÍ-]+.àÀcº5ž$I’$õ¹Œ7âèÒ!4wte ÀeÇÆ¦Z\,èø`’$I’T×N-dhÉ)¹¾tõ¾®Ì˜jñ�xó/I’$Iíö{ƒø¿¥Chnèø €ÑF¼<à«D’$I’êks«Åa‹ÏÈ«JQoëè €ó�ŠÁ€vr I’$Iª¹ù1À_—¡Þ×Ñà€ýùSà°NŽ!I’$IuÉŠ±cã)¥s¨· ¬^8¯Æs�\ü•¼mW/¼ªûì¼W¯#I’$IÚ¡ˆžÓŽ‹��‹oŠdßÉàÿ-iæåí¸®ÊŠÑåN‹‹�ùׯjæÅ»ráñeñÁ 7£�$I’¤nIxÉp3ÏÞ•kŒ.�WUÉçvÛòЯ71tÈY¹® UPÅïaËÍ?@Â#¾5º4ž¼³]³"öÏà-mI(I’$Iš‘ N""vöõcË㵑|é>7ÿ�œXÈñmˆ§Â*‚nåñ}£âÜÑ¥±dg.:1Å»€½v-š$I’$i6Ž\Ýàe;óÚ±åq\$ÿÂVöŠ‹äÅ»NÅUܿٹ¯EÅWW5bŸÙ\pÍŠØŸäM»M’$I’4[SÉÿÇI1« ßWÃ$ŸOØÚ÷¶'�Jª€‰í|ÿq á_g3…db’÷{îr2I’$IÒ¬ ��ñŠ™>¼{¶Z4�Ý·sÍíÝ7jŽØQðÒ±¥¼m&[³"ö޸˩$I’$I;-á}³ø ÷óìøøv €>PLîðYÁÉã�ÚÑÓ&&x+Ûi�$I’$I]qøøR^°£'�-‹c–Ïàz›Û�I…UÌì¹ á³Û[G2Þˆ= ×þK’$IROÞ³½o_öŠØ�à“3¼š3ú@•°a†Ï}æè8ÿ{[ßÌà À~í‰%I’$IÚ Ͼ´OßÖ÷[ƒ|8`&× ¸«mÁTL¬›é“#ùÈèqñ¨>¾ê„˜GògmM&I’$IÚ%ð®­=>Þˆ?HxÕL¯“1óûFõ®*gQ{Çàƒ»­¥ü^ûbI’$I’vUÂËÆqð}»òE± áŸ�Ÿöü¶½ÉTBÅì�ÇŒ6ây÷} ƒ·´/’$I’$©Mª Þ|ß6ïÁ;€ƒfu•–3úAUÍn?ÿ¨¸´GOk{2I’$IÒ®K^å«bo€ÑñÐ þbÖ—p @_¨vò¹hÿ‡ð€×þK’$IR/ÛkÓ¯ˆ >ì½×p @¨vv*GÀ__ÒˆC2XÖîP’$I’¤6JþÏx#žJL³æ €¾PQqÛN¾vÿø.° ��$I’$ImwhÂטÞnör§ïÕC*`í.¼þáí "I’$Iê¨�¾¨øM;ƒ¨Œ]-$I’$I}.ÂûÆ~` I’$IÚ®¸Ëý Ê)�’$I’¤mš8äëžÐªt€$I’$iÛÖ’™¥Ch×USS’$I’¤mrÖxŸ¨žøoÜL–"I’$IêI~hÜ'ª-S9lt$I’$I¿#áÖÒÔÕ–¯¿.šB’$I’Ô“ªä¦ÒÔ@XH’$I’¶¢Uy¿Ø/¦g¤?PI’$IÒVx¿Ø7î^à”I’$IÒï²è8¥C’$I’´uáýbßp €$I’$i›Âûža I’$IÚ¦�MÞ/ö‹éSü�J’$I’î/`Ã!gåºÒ9ÔÓ@Ë@’$I’té‘ñ}¥ZÄÍÀDá,’$I’¤Þò«ÒÔ>Ó{œ˜-àÆ²Q$I’$I½$àúÒÔ>…ƒ½Ó IDATÕÝ¿ñ+I’$Iº¯V8 ŸÜS¤?XI’$IÒ}øAq¹§ e I’$IºWxŸØW\ I’$IÚª)gŠ÷•{—XH’$I’î#,úɽ3lv$I’$I[LÝz“§Åõ“{ €ÊfG’$I’t¯›žs^N–¡ö¹§hMqÐ*˜E’$I’Ô#?$î7÷CÍÜ ÜR0‹$I’$©GÜP:ƒÚ«zÀŸ¯-’B’$I’ÔS2¹¦tµ×ý €ð,I’$I‚ ~Y:ƒÚë~@ØðH’$I’€Êûþs¿À)’$I’$€ðþ°ßܯ¨*À’$I’$ØØòþ°ß8@’$I’ô@·ÙÌ;J‡P{ݯ¸®²PI’$IRo¸¦tµßý €§7spK¡,’$I’¤Þpuéj¿j+�]Óí’$I’¤žrMéj¿ß)¦G’$I’j-ƒ_–Πöû�À�%I’$©Þ*ï ûÒï6=’$I’Tk-�ìK¿»@ò‹9$I’$I=bÞ„KÃûÑÖ–\Y"ˆ$I’$©'ÜtÈY¹®tµßï—UüØ\ ‹$I’$©¼+JPgüN°¬™Sxäƒ$I’$ÕR†³ÂûÕïî„��$I’$Õ•@ŸÚj€?pI’$Iª¥ªåÂýÊ@’$I’t/7†ï[[-2l|$I’$©Ž&,úÕ¶ à’$I’T?ØÇ¶Z¬nq (I’$Iuã‡Á}l«€GJ’$IRý¸¼¿mk@ÒæG’$I’êÆûÀ>¶Í ÂæG’$I’jÆ �m{€S?$I’$©Vܾ¯moÀåÝ "I’$I**³ÅšÒ!Ô9Û,6'«»D’$I’TÔµCÍüméêœm‡7óú€;ºF’$I’TŒ÷¹m —u+ˆ$I’$© g�÷½íØI’$IR=TÞÿõ»í6@’$I’T áý_ßÛ~`$I’$Iµ08èð~·ÝÀH’$I’ú_À-O85o-�C�µÝ` ®6v)‹$I’$©€–û¿ÕÂv €eÍœ ¸¢[a$I’$I„@ìèZ.�$I’¤¾-×ÿ×Á 7”$I’¤>ç}_-ì¸p€$I’$õ57€¯‡-ß’$I’ÔÇÖ�p]éê¼ ïâr`² Y$I’$IÝ7Nf–¡ÎÛapð9¹ XÓ…,’$I’¤. ¸¤tuÇŽ—„oI’$IêG-¸´tuÇŒ €ô !I’$I})üÀ·6fT„€$I’$õ¥ÍÉhé ꎕ€$I’$õ¡Žhæ-¥C¨;fTz:¿nïpI’$IRw9ý¿Ff¶ àô‘c��"I’$Iê&—{×ËÌ Ò7†$I’$õO¨—ž I’$Iý%*—ÔÉÌgXH’$IR?™\p'—•¡î™q°aúlÈì`I’$IR—$\vð9¹©tuÏŒ €#›yp]³H’$I’ºÄ}ÞêgƸ @’$I’ú…÷wõ3«À�%I’$©?´Â ëfV¾A$I’$©/T~À[;³*ZSü´SA$I’$I]ó›¡f^[:„ºkVÀâŬÖu(‹$I’$©;V• î›Ý€³ü¬3Q$I’$I]ò“ÒÔ}³+€ð�"I’$IsZ¤÷uu4ë Ã}$I’$i.k XÔѬ €–M‘$I’$ÍYw ¯äªÒ9Ô}³..ƒqà®d‘$I’$uXÂOÈÌÒ9Ô}³.–5s Ï‹”$I’¤9)ÃYÝu5ë€ðÈI’$Iš‹ª–ûºÕÕξa$I’$iNrÀúÚ© ò #I’$IsÑúÕ-Ö”¡2wæEÙbØ,hoI’$IRýl˾ns•¯Š½7läáÕû~À¯ù$û�ìEõ€ûÛ·$Ád$·µ‚ÛIn#¹ X;8À wãÚÇ|!7v÷oUÎNCÍÜ<Úˆ±€'µ;�$I’$©3"{k?·+_ &öæñ­ä�„C"ytÂ# < Ø»ª€�Y[yNlùšÓߊ¼ÿãS-X¿Æqppm$—'\Ú Æàò¡fnnÃ_³gìTÁOH I’$Iš3¢Ð~n±úžàˆhñ¤ {ò˜l10íîˆ]wà–_OÉ-ƒoé&Ʊ&ƒ‹I.¨à¡VÏå#cg³�6âO>Óæ<’$I’¤É‡Ÿ‘—tzœŸ7âÁ3žžÉ“žìÝéq»`-ðÀoMµ8gñyUé@³±ÓÀøÒxZVü¨Íy$I’$I�±qãƒØûÈÏæD[¯—.c¸JþgVü~$Ïdz ß ¸<áìL¾1<Ìqb¶JgÚž�.®|Q,Ø´'wàF€’$I’Ôó.jæï·ãZ£+â¡ÕÏÊà��lÇuç²€ëIÎ$jæJçÙš�.Æq1ð”öÅ‘$I’$uDð‰E+óí;óÒ‘F Ϙ‚£#y°¨ÍéúÍ%‘|~`3_<ä¬\W:ÌÝvzÀ-.Â@’$I’z_‹‹fóôUGÇî wã¹$/‚£[É�6蛫–dð©É|p¬§eÅ'†OÏÕ¥CíÒ €ÑåñªHþµ�y$I’$I00Àc=-¯ÙÞsƱ'ptÂràù¸ä»]ZÀ7«Š“;=R*Ä.«—Æã[kÚ˜G’$I’Ô~7/jæC·ö�kŽ�…ëïây‘,Kx9°g—³ÕJÂV-Þ=tFvýHÆ]*ˆˆ±eÜì×¶D’$I’¤vûÆ¢f}ÏŸ"b|Ï^—°Œþ8¢o.i‘¬¬Z¼÷°3ó—Ý´Ú¥WO·ÿÝž(’$I’¤NÈéýÛøy#1¶<Þ3¶ŒË¾Ÿðz¼ù/¡"8.X=º<þêšãcawÝE³ÛHB’$I’Ô]U08Öˆo µ$'�/�I�°[$'®_Ï%ã�xA§ÇÛµ%Àø²xaç´)�$I’$IõŒ´9añWò¶N\~—g0=`×ZI’$IRÛxƒ6G%˪ ~²zy<«—ßåc�XƒSH$I’$Ij‡ÁÇ6îËûŽülN´ë¢»>ˆtI’$I’Ú¤"y÷ÂÛøîèŠØêñ�;wÑvp#@I’$I’Úí™1ÉEã�xb;.Ö– + I’$I’:àÑ ?mÄóvõBíYÐâçÀÆv\K’$I’$ÝÏßmÄËwå"m)†š¹9ágí¸–$I’$Iú VîJ О=¦/ä2I’$I’:g^ÀéãËâ¹;óâ¶­à‡íº–$I’$IÚªù|ug6lß €ä¿Úu-I’$I’´M{'üÛx#<›µ­jæMÀUíºž$I’$IÚ¦G·`åH#fú‚¶?hëõ$I’$IÒVüáPòÞ™>¿½’$I’$uMpâøÒ8b&OmkКâûí¼ž$I’$IÚ®Á¬øâªbÞŽžØÖ`ñ™\ÜÜÎkJ’$I’¤íZ²àvÞµ£'µw @f&(I’$IR7EòÞÕÇÄö÷œvï@•î I’$IR—íÙª8i{Oh{€€$I’$I]Á�/�EÛú~Û € ûñ`}»¯+I’$I’¶-a 5°ícÛ^ùÙœ.j÷u%I’$IÒöE²ü²ãâ1[û^û—Ls€$I’$IÝ78Ùâ[ûFG €´�$I’$©ˆHŽoÄž||°ƒUpaÂd§®/I’$Iê¸;�Û€µ÷| €dï„�€*က‡û•‹ªØ“dð…û>™Ù‘ÑÆñã„#;rqI’$IR;ÜpiWWf²f°âŠõûpõ–ýÝfìÊÅ‚‰Ý8pªâ±QqD´xRO 8$a Cùµm,jæ3ïû@Ç €±åñq’?ëÈÅ%I’$I³µø ÉE\40Å�;3ÙéA/yMì1¸‘çfò‚—0=[@]Ðjñ¸ÅgäUwÿ¹cÀè²xEgväâ’$I’¤™º8ƒO/\ÇÈÁç䦢I"bôެ‚W¼6aŸ¢yú\$>4’{ïŸ;T\öŠØoj�›éÜI’$I’¤­ÛLpðÉE+ó‚Òa¶æšãcáúßÒ x;ðÄÒyúÔý–t¬kÄÏ€Ã;6€$I’$éw´‚Ï0À'‡OÍ_—Î3Sã�8:áÃÀPé,}¦•ƒ<üî÷Bg?�O¾ÛÑëK’$I’¦#SóxìðÊü¿séæ`¨™__´ˆÅ‘4€kJçé#ULpÔ=èìPœ×ÑëK’$I’rÞoZü•¼­t��vb¶†Fr$`1ð9 sÓÕëåîþMG €Á�œLvr I’$I—<áÔ¼µtˆvjæo5ó„L^p}é xÎy9¹hˆã#ùr»®)IÒŽ$|çÈϦ›ÒÎP$§—ÎÐC ÍÈL’s‹Œ-Iª�€÷¯Ì�µýÂ'fk,xá?.$IÝárêÙ™ô¿Ñ÷ÈRK ò�+Iê¼H>6ÔÌ“;uýe͜ڸ/¯¾Û©1$Iº[Ly5Kšy9ðÓÒ9zAÂ�Å €y|h•_’T ÿ>üE§9ò³9° ¸¢ÓcI’jmõagæ/K‡˜s\p·;ŠO85o~\j|IRßh,kfWÎjæÚV‹£�uÝO’TCá§ÿ;£ü{é =âörKÀã+$I�²‘ŠCÍüm7]|F^–ð†nŽ)IªOSÛ ‹GÅMè¡t�¾�%I�¼uÑéùóC7s%ðÅcK’úWÀ†;“ÿ*�cNÊÌ€ÿ,£”Û`up°¶dIRßù�E+óŸKX0Ÿ·×•Ì Iê/ ß{z37”Î1WµàÛ¥3…glY—é®É’¤v¹«ÕâÍ¥Cüå¼³ ÞX:‡$©�¸|z—Ìà;¥3”–%7¼O—H’Ú"’,>#¯*�à°•yÁHé’¤þ�»â�Óò†€ëKç()Z¥7ä›x $i×]5=_:Ä} T¼ØT:‡$iÎûÅð鹺tˆ¹.aUé %ÜR¼>5 üwé’¤¹-à=Ÿ“=u³}èiy ÉgJç�$Íyg•ТöÇÐ_[¼HøFé ’¤¹+`ÕÐg–α5S|èêq„’¤>|³t„~PÕ}À×õJðõÒ$IsÚÉdfé[sèWó7Ÿ/�C’4g­½åf¾_:D_˜ä§¥#”´i¿ê‰`q3/ ¸ºtIÒœtÕ|­tˆí™šäo�Í¥sH’æžHÎyÎy9Y:G?8ì̼XW:G!ëžøµì�Mïå,IÒ¬eðÉ-ÇÊö¬%g毢ÇK IRoj9ý¿Ý~Q:@!×ôN�î IšµMó8µtˆ™hÁ¿”Î Iÿ?{wWYöüs�IÚÒ–MZTE@ÚÌLÂR•]ŠâVeïLJA}—GEyÔ‡Ç¥àŠ Š¸VDh›œiÙdd)¸b)4™I‹E�Z(¥Ùæ\¿?ülÓd朹ϙ¹Þ¯W_Jš¹îošIfÎuîÅ$ÎÀà€ÿ2kÄÁ¦Wp'°ÎucŒ1 ¢\¹ïB]ë:Æhd ÜüÍucŒ1‰rûþWéz×!ꊲÚu'$f €óuå·®scŒI¸Î0jC›ú®ccŒI±ÓÒÂç5æ ј5ðì nŒ1fÔžŸ<‰[]‡ ÛÀcÌXx)[ÿ6 ø—ë Ž¬†˜5z•°]’�1ÆŒÎo÷¼D{]‡‹t�{�G]ç0Æ“÷O_¤»Qoˆgð<; ÀcÌ(¯(ó¤ëÕðÞÀ0Æ™Á¦&»5m =îÛü¿cÛPå`�ëÆcâEá霯e×9ª1$»�aŒ1& K÷]¨vRŒ �òÒã$cÛHûÚ�ÚôcŒ1/%°Ñu†jyM¼à:ƒ1ƘøÁw�¡xÐì:C­ˆ&d€ ׌1ÆÄK=lÜ3Ác“ë ÆcâE \à×9�6P hJPÀƒßë]ç0Æ+‰_·×ߟü&†1Ƙp)ÜÑv¥>å:Gƒh”ÀÚì"ýçæˆu ík?bËŒ1ƼD=¼h�sÀcL¼ˆÚôÿª‡÷£±ìåˆu`Øb׌1ÆÄÊתÕÛ¹Î`Œ1&>ʃe®r�£�4J`ùË?ûÀø Ü,ð¬ëÆcb#ñÏãëàk0Æ…;múMíà:@-Hgìsƒö¡üÆucŒ1±1q¢e˜ê:ƒ1ƘøPlóóÛÑu€ZðRüååkrd̆N8Õu cŒI�~àqàQ…çDØ<‹ l�GÊd…W ì ¼Š¤¼&À¸Of—}!±ç$‹òj’ÕÂèøWO ¬Aè¥Wa0aÊÀNÀ =Ÿb“Ácb"ð°éÿµ²ìX™8aBò—ŽÂãÓéÃ/ÿ`"ÞìMœÄÍ7ò 2UÃcÆèQî�€xå> ¤£ßcb*H¥¸ÒuˆF¢)vŠK>Jܵ¥�'¦°^¹iØlï:‹1ÆÔÐ࢔Çüéú Ë ûùúðà;Ý99T„Ï ïbV€ÙZ�&ÁYþç�K~ÆÌ‘j ?Ÿ..(ååp>!J.6³LŒ1¦6þ8m‘>î:D#åÕõ~ý/C{ôÜ¿¥¿KÌä‡C|Ý„r�ëÆS#ψrŽÀž_Ïr}ñÿrÙ‚þ)ãëìrÀ¾(ƒµ_áÀZަåy™ÊÐFyµôÂW‚f^›ñõ“®/þ_.íë2�zrà1møùÔï:“1ÆÔ‚ŠMÿ¯5U^ã:CÔî^ÞùÓP[cŒ©ýÀ÷Ø;]ÐsÓ¾>ã:ÐHZëß2ýHyèŽö¨Ù¤º7ôœ$¯®ÑX¡jVŽ vkßû.hnbïL§~­u�®«Ñ¸ÉvèC™‚~D=Ò ï`Œ1u,(«ý®«5õê¿ lyý?$h ÀáÆ†¦/Nv�Åc"ð¨ðÖ–ÅúW×AƪÍ×UÀìR^Þªð3`ߨÇ,§x Ðõ8a�#jÔ&¹­ oëÔU5-DÙ}˜Ý•—#=Xê:�1ÆDä®áåP¦†<å5u¿@øÓÖþ.Q3ñu“Àõ®scLDžHâÅÿæÒ¾Þ6þyÚ€¯ñ²QÞeý¨Ô ÷3 §e =ܘI¬•ð׌1&2j³›]Pê~@ ÊÝ[ûËD5T(¸Î`Œ1Q�:9mŸ´/ãë<<eè¸hÇr®$êu¬”—}Z£ª¯pwÞ˜õõrTƒ#ccê—ŠØîÿŽÔzžZ[1ÒÒD½qèÝÄ� -0ƘºRo»Ÿg:ôÞ^x#Ñ­å~ew7GT;�p|D¥U…s{àð6_ÿÑ5÷l�ýLcÌ‹îNûúˆë�fÙÒ ìæ:G¤”ÛGúëÄ5f\«/ˆrµëÆ6�]gÛ _ŸÍÈ1´$ ô;Òâ‘ »f”DÉGPv#B.Û©çä|-GPß™ëðgÂcTXà:C#÷4{“°}ðÆÌ«³öcŒ©C S\gˆ„ªf|�‡p a列ºz–ŒµfDºgKð¦�Ë>!Gd:µ.w‘¯N&Œ1�n _ñ]‡hD)ašë Q(ôóû‘>'‘ €§Öp ð„ëÆ²í“r1[‰L§.ò„6…XvJïöb½Èx ¹ä#^À[Ò‹uyÈucc0`׌1&7àë×!Q ÑŸRä’Â}û_¥ëGúœD6fÞ®ƒ®scLØú'×÷Æ4-�zƒ ï6†VTùDhµ"²ê8Ù^á´KþÍ+󖤟±-¯u�Ác¦p…ë �Ê£¾g #Oÿ‡„6´lËŒ1ui×¢–éÔÛE9è £žÀ[ºsrhµ¢20�3€�C*÷TÊãÝ-Kô!Õ‹-QÞà:ƒ1Ƅ칾^~ã:D£Ò:oÈ66„7²‹õ/ÀJ×9Œ1&Lõ>5íEé‚ÞŠp:„QO„χQ' ¥¼Œó”3C*·.€£§wèƒ!Õ‹7ÏƘú¢Â’×ê ®s4°z~Ÿ5�êã�Ûú¤Ä6À¦Ïcê�d]g¨•L§.RáË!•;¶8GÂÞ`/Ê »‡PiP”\«¯]!ÔJ¥ÕucŒ “Ø,fWV�,»»ºÎ�¿L»F7lëóÝH•¹‚Ž•2ÆWD’u®}µ²>ßÒpvB ø^uBµê8Ù^…/†RLø|º ·†R+V'Û-®scLˆ/ K]‡hTep�!J*Œê=B¢Ãë·9ÍÁc$=|áÓTÕ>ôT[Jà-¥œÄêD€� œ ¼²Ú:�™NýA‘£<Ž7“ð÷)Æ÷n´ IDAT³9�9_Ë®s4*t�!J¢Ü4šÏKü «¨-0ÆÔ…Ôàb½¡]ØÒ¾>ïyœ ôW[K…–ò29„XU+Í–Œ(g…PêŸý|4„:‰xá:ƒ1Æ„)ìºÅ%Ѻžðܦ�¹g4ŸØu’È à‡@Ýž��}kuèÏQÖ¨ÇZ Øú&'Û£¼ ˜ LÙì�itï‚ÑuqëEK‡Þ×Ý.çŠò�*K½ø:„¶é^eÎ/ðø¥À¸*+ØÖ™¾õH”Y®3ãš@Ya�ÂZ�5(OÈÐoÚêc„v˜¢C﫦»Pïû“mEv±®p¢‘)õÛ¸uÆ|Íç&þAÚ×gJy¹Aá×YY‡µúº¬Ú:K�’¦)¯äu^™,�<2¢¤Z:¡ê Æ$€(ï>ã:G­õ(ßNCØ¿ÊRÿ]ÊÉ’tAF®Jt—ø¬Ê~¿Lûz[ueʼn²kª‰®sS+Ï%Uº�’ Å LOÛ}4ŒúÝyù˜ÀOèe*¤¶ùŸK]§ÈÎÞÐM‚º7�ösßPaj —<8˜]m�™·ë ðÐðŸk^üx!/©é�á(QŽÞ‚Í0uJaZ×l™ÞºXê¨Óœ¯å®¼|܃?PÅ5…‚•'ÊÓ¯Ô§CŒ8*Å9ò¦f2¬M ò!ÔIœTŠc©ƒeŠÆŒàa`)ÂÒ²rg›¯�j ¥GIÓ®SùœíšíTPXè:D#“ÞˆëQÑrƒ5Æo຾ɬvr�¥��Ð=GZ²ZõF^[2¼aJ×🠑®Ùá†À»€£�æ(Æ6Æ…ÔКø/¹ÎQk­¾ÞUÊÉ¥*|°ÊR{”›¸‘ãP­ÙûÞeyÙqtPýÔ¾è¢� Â)®#²çTø�Àï¼A–od]S§0WáõµÏlÑÒ°fs˜ ‡ÕñÙqm]¬í'×Ew}Ÿ´¥à:Gƒó$àó5MU[}íÊvê…_gͼåýÀuÀ¨Ö¿g §"R·�ê‘¤šø²Œ°¾u ŽéÎ3/„:£RÈKj\ìB¹ŸZïB¨“8äew†fy“hÿǮCyy»e;õÔL§þº–ÿˆRÃ÷gf‹lÓòPs!BcÚ7ª.�غš8¥ç$q²¶¦u�®Ëô²Œ¯Ç47±›(îu‘Ř�¼®'ÏÛ\‡paÚ"}\…ùaÔå+¥¼Ì £Ö¶¤áà½aÔRøÊð’¨†Ó ¢ŽÞŸ˜†¿È= »d|=&SÐËÚ.Ó�.Âóœd\Œm†l7ž%®s4²B^R¹Î™1¬ÿ‡:z�mÍð{ vU³%Í�Çç\‡Øw¡®Mt~Æ×7KÀÁÀBB8^̘ZSu¼“½Cšâ< 7„R¢pq)'‘6Sºóò9à¿Ã¨¥Ð�Í4欶ճd¼ÂÇ\ç0¦ëU8?xCÆ×cÓ¾.>Ä×0f2UNDD9Ûipí>Wès®C4²L@°½ëéoêeéXP7 æi b›k8'|dE^¦¹Žñ¢ôb½'ãë)ÚÄkþ°õW&1fuÍ–é®s¸�]¨O ¡Í욠µÝ9™R½—(¶Ë'¾ZAáÌÓ ´z Ò·=s€W¹ÎaÌ<¨pfy¯ÉvêÿŒenÔJ³™«Øi®6ýß=áp×"ô‡i×膱< ~€g?`qÐìÁ÷]‡x¹ìB}2Ó©ßž4‰7œ¬u�ɘQI5îÚÍ2ü0ÄrE¸¦”—Pß”rrÊ�iga�5“'6f3»�—Ú¸Ïw“8+r™Ó³¾þÐÕÿ­YqšLRá<×9 kû^1¶õÙ&R¿ëÿ®ëcêª�öµ¤pŸë�N`Vw^Þã:Ç–ìy‰ö¦}ý~S{©p.0¦Ž™1µæ)§ÅiVM-µúÚ¥pgˆ%wn.ååØ0ŠÛåË*üœ�R¸xÏK4Œ¥‰Ó"œ ¤]ç0fQáC%Ȧ}]\ËSFÆ¢©—³�׸Îaè˜1_msj—DDëxcÙÁFoxp‰ë ¾_ÊKÕÇ`EeÚ5º!Û©ç47±C3ú\g2fKRžòU×9\åò0ë)l§°¤”—�TZcéQÒTÊÉψàû"„ûõ&Ų3¤Y´v'6S�µ(Ÿÿ<ûf;õWÃÇÇÒŠ¼¼^‡f;Ç<Ï®K\ë>‰VàÕ®sDäom¾®ëƒê®ÀІo y÷$fö àÓ®Cl˾ umÆ×³² ·¸ÎcÌ–ˆ�‹jýzÜãXBø º&…ù¥¼\vW^¶Ëœ+S¦Nå·*|4äL,KûZ »nLx†Ïû¸ÎąÀåÍM´d zÁ>7hìo /Åœà:G£èjéP›™ì˜'¼Ýu†¨ˆr]%�«»@Ú×g®q�ÀÀ—] 8Vi_Wg ¼Cá¿€g\ç1æeáGK�’&×Aj­u�®ƒ±o3Z ïÛn[y²ì9šÏ/¶Ëaƒ,‡hŽgTÅ�¢nÜuŸ,{ |Ùuc¶àAUÞšöõ´}j"öêÎË{Žw�Ã@ üÒuZÇ € ‚éÿP‡ €@ù•ë €í5ů9W’ñ¼f ‡hÏ'ãœBkß$æ»ÎQk*5kÄM¾ây<„r!ñ7Qî®Å8qñðé2!�Àö®³ô*œ™öõ´´¯Ï»3VÃÍ´ \ç0C+Âï\ç0 B,�%�•­ÿ‡:n´ùúwà×9Ì¿e6¾À·\‡¨ÄÌÛu0Û©ç¶$ÀÄ„ðþîv }úX ê|&Ní±ðÂó\¼Éuc€ xcÖ×DÎF)åe\ ®vp�ÅüÛ¥q>&²QtÏ‘½²®sDAàî¶%úh¥�¯Û€ŠM¿‰åÌb»¼ßuŒJ¥}½V=v�ÅQ~ØHGŠð×"Ô÷ÔšÆYÿ_ÌÉçU8Õuc€Û84½X‹®ƒTJ•‡ºÎaþM�K\‡0àç:Cd”%Õ<¼®}›¸Xï:‡ÙŒ2¿;'‰}¡Êvh�À! v®«qmœ×ôÌ‘]©…þt�!Bͼ]]‡¨…b»¼á<×9Œ ¼kÿ«4±ïK9ù$‡]ç0/qG¶CrÂp¬ëQ)+WUóøºn̸V_@페/Â’î“e×A*•öõ Ž„=²ËÄÉAÀ�+çȾ®ƒDmÿ«t½À×9"²Úu€Z(¶Ë1(¿¤Fû*3‚ó2NMûÚï:H¥zÚåh¾ï:‡y)�‹\g0PÊË+s�#"÷¶.Ö¿US ®ªüÂuó^%e®Yv¬$öXŽ´¯Ï¯Yñˆ�·kœÛµpGÏ©Ëun›  >ïªh�~]›)¶ËI(‹�&×YLã(«ð±Œ¯g'ùÔ�R^ö ”Nìç)nžž8‰+]‡0 Ê{©×Ÿ�¡×ÒªÔ} »XW(�µ»rB0a‹–�!Í®ƒTjæí:˜ñùˆÀÏ\g1 ïUAÀÒîÙòF×A¢$ð”ë Q©Ï¯ëEÅœœ&C+ã\g1 -PáCÙNý¹ë Õèž+¯®^á:‹yå²JÏe7!“ú�þ¯©êÖÿC4›ŽSÇŽ†+ yI¹R1UMø„�÷jb`ñ¸½§]Žw$*¢¬�°üSÀRàRQ.Dù6ÊO€…ÃMä Q ¬Ñ~]îˆH)/_A¸T!¹¿çM=P��e:õ×®ƒTãÁ¹2Åäw Ó\g1ÿISv½+N“IÀ»\爂Â}aì1QŸS#^&OgS/ßWØÑuóR"ä3Ðǹòæià:OET5}®|¸»ÄxQNqÇ4´É�²¤”“/¥s^’§¸n‘ðtˆÕTá÷"ø¢Ü”öuÄuø…¼¤2mx£0h -<V­¸¸+/Ûí˜ã…v×YŒQáÌL§&zIèý'ÈNMÍÜ$Ðê:‹Ù¢ßg;´ÇuM½§0ÉuŽHHõwÿ¡Af´]¦Ul3À¸Rx_©È/IîÆPó4Xû€ê×åS%O…os\ýà\™â:L˜Tè ¡L€òk�lÖ×#3�ú“m]üä|-§ëò´¯_ÍȈr4C3ªÎ×¥Ù’Ù ʲ�z¡ëÕX}ªìÐÜÌoâÔ—$R±=Çâb¸I_—´Î ѵi9q¦ð¡bž'¹ 0óvìÝ™¹ÀÍ®³;0È=ír´ë aQ(WYâ/x˜)èÒ¾–*¢š.è­_�åxàñjByJ2g?½œˆsòq<îU»Kib@…oe ú×9ª±ê8Ù¾¯Ÿë�ƒ\g1[õÌä‰v(î?AvÞá:GDh]¬+Ã(Ô0 €´¯÷v�ÃŒ@ùx)Ç¢Õ³d¼ë(•š1_‚fæ@]ŸYn’c·@¹¹»]~µòDÙÅu˜jy/iå{kÖpH¦C3Sº ×ÍdiðcA»fËôRŽÛ~¢°�ë<Æ(\�Mó%×9ª±êdÙmp_ÁÃ�3ÒýÜÌÛu0ôp ýÌ—àæWòx.în—r®$î5yÕq²}±]¾æyܯp¤ë<Æ [áÁû»·CKiËÜìï:‹Ù†ÀfÇ…WÇKÏT›e"õ¶GÔHVœ&“šzyÌ6L„’WfVËý‡ë •*åå]Àu¶ûµ‰™…/f \÷MKy|@a°[EE„�d:µ6oÎD¤”ã"…UXa¹'|©ÅçÆ¸oVÏ’ñ½“ù¨_T˜ê:�1/Xã¥xóôEú°ë,•êÎÉL®vr�ÅlÓ2¾á:„�'Ê®©&£>7¹_‘ñu¿°Š%înC5Ú.Ó� —»ÎaF%¤¸«+/3\©TÚ×ßBEw,�‰R‹À•Å÷uçå}ÃÙ±²â4™TÌÉ™ )̧‹ίÙÅ?€ªnÚ™� ÜQa…åúbŽe¥œäâ8[ãþd§b»|¡2 \`ÿ&fúQNJòÅ)/sEø-vñŸ?s�Á I¥˜K}^ü#ê¦ 5 {Ž´H@Hìfs ¦W…Ïd;õ箃Tª˜—0Ûuc¶Dà±@ø%Âåaœ-[�Òl9�sC˜©µ¼wgš1_ÂÈ6Ý'Ë^™®¾†Šrñ`ÀÅmKôÑPÂU¨4[Âãý ï&»ÌbÌÖ(œ™õõ‡®sTbõ,ß7™ïÿí:‹µ'^›öµßużÜ„v—ç:ËX­Uv8ÚuŽˆü5»˜»¢(ܰ ø©ë ¦z ¯”ë‹y¹½+/‡¸Î³-g‰;ÍÀ˜$ð &§Œ–J¼òSG–gÒ\ì:ĈD¤;/íS§RDù1¶Ñ_=xa`�K]‡0CúûiSH¹Î 岨M ÝÈt)Pt�Äf¦*æåÚîÙÒæ:ÌÖ¤}}Báë®sS�TØà:Ãæžu�Á˜:¤ŸbžÆvI]O»Ì*æ¸oxmò¾®ó˜�( ö¿J×»Žaþm×"¢eaATź p¡ë &tLjÇòb^ôÌ‘Xn¸çÁ�¿ºÎaL½Q¥Éu†—ˆ[cê�Ò‘öõ®cü‡¡;þo/æå�r=õ{qÒ°áG®3˜ÿO…ý\gˆÈÒ6_#›AØð €M½\<ã:‡ �Ì ºŠy¹µ§]Ž/ä%6S„Ò¾ö«òY×9Œ©C¯pà%”]\G0¦Î¼Pø¼ë›+åerw^>VÌQ¸8Ìu&‰ÛZ}írÂlF‰íŒßª¿Ž²|Ã7f\«/ \ä:‡‰Ô[åª4<ÒÝ.ç¬;˜¦þ=¬X C»\OvÄÍŽ×A3¯ŒÃÑ`ÝyyûðtàZS`=CnxA‡ÜÛ3´[òTêðM“©§}ý¯Z�»]&¼°�ìÆþ–X`3«gÉø¾É< ¼Êu“\ÃS¦·65Z€�j™Ç˜<‡r±§ü¬e±þÕu€b»|eÕ-ØP†ý¢íë{]ç0/ÕÓ.GÊï\ç•ð•L§~­&CYà¥J9™§Â9®scL„žRá»}ÊE3|}Öu˜-Yq’¼&ÕÄY(&URCá¾¾^Žˆz7ÝÍuÏ‘½%à ÒãFÿ¥Â÷=åçÛšMäJÏIòº ‰3Q>ÊІ�ÆS—Þ‘õµ¾.4ë@±]¾†ò%×9B4ДbÏi‹ôñZ f €—Yž—©ãá Û¹ÎbŒ1!Û ÊùçÇõâòå†'Ÿ«ða*¸ë,pý¸ç9iŸ´/‚x/±êdÙm°ÌíT6Uþ9”oLšÌ…ÛÚ\1.ºO–=¼AÎAx¿M¡6ÆÔ¡™ûcK±SÌË€Ã\ç‹@gÚ×95ÏžÓÿ©»]~.Ê®scLXTX@г² õI×Y*Qš-õøðæ ~S/´G9Û¡g¶¼!ð¸ŽJ.þ…MqfR¿7]yiõàçÀ¡®³cLh”÷g z™ë楖+'L`Ñ�&TsÌlõõŽZ�WO'„&P~®scLV{ÂÛ³�zjR/0Ò‹µ(Ê >ü�àîÒl9 ÔPÊírRàqn’'ʯ“ü½iõµ+“á�3€õ®ócLµ¡ÃuóŸÆ�çpêèâèi-pg-´À´ùº ¸ÎucŒ©† —ÐÒ©·¸Î•ª^³¦«Ç=Åœœ·,/;†‘§k¶ìUle1°s¥u¤º¯+æi�öõ^™ý�?¸ŽcŒ1ÕPáGi_û]ç0[à1Óu„0 ü´ÖËL’ÿ¦#"žp¾ë ÆS¡ s²�úÁ¤¬õ ©~�y3Â&ÀC¥œ|£ûdÙ£’"=säÀîvù•çу’«2å ~^‹[–è?J0ø*6“ΓLú™ï:„Ù2QŽv�!Dë€Kk=¨í0‚b^þ ¼ÉucŒ-�¿‹Ç±-Úí:KØJy¹@áÓ!–Tà.�›Dø“çQzù¼K�’¦]váµM)ÚÊp¸§¼WaZˆ@99Sк›jÚÓ.ÇÊå ÅfŒ1‰ ðô¯gºÎaþÓò¼LOP'7±¾‘öµæ§Ø9¾#P8_°õ?Æ˜ÄøCS'ì»P׺…@˜"áö¬8TáPUÊPÊË&…� �-¾óÔ©Cçˆ:ôÉ‘´Ì½Š� Œµ–N½º8G'à7@E³-Œ1¦Æ½¸a¶lœònêaÙÜ�>)ó×Ë?`$z`1ð7×9Œ1f~û¼£^/þD™õÃGÀNöbh]sÔcJÀ”¨Çp%Ó¡üÕucŒÙ&añôEú°ëf+<Þí:BX®hY¢ÿr1¶5F�óµŒò#×9Œ1f$W wˆ¯›\g‰’À«]gˆ‚ »¹Î¥´¯�xeŽŠ®³c̈„ﻎ`¶¬�—ÊÛ]牂»çš5¶¡©Ÿ‹Ú ÁcâèÆM;Ó^÷»‹°�ëyƒëQkY¢ÿ8xÈucŒÙ�;2z¯ëfËÒÂÁPKænHûZr5¾5¶aÚ5ºAà§®scÌË)Ü]ž@nÆ|p�%jÝsxÍðôüzT÷ €´¯OïœLy4Ƙm8Ïu³u '¸Î–2|×åøÖ…>ø!ð‚ëÆ³™ÕÚ̬¶Ët£ë µ i×"´û²¼ìè:D-´.Ö¿yïÅ^S�1ñrºÀM®C˜­­›À_Z}½ÃekŒÂ¾®Qáb×9Œ1fØóžÇ ­ ´a–'‰r�ë ’‰Ò8GÎbå IDAT¶tè}§Ñ¡ Æ3V çag£ÇV÷ly#C›ó&žŠÛ»ÿ` €QK r>P÷Ól�1 | ¥C»]Ǩ±7×p¬AàžŽG¹¾ÿ!Ó©K€¸ÎaŒ1ÀCÃ'™˜�“\gÉÃkŸâJ×!¬0J-Kô( ]ç0Æ48å¢á‹§†QÈKJáà w›çq@Æ×ƒÞ-°ªƒ V‹qâDàl`¹ëƘÆ&Êws¾–]ç0['u²þ_”ïϼ]]ç°Àˆð p�ÃÓ°V‹ðY×!j-ëñ&¢ßù÷i„¹_ßöâ슴¯¿Úæý °#>]&Dï:„ ¥¼¤�ý#(ý”*oÏtê¨7¢ÛóíÍvêUøÐA¦üÒ£¤)‚º±6c¾ð ìTcL üdŸ+ô9×9ÌÖí:…·¯r�£jÂ÷÷¿J×»Žñ"kT@±YƘÚQá»Ù…ú¤ëN(§„]R`U*ÅAÙ‚.­äñÙNý¹*ïx6äh»N™Ê;C®™Ãg"ÿÆucLÃxap� ]‡0#Sêbú¬îþƒ5*’õõw w»ÎaŒiOyÚ˜oR–%M*œrÙ?75qøôEúp5E†›3�—Œ•À¬—(_Á6Ú5ÆÔ‚2¿íJ}Êu ³uËò²#Âq®sT-fwÿÁK _s�ÁÓ„óâ²iL­í:•ã�׆Xò�oÛw¡® £XÚ×ûÞ<F½aÇ—òæ×œ™}¡¡Ž¸4Æ8Ñë|×u3² C7&ºÎQ¥ØÝýkT¬¥Soîu�ÃS×Ö‹r‘ë®(|&Är˃fŽ »™’öuuÊã(à‰�J6ÿR­ÄÑ2ßq�ÁSßDùŶ6~51 ü—ëU‹áݰ@U¾î:ƒ1¦~©pq£Þý/¶ËaÀ¡a• šy[ë]R½—˜Þ¡jÀ;�P6“Røp×)²sµ’&»Xÿ"p—ëƘºÕ7hwÿc¯+/‡ÍÀµË»ÿ` €ª¤ ü¸ßucL] å'®C8£á,³XS†c¢ºøQv±®eŽ@9„r;¥úùŸê$’J<ß0c’OàWmKôQ×9ÌÈ<å תӻÿ` €ê¨*b³Œ1‘¸³Í׿»áB)/oŽ ¡TŸ 'Ôêß1]ÐÑp–-¨ð©'Ê®aÔJšç”« i6…1Æl¦;É+öJyy…y×9ª´®7Æ8[ JŸ+º\ç0ÆÔ…+\gp¡�—”Â÷¨¥Âç3�úÇ0j�Vº ?†Pjr*Õ˜ æC|ݤ¶ 1&|—¦}}Äu³ Ê Û¹ŽQá3| û¨àÐX ZªÀ7\Ç0ÆÔ•þ>Xì:„ -Â'€B(umÖw3•¼>=ýJ}:ŒX•jéÐ»ÃØÌNàÀ]§ðÅ02%IÚ×~àV×9Œ1uaá[®C˜mSáS®3Téã6òc×!¶Å!) @ÉucLHq“ëµVÊñ à�!”º.ëkguªVÏ—€‡«­£Â—q)€J6ÂŒ1¡øuÚ×Õ®s˜‘•rrðf×9ª¡ðå}nÐ>×9¶Å!ÉùZå×9Œ1‰·¡Ðí:D-•fËÀwB(Õ¯g†P'm—éF�Ï…PªI=t�";‡P+1D¸ËucLâõ{ º¡jÒ¨$~¶ÛÙ \‡ k„(½˜ÅÀý®scíÞœ¯aœ%Ÿ+O”]ðXÒŽ¿?Îvhõ›ï…(íëb Œ“ö–üB^R!ÔJ„áF˜í`Œ©œðËé‹ôa×1ÌÈzæÈ�À;\稆Â瘧�ë£a €0©ªÍ0ÆTE¹×u„Z)åe\ÐÄ…ׇPn½ÄôD�ÿ ©ÎÑmœ]¬‡aË]ç0Æ$Vï òM×!̶óq�£ 7g}ý�ë£e €�¥ z p�ëƘda¥ë 5q®xÀe G†QNà'i_Ÿ £VØÒ¾þXF-þ§”“³Â¨•Ú ?Ƙð ?ßÏ×Ç\Ç0#+Í– ð^×9ªxg»1Öˆ€`³Œ1kˆ�ŠŠ%~¤ÐF-�MASõ;îGIàÛaÕRá»Ýyy_XõâL…¿ºÎ`ŒI¤�šjœSI¦ç�àkRQ¶tè}®sŒEbÿ±ã,íëo gͧ1¦ñÔw@DºÛåB”�‡URáòìB}2¬zQH¸I +¤râÁ%�ÐHYÀS á'q]0Pœ#û'ºÎQ…þ²2Ïuˆ±²@DD“5Äãž@9�á)×9¢RÈKª”ã"Q>f]Ïc~˜õ"¡ª(…VR¿îÎ˧êK®#cçù~å{®C˜Qø6 ¾åÂÖÅú7×9Æ*±ÿàq—.èï�Û\ç0Æ$‡Âº¤ì ;V¥¼LNÃ……\zyb¦Þ €Þ0+ ü ˜“¯"’äÍ“¶n�§]G0Æ$ŒpÁ¾®qÃŒ¬”“#€wºÎQ…õ^9™ËL¬!U¾ì:ƒ1&QÖº…ž“äu:´,기k«piØ5£’öõU® ¹¬ |¹˜£°ìX™rmçÇ×çÏ„1&2ëú9ßu³m*ɼx~‘Àצ_©‰lR[ BÙ‚þ B³gŒ©_›\[O»Ì Rüh‹ ¼zÊÕÔ�ŽpeD•Oš0�»JyIGT߉íÖñ‚ë Æ˜QÎÛÿ*]ï:†YO»ê:GJ›vŽ÷æÃ#±@Ä‚€/ƒ®scâO n¦ÿ¯ž%ã‹99/P~ìÅ÷¥}}$ŠÚQñàzÂ]°¹6…eõ´/À³{ÔÏÏ„1&r�÷öñc×!ÌÈJy(ßq�£*ÂggÌ××1*e €ˆµ.Ö•À®scâOë¤PÊÉ}“¹á Dø:×EU;*i_Ÿîˆpˆ óòÛ®Ù²W„ãÔÄŒÝ(»Î`ŒIeÞŒkÕf Åœ*gop�£ ‹3�z“ëÕ°@ Ì#º;>Ƙú‘)åå>]&¸R‰çÊ”b»\¤Â@ôSÑ–F>FD#m¼è�)�îRNÎ^=KÆ×`¼Ð-ÏËÔRÑîæcFeåšµÉÙ¦Q­8Qváÿ\稔À¦TŠÏ¹ÎQ-kÔÀðÕŸºÎaŒ‰½‰ ßÚ¸‘žbNæp®$âwt)/“KyùÊÀ ¡üP‹éû6÷Ô`œÐ©Ç�5¶Sá›}“y°”—ò’ªÅ¸ÕZv¬L,æäóãᯠs�Ǫ|qæíjKnc.•âë ;ºÎQ)¾5}‘>ì:GµDU]gh+O”]‚&Jò“ÞSs+Îë݉…q\k¶òDÙe°™3Dù4­óÁŸ2¾Vã1C±z–Œï›Ì³@­ïÌ—DùÞ¸�,Üçí«ñØÛ´,/;އÿöàÓ S]ç1Æ$ƒÂÝÙ‡b5±Vœ#o’€»ьނ¿MšDfÏK4ñ³º­PCÝyù¢À×]ç0Æ$Σ¢ür0àâ¶%ú¨ë0¥ÙrVx?àäè9æg;õ£.ÆC1/ÍÉ£ñ„ÀÏ€Kã°‰âfϧS€\ç1Æ$K3[}­ÅÒ*S¡¥GIÓÔ©ü8Àu–J —öµ.Nw³@ ­8M&¥zù+ðj×YŒ…µÀ“ ÿòà_Àª<.ÂS¬ñ \†g·ô@OØA&“�]áº|]S«�»fË^âq’í 3j5n €Ç�‡Uø‡À x xx>Ö{JoYþóEÏÃó”5 yø÷ð«DØM…Wª²›¯Tؘ\Û/ɘŠÜ˜ñu–ëfd¥œœ¥Â÷\稔ÀïÒ¾¾ÃuްX Æºóò1±ýL¼<¬P¡K KʬÀ£8¼[ydVœ&“Rý샒Vh¥xo”cÖ“áfÀïEYZ–n?‰{œ–¶8W¦ ²«S‚€=Õcº(Óšš¾�ƒ¯aÔ¼€}[ë_]ç¨Tw^Þ'p™ë#º�J�À*õxÜ+ó”7À ›ò²3¤yÜóLn.3µ¬ìNÀ{ ´êÐói/j³9d=H§}]í:çŠ×ÓÅÞêñ&à­:ÔÌÙÓq*Ó .Oûzšëfdż\ë:GÎËøz¶ëa²€=ír| \å:‡i·ªpë€r{-§ùŽÖpc¬H²Ï…�=�M:túK"�…Û\y“üC]k¥œ¼M…[\çÁ @óð¡#Ó©'»Ž±%]³e//ÅÛDyCM[Þe"'°)H1-»Hÿé:‹Ùº4»·åŸÃ ØHgÅÖš5)åe©Â‘®s˜ºUDé¡#w�¶¡˜“�#üÄu“ Ϧ}ÝÉuŽjtÏ‘ (¹ÎaCxS«¯Ë\‘ˆ”r¼I…“QòÀn®#™ú$Ê7Óý¢ëfëV�,» –é^á:K¥D9>]Ðk\ç[“ë�ª gyðg†îƆ‡� X”]¬+\‡­ûO��š›™ç:‡I…ç\g¨V9à9{6c )8‘£b}Ô™ª¦‡ÞÛü™så¬b‰#�¹(';;NgêÇ“©~ÎsÂŒl ÌE’ä‹è¬Ç‹°‹OgZ}]&°Àu“l›P.Rå°L�½2¾ž�¤‹€qMœKíÏ�7É–ø3x›a“ë &YŽ,ΦÝuŽQ›§A¦SoÏtê‡^…p¬Àõ �``LÅD™÷ò}HL¼tçåCI>�á™ ‰O»[àÐyÙ½ ÄvÔ5c÷$Ê¥MM\8m‘>î:L¥J³%£˱õÃflVd|Mô.òwåe»øÏ#ÚŒ‰ÀcÀô$¯Gíž#{{e>¥Â‡€I®ó˜ÄéY³†¶™·ë ë f˺çÈÞp°ƒë,•åƒé‚^â:GTl€Cûùú˜À\ç0‰²åý¯Íô“|ñϹâ?Å.þMzõ$¬ûnÆLaw4ÙK¦²úPº ŸšÙá�G]g2É!ÊYvñ_ËÎ�f X@‚/þ�¥éÅ\ê:D”¬àXª�oO¸Îabï�oÍøz`¦ —E}þs-t9Cà-®s˜Dšà:@µ6ô³�ë &™T8³{¶¼ÑuŽjµ.Ðu™NývïÎì%Ê© �XcÌHnNôF×!ÌÖm·Žo¹ÎQ…Ôã¿b½×J¬àØ´ktƒ�ìn¾‰T�(ùL�#2�z»ë0ay /»{ð-×9Lb%¾0.°€©X“çñ«R^ƹ†óu ]н;Ó"pð/×™Lü”ø×9ÌÖuçd¦ÂY®sTCáœl‡Ö}3Ò1P„‹º]ç0±òˆÀé%hM´PW�Hi‚_*ìè:ŠI¬$O-  ù_ƒqG¡ål×9Â4c¾¤}ý…À¾Ã7Fl“7óo*\Òêk—ëfËV�,»‰ÐA‚¯-î[»¦1–fÛ&€1Ñ�“wˆp“ëƹõ¢|}âd~²ç%šø�礔“Oªp¡ë&Ùz{™4ãZMì&z¥¼¼UáV×9L¢ zG´tèÝ®ƒDay^¦6 _åcرÕ�î9�ii_mÉl -;Cš'¬ãVà×Yª0ÀÁ­¾.s¤Û¥©7Ù‚Þ ÔåY“fÔ®+—iMôüº½øÏKáÛ®s˜äÛn»¹ÎP�vw�Á$^Sü?öî<Ìîº¾Ûøý93ÙHX¢€‚" 93 K@E± ÒVS…ÌI\p£Uëö¸¶¶HkkÝÚjõ©»AÈ™q«((b¬6¢ÉÌ$‚K!`ÙfÎçùc£ K–™ùžs~÷ëºr�27—æb¾ïó[8gí©Ñ•W“ÞÌuýËòuÔ8øŸÒ=*'ƒ¿÷ðß¾fþ†¡³ÿ�|°*‡ph+YãÿÐï·ÖûuÀ@_3Ÿ»àüìÚ§!¯hĬ„sï}Ö®ËàQ¥vE-ydéu…·lá#¥#&Sßyùãuë8:àø=Rå\SK¯lWCKâT‚×”îØE×ÞœY:b*9´‘þóò§‘üséM¡`°g”þz3——N™l»”îP—h1¯tÂ.ª—PwHxÑÈ@œ^ºc2=ã²­7óŸ²F?ðÍÒ=šBÉ»áÍGÝhu#FòñÒ»bÛÃ%_rt37–n™Jí&xOÀ¯JghÒý¢üqß²lrAÞZ:f² /‰WFrZéu�úK7ìŠìð~µ— >Ô ¯|0ýçåOû9>ƒ¿î,Ý£Iw‰¯ýkOkNŠýjðŸÀn¥[vE&ÿ8¿™+JwL5€6Soæ’·•îФúJÏ(GÌ[–—–™ #‹ãIxùž&XvðÕ$Û^ßvHéu•QcpÕ‰±oé�I—™ýËòcµO®.�£I³¹ÖâM¥#ô‡V>/v˾�}+[ÀÊMáïKw”àІêËùB·KwhbŒepf_ϩ§þ0þZjœO¼·]mçÈŸ�ùÿ«1Xˆ¿'4ñèé嵋bFé�©0ï¼ 8ŠäÜÒ-šÿ2oy^[:B÷3gñéÿ÷X'Û5^ºðã¹µtH í(3k-Þ0V:E#`]+YÔ¿,ßÅÙ*Ý3V>/vã¢ôiçš3îÚÀQ¥#vF-ø£Ò êZOÙ2‡ÿ "J‡L…z37ô æ N6—îÑ„ùõŒé¼§t„þÐÈbÞG²´tÇ®Jxû¼ór¨tG)mª¾<¯Êä3¥;´ë¾ÝÓÃaÛ^õX #�˜>s&ç]OªÊÉÏ(ݰ324y–Œ Të²Öz3?A�§?+Ý¢]—ðÖƒÎÎ;JwèžFñÚ Þ\ºc|£°Ú·¦:´±-Á_·•îÐ.Hþcó\Ž?øÜ¼¡tÊTlDOÂ9À³J·¨Ë%Ï)�°£F1§Ç–îPwKøëá�xk鎩Ôw^þ` <ø~éí’ïörvéÝÓÈ@œ’ð¡Òà¶€—‘™¥CJrhc‡7s]Àß”îÐΉäÃ}ý¼¬R÷ED=ø°¸tŠ*á¨U'E§=„èY ³JG¨‚÷/‰7–ΘJ‡7sÝØLŽ øRéí¸€±hñÚªÎÚÍš%±(ƒÏÒçÆ€×Ô›ù‹Ò¥uüÿ�Ýnþ=`eéí�V¯¯æë«r¿ÿ݆ø0É+Jw¨2¢§—JG숄”nP…$ˆ—ΘJ ÎÊ;7Îå$ÿQºE;(ùh}y^U:C¿3¼$ŽÍd90­tË® XVoæJw´€67Ð̱V‹?÷�€c É)ý˲r÷ -‰^[ºC“¼¤tÂöZÙˆ=�ç—îP¥Ô"øÌÐ’h”™J ?ž[û–sZg–nÑvûõ–QÎ(¡ß^O%¹¸K®Z»xuéˆváÐú—çÿŸ(Ý¡uÁ³úó¼Ò!SmhI¼+’w”îP%5´8”ŽØ3à…Àn¥;T- =‘|~d :êj™]–™ýËò] Têj¼Ž¼é° Óç^µ‰¡�x ÉW€9¥[&@+á¥õfþ¦tH»pècÓøkà¦Òº_w´àY}Ëò²Ò!Si°=#ñï‘®ö*'‚W•nد,Ý ÊšNpþH#:â÷ÊDª7ó#$YºCè}ËòÜÒ·fi<9‚¯»—n™ïéoæ×Kw´€1ÿœ\OR©'úv�;[ð¼ùÍ\Q:d*­]3êÁ¹üyéU\pÚU�اtÆY³$Ž/Ý¡êJèIøøð@üSé–©Ö7˜ÿ—¤RDì [Z-olÃKâØV‹¯{”n™ ß¾yï*ÝÑn:Hßr>ð­Òú�€�‘<{~3+õ¿ËH#²y—’ ”n‘€Ý¦¯)ñ@ÒWí"xÛp#>>؈žÒ)S©o0ÿ5àJwèžÞ?y^]ºC0Ôˆ?‹äKtÇeÿ¬ƒ>ã²-ÝÒn:ÉøkQ^ l)�"F3XRÌ+J‡L¥¡“ãQ WÇ”n‘îÉk·=d¯íŒ4≠\ºCú=¯ªÃù+Ñ ÷Únõf¾3’Ê=¤·]\»£L[jÄ’€ »ä�0þF®ÚÌ_•iG¦ÞÌàŸKwˆŒäU}Ëò‹¥C¦ÒÐ@<¥6Æ  ^ºEº—‡Î„·—ޏï+ ݇ö€Ë†NŽG•™Jõå¼!’ϔ×ÝÌ�¥;ªnd þ²çЯú»[ïí[–_+ÝÑ®:ÐØLÞ ü¼tG¥%ï®ægKgL™ˆ^oŒàò„G”ΑîKÀëGñèÒ¿oh ž“ðôÒÒýxRŒñÃá%ñ§¥C¦Lf�?8ÔÃAAöæ%¥;*-"†–Ä»2øpB×Ü”ð½Í{ùpêãW•«ÓŒ4âY _)ÝQQ_ìëãùœ‘•x­ÐÊFì9>œXºEÚËûšÙϦXшY{À��Ç—n‘D x÷üÝ@3ÇJÇL…Õ§ÄÜÚV¾Tº¥jnß }^ž]ÎÚE1cól>Kpré– ö›ÚGÌ;?ý ôx@‡ª7ó«œSº£j®Ù/ªÊᤇ̈́ÿÁÿ:Çâ5Kâù¥#ö=¦‡u‚ð·u¸t¤/3染ë[-žp{é–ªio÷ð_ΪcßÍs¸´ ÿY ^äáÿÁ9t°­ã¯´¹¥tGUÜ> ',lf÷³#q:ð]ütD&“�”~ àš¥qÁÿ)Ù í„gÿ3¼$Ž-2æ/Ï«[pZ鎊ùN�O”ލª‘FÖÓËÓ�rNÞ7oY~¹tF'pè`‡7sé7˜S¤ÕJN]ÐÌkJ‡L¶U�xìÐÿ•ÁǺèi°ª�„GÌ„O•úú«^³[-ÎzK5H;+á$ßiÄY#�xHéžÉÖßÌ V–ͧWå*Êv32§0þÁÎ…S&Õëná�¥#:…@‡ë̳€ÿ*ÝÑõ’3ºýa5—½CKâÍ=0p|éi-iÄ«J|áž�|˜WâkK$^”°º]n©™LYóÕ€S"ø‡mo³ÒZyzLnÄ38»K?ع¡·‡Æ3.ËÑÒ!�  ŒÁŸw–îèbßèëçKGL¦á¥qè>û°"’÷»•î‘&È¿-Ž#§ò Ä+^2•_SšDû·’ ‡—D³›Ÿ Ð\Zº¡Û% EòÞÒU3tri¤�nõð-à1ùëJà(’oŽ4⒡ű t̮ښ\x_ì‹äϾ([º£Ûm{�ó_µZ¬/Ý3É~¾N¬7sKé�Nå3ºÌ4Y IDATÚE1cË~�0¿tK'‹äÔú`žSºcW­]36ïÎR’7‡•î‘ÚÀ­iœ0ÿœ\¿«¿ÐÐÒ˜-¾ ¹ð⼫tÌŽiÄ¿&¼¾tG—¸¡5�þ‰[ußV4bÖžÉ;3x ùž?à”z3¿Pº£Óy @ª7óG„¯ZÙI[£ÅëJGì¬5K㈑�øôtøÉ?áá_º/õÚ+Ö,��ú´dx ^ \އé¾<>à_gÎäç#�x÷ÐÉñ¨ÒAÛ+‚KJ7t‹H^ááò¬Y´ü0ƒ¿¢"‡‚÷yøŸ^Ð¥VžÓf¬ç{G”né0ÿÜ×ÌŽz¨Èš“â1c=Ü<¤tK' øt½™¯(ÝÑ�®>9å½ ÐÝù»·¯�ÀŸ 4s¬tH7pèbk–Æ­ߣ*Ëà®»u.΀Eõf~uò¿T5¬<=¦Í¼�—’œ ìWº§€ž\oæ/J‡t€.7ÒˆéÛxhé–6÷‹Ù³9ø€Ïæ¦Ò!0~è˜×âðèá™$ÇÇ»•î’*à‹­o˜¿<¯iÄ1 ÿ†oÐ�¦Â-—E‹oDòÍyËóÚkÅŒÍs¸Ø£Ä×ïd^ú?�ÎŒÚÈ'eðÀãKçrWÀ±õf~¿tH·q¨ß ðà¾Õ >Ucx·ÝY3•CÀÕ'ÆC[½Ú‚ù5˜ŸãcMüR)›®H8žjÝc)µ“ß«2X°:ÆXE�áz37Löˆe4&ûët™_n‚ù^ú¿‹ÎŒÚð/Øö‰_éœRÆZpB3¿Tº¥9TÄÈ@œ‘Á»Jwt‚€±„Ÿ? ¸>“Ÿü*kÜR Ö�ÁºÞ-ܶ¾—»ŽnæÆûûuV4bÖC{™=:ʾÀÃ[Áþµdß„Gdð°HööŸª6I’:X ¸¸–䦬qðkà×µ7Öz¸ikë¶ÌaÃÂ�çÖûûE®9!vß:›ÝZ£ìÕ ûD°÷</v›¹}ÙbA æ' ‰¯ë›(£ �þf^X:¤ªÄð’ø’¿+Ý!I’¤JYŸpMÀÕ‘ü¤Uã—µ?K~5ë.~uЗsóDÁÁFôô�±o�“-Gð¸„Ç1þã±@m¢¿®H’—ö æY¥CªÌ@pfÔ††ùZÀñ¥S$I’¤mn~“ðà7µä7ÜEp-6Sc+°áî¿8Zì‘а'0'ƒÝ�ÝöIØØøEDòºú`þ[鎪sC/Œ‡Å(?^ºE’$IR÷Hxg3ÿ¡t‡\¿´Mÿò¦€Ó!I’$I"àCþÛ‡€þ¿z3¿šÁ?—î�$I’Ô>Qä�¥#ô;º‡Í{ñŽ„ï•î�$I’Ô¹>Ý×Ç_à=çmÅgè¬^öÔøaŽ?DéI’$©Íl&øüXò�ͼ¦tŒ:›€ÚÂP#þ:àÝ¥;$I’ÚJ2Áª„#J§hÊmˆä3£-Þ¿àüüßÒ1ê¾@m¡¿™ÿɇKwH’$µ‘¤Æ+êƒIð*`}é M‰_¼c<²>˜¯÷ð¯‰äjgFmx˜&pRéI’¤ÒÞÚßÌ÷ßýŸ¯jÄ>3à= §áyÝèÚH>¸Ûþã€Ïæ¦Ò1êNj++1kwøjÀ•n‘$I*&ø×¾eùÆûú¯FñÄ„÷ϘÚ(M‚M$Fð©ú —ááL“Ì@mgí©±Çæ-|8²t‹$IÒ” Îê«sgdë�þ²‘F< xwÂÂ)*ÓI>UƒÏ×›ù›Ò=ªµ¥Ÿ¼0öÞ:Êå@_éI’¤©páÍëh<ã²ÝÞ¿gu#ÖàU/J˜5™}Úy3¸¤Ÿ˜·,/-Ý£jrPÛºæäØtŒ+€K·H’$M¶€¯OßÀsúrnÞ™¿è…ñ°Ú(§/M8x‚ó´s6ÿEpAï&.8ø¢ümé U›€ÚÚH#�pðèÒ-’$I“è»c3ù“gå�ñ‹­YOÎ1^’Á`îDüšÚn¿ ør+¸ –|¹ÞÌ ¥ƒ¤»9¨í]½4ž0ÖâÛÀÃJ·H’$M‚mÝʱ‡]˜·Mô/<؈ž>8šd ƒ¥À¾ý5Àú€KH¾8:‹/OÔ�#M4u„á¥q(-.Ã[’$u‘€kZ½<½ÿ yÓd­‘FLŽËà¹$‹€&ûkv±-ÀgðÍL.»uWîÈs¤RÔ1V7âè|˜]ºE’$iü´·‡?:øÜ¼¡ÄY}üYO8Ø£DG'Kø!É7©qÙØ ¾ã§üêDê(ÃKâOI.¦—n‘$IÚY¿…§-hæõ¥[àÿß*0ŸäiYãi$Çû•î*è6à‡‘ü�àŠ�ð­…ͼ½t”´«ÔqFâÙ\Ì(Ý"I’´n 8®ÞÌ‘Ò!dÍâx|Çdðd ? /aÏÒ]“à&àªH~˜5~ØãªùËóºÒQÒdpPGr�$Iª#ÿ÷gèäxT´¨'Ìê‘ôuÚÿÍMÀõÀO~JòS`íÖ`Õ¡ÍüUá6iÊ8¨c­Y‹ZÉ8H’¤ÎpsÀ±�zø¿_±æD><¢VcÿLI�ýhñ(‚ý€Gû39sÞ Üpk­À­Ü-n¸~,¸.Çøé‚ ø|$u¶¡FüYÀù8H’¤övs´8®¾<‡K‡”´öÔØã®»˜5æÔzÙ=F™=ìÌiµ˜ LØx÷_Ÿ56Õ~ÿ?'›¢Æ]låÖìáÖz37”øç�:•€:ÞÐ@œÁyÀ´Ò-’$I÷áæZ�gÎ;/‡J‡Hª¶ZéiWõæ™,¶–n‘$Iú}ë<üKjê ýƒyÁÉ8H’¤6°n ÿ’Ú‡€ºFß²<ß@’$µƒ»ÿ󛹺t‹$ÝÍ@]¥oYž¿ív€-¥[$IReý:jçá_R»ñ!€êJ#�xpA¬Ò-’$©R~Qkqü¼åyméIº7¯PWª7ó«$ ÜQºE’$UCÀõcð ÿ’Ú•W¨«­nÄÂ| xhéI’ÔÕÖôöpüÁçæ ¥C$éþx€ºÚüf® ø#ÀK’¤I°rZ/äá_R»sP׫7sd Ž~YºE’$u�+¦Oç¸'|!o)"IÆ[TkNŠÇ´z¸8¨t‹$Iê —<¯ÞÌ ¥C$i{x€*cÞùùó€§øJI’´«.™=›Eþ%uUJ½™¿îíå8à¿K·H’¤ÎÉgÖ­ã|67•n‘¤á-ª¤•Ï‹Ýfͤ™ðg¥[$IRçˆäÃõ弿‰–Ô�¼@•´ðâ¼kN ùdéI’Ô2’7×óõþ%u*¯PµEÄPƒ3"9£tŠ$Ij[›^ÒßÌe¥C$iW8HÀð’x ɇñªI’tO·µàùó›ù­Ò!’´«¤mÖ,‰çgò…„Y¥[$IR[¸1`Q½™?*"IÁ@ú=«ñô¸(aÏÒ-’$©¨5Ϫ7ó¥C$i¢8H÷2´8D�¯û—n‘$IE|·g”çrAÞZ:D’&’÷;K÷Ò¿–ÝÌ�¥c$i2x €ô@|M $IU°™äU}ƒyVéIšLÒvjÄËþ˜VºE’$M¨[[p’¯ù“TÒvZ³$Žo%ƒÀ^¥[$IÒ„¸¶§Æs9/R:D’¦‚€´Ö,ŽÇ·j\<¡t‹$IÚy —Žneà° ó¶Ò-’4U| ´æ-Ïk{FyJ€— J’Ô©‚OmžË"ÿ’ªÆ+¤�°vQÌØ<‡�/-Ý"I’¶Ûh›û›ù¡Ò!’T‚€´ Fñª„¦—n‘$IèÖZ°tÞ²¼´tˆ$•â í¢á%ñT’åÀÃK·H’¤ûô£18qA3¯/"I%ù iõ-Ë+GáÈ„ï•n‘$Ià ›6ñTÿ’äÒ„Y»(flÞ���¼¢t‹$Ib”à�}Ëò½¥C$©]8HÌçH’TÜ-‘,­æ7J‡HR;q�&Á¶ç û•n‘$©b®êéáÄCÎÍŸ•‘¤vã3¤I°í¹G¬(Ý"IR…|nölžâá_’î›WH“èòc£wï}yg$ƒƒ›$I“eSÂÛû›ù¡Ò!’ÔΤ)04ωàsÀCK·H’Ôe®ÎKú—çªÒ!’ÔîüDRšýƒyIöp8peéI’ºEÀçÇfr¤‡IÚ>^ M!o �$i×llÁ;¼ä_’vŒ€T€·H’´Ó®nAc~3W—‘¤Nã'�RýƒyÉØ‡á-’$m·»/ù÷ð/I;Ç+¤‚.?6z÷Ù— y3r’$ÝŸ $¯é̳J‡HR's�ÚÀH#ŽKøð¨Ò-’$µ™ï÷ÔxÑ!çåOJ‡HR§óG© Ô›ùÍM0?’³K·H’Ô&FIÞ»i.Çxø—¤‰áR›ˆ� >Ì-Ý"IR!? xQ½™ß)"IÝÄ+¤6SÌÁ€Ã€ËK·H’4Õ>0ßÿ$M<¯�ÚUD ðº€÷3JçH’4™ÖEðªyËò?K·HR·r�ÚÜš¥Ñßjq° t‹$I“ä¿z{8íàsó†Ò!’Ôͤ°¢³ö„÷$ü%Þº#IêÞÚ?ÈÇð›RIštRY݈£kðà�Ò-’$튄o÷´xżåyméIª ©Ãüì´˜¹á.ÞÉ_ÓJ÷H’´#nÞZä“~ê/ISË@êPÃKãÐlñ™€#J·H’´�¾’=œÞnþ²tˆ$U‘€ÔÁVžÓfÞÆ›Hþ˜^ºG’¤ûq[ÀÛêÍüDéIª2© l{SÀg€£J·H’t/—ôöpºOø—¤ò¤.qù±Ñ»÷>¼&à�ÝJ÷H’*呂×Ö›¹¼tˆ$iœ€Ôe®^OhµøH—n‘$UR+ƒOf/ï˜N®/#Iú©K /‰ç’|xTéIReü¨¯žßÌ¥C$I¨V:@Òäè[–_›É¼ ζ”î‘$u¯€ÛÞ0Gzø—¤öåR -ŽQãß�§”n‘$u�K²‡Wûj?IjRUDÄðb^Áö)�#Iêxk ^Û·,¿V:D’´}¼@ªŠÌì̳Ʀqp$Z¥“$I�'`cgÎØ@¿‡Iê,^ UÔH#ŽIø4ð„Ò-’¤Žñ�V‹WÍ_ž×•‘$í8©ÂV4bÖðnà�@”î‘$µ­ ¼¥¿ÉÇñ›GIêX’^'‘œÌ(Ý"Ij;·¶à¹>Ý_’:Ÿ€$FâÙ\ ô–n‘$µ�›žZoæÚÒ!’¤]çC%P̯¼³t‡$©m´Nõð/IÝÃ+$ýND pphéIRqŸèkæé¥#$IÇ+$ýNf&|°t†$©¸ì©ùïIê6’î¡gŒKK7H’Šûù!çåOJGH’&–€¤{˜w~ÞÜQºC’TÔ5¥$IÏ@Ò}™Y:@’T”¯…•¤.ä éFñp`zéIRQ�. Išx’î!“?)Ý I*îÀ¡¥ñ¸Ò’¤‰å éž‚–N�$•WkqJéIÒÄŠÌ,Ý ©M /�Ciq¥[$IÅÝp@½™J‡H’&†WHÙâxø—$�{(É;JGH’&ŽWH`¨/øTéIR[Ùš-Žì_ž«J‡H’v�€$V5âàø>°GéIR{ ¸fútžxÐÙyGéIÒ®ñ©â®9!vï� ñð/Iº oÚÌ'‰ð1IêpR…­hĬÑ\Ì+Ý"Ij_4FóîÒ’¤]ã UÔÊÓcÚž0[ºE’Ôþ2ø«á%ñšÒ’¤�ç UÐ`#zfÞÆY VºE’ÔA’jÄ_”Î�$í©j"¢/ùÉÒÒ)’¤ŽjÄËK‡H’vœo�*äòc£wß½ùx/+Ý"IêhIð޾eùÞÒ!’¤íç UĪÇìžM Ï.Ý"Iê‘|¸ÞÏ9#[¥[$IÎ@ª€‘F<¸$áèÒ-’¤îÉÙÂË~<·–n‘$=0©Ë]}rÐã« —n‘$u­oônæ_”¿-"Iº>Pêb#‹ãIcc¬ðð/IšdÏ�Á7¯99ö/"IºR—ˆ�¬ñMàá¥[$I•päè?^G•‘$Ý7©ÛDÄð’x[绕Α$UÊþ´øöH#^X:D’ô‡|€ÔEÖ.Š[fó© N-Ý"Iª´Ìàïú›œ‰ßlJRÛp�ºÄš“b¿VO*Ý"IŒ¿!`·9¼ò€Ïæ¦Ò-’$©+Œ4â°„‹€G—n‘$é^®ÊNè?7Y:D’ªÎgHnhI4®Äÿ$©=c|χJRyR§Šˆ¡%ñ®Hö'Ij{ûÓâÛC�xQéIª2o�:ÐH#æg%¼ t‹$I; IÞ××Ï_qF¶JÇHRÕ8HfÍIñ˜ìá‹ óK·H’´“.›É‹œ•w–‘¤*q�:ÈÈâxRÖøOàá¥[$IÚE?ΞëÃ%iêø ©CŒ4bqÖø&þ%IÝáÐã{C‹ãÈÒ!’TR»‹ˆá%ñ¶„eø°?IRwÙ?j\¾fI<¿tˆ$U�·Hmlí¢˜±iw>É)¥[$IšD­„·÷7óý¥C$©›9Hmj¤sÎþ¤t‹$IS"ùh_?¯ó ’49¤64ôÂx£|9àˆÒ-’$M± fÏæ”>››J‡HR·q�Ú̪F<¶¾<¾t‹$I…|sÆt^pÐÙyGéIê&RY݈ù5ø*°éI’J X9:Ê¢äÍ¥[$©[ø©M /‰ckð<üK’Dž^®¸úä8 t‹$u ¯�ÚÀH#ŽÉñOþg—n‘$©Íü¢§‡§rnþ¬tˆ$u:¯� [݈£¾Œ‡I’îË£ÇÆøú�ñˆÒ!’Ô餂Ö,�#jð%`÷Ò-’$µ±ƒzá²5'Å~¥C$©“y €TÈH#Køð�Ò-’$u‚€k€gÔ›ùëÒ-’Ô‰¼@*`u#æ'\ЇI’¶[ÂÁ _»úÄxhéIêDÒûq#Q¿çßo^$IÚq Æz¹èg§ÅÌÒ!’Ôi¤)tÍ ±{ïø=ÿ�,Ý"IR{ê† üQ:D’:‰€4EÑ3:ƒ&phéI’:]�¡g”î�¤Nâ M‘>8xVéI’ºE$»fI<¿t‡$u ß M�5KbQ+ù"Žn’$M´õc°pA3¯/"IíÎÈ4É®99öo%gáï7I’&ÃÜ8÷òc£·tˆ$µ;$Ò$Û:ÆGñ‰ÿ’$M¦'í»7o)!IíÎ[¤I4¼$^Bò¹Ò’$UÀæZ�#ç�—C¥C$©]y€4IVŸsI>XºC’¤Š˜Ñjñï¾P’4Ij[ø¼ô_’¤©tÌÈ'•Ž�¤vå-Ò$Z�‹#ÀôÒ-’$UÌu36P?è˹¹tˆ$µ¯�&A­Å;ðð/IR nšÃ©¥#$©9HlÕ‰±oÂ)¥;$Iªª¼ÅgHÒr�&Xm¯f–î�$©ªàOKwHR»q�&X¤—J’TZ+ü÷±$Ý›”&К¥qD«ÅÊÒ’$‰ßΞ;|67•‘¤váÒj%/(Ý I’Ø}Ã�<³t„$µiEò´Ò ’$i\À1¥$©�8HeüiÇ•Î�$Iã–n�¤vâ M�‘—°géI’4.áˆÒ ’ÔN¤ Áþ¥$IÒ=’:ÎÝW ô$f�IL80à@¼r@R{Yp]×Ñ⺈ñ£c\7ÿ|®ÇoÄ$ISÈ@RWiÄô±�ìíáÀÌñÔ80’�ƒö,Ý(©«ÜïÿÖ[ùÅ3.ËÑÒ�’$ÝÍ@R¥¬:1öí­ñØV�‰û�¦Æ~$� 쇷Hwð à†€_µ‚ÿ­%7�ü2{øÙŒ^®?èì¼£t¤$IÛË@’îeõ)1·g3ûGûµZì¿m 8Ø?`¿„ý $u®õŒ?hï†Ü˜É \—Á�­ä†é=ÜxðyÜè%ú’¤nâ I;aÕ‹cvm �®µØ/“GRc?Z<,‚½ö°Ï¶?Ÿ^ºWªˆ»€uÀ¯·ýñ’›¨q-nŒàGáW»mà²'Iª"Išd+1ë!=ÌÝ2Æ~µ`ZÌÍ`n$ûE°ÂÜß»²`o`Zéf©�¬nÖÜ-nlÕXO²¾–Ü@p#-Ö÷LcýÁçæ ¥c%Ijg’ÔN"bÕ Ø§·—½Ç`ŸÞ`n¶˜›5öbÛkÉ^ s�½öÊñ?Ÿ]¸^ºO·'ÜÆø�õ ·ÜF²>bü�­à¶n~Ó¬»³ÅM ›y{átI’ºŠ€$u‰‘FLe¯éÓÙ«5ÊÜì¹×hÌ%Ù‹ñ«öJ˜0kÛ˜0kÛ�½ ÿc¨�Œåø»ê7~›ð[`#9~`oÅïò±í�£Éú¨q[­Åúz·qF¶ ÿ£H’$$I÷²òy±Ûì^fm­±go/»e‹Ý"Ø#[ÌN˜ÁÀœÌŠdwjì¾mL˜C²0-¶½n1ǯJ˜ÔøÝ+ïþ9íš»€Í@2þÉ: wÕ`sB+áv`Kw2þ üÆhqW·µ`cmü¿þî? n‹wõ·Ö¸½g+wÖ›¹¥à?Ÿ$Iš`’¤"ÑsÈ4öˆsr+Óz¡g´6þsÀœÞ`Z&½$»ßýsÄ<#aNþáÏÝm:­¸5"˜»#Íc™ÜïkßnÏ÷ùiwÂÆZ²é?—l Ø5Ö´`c+ÙÔ[#GGÇö½ÉÆÑ™l»‹<ì¼mGš%I’îæ I’$IRÔJH’$I’¤Éç I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià I’$IR8H’$I’T’$I’$U€€$I’$Ià ý¿vì@@�¿õ F 0 `@À€€ 0 `@À€€ 0 `@À€€ 0 `@À€€ 0 `@À€€ 0 `@À€€ 0 `@À€€ 0 `@À€€ 0 `@À€€ 0 `@À€€ 0 `@À€€ 0iX�>J ë¬IEND®B`‚qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/icons/qtea128.png000066400000000000000000000106261525155022500231700ustar00rootroot00000000000000‰PNG  IHDR€€Ã>aË pHYs°°'Ä­tEXtSoftwarewww.inkscape.org›î<#IDATxœí�y˜TÕ™‡ßïVÑ ‚D! ÈDG±« Dq n êh"cT »Q&n1Ñqâ̇Qˆúà<ŸÄW2®ˆBU7—AG�{$.=l]Õ à`paS‘E »ê~óGUi/·ºëVÝZºë¾ÿðô=ç|÷£Ï¯Ï=ëwDUq)_Œb;àR\\”9®ÊWeŽ+€2Ç@™ã  ÌqPæ¸(s\”9®ÊWeŽ+€2Ç@™ã  ÌqPæ¸(s\”9=^ ÈA&Je±ý(U¤§ì Œe˜ §§£œ|8(™e7°Ø¢BðV/ƒ·F,ÒÏŠãqiP4M‘£â^Æ ŒA©Ðë[„b²ÎÖÐà ë†LíFƒ2 e¦ —?ÈÖ=”ÇDXà ë–L 5VË(F ŒPa„Â÷Riß«L/ïžÒ­Yú–wò&€53¤¯w?5 W§Ù(å鸰tdX¬24epƒÀ€8á/–#Ìó‡ôORo#aÊ…*\•‰Q�8ð‚ 8”çÆÌׇüuÇP�O¸å6`@ŽæÞež/À³ÌQ3”Ó�y §8àjg<-0ËÖh4(¦0]”ªr´û1Â�þ�.qÂI'èT ÈA½b¸Äùk¾ÆÃæ@ˆ�HShmPN1à~`´Ã~6)üŸÀD‡í¦E ®°Là…¡Û~IL~^U¯Z¥¿v¦xd˜ü¥Ò>Úw(æ£õ°À¦™Ò{ï7ü Ê/�CÚ'£„ åáÖÿ�H­üånÀë´“=”]Óý!}6õ ±ZN6 þ¨VÔ.ÿ'*Ì „™Ÿî0: ùí^¦pNecÀ#ñ8·{<ü ø…SN•Š2ÏãåA3Îm Óé¢O#ÊÂm;˜9áU�9á@[Ü*F$‹ÀÙ6l˜”Á|Bž±õ;xÀÖk�xq›—6Fù%ö*¿ƒ —¬°õ;TøYc�œïÈ‹#µr&@Ó"ÊíNuÉ?"Ü J"’ªÃlð¢<­‘jÓËÙ¢ôvÒI—¼r¤*3"AF™œ˜�/ðµ ˆ2ÐYÿ\òŽp Êà½lMx��ä>ÁáRŽLþûU¶Œ\ »”¢ì̶¬!°ÙIg\Š€ðq¶E ”�NúâRr¨CÃ>rÒ—Âϡݠ ±Z¼®º9{F-ÕmÙ6Çó)°ßA‡\ KNÀsÔ>pÈ—#°.—òFÒÈjgÜq)«r)œX…RWݘœ�Ú½““—¢òmÝm˜.ý÷53\„c�à e¿ » a}U«’Ÿû6ˆª²ö9ÔhaîÚ~·BàS1ø±ç"„óÆ)xÒdÿR”åâáΪÅÚø­�ÔŽ HP"€¯~»8…² a°ÍR1æBz´þ‹ÞvÒ7—`¿ò¼¢Ìm¬•YÐJ +sÌ¥äå×k‚rô·0•ާa\J4„sÔ`˜À„ÓE¹‹ÄÑ´®èå…ŸµÙ Ê_ÈþŒ�KQåµ@�Zî\7UŽ‹›¼HÇ×V´éõ«ð²ƒ>–ɳy=žK—vübý@L&�ž$RÞF/9ä_©°ÙTÆ#T»ŠíŒ“¨§ó?V_½®DXÔ…™~moá�@Ï{Ää¼@�¾íé…êÔlõ‡XÓU&5y²‹,±6H.+¾Ÿ‹g%ƒ0ÏW¯‘Ô��°¾d ‹‹é’ƒ<ŸÉùÀ^ͬ ó?è­fþDY–‹g¥‚ã¡M‹gÝQþ�I¾Oën:ßô»ÙJõÙ:VB|QµD?oÿ°¢�V™»ßì;�y_­³Ïž k; yä;š¥s…B� À+ÀJ�}íÒ-OÎîŽuì | ¼#ð:ð‰ÓŽæ�çÇ<£™ŒóÐÎ>ÊjËÅ¡t? †Á(X‡ûÃz¶?¬'Å{1á&¾ÛÙ4xÕ$i×€>0¢Õ�_(\ñ5 ñ‡õ‡¾°Nð‡õ¢Œ§„·Ê«dÖüC"Z‹ÀÁi3¼f½úgv9|( Ÿµ^Íù¤~åé�jr‰h`RáåR‹²©g›Œ8ca}ø”°¶i=|uú&¥»Eno¯ý<�iæ0L¡Ošä�‹u£¥’½g[çÍDyD” ÂUÀoÉßgdÌkgŠe’@½¾¯Âµ*ÌZ?MŽH¥5M•“~ ˜µUKÔò0EãÅrptüVà]�¹—‹^°c@`i²c—!Љ­—¡³p.Âã(“éËLaìŽí\Ý*rÅ�Mµ2ÞTîÀ^”°®8âûƒ˜„¬>žŠF¸MáèXœçÖM“É-q‰ÏZày_XßMgÜhágÃÜ,ƒÙ­[®hPómšzÌNf…1éÂ�¨ðGèdˆ(‹€™¾L 0hPÛøU!}Ãïg<Âlœ`2àžÆib½f1GMU–':ÑŒ³Ê€?‘Zãþ;�ÝhµŒSa–S~T¸ÔÖÉm>["¢ðp¨ [›|~^³órQ.J“kÖD �V¾°~ <›.= ¿j¬•ëÛ<™£¦?¤·«pƒM[iQ$qþœ.0BjT 2•‹.RxÓBÔ" ÊÅjð2Pá�›1Q&Bº°ý»"ÕÜ\hÓÞ«-]éˆV‹Ÿô§¾_>1¬Û¡‹0qÑ œ¥$š ›ü^àF_X÷´±W#O¨0= {�ñ^rk‹ÀP”³€“�&¿Ÿ@ê— J?…-$BǾ‚°B¡c�å'ÀqN:¥Â¿¥vݤˆåpà!…¿·i®%ç˜QK4ãaj4(³nµL.÷‡ôqÈ Pd$(+É.îß6…ÿ4 ” ÿºf² ö$N"õËÂ^g¶‡“ü xÉÖs[gj·Üý ðE²L/œeãþC©JÅõ‹Vˉ¦‡KD¹ŠÎ†eéPùëôb;E"Ay8Ý"iOeC‡-Ô]�‰jå2Ô^çÂ-ÀG¢àúçh…å óF†õuHŒ{«”3D˜ œ¤ÊÙ�:} Z#—¨°Pá†Ém¾z]™*ãWÎO~ûÇ:á° ø¨Ž!׈©cý‹5ãQÙ†‰Ry ;Á2äϽþ°^—ú¡KDƒR¡° ’©A¸ÉfžÕ¢Hc­Ü!Ê¿’ò­LŽ…^•Ëüuº }™†«¥Wï/¹áʼûn�·üa=ÃN�µAù[ˣơjTX×§t¹ ÜÖf”ûí8�oTxÔÒ;Ó­ˆ‰&>Y’y¼€~7§¡£¬ÊŒ™¯-Ûwp-ðf>|ÎU~g·ŒG™š&é¹Ö•žh‰q/¥J&WnI—Ø4EŽ8À„™¾°Þì¯ÓË%1�(—®ŠåìØ„W5¦Êìü¸m�µ�@æS¿+‚ÒGÅR*&sÚ?ÌH£—éN�yvÉ#+Në§V uAñ˜Sð¨ðd ¬O¤Ò|nÞ÷‡»ÓÔóº$F¥ÀÍv†~ý£¬ë ªÔ¥ú=­Éø$P¬7÷�èÌÁ²ò£APÏ<ÂoÛd˜£&òmÅ_ÕX+Z^%£ªZ«‚ ö…õ;eÖÌ�¾(¿¶Hjöz¬[M[÷Dƒò …{ì8•Žd8ö÷EyGáSvªpJ-‰‘B:xA…g eÊ@~(piêÖ�}¾:ú¶ï#4M‘£L›Z=ú\”GMƒÕ({EN¢ù×…ûo ,7…�ßÃäXNÒϽÛF8ËÒWí‰ÖÈ•Ž˜ë ëÍ–¯±)€ `�æ¶X²WànÓÃüÀ"m³ìº:(C½ÐD6cå¶lö‡õÈöW¥OÿÌöÌwÅÆ]0²ýJb´Zü¦‡ë åŠNÎèu‰ÕFWDƒ2VØö3™Ç{ãµ@÷Z•³u49"ø';eZ£ð²z¨ò…õæö• J…�{å i¸Z:Lîôý.°b®Û_ù�ö}õ „ô5D,ÊeB3Ø›6_”A ut¬|S”Ÿ¦«|Èâ4°¯NŸVìõLPþkÇvÎk_ñ�ƒ+< œeÛ®5ÞÊ/ùQ‡‡Š#¶®ŒÅrªÕ¿XWWVpªbÿœ…Ào|aÍx)}Íd\‘xOGq+¿ñÕi§SùY7ã\GbãE¦,õ¸Æê’ƒ¦)2¤ÏW¼Øšêì C˜ÕzßÀªIrˆ ×wV& fGkä‰õJ‡VkØBÝeÀ$”/lØÛø5ÌÍ4óÚj9ÆãåU°œÛxoÿ€ôÃåY_Õ””N†S­ø¬²‚ªÔÜsŠäzøU ³p¦Ùï€À¸î˜ýTöîÍàÇùxðÊœýxªý~½µA¹É€ÏĈ*? Ôé‹™äm¬•é¢Ü‡õ´úõ0ÖªµmOÖ¨ ŠÇ—8QÜé¦�e(�‹Á^3ÑK†r*‰É𼇧x=yÿNÞcH"òúó +<ð`�çh5ø}WwÛ©ðd ¤]®”6ÕÊßÅ•[Ƨɲ_L&øêõ�Œ|Îåþ¡Æ©r¬aÒÐúÒDû(Ä å~1x5nÐp ?[ÆÌ×–º xFÄâõpœ*ç"ü„Î…C˜jçZºœï Œ¥:Ùuq–$†’mOKîÿŸá ëSv^’sL _XëI|‹\œ¥’̯à‹%×=lU>8ªr/7 X^óê’wöˆrAëu;8"€aËõ€á¡èpË%¯|$&ã}uú|¶ wü"Ýdœ |é”ÍŒ­> ö ÌîÛ¿Õ Ÿ¿<:R+§¡¼Hbó¥KG¾Re²Ó€©ØÛ×$ðPs �Œ^¦Y_Óš¼\ß”s$ÂÄ©-Ö=…]礦lš)½¿Ù˹(ãT88Ä%q(:x`±n¬¬àT¤l¦ŒU”»¶oç¬Ô¼R%öDjdÂ}8<¬TØf3«Bº¼ë¬Å§à÷øët�$nº~¥ÐïÎ7¢,l†@w©|(B ðÝ›E¢5\ÜÝ–“7#\ééÿÛ»OI"525ƒ�¦%�šœ¨×.#w–"E¿"F N-¶9c8§ µˆÔÈ ˆýÃ�%H3Bµ?¤v#ª�¢ .(Ÿpê\ؘb“Ü‘sƒ/¬÷Û;\kfH_c?a�‰}q¡î�*×ׄµ[D&/¨Ö_(Ç*YŽuè’ƒ O6)—u´«äAzxåˆr‰ÏÙpsy£`-@´FÎî‰WÒtB̈3,]DÒR¡`-€i`+ÎMÀkzKˆ[0¨ò,öÎvw>‰i28e S0Œ kƒi2a�E|ÿžÄN”ßybŒNʦ”(Ê<ÀšÒ×»�‰j0åt௠|€òºK�W|am.¶C™Rôµ€õÓäÓd¬*'«pÊp`¥·dü‰�PšDxx7W¹[RHGÓB/ŽR“Á& E8L”!À…C$±¥ºòVŒ~6WØI¢_²[a·»U؉É6 ¶ªòÊV>¯ôòñqOéŽ<ü7‹JI V¥O¿^m�Ÿ{ZØÛ�šçBÐcà’E_v).®ÊWeŽ+€2Ç@™ã  ÌqPæ¸(s\”9®ÊWeŽ+€2Ç@™ã  ÌqPæ¸(s\”9®Êœÿ‹[DàêpŒIEND®B`‚qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/icons/qtea256.png000066400000000000000000000226771525155022500232030ustar00rootroot00000000000000‰PNG  IHDR\r¨f pHYsaa•ø¶tEXtSoftwarewww.inkscape.org›î< IDATxœíÝy˜eµøñ艹™$d"È&È Ó=À "*h"0Ó“„}Q¼ ¸ÝëU\0n¨?—Ÿ "²#„LOÑ(‹ì`„dº; Dö- KHB2[×¹tO˜ÌÚ]SÕ5Óu>Ï“¦§ÞzO:]§«ÞUTcL49a`Œ �%c"Ì€1f À˜³`L„Y0&Â,a–Œ‰0KÆD˜%c"Ì€1f À˜³`L„Y0&Â,a–Œ‰0KÆD˜%c"Ì€1f À˜³`L„Y0&Â,a–Œ‰0KÆD˜%c"Ì€1f À˜³`L„Y0&Â,a–Œ‰0KÆD˜%c"Ì€1f À˜³`L„Y0&ªÂÀx·r¦LÜ4†±U.ÕA¥šukؼçµÚvlftU ;3€–¤Ä°¿+¼ÏQêöö(üÙy�¢�/Ï«ð.Oá°´Kù÷)}©,Á›QÁÀÒ’”XÂå`�q ÊÇ�éÀ6>W³¸_”Å9eñ´ú´Ïç7£HÅ&€e'É»¥ŠÚìOþÛr‚¶1…°Q”6„WTxN”€Uñ”n,gœKΓêmÖñqUf)| ؾœõ«Th!Çüºº¬Ìu“ž#;IŽ)¸ì®ï—Æ51 C•õ"¬Sá9GXÙYÃÊúôírÇZ‰*&´6ÈÞã�£|Ø¥ÔsäžWxÔqù{|�fü�²I9å<�wQ‡YQnìÊquý"]ã÷ÉWÍ�1í9 å(�é ïÃÿ  �{îÝ ‹§§ô-¿ã�‚Q�VΖ]s]ÌV¡ x@Õ¼ ü a‘(�§´Ã뉖œ'ÕcÞä$�ó�Ãý ÑwíÍ—&æëcÃ9Ñ“sd‡Ž.ŽŽÆûâVÚî¥yün±FÐâ�ÊК”é"|Y”$P]ƪß@Y( ñ”Þ_l¡lRjPÎRáÀ{Œ/÷¸ðÝi)½·ØÏž%c7n¢A”9ÀÇ)ooÓàwZÅoëæéê2Ö;*�ªК”é1¸Dóª°-E¹´­�yÓoÓMý°ä<©÷g�Ò ¿·{áâÚfýç@d“²‡+|ÎQÎUرœÁõ£]”+ªªùþ~óôµ�c±FEX1[ö̹\‚ÒHØñôò†À¯6ïz>‡f“ò …_SCŒ-‹\—ÿéÙ{�ž%µ’ãÛ"$5ßp7’¬Wøé„ñüÜ úÙ `®8é,ç‹òC`BØá a�À/sðg¾K¾E¿Rµ©ðKU:ð`#Té �Ï”òèÃJËgI]Î妓U lVxËqÉä„e1Xâ¥á,›”) ׇyИ­¹Ào×Ã×MéæR g“2Y…÷ãr€À^ê°e=ðª«üÛŒ§ôUß#Hé @DÒINå«À�E”Ø,VH9ðÇb’A¶QU¸ ˜TZpÆe©ãÒX»@ŸêÀôÙ‰.N˜)ðÁ¡q ]É·:?¬�¯ÿö/ä`””ZdoÇá:àO•ÁZW¸ª&Æ/úk˜YržT�YÇÏE¹ÀËù�)Áz�sâ)]Ðß/³ r�+|]„O5¥ž\ ‡rYÍÛ|mÊÚ>ìhRtÈ&åh…þ ZÙˆrY›pIwÃÙªSeR{-À1>œß˜b¨(ߌ·è%Ý/,Ÿ%u®Ë€ð¡ÁYà!ऑúXPT(\üÆú\ÿë ßws,ŒÅ¸ 8Èçó3$Q®éèâ«U5|I”oàáOjGŽÄq C&€lƒ¤÷Ì®nøÿ¦SŠ@?ƒKÞ‚#¼4>iЮ›ÖSd{uX@°?ØÅoÂègPaúDáÊ ëðbÐàtñ[`ï2ÅbLEå”L£Ì ;Žž|È6Ê'U¸£ÌñSé^«®¢v¤ Oî÷ ›”„ËÊŒ1°Cg޹aÑÍI'eq¦IÎèõúg ËOcü¦|&=Köéþ±%)±L£\—MÊ×ËŠ#p$Ê•éF9 ࡤŒSøV¹1&Bª—‹»H(?F8Cáàr"éFÞ"?äö¹¶6âãÆpš ¿+w ÆDL§ÀuØ —‡á†D³ö¾T°‰|xïØq|C•“Ë€1Uí âò)´Å)”}Œ@°Žî%¦•‹ùÓ:�©¢|™×›¸¬+w °¶×ÏÆ˜òØêzÁ÷…X‹ `í�Gcç†p-:*–Œ ¥ìƒƒqËÛaŒé+Æ#€/–»RcL_ÚÅ å®Óž/w¥Æ˜­ l®ÿcmX0f$xž–è¶`ÌÈÊuèvÃ}#ŒÊ�1[„“ž £rcLžj8×  “aTnŒÉXF½Ýw¡TnŒÉÓX8_Âù;KÆ„IÛ61ä.EAp±`Lˆ^h‹ù 9�5¬Fð6ÁÆT®0ïÀ€úôm�—à ˜(S ¯¾ç|älXAiËëúO„„1Úµ÷NP–†„1¦cªi «òwÖ#‹Y0&«¦Ü¨ëê|KX½š@[X�Iî£÷–pÔÝÚ¤CŒÅ˜ÈÑ�½·^•{ 0¦ÌB½¨Úê'e)R$ÆDPn€°j†ŒiŸD½ºÔ‹P‡²—À»v$¿¥Ÿ(T¯þ<)°$çòð´út±õo•\Xb׿1e³ú€”¾ÔýC¶AÂáx…ËÅeœÀ–1º=‡êöøÿ÷ô|Íq “”e D¹2žÒW @z®B´j†ŒiŸÀ:`ìpþVƘ¢,ø6p¦ÂÉÀÞ>Ÿ¿M”ëæ”¤÷2d™¤<æs Ƙ¾žö,C=o |%Ѭ×÷þEŸ­ÀTx¨ cÊsñLF¹.Ý$×,9Oª{þ¢O,S‰D9kÜ›\�È–¦¾¾w1î/oXƘrQ8-ÝÈ…Ý?÷iÈ&åi…½Ê™1¦\6vÁÔRúR¿Û�»ÂƒåŽÈS6ª”¯Âw™&ùÊ¥e˘hyAàžÂLÜ,Âë9ÈÅ`ʾêP�Ò@�¾~­?ž]úh�„:6/À˜ ´©pöÚ5´æà l®8Ù4Ç"üRa?ãPåØ~@&)/Læ1&²ˆ)—Õ¶èù¥”Ë&¥Æ~&Ê>†óã~Ûîò±"c ä§Ú8ü½Ôrñ”vÔ5ë…?ô+…ú€jéAc'�ëªâ^¯åã-|ø“±8°Ï€ –ãïØRá£ÅzÀ ;S”G§Ý¤oz.­ªp>l諰〠 v¡¾"¶@Èh°P«ØO•# œÝeLñ÷¥t­(¿ö!œ‰·`�#žòýD �uótu]‹>(ðA…†–˜øuM ¿Ø<¼Sà šÄ‡le‚!ÊÏ-úztãÄSúÆØŽ143° ›'ó°'Чô exÉD¡mа¹�{�öáTbü'ðPFøz¿›r£®Ïåç–o(sXfh÷L¿B;};›rÛpŠ ¬4L¿M7)Ü7œJŒï\qølcJsPŸÒgD¹¤œA™"(wúy:'6¼» VšDùãp*1¾[T;_‡nœ~¬ >S$ínõó„›¶e%àùŽBŠJÂ"¬‹iÄP¸®˜ãâ)Ý(°0àpL‘é¹þŸ �Ïz-/Ê+C&€xJ_UxÔk%ÆW](a„¦ò×c1%ðNÚó]ž:¤‡L‹¼Vbü£°âДßõ#Ö0RÄbÜÄyÞòZÖÕ"€ƒµŒ«K9>Ö^Úñ& é©óõÉ€Nßáµ` Z‹Jñ”®ÂÛÁÔl1øÔÑ^ÆLöÞ@dü#Ì·?€À6‹¾OéUC—§ù»€i+3y�À#(�‰ð¢+lr\¶wöåP`êå'—RY{ÛÐÇ äDX¢ð’ã²Áux—ã²� ‡“‚#�ÞA{J ÿ‚Þ[ƒ Bà� ßñRYÔ ¬u…Ÿv*×”Òµ·|–ÔiŽ/«pùmŸz›Ê\q¸X‹ê•éÌ‘h§'�µªü¬ªškö›§¯ tŽÖ¤Ls„ QΤ„Ï‹ÙâÙÚfg~`ç/éK¡›H~Èx±�€ÄSúPôžcæ®òéºfýÙ`?@í|MÇ[ôu9˜þ‡óNlÍpP±õJ~‚P*\ÛÑÉ~‰ýé`?À´”¶&šõ3(?/¶^Óƒp ­º3L-I‰{x)ëj‰ @…f/•E�#¥mµV·@—­‡Aß�#1eVQ'„Ù½^u.¨kÖ³ü£–Ô}$%þLžä‚ûîŸcw ÆCÑ�¯¯Íï^R@øƒ‡Ê L)µÀ¡)Ýܶ=�}&d ŸÉ&eÈÛ¾t'ö©Wùj<¥ž{UØÏK¹ˆ[_Üš®ûz,z÷Z„%%€ºùºœàgš=ü ¡a~aÆÓ*†ÑÝ:å/Å #½f‘ßþ¹p*¶Uå{ƒ•[r‚l#Òk.€Ð’hÑÿï%Ž–¤ÄöRv„X,nh>W›‚¬TàAÝþ|ÀK¡ž_*%7êܨÿêAWÛö|ª÷¬©–¤ÄâÂŽs”Oéhꑎ¿ç#R5ä °ýˆ§ô�l£ü· 7ö8ßçÓ�rg]‹ÞÞ_™qcùu¯oì�ó¾˜d­r„ ;z-‚Nànþì(wÄSºª÷ËgÉû\7ßun ðü¼ßK9×á/Ýÿ_Ú#‹1_`À™h>Ø{Ì›œÛûÅÆ”æÍú@]³^Oi½*þ`¾QØq‡û<�-#ÌgëÕ~D„ùÙ¤ÞçØFùžæ—Œz§~ኺyêyP�ˆ¯+Ѧ°@Æ¥NŽ})=¶®YÝßÅàºü�Â�y¨n¾þ'Àóƒ·ð\áNð�ö¿Y_v vŒ¹À·–$eÛÁŽ©kÑ{)=áp ¨QV¾¸xÉ â©Ï¶1¥¹~Ú_Æ+,Î&åL€e§Ëøt“\ƒðíÞåUé³-t±–Ï’ŸöZ¾Œ{'RzAíB}n°ÓIù8ð‰@£Q® òôÙI»–ZNeë)É%'€‚«<–+Ö®cášž»˜$Ѭ´µqp)#{Ó}ÆŒãÇ^ »Êý¼¨ÌëýÚ€{#�”Åó|‚â)ÊOǼÍÅSîТ)Í$å&`NÀq — Ü®0¯¦Šô–›MÊÎÀÑ §’o´ênYš…é­ ØÚ Sci…Xá¥�*Ü$Мãõ7èÛ[‘å'3Å�ñ)QÎ Ý«*4Õ5kª˜c³IÙCóÏüGU�ò…D‹þ6È*ÒIyHàƒ%[³v-»õîŠVÈ6ÊL pªc?–ápzb¾ù\›MÊ…'€}Ê—_^QxÝUx7°S |5žÒ_ v¢LRþ ýÎè^VxÍÉ÷$ìLväe¢ÂuÍú¹bŽÍ4É¢üJaÐ%­¯jç=A>ÿ§gÉ>âò%vaªð›ºf½°÷ëÃjÝÍ·3Œ5É<¨—%™F™—n�úÁŒ§t#ʷʘOv¨+| ÷{ñ¨òò�gR^à7UÀï+l7=j.~`C§öíæÜÊ\q2Mrr6)ÿB¹®Œ?¢\tã.Gáaü‚*7÷÷ú°¦w6¦4—i”Ë~2œó”B!†0[„Yé¤üÃ�[»àÏõ)}¦÷±‰:R™ _#Ø‘‹¾ØìÂr {¾ ìH~.þ˜>Ç {u>öàSòºÀ“.¼-ù/€ÝÉß%�䮾n¿ìwFå\q–/çêò) Ø?„þ`ub\x-ÂûKmySHOké ña=@¾EÒ­â…qÃ:Ñ0 <ãÂDxV\^T‡P-p¨Â¡aÆ6ˆ6®�Á¼Õkx°÷óY6)5Àá®pª(§ðÎ̯§Æ�§¾w‹n·tƒ,�òÎ7Å+¢\�ÐÒ_«ùªSeR{;3T8§Lm:ÞóqyN$ßËã {в'ù®JOóâ}tg"¥žúæK‘IÊc”8/C…sêšõšþ~7ì�m”ËU(ê¹Ìl±  ¾TìRÑ+fËž¹K(|ÐþìtqÆÔEúzÏã2³äý¸,ÞSxé/mm4L¿M‹šø’m”#Tø=¶PIŽ©Ki [é=q¢lWSÍk=w‡$°v›ñì1З…? )S€¥a]ŸO4ë•¥Ì$e-°C�—6 ,FYî:Lå@òýÃ[îþ®Ž§´ÏÜŠÁ<””q•ëDH–cD=žHéû‚®$Ó$'£,(©�ðƒD³ØnâËs_<¥«Tléð"¸*œâåâ_r‚l#°}¯—'(œ¨ÂE¢\@¾Õ«G…ÝJ­ëДn®«c¶(E�°‹<áÿ•©¦Rç/tv)¿ìÿ~Ê÷&ŒZ¢|¯ØþëÞjÆrÀwXZ¸PZ§áÀbæTôq±º5os.ðXÉe£åÙµkh º’%çI5ʉ%R õˆé[HÌ×Ç€»ý:_¥hÝ<™y-S>ÕÏËëfÄ[ô´µkù€ö^$oçL“·Å<¦Ü¡íŽÃÙ cÿ¹J'Ê/¼¬óPª1op,ð®ЏĆî�óµëGà~ž¯’¸p±×­¡³I©Qáô^/¿î8Oé�GÝ­]uÍzJŸÉF’£è¡Ô½ÕÎ×4Ҳᕷ$𙱈Óçß(ó‹0çkˆ§ô.%¿Ú¨y‡ÀKu ï;úÂÙ¼Óªù†Ä™ýí\†ºÕ´cÎZ1[öôZ¿äthëh¥ð“’¶jóhålÙ-~M�\ŽÁ—�ëæûà¾ë÷9G=åOÅ®åßÛÒ¤ì&ºõ­½ÀOÍúÀ@eÚ¶ç;lÝ&0&—ã Om@|!� øº³mxyü¾u¹ü%LþQåšú”®,æXß@¢Yï¸×ïóŽržV†}()ãªò+Ýl×ãå×bíƒ?ÛM¿B;Uùz¯—�É6ò}/q ªÝ;ɘZX¸¿nH/ÞÖÞëmÉÏFœ„?ïs9d³P?ÐZ ¾V””ù MÅ/Ê©ñ-i)òÀ@&)×gV�w›€Å»ÊÃŽð¯xJ7ö9JDÒ 'Ÿ|¬{¿^r”6ò£ù¦’Ÿà1T?ï#‰”½D6);+¼RLLªüÛž:\aÊ>…E'üšdóªVqà@Ë“¯œ-»væ8ÄÉOÜ:\óu�¼»á„D³úùyèWºQŽ)iõí»)ýh©õºÛ«ÆøŽ“£)왂=,E¸²³ƒ›ŠÚOU�¤\èsŠœ‚2Eð´žZIûùÕläÍö ÅÅ$”îx$˜ï„�¥““¡ÿ.ÅýoÖ—ÉoAÿG€³d?×å\…3È/Ž:…Ö•áââDÙ®ºº¤ñêp¾—º½=¯»Y_PøU�uiÂ')=0Ѭ—»1f¦IÎPøxÐÁ• ÏÚƒš\âñáGéÙ²{1ÇN�¯OÆSú5�ÝUøò�faRÇåk�×""…‹¿¨÷ å'=Z%ðçóªv~E¬`Œõ¢üwÛöÔ'šµ¤ÍL–%eÑ‘¼zÚ¹”ƒ7·•¾qD�¶urü¡°ÎAQâ)í¨kÖŸ99¦ ü�°ö~Pnˆ/ÐG‚®&ÛÈÿ'—PdÅúþ‡€%ð°ÿ­ºῃ®§O¹.‡Ä[ôç¥Á]v’¼;w”s9©"í·r¦L,öà˜CàSTK¥ðaàªR»"kê+ñ”ž.ùRo�ïe�Vó¿AW’MÊ ?,¡H»¸ÌÎx„²´Ð'šõfÊ;Qè¾øÐ´ºbèC·öPRÆUUq °wq —“«)~J¨ÂqAã•Âi™æz)Oé¢ùnÛâ¯Iáñ:¬ÝºËÖEç8\H6ìP¸eíZŽîwí¸!<9Gv˜wŽà%ÄPéwû¯>²I™ Ì 8ï„og“òƒR7Hˆ/ÐÇ/Óðä¥k^ãò +hMʇQn£´®Ð;)±€³z ,;IÞ«â`JH‘yå"\Ó¡\TÒ㛈dYOiß Åx¾ª�º Öù_q’¼««Š«Ä˶ëÂ×ÍêÛ2üeO™Fù=Âgü:ŸÀã)-n�¹â¤Ó|LòõŸÄèªÜ—råÚ×ø|÷-jz¶ì.9nÝ4e„['ÊU9åêbqÓ�r½ô]0eXD™oÑ¿øyN€t£œ$Âodã—)×'ZôL?ã %,IʶcóP¾gȃ‡ö²Àþýå-X9S&æjø€Â‡ÉPÞëC½#Å}ŽË9*ÄUø%ŽáîCh–®y�Ö�žÅÓM’ígâ“W ‰fõu#ÑlRâ*|¥Ñã)³‘�»7f±BIË›d†«ÜÎð6ü[áQ^ChWe&)l+ùí¯â¾dyëÞ–üš¯*¼…°N”N”‰.¼G„ñç±òe�iñ”¾áùH7Êa’ŸÑçùnSà™v8ÄKÏÖ�ç+d’òð6†Ù˜¨_¨máwÃiaOÏ–Ý�.’®0Gö`¬uârx|�f†yž~…šVÍ�1íx8 ´ ŒéE`­Â½¢<ìB+U,wr¬Ž§´£÷±OΑº:؇Zàšß†¼Ö§PÖ‹Ë1AA5d$�Ãc#hÆ 1Yl:È÷:L&¸G¯�ŸlíG?„ž²I9_á7aÇa̱Ʌ…•µ5"@¡/7E~kgc"K`3ÊññýG9ê}àª*pHC‡1£Ä:Ž+×Å#å `yƒì«ùö€‘6 ט =ï8×ßf/Awµ ô)N´6ÈTÇá¼Ì¡6þ±Ž?4¥›Ÿ8Q¶«©æl…sñoÌ~–£Ü–®-v«î0ŒŠ�™%àrþmUe¢áA�cû[/"Ý õc&ÊQÓ‡9þd�ÀªÜ«âŽ©7ë³Ã8WÙŒš�m�ƒÔᔲ]²‰²Ç;;9º¨� DdEûº.q”w©°#ù/œí$?6e£Âf„ (o¢,W!“ƒì)-Ç Å¾U  5)‡:ð7ü_ÎT–¥Gûµ°G¥‘ã3-¥ |x=ìẌõXu³‹h£î [a�¿*ìv,fD¹«ª�O±šo%uwÝâ 4ÓG«ÂŽÅŒ ·ŒÏqvñoÔ&€ú”>ãä8R 5ìXL¸Dù]]‚“÷¼V˽qè¨6jzZ9S&v�áFà„°c1e§*|¯®Y¿v £QE$D$�äbQ.;¡Ei?@IDATS6D9-Þ¢·†ÈhU9   Ó$³E¹Ú­xÿ—™A-——–Ï’ªËë!¨X˜mÝ|Ã7ªR;_îè¤N•Tر_u©07‘à“vñû£"ïzÊ4Êé—Û„‹–çT™S×¢†H%©ø…�áfF÷®¹Ñ%´tvðÙ¢Æô›’D"<””q“ò»³~…ÊßH³R¼ªÂëšÕå™Ð-Ý õâð{à�°c1R��.¾ìX¢"²�™F9×.þ‘Ea/…‡[“2=ìX¢"zwsÅÉd¹åka‡b´A”¦x‹þ%ì@*]¤À²Óe|¬�€“ÂŽÅ N §Â7Íú“°c©d‘IK“²[5ܪ`·—£‰reÛd¾0ý í ;”J‰°|–Ô¹.‹��ÃŽÅxò×õpâ¡)Ýv •¦â@6)*,v;3,÷UµÛ’ß~«è^€tƒ¬pvñW‚#ºÆpçÊ™b“·|T± `ùɲ‹ãp ¶‘h%9¬k `®Tìç¶Ü*ö�tcüÁ­H3³>v•¢"Û #ü†‡ †À[¹jöšv“¾v,£]eÞÿv&8 Û:]Ì ;ŽJPy @DÄø¨xêÚìA?T\xâÓl Œ ;0±1~¨¸PX:úî°ã0�[v• â@uIà‰°ã0�¹´®…_‡D%¨È°ß<}Mà”ïo‡�ñÍÓ3)½€Jì¾ AEvöôäÙ¡³“ E8ÛÆŒZ�(\öÚZn>êní ;˜JRñ `‹¹â,Ïr´ M(3€]ÃÉ HÉ?Âý)óêSº2ì€*Ut@O"’=™q88\áCÀva‡qO#ܯÊ?«cüeÿ›õå°Š‚h&€ÞæŠÓš!!ÂûE98ˆü>BެR½¢ð¸ÿV—Ç««xØ.øpXDë)²}¬“Weoöeo…Zl»ñ¡´‘ÿVÏàò´HþOWާ§-ЧÃÎäYð %)±©.ïubì+.»*솰ùv…�€]vQr¨AyxxU”—UX#ð’›ÿï3¹Nžª_¤kÂÒ Í@€V�*“6·±kUŒw«ËN®0I”‰8L—I*LRe;&’ߤt’ÀD}§=b`ŒÏam:º4¿ÿ:…õÀ68ÊzUÖ‹°N… ¸lx+'¬‰ÁK5Ym{÷UK£È'Êv±m€®NªªÜ¾;«ƒJ5ë¶ü££þµ±¦_–Œ‰°Š hŒ)Ž%c"Ì€1f À˜³`L„Y0&Â,a–Œ‰0KÆD˜%c"Ì€1f À˜³`L„Y0&Â,a–Œ‰0KÆD˜%c"Ì€1f À˜³`L„Y0&Â,a–Œ‰0KÆD˜%c"Ì€1f À˜³`L„Y0&Â,a–Œ‰0KÆD˜%c"Ì€1f À˜³`L„Y0&Âþ|÷C_)÷ IEND®B`‚qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/icons/qtea32.png000066400000000000000000000017061525155022500231010ustar00rootroot00000000000000‰PNG  IHDR szzô pHYsììy(q½tEXtSoftwarewww.inkscape.org›î<SIDATX…í—OlTU‡¿ß}Ó™.´ACb”m©Û�V&ˆ6*Ñ•Ûbt£ ˆ‰ %¢1,\ɪnŒ ÆI""ƒ•¨ØÄÒ±A‹�¨@C©”´Ó7÷¸èkymg°fÊ‚³{÷þÎ9ß9ï¾{ï“™1›æf5û €ë Ql°g…îÅÈîÁÓïû/Íá³êžÀxX ÜC|šp¼](�0ã)ÄÞ‹ÎsgÙÙtÈÂ+ÈÌÈeô*F3ÆçÀEÄ& 9E; T—ˆ“�Š™ÔQÁaૌ¸€u ?´¾Iš\  ¶\‰ò´/ÌóRºÃºÇœÁ JÐ$Ñp§+€49Ÿ“q¬’aÈ/ÇW«¦ïU8?T*¹à|�àû‘<††ȵèyç�¯®2^¹fô¦’,6±H!Þp‹²vø£¼H¼ïMeˆ­õí6h ¶���·ŸÄtÿç‹�±ñ´9Ã�Ø)ãAQty&/ðáp”É‹„€ÝÀ<ïÆ„—̱TðV‘ òFÆüÀñšíó îš"=á=�‚=—éÉÞ·Ë I«‡ý Ú¾�¤·ÉÓepD‹Á\'îx3†½g®`ž¦oéæû ÖN´ÃØ›uðÁå­S¼TË"€>A!ê@›)O¦¡Ã¾›(¦Ø¥ôçV­3Ø è’ÿ:ZÏ2àÖ@äÌ8Ø�µ|\T ‚XiÐÜtÉ÷¦’¬ªo·Áÿ–ènUm]Œ­…™‰-é,™á}¿ô�PR Ö”“@Fæè“ÔÎT_ §™å¯”“<²:9Úf*.ý $õ´ð¨ŒG�‚; nRÀÍ‘* 1¶ùœ~ÃøÆªØ“Þa_@…lÖÿ nÌ:À¿éŠ:úÒG»NIEND®B`‚qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/icons/qtea48.png000066400000000000000000000030251525155022500231040ustar00rootroot00000000000000‰PNG  IHDR00Wù‡ pHYsbb_'ÐStEXtSoftwarewww.inkscape.org›î<¢IDATh�í™oŒœUÆÏ�Ùî¶«M ´Ñ„¦º3³ûA,‘DkEÔ(Ц²³)h©‘ Ð5Ö€`4i¢*¬&ŠP±;³U> ‹°Q 4kéìlk¢-³4´´¶ànwwÞÇ3»™ÙÎL·³ÿܤϗÉ=çÜó<çÞ;ï{ï}e›…Œ0ߦ‹óÌ7Î0ßXðÄÏ%øðÍjy×/=\Íw`½.Œb| «%–^}ˆ¿&2™¿w“šNý¯û£Ç zï�lZ±¤Ùhq ð> 8 ìEì–ùUÞƒ-†OMUÒ•y0ÞÄÖÓ#, âV‰OÞSŠÃæ)àþTÖn¬€{ò9î´¸xMðð Ð#xo�þ'�·š×›@ µgÝÀÏã§ùz¡™ |B ÁöDÆÏÔ- ŸÖ]†{&ù†K„s�ɼc‚'2~¾ZpèïÔ6Ã7«øæC|5Þx÷÷wêŽjÁAâóÀ’Ù×Õ8JË8QÍ€WçVNcpàp5{ˆÌ?æXKc¨¡3(�›k-�À�¯f�˼¸NoÅb,ëïÒV™wÚ5ô¤²Þ£ƒ¸htŒ×ç[a=† ‹Ïp˜;ÃêG|˜{Yçñ”ã\AðR™ý¶ óû¤{ÑæÓÀ[3•а5õˆ�´g¼?6•¹. <>Sd2w§²~ÌâÑJy,o^o´uÓŒ–šƒ`xÏÇ$xÅæs‚Û�W#((b x³Aæ«�ª—éí̸0ÞÞ³Ž¥½—a¸b‡G-vNê;jñ™ïÇêp,:%z?@à:‰ïìOëCˆ¶ÖV>–ÌzWûÏ¢³OæË?ªâ{°¼±b9«)mƒyfâ@ ì˜Ô±)˜�C⾬ŽÔ ¿d)<žïÔGq! ‰6Á††Hä;u£ÄCuÄ?Öü&WÄK27–;=TìD#¸¶ä+Dq�( Ñã~óåÁ†�¶À¡¸¹—ú[ŽåQ ‰IÇl"h.D$)îa–Õé;|úmü.À ÀÅübgXÖ—~ŸHýÆÿªØ›ó€ÅÚI.pqÃW 'k“Ý~#·AïP�¯H´ÉÄ’Yvb;ŸVŸ![£ÿõ5ì§¢xåòÉÝ •‚+"³&�‰)vûêˆ+ùË—Ó`!bE>­«U`·áÛ©nÿìïä¹ëÕ™“åI�ÖáÁb[û¯]ñ`Q�o•4÷¦²~òŒ¸Û‘Í7ªå³ø‰`åð¬Q%y[ žÖàÒÓ¬ø{“û$þP™Œ�ÉŒ/�vÁ_ªð ¶4±­Ü�ëÔ:™Û�ÿF›ÇígÜJ¤²~±«¢røa*Ã׸|ñqþd¸ª i1VlΧµJâ³µb÷溴}$âø’V®6 U(îXµÓ³–Oë‰^CLæÖö˜HUíPß—ÖòEð7àÒ’é0¬¨)ªS»²1ðoÄJ?ÇM;¡×k/X&ç¼74N38Œú_È—–G ~ÚÒÂE{^á+ÓNæõî(ب­à�GXÏM?O}ýY?„ÓfN[vžß›v2ÒøT¤dÅ‘6bíh ÇÑótÒ]Ýá.Œ9�SÌý©4“Y:ݶ+g8ãT`—4si0k�¹!œ?©è ÓLdá)6lÄóü‡³�£€ÑiæƒemA™_N¼ÒN;iL*voÁÆ7>hÎ'¼§+\£ �;Ú‡·py’OŒË�³1ëËœfÎg€-“ŠÛ¤n3çìl»ß˜XÄs-(urN«³Hv]LÒBàÚÀ8ob›ß�v2ÒXT$dÉ,Ë{ȧŽ'½NqiYüÞágùvnˆkž³ã8Ûž2Ÿ7çTª\½-CvS`œ;±ÍÿW€RÁvv88xs\qjØ]?Xù,Wj7�DA@̖̲·…!_ÞM}ÍGÆe)Æù-k¹düÕþRêÆ_S"/J;8 8ª:/&ჯ=ó,¿T! C¡ &‹ ¶k¾ Ì¢¾õ%eµ¿�O.ú²Á °tºm×=ŒÿÑ�¿&ÝäÎóí~û`>\*ØèÐ8ÁœÓ€\Ĺ5Š¥�ñ?Ûü7i'"õI@Ä–gcº»ùßÞW•�ÞE. üÉœ¯eÛýÖJ>°`šµŒénœlkv2Ž3×[8£ÒÝ!‹¦Û¸–>|Äa«˜ók·cœžkóÛÒNDê‹ €ˆ,˜f-cÆòƒÿE Ïë&sÎÙT!ÐQ°# ~€ž ëÉ+ßz¾s`Ñ_íë‚EÓm\K†Ï{ÏŽ�Íί!8ü&€Oe‹þHÚ¹H}P�Ž6Ù.Þžv. â +Ë;fÙ¿™ó œÖ4“Á3xÜ�/äæqék Aµc#r¯`|¹ä|·žš6I:T ÁC'ÙÈW^æ‹n|µ’�ÃÍß0ç0ŒO#ÒNH†ÎáÏœGšóQôć¿„!ž4Ï—¦�ˆÔ®š)–N·íº‡3Μm¡÷!ë‚€Õî¬CV�e‹þ|Ú¹” v°ÃÏ� iç""Ò‡µn|eÝÖ|§Îï(lx7ìÚ[™±¥‡llað¢9«€ç�ç³9«§öâõ,µ £Õ28ãíÀ¾TØ©Íàq‡Å‹Ì¹¿»›&Ï÷gbMv ¦YËØq| çshu¿ˆÔ8ƒ…aÀÌü\ ©˜ O±a#_à`söwg²“¬çÔÒJÞ”¾,4çoÀ_3ë¹.ª-ò±D €‡N²‘k^¦€ñÿ€É ÜëÎ fü.›ãö¸ªÇû ¶S ÌŽc|‘˜¬vãÃù6/ÆàÞ‚�áLÅxŸÃû€­#ú%`Ž…ü0;Ï;#SH¨h/Xf"œfp6°Mœ± þeº¹xâ•þdTãvδÿ0çR‡±Q�)"’ Ç8Ïœ3²E_Å€½OúGá|„ž3Mâ|+êóÊÝ|vò•þXŒqšFìÀ’Yv@òzÎÞNR·Áo� ³íüq°ígÛ –Éçà|½ò‘úwWPfæPêmtöà¿�7E–Ye^6çœgVrž:!M|À¹t–8·Fnœ÷»óåü<®ª¦(l[‡yÀ´sIÚó³òE¿¾š• ¶»;ÿ‹q<éŸ`zw¹Ìt½ ¼X €RÁF—8ùàCàÐaÎwry.h�@o…{-Zå/"�©Û�OäÛüg]¸t¶íR.ó?ÀIÿÆÿOÏ–¡uRÑoI;—zy°äX{k˜á÷Ôv§¶ûãSýXRšaû{À54ö1£""`|5WäK}½½·`c‡;_Ã8‰ºñ¿Î:‡ç‹~iÚ‰Ô›H €Žãlû ›[¼g»G=ø�gøØ†}Ê—Ì´÷‡ÎåèpiFûæ›qâ.ûZ g ·ƒ0¾ŒI7¹Šxoð‹´©'‘÷lìpXd#09kÜønà|=„S ¾OúkDD’vû°Ž^×Í[ø1°Ú UàìÎ ¹vŸ›v.õ"’`aÁ¶ ·{ =¥Ô< ì�v"")z ذ´¤õæ¼?ÛîH;‘z0ô']3 ¿¤¾oþ ›¿ˆÈ›¨ß›?Àp7ÚÏ0-Þ®À� €Ò ΦG�‹ˆˆÈPm‘ (.<Ê´ŽkC*:gÚ4Œ¯D•ŒˆˆÈP9L9’Ÿ§�G­ô€¥Óm»r �ổˆˆÔç¹v¿$í4jÕ ß”[ø.ºù‹ˆH­2¾¿hº©ŸK?Ut´ÚTàѦ"""©í‚a|?í$jUÕS+Ž´ëGs5û‘&æÎûòíþ»´ó¨5U¿X·9géæ/""õ"0~¸âH‘vµ¦ª`Ñt‡ñ鸒‰šÃ®kGóÑ´ó¨5A©ÕZ; vkG«½k ‹3-|Ø"�¼DDD"cð…eGÛ&ï_ÇÙö3í²Î™ökε†o ¸ñmà`3~ß9ÓŽíïÂÅ3l7à#É¥&""™qåá|¶¿Ÿì8ζ·n˜s<ΉKJšdrièiýЂsYi†íÓ×…–áËÀðÄ2‰�Ÿëk[`{Á2ÖÍåÀ?[{ØøÛÜà• ~<ÒæÞQ°Q^T*ØîæÌN65‘H�niᓯÿâDã‹Àa~-„WË*%°öu_Ûs ㌠¿àð)tD®ˆˆÔ9‡S�h›¿öãÞÜ3^]`=7¤€>ªsÎ\T°ñ‹�·m€ÿN8/‘8l¬åÄ×~àðC`äë/*7ãÏ*gD ü ÓÅ)ÀèdÓ‰‡Ág8ׂR«µïéëš h‚7Þw€Ã�3m¶ÃÇ“NJDD$F{t–˜éÖ›à  Þ´/ôû³ÎÅ€º'‰ˆHcàþ¶>dU‚Ù¤"0çÙMü¼nþ""Òˆ6yÆ&ï� !ð&øEŠˆˆTÊàÅlÑ×§�GÜS ""òOÍò`¬7"""h–c½Ù@³<a“üBEDD*Ñ,ÆAfÓ»DDDšJÓ¼XWnŽ_¨ˆˆH%ÌY™vIö¾Ê_ Ÿn€"""ÍÆžH;‡$�¦�ˆˆˆH-ð�‡ÓÎ! ¯ñûHªYˆˆˆÔˆ0lŽ{¢ ‘éZ–áÉ´“HBOàšo-z9í$’ 7"""½¼‰î‡=€5Ç‚‘M ¼Ù €&ªxDDDúÕDÄÀð—yð”sIW­‰ v¿Ö×O§œ‹ˆˆHÚšæ�x°Á7Í/ZDD¤OÍ64Õ/ZDD¤/™uM6à°"ÍDDDDRöäø«ý¥´“HÊ? ƒei&"""’²¦ºþ³¬¹~á"""ò&»þ³èÎ4×/\DDdC�³<í’ôÏ`Òå¾ÊàÙ4“IKجSÞd¿x‘×MvܨÐB@iRëŸy–‡ÒN"I¿h²ù‘^N½Ù»ÓN"Iz ""Ò„÷¿� €²7ßo€ˆˆM¶^W¬ßŽ€®”rIE3N�oTL¹À» ¹Aˆˆˆ4Ûx]Ыé~DD¤¹­kÂ{ß s–¦‘ˆˆˆHJVíSô¦k„÷† 4¥‘ˆˆˆHŒæ¼ï½¡p¸/�DDDDÒà°8íÒð†à¹gY¬M!‘Ä™ €Soön‡RɈˆˆ$ÍMüë‹®ii ¼JgÚI¤¡Ï ¸?éDDDDRðàø«ý¥´“HCŸ@F ED¤ 4ëè§xŹð„sIT3o}ﳘRô�$œ‹ˆˆH¢çž´sHKŸ€¡u""ÒØºË*ÞÈUˆˆHC[9ùJ,í$ÒÒ …€""ÒØþ–viê T ""�Ëšxþ ¥¿Ÿ˜x¥?ÜY°ç�mÌGDD$DSÜQ°Q£!Ûb¼%„�pƹ±½9;8Œ `ØbÃJŒ§ÍyÚ�'-ä˰ÄC:²E_E^é·èu?0-‰DDDD’TÄ€e³mÇî�&™“&o»9d 6Ï[ï›ØSï½?çà°¾T°Å 1þfÎÍÙ¢¯¨6ÏJ˜{ÿÛý;[íûŸ‰#°ˆˆHŠVåÚÙŽMÝé¹á—ËLug*Æ;�=ÊoCË ®C.ËÏóÈúlò €wYT‘DDDjÇ]}ÞüͬÔÊÛÝ™nÆûÆ÷|=éô6²§Ãç-àó�»çÇ«�Ë,ú«Ct“o–ζ]Êe5‘Æâƹù6?€s-(uðï0g:°sªÉUf%ÆwË#8ò%¾f0l²è,ØSÀöƒ\DD¤™s¤…”€“1NÞœvNƒô´ÃYùsvï*‚ UR\¼o(Ù‰ˆˆÔn¦²é~8õä. 99;Ï+>ÚxÀ_¸Ã]CËIDD¤¦p(�sóØßþÖ9Ó>ƒYE+üÅgL€ˆˆH‰óýÎVŠ�d#ºxÀàçn ªyIÍŒ5k¸qétÛnS Xô ¼,²´DDD$n•[¸¾T°Ñý]PÑü‡ÁíÑå$""" Ø'„¶ö‚eúúÉÊ@8·Eš’ˆˆˆÄÎàȉÆWúú¹Ê ãÖH3‘D˜sæâ‚øú¯WTôDðdäY‰ˆˆHÜ,,˜fµÿ¯f¤¦DDDê�äqcùè†_«¸pøKô)‰ˆˆHBÎ\xŠ {í*DDDš€ÃN#^à˜×~¼Éã€7´îËÁ‹[Å“šˆˆH*ž2XæÆß y˜€Uæ¬Âé�-Ø)4v4g°°yº)Ž9ŸŠ=ÿ=Àa@ê,Ø�wÅ”—ˆˆHÖ¸qYrcØÂ�ù9þh5n/Xf¢³¿ïfo�'Íx”a·ÉEÿGU@ÇLû‚9_‹1/‘¸t§�œH�[ýÊÖµÓ½6;Ï;~“v½‚A¸ ‘!q~¾vÞ»OÑŸÝøëîù6ÿ¡Ã‘@ªs—"õÌàÆ)xWÚylÈœóÒΡ— ºÈ¬ç& ¾¶Š" Ì�³ríþ‘M}sÊýz 9m»œ|PͶû­À’´ó`(oÆ_í/·G˜ŒH³8?ßæ_¯äÂì<ï$àHàå˜si8ÝÆŸÒΡ/sÓÎ(~ Àjgq…H]pæäÚùd5ÉÍõ»Í)ÔÐâ!‘z°trÑÿ‘vý˜—vÀ C*¬_¯ˆÔ*ƒ´¬çª9ƒ»W¶ÝÿàÎwãÈK¤!Õðj¶è%àÑ”ÓZ�mç~à‰ˆ’idaNê�:”k8XaN" «ÖPk ?Áê¡M¸»[mÿ&‹Ôs.œTô!µÐÞýZ_GÀ‡¨Ý#FEjÅ+/ÖxËúÀ¹3åžZàü6‚DDÙÚî�¯E1Pn®ß ú7'2€ë,ú«i'±)eX˜jÆcC.‘ü µ/é—Á“¯ôÇ¢/„ÿíù?‘Æåk-¯ƒ"yÔËt¤¹°×áñ!“/ñ5N:g-‹Ô~倓оR<ÝL$ÝPa¿�n¸xì~­¯ót>2ô) p®‰b‘FãpW~®?õ¸s¢S¤Ü•-úSiçQ ‡©#˜È´ð[´0Iä�,žuyíÀº8Æ©ku´.Íà™Ô‚gx ’`ü‚´4ˆÔ –˜ö"OºÜW‹cl‘ºVGo¤Ýô¶à!Z»$ä¡H «ƒE"I2xqÂÄ_ñwÇ6¶H}z0;Ï;ÓN¢R�³:¥ÐËZ‹>ÄVÀ«›ªK$ ãl�mµ¾¹ ‘�8W§�B5R{`=‡EVd‹~ðpTã‰Ô;ƒåqŽ_†eqŽ/RoÌø]Ú9TÃáÅ4âšG\ü&ÊñDêÜóqî1�/RgV>ól}m�µ�WÒˆ:÷@Ä€íQŽ'RלUqvÅ;¾H]q®šz³w§�F5Ì™FÜLسh?Ò —åƒÇ£S¤^yo‡ÌÑë¨éV§"‰ ¸2íªåÆæ)„}zâ•þ$D\p¶‡xýý!ˆÄÁ�­ãýh¶‰s|‘:²Êœ›ÓN¢jaò€m°}¸%†ñ矌a\‘(¬V¬rØm°¥Ã¨È#Y¼7èrÈÖA´%<e‡Õ/8¼DÏ÷‰í Æ8d¢�(24nü&׿ëÓΣZ°™%ÝBoƒÝC‘Ù<·uvò°cÔc‹Ti•9¿Ç¸Ëî²�û³Å>¾IœkÁÒ%ìÞíì8ûG9Œjpƒ±CcSZ2Œ £ùæ±ø�·fŒûº†³xò%¾¦¯ —ζ]ºËìoÎþ‡“#É@d‚°nן�N: ÿZ(ý€³=¤`ó�Ó"[d½§k]Â¥#_æÚݯõ�Ûåžíᄞ-{Ë�"púâ‚MÊ8³Ü8ù$ïì=¨ÏU¨ {áw¸:€‹‡¿Ì+ú}&Ìñ‡€‡€6€Å›”�ÿrø0nðéˆ Ú*ŒÓNb0ÌÙ"á�ëW;wþ+¾GÿþaÉL{GèÜùÀ"ýsƒßòÅ(;�­8Á¶\ÛÅiæ|SåÇ»×®e«)×x,[}J­v©'Tù±˜ï!_ÉÏóEQå²èDÛí<㎂�¶O2frëF?Ž/’Î+—丳YqòE¿* Ùø{%×»1kÁ4‹~­�s\%—”q>žk÷Óú[Ø¥r9ùEMÒÔæUº~¥Öl²0„e<Õ1(¿jܾá×b+rEnŒk|‘ yïžû Mšçz ‡8=í40nÜX�2þ‚iÖ‚3»‚Kך1#×î?‰2þ¦”ËÉý9ˆ bZ®f„Æ® ‡¼oJÑ7:{ ¾7îŽ×ïŽÔs²IÆË_áO·tó.*xàðÅ(c�ljÀ[ kpòÄ6Oô|ŽÐÈ'Oš—Áã%¯¯Þÿ Ÿÿ¿õõ_‹¯çÒ8Çy�¥°}Â|ÎÞcðì—ÔÑjïŠ"æÂSl˜9g x¡sf¶èWD³“’Ž)ÍÉ�ËZ‹^N;�Á BöJ2ž÷Q,ÅZLœç�Y.ñsØiÑtK|z~®?€ó�/4¾ÅZ€«ø­6Úsíþí¡Æ”˜{ˆ¼&ÈpYÚ9 …û'®{Üôú/ÆÑ x#—¼=î8±2¾j!zÀÊ€ÀR cÌÙc�v%æâJÞ(Æ{�_&7Ûîèlµ_cýo7†³€sgQÁÆgàë\ö\¹+�&\‹N´Í3ph±…ç:§„ñ0ÎÓ}~¿2Æ„06€S£èv™¢û'ÎõŽ´“¬eGÛ6‚ Iu6¸íõóÿ�@@ séæ»‰ÄŠ‰Ã‹¹v¿¸ÒëK:0ÕœC�ýHpµgÓrŽ%…ÀŒÏ:¼›Mlëq㬎öûü<ÿ[×ôgÁ4k;–K`Ó»>3y¾?SíøQhYË{|€ü$�;\�ssrËÄ+ýáJ?»äXÛ!ÌðÍ8ó‹›[}?ýw�d_<Ñs5®ë닱?¥æ¯ð§¡>÷i¾ÆœÏ>t’U|ns¶è/çÛýOù6ÿB®èx†·ü?68…I¢gpØÒé¶]±³Eð›ê0 ˜ß1ÛZÀ·137† è)$7eQ¾=½oŒnÒŠÝ zךœopH6Çι¢Ÿ”k÷Kª¹ùxÀg!�sè£`P�øú–(™'úúøC__Oä5µÕÿn€^YÇûáü4[ôïçŠþvƒý{·®¨aJôFtãi/�âç Ü$è-VæºRÁ¶­tÜR+_qãƒ^è|ƒ8z{W`ñ Û ç˜4b7:‡{Ìùàf›³s®èŸÈý/œíá`Æê8ζwã£Q瘤n?ÇŸH;�¡ðd§ÅŸÊµÑgçÏD €îQüx9‰Xqq8§šoÚýÉý¯ù6?Á`7.î=¼F"bÎ'JK¥ÍäK|�9çWpiÖáºRÁ޴ɫ̬Ôjg;¬ú‡K–Þ‰hãóÔñ4_�º/0þ3_ô)Ùv¿x—‹}íP ºø:)œ@%«ó×ÿ˜TÝÆ{ÐÜøC‰½ß‹IÄŠÑvî|9<Âf IDATªÁ²E$ßæ,‡äég~Fe[w>�ZôÊ“¼ÝᮎÖçöŇN²‘�­\æÆ9…u榵%jñ ÛÍ�ÿN#vƒzÒàø\Ž)ÛüÚ¨í˜aû6ÀŸÓêòˆºîýODZLvL*^öýú\©^6.J*VlŒSJ3,Ò¹›Ió|i®èï18x:ʱ›–qÖâ6!�ÐÙ¢¯î¯ðò�-à/;¹÷©€Ò Ë­YÃ-PY»_€²¥tö†™RÇsÊ5$4øéZ˜˜-úƒ}Íß—…§Ø° àgÔÿI´´ŽS`ügR± Ê›:*9±¿ “Š~éIm)hñ€K�h›G=p¶èW k!ïYÅßÄFq®¥òÍÎ�jºïmapQg+7-™eùŽ™vŽÜÃÀ þ6ôè¤öŠÚG®³À‡€ÃÒˆÝ`ž28"[ô�õµ]k¨F­âl‡)Q�›¸ þ$ÝxOb±àÎlÑŸïïç“ýiü"ÑxñØ#³–ïÇ1ðžWøÊ|;ïÅ9èŽ#Fù÷ÎŽ÷ÌÇ"ÄǦ†!‹Í9^ågïNcñß’Yö6œ$·Ýè-ì�-úµD¡T°ƒ�3ã;a‹rs½®ËÝwŒm ˜T÷ ³×ãô =‹UW¹ñ’AÙ�1c€€«f°Þ)¯7g‹þÔP’ê,Ø5ÀûªüØ Àr‡•f¬ÄYëÎÖflŒò¨•o|Œ/åÚü+Q{oÁÆ3~`ÎñQ�]3ö«÷æ?ËfÛŽå2�$Õ‹Á�“ómþËJ®Mïô.w÷™v¾9?M-‡xíÀÍ¥V»8(sú„ùþ\TO.ú²Ž™v¶9߉jLyƒÝzÿ‡õÖÈC™áþüoþ8×aU[ûYÏçˆvµ€ôÇ`ñ3Ïív¿ž)§‡Ã÷ð†^”yW½ßüºCf’\#¦WF«ü°¤T†Gp) 6LI�¹ñÁr +: vV”ÇÔÎ�åQ�'±{$ŠAÜx8Šq$n|*ÊF?¥‚½»ÔÊݽóÉ�|óÇ­¢£µkž9±5Œ{=7®ªf�IªÀäK| –ØÂˆ4mmðU‡: vÖ½;Ô³E_Ÿ‰"9‰_ÑœzÆ47_G®ÌµùÍC¤½`™ŽV›ÞY°[þÐ@Í}6åé‘/ÑžvQpx[bÁB.©æòÔ�†4çÇ@dÇ^Ö¸q_�v¶Ú¯J;´½`ƒ~5Ô{Vøíæ'1ñÞé„!�V·ö@R|i(,ža»uÌ´/dá3®Ž(·Úç\¸ûµ^÷çÆô>ì½5¡pæóÜPÍÒ[Ð+[ô»ÎàÈ´sIÐŒ8| O— 6ߌ?¹óçjÛ]ºó ³M7Š‘êôvª¼XáÎjàeº,dL°�9;ѳ ã-U ;qé,ÛsÂ\Ò´�[Õ{‰×üÍ�åÏb<«fl‰³5Æsöñž…€IuIlx×äŠ^ªæ3½»1öõ2ÓܘìÛ¤]?ºº� ÒN" #œ}=¡õ6?ãl¯êa:õ pÎwkª`CÛ;œêΩ@ØY°EnÜ‹³$ctv;�fàÙNx¶µè5OºïÛzä–—CC³ ŃßóÖwqÃÞWyEëR–Ͷ»Êb0›žN�›ÜžWùÀ)ƒMrÉ,;€ ž:̸ ãºRHÇëÿÞôeÁ4k»=ûPæXŒT¹ËA68×,9Övxe +§\à]þÜŠlËWÖ³C Œug�5#?v,„![4{»%ƒù{ýñ´óˆ‚'WÄ­ë¢úéôô¶n¨§ÉÉR`�´S©qk�W{ÿ{ j¤€«c�8|ó%øÕ�EuàËûW*ضqð¦~. 1̼p©`£½§ÿä¾~¾w›âedøAn®ß_íø¯×9Óþç,Hôô²†dð¢÷L [¥�O­38$[ô¿¤�G: ö[à½qÇl¿„Ú(€Ž™öÑÞ(µe¥ÁYÀ¯²E_åÀ‹N´Í[Öò ‡/ÐS¤mÄàEà]Ù¢ÿµš13k™¼«ŸK®ö€ÿÉÏõ%ƒËº�³ìí„|˜õØ"}¸+WôÒN" ¦YËØ±<lw¬ àÀ‰sýÎj?W3Àµ%Ìð�¿¤‚›?€—“y*ÏÏõÂaâ$òT#MÆà{Õ®b¯iVÙ¿ß¡…àq3æöó5Ud‹þ<ÆEiç! åƒwfÛýÆÄ"žký/Ü”AÝÈcÇÁ|n0&]î«FoÎ8\›TLi Om¶yuMljÙ}ÇØÖûÆÇ�eSMån¾t x¡ÈÀº£5[ôû’ ºt »“à\¹Ã¤¤bìr±¯]·–V â…Œ"›bÎw¹Ø×¦�GT† çèÿy©«› ‡2@Í“¯ôÇÌiK;©æœ2±Í«êŒ…²ú†<¨³â½Ÿ­�qšr�¿Ò Ó b¿¶¤ê¥òp~–v‘rfŸ°Òž%ý©¹ ì9å®6¶'H]2h˶ûÅ©÷~Wÿ÷'tãG-ëx³A+ðd56ØÁ4K|Aï^EÜ�““Ž+ çç“.÷Ui'•åÇÙà°˜Ãtõ7$5Yäçù"ິó�ºõ\w7ŸL%²™Ó«øÄrP¾Í?9þj)[ôy]]d .­bŒíÆ�åUf‰\›ÿ‘At éÕåþ/í$¢´¾Ì ":ü«?æ\š-ú�O­ÉÀ�o§�ƒÔ'‡3&Ï÷gÒˆ½¸•·»Txù_†µp@vžßµá÷¾Ê_ÈýDŒ3©ð ,÷ªŠŽHü? ažà$AÆœü4í4¢Äüúß lÎ7£«f €|»/nM;©;­Û&½ÕÄüw%×´�x™Ã÷¼ÂWöwM®Í¿åN+,Š5£°ð(‹·@?²EoŒ³Û%9å²óõ´óˆÒ¢‚íêpH¬Aœ_Oœç�b¨š-Ì97í¤¾8|ûõ‡¯$eÑt|p ënN¬ä¸Ó|»ÏÇø¼ p;bª8ÙˆeÊœ‡zxHu®˜\ôei'¥8•xï«]eçkQ VÓ@¶ÝoTÓ©ÂêÑ›“ÎÂ? ƧaÀ®| GòþjöîæÚ|Ž9§t�9Ÿ+l“'ÆeÂ|Î�ËÓˆ-õÇ |5í<¢tGÁFyCapɤyþ`TãÕt ·R±ß¥µ—xélÛÅœOlêƒ Z'_âkª?ÛîßÃhಷ„Æçª;*˜—Vl©/n\>a®/O;�(ma̶‹1DW9ŒvÊ¤æ €lÑo2¸%í<¤ö¹se*�Í,,s!›îÿ�;ŸÊÊÝa><µÉTœ/• –lŒ¡xúý®i�Æœûœ�ÅÀ¹0ʧ¨ƒ tÎI;©yá°õ\ŸFàΜ:ÐÁ׿Ú}H‹÷¼ÂWºóñ.\´ð‹uR_¦ÞìÝîÜ”t\©/î\Öhsÿ­6ÕaJŒ!^òaÑ”W@)§!µí�ñWûKI]2ÓÞ�ñý.óΊ"^ïQ©›lÁëpàˆ¸ ŠxU ¸?•¸R Ê™Lã=ý›qv¬ãÃwã8¼. ƒ/¦�ƒÔ´EI\<Ã&„ÎoèyêÞ”+£<� °�×ŘsRÇLûBT1+&ÿç õ#4.i´¹ÿR«L�1Ä3™uƒ?òwSê¦Èý/ÀÍiç!5+’}±•*Ͱ}‚€›€m¼8ˆ¶©ÕÄ6¿Ö`ñ@×™óÕŽ‚Eòæ¡R§¡^íJ¤º¼ÜX+ÿBãKqŽoΗâz»Y7€y¼¯Y¤~¹‘ØëÿŽ‚á·;TpùòÜ\¿;†4®¨à3øj©`?i/XÜ'“àArR_¢ÞÂV :Zí]F¬m¸—>³’_Ä5x]Ùv¿Õà÷iç!µÇB^‰;ÆÂSlX©`_êý;¸E%ŸqcN¹X™9Tx`–éY¸aQÁv�#—×Q3 yƒWÃLcmén/XãqÆpçSSoöî¸Æ¯«ÀÎ4(§�‡Ôƒ]ã<¯c†M±Š;½§/EÅ+ì3Æ5qä3ñJªZp75‹:[ícœkñý»Ù#¶±¥n9œ×h=ÿ'ÂG Þ×øWåÛýOq�uXLœëèô1y7>9n,�­vb”7¸Ò Ë• vIpÏ þ±¯}e«�çê‡`“»ú0ãÇ��,/ì#QL‹ ¶kgÁ. Žé©o+×Íá5µ¢T°m ¾×ø¯v÷²+s¯è-bM¹¿`;µÀrn»*ÕéžžžÂX‡opÊ›³Æ6À6ã€�™[®Ò 7.œË²E_Qí‡l«p0Ëà=€ & ‡;óE?p0Ÿ­DçLû0Î…CbÆ%nÌËÏõ%Õ~¸T°Ñ!cp¼Áá5úwá9àQzN+\e°Ê{ß š³™#Æõþ}~34s’ê9|:_ôóÒÎ#J�­v!Ƈãßœs²íû”I]¥‚}Õ#Ú[ݤ^nqcaàt‹‡<ÐZôЧWVi#ÖoÆîa†CÌùiŒ¹šCGw¹q—•YÔðL <›-úË‹N´Í[Ö²°mhä�½Í™¼“�·ö ̸(׿±}“X2ËCîˆh¸ð7îÍ÷yÈåa¼4ér_U*ØðL†1]]ŒÉdØ­ û™s°?µY„_ãηZÊ,›0ߟ«æƒË�³1ÝÝLaÆ^æ¼Ø-¦<›Áƒ«9û¢Ö• ¶ŸÃÄôÝà/BîÀ¢¿ÇøŪ×`Å ¶åúõ¬p›v.õÂ`1ΕpóÏpWT‹K:fÚÏÌ9%бŠó­\»Ÿ×ðKfØa@Cí©ŽÈÊ®.öØû*!ŠÁl׌sÆ{�wEqØ$få‹Þ–vQ¹£`£¶„…ÀÄØ‚GåÚü·±�¿�ØMÅm÷Ë|u©`_~”v.5î1ƒ_2';Ï;£|qÁ&eàCõYFÆËŒHn@ýÉ gUÛúàº6fØ0¾HDs¨“‹þà"à¢ÅÇÛ6ÖÍ1æüñ6iwçÛ)¦�D”¶t¾ƒÅwów§˜/&só‡:\¸¡W·ánSGîÆ8ní6ì–-úÿÆqóÇÌøA�Îý¦.îÞÝݬŽsü:wÚ’ùŽ„I—ûª|›ÿ2Wôi²—뢎ÓÜ9�z}Å܇ނ�Åwà�Á‹ÃZøL\ã÷¥® €)x—AòíNk˜Ã�‡æŠ¾_®ÍçL¹À»âŠÕ9ƒ“�Ãâ¿ĺ ,讬A“\g¤ü<_”oóìœ4Ì>w�lÑŸÊýaÈD¼òM ¬ÛàŒ´“ˆJ{Á2å.vŒ1ÌMù"Ç8~Ÿê¾ÀÝËð‰&n´Þàlƒ½òE¿*‰WníË”Ë\L…ÝðšX¼7è¶‹uü`ðå%³,ŸD¬IóüÁ\»‡qPõöÓ†aœŸ-z)í4¢’u¾FÏvàX¼jpJÓ%õ_“оççiç‘4‡; öÉýËIn³éý15©xõÊz¶Æ&,Ç;~ƒ†Ì¿ïÛ:©€¹6¿y5L6øN>˜<µÖ9'í$¢Ò9ÓŽÅ8=æ0§¦_I¢À8 X™v qs~¸nÞ‘t¥�Ð?ˆ†à°ÏÂS¬â¶ÁU3ÞÛØ�e�áÃ(&u À�E5[ôÓCçpàɤâ¦Íáô)E1í<¢Pšaûà\BŒóþ×gÛùq\ã¤a €lÑŸÇšbAà*ƒ÷gÛýSq.ðëËâ‚M‰ûDƒ9ê¹XŸÒUTÈáˆñÜÒ—|»/hɰ/pkÒ±Sð—|;—¥�DlW~K¼�®VuÁIiî”h˜ —åÀ]i磇Ã�ƒ²E�候MY:Ëö zNÁ«ÅÎoµË8*ŽaKÛØ;ޱ•ÃçK‹­1SÆÏñ'ž}–C�øŽuM›AÙà�°í¯ã8Û¾þà°S¬�œ�íUôÇc�1€†*8ÛÃ>„i§ƒNÏpȤy¾4éÀ¥‚í\¹Ø>éØõÎ�bw6zS5‡otδD÷ZL½Ù»³í|Ø­±ŽÄ}Mhü$[ôûÒÎc¨–gc¬›ÆÇÈ™“k÷¹±Æ¨@cüsA`£UÚwuuqpÇi.*Øx‡?;'»AìÞ1Ãö�|Tgväc6 绥‚�–|\÷|›Ÿã4Üšgº×ó¥´“ª…Ûª»›ë€\Ì¡êꎯ¡P5®0ãLgAà"ƒ#£êk^�RÁöké™»|kÒ±Ið¹(Ç+ìÝÀ^QŽÙd‡•Zí<Ì‹’/úwéM€Ái|ŠR©`o ·8L‰9Ôzƒ™µòûÕ�@¶èÏ»ñÅ´óˆÀÒr7Gd‹þ|Ò�—Ì´÷;ܬֆΡuqÁ&E8Þ9Q�ÕÌÜødç .^q¤%~¸O¾ÍÏqã{IÇ�ÁíÙv~�vCQ*Øî·‘DQmœ™-ú_c�S¡†,–ôô¨ç�+3Þ3y¾?“dÐÓ¬¥s¦}+tæ£Q øZ•ZíhzŽá•(X?šÛlפCç‹|Þ½®Ëé"àcõ¼ðoqÁ&9ÜBG>ü>WäÿâŽS�†-Z‹^¶�“©Ïƒ:º fN˜ã%ôþ‚í4f,7✎˜Eí}¥V;~(,�nÛ¹ñÓ¨’S2°°·¸J0°{8ŠR§} ¾�›ë÷§�Ç`u옠çÉ?ο¯y8±ÖŠ¥†-²ó¼‹æÉ+QÆé٢ߔ\<³Î™öáè0xGbq›Œç/:ÖÞ<ØÏwgø °C„)É¿lãÆoJ­véòãlLRA'_âkœdO€‹HiøË|%í$ãµ·œW’L;óu23�©Ü�4t°vk¾ ÔM•êpm®Í�T¼EßÙÊM8‰µKmR[·d(.<ʪžZé(اÌ(Ä‘”ü‹'twS*µÚñI-ù2¿¡¾N CøÐî×zݽ]½·`cnj剾åtNËÎ󚜎nø ÷Èàÿíš7H/„eNI"ÐòãlLg«}3‹P_ÿÄ88j$ÅÓ¬¥ÒÏtl¦¡““â0Ö�Ë:[ùk©`‡Æ¯÷FZ?��ó&½îN`-µÚ{†Ã}‡'Ôùq®Ý/J,^•¾èmPQû+n��M¾Ò‹3Ä’cm‡Ž™öõ®nÂ8gå=¯‘uÓ¯ Žíon°T°ÏßvHìÙ¤{qþoÄÚ¢~ý]*Ø~^û»–ÜàðD×' Q©ÕŽî]8›ôÚ™‡×ÃÛ÷)ú³ Ç­JÓ�3íßqþL�=M”=`JÔ+j;fÙ¿Y™Ùô´�ÍF9¶Dæï!ÌžTô…¯}aÙѶEy8ÿçÆÓLLúõ‚WeàŠçæÖ¢ýÈ_3+µòhìýç‡Âùy®Ý?’v•X\°Iß482…ð/[È;²óüÞbW¥© €R«�çÆ'ÓÎcC¿ÈýCCgÙѶE×pÞi‡™s˜CdÍg$VÝnœ·îU¾4r‡áüxKÚIÉÀ žnn nÌÏõ;VgÁ~$ߢ¸2�­…|­õ{Ávj�/œœÆ›3ƒ2αÙv¿:éØƒÑtÀ¢mó–µ,vH¼ñÇ&Ü…±Ð�å,ž²2«†�bÕî—ùê^u®Kïg›îáŒó�q™ž§…Ý{oô{ÿF�½Ý�ª<l›v2$Ï÷,v§Ã�'ƒ�'ÌyjÔ–¬Úåb_ûÚ…+Ž´ëG³M°�9ÛGõ®N¯9î¼/ßî¿K;�þ,�m»”»ù¤u•Z"ÎÇsíþ“ÔâW©é è™ 0çÍ­ŠˆôpúÞçÆù6ÿhÒùT¢£Õ2ã3ǤýýÜœïfÛýóiæP­¦,:fÚ9æœ�v""5ìïoËýå´yÍ¢é6.“aÆ€ýÒΧ׼\Ž™œíuu}ÓœkA©“›Þ™v*""5ÈݹÂ~ZrîŒd±ã • ¶mÇ084í§ý 9üù%x÷�E5í\ªÕ¼Ð1ÛÞbeî¶I;‘ö’ÁŸC¸Å”B X|¼mts0ÎTëyHÛ»–núøÛˆá¶ÑZ­:ÒÔ@©ÕZÝêúD.‘D¼Â3:Ü霜GÖ ‘<^†Cáæ*þ)7×ïÆêó|k‰Ý£ÀÔÉE_–v"QQ°�’óuàOiç!""5嘖-úŠ´‰’Ö¼N©`Û:Ü ì–v.""’º‡2¦M˜ã¥�HÔôàu²Ež€éÀ+iç"""©Znÿ¿½{²³®ï8þþžÍf7�H¢Dd )E³Ù€š¡(j…P {‚¥µÞmEnvl;ÓN©ãt:¶¥• Eq“®¢QAëÇP’l‚MŠ`I€0!—ÝçÛ?¼ Ä\v÷wÎyÞ¯2dvÂ'3»yÞç9Ïsxm7üÁxVså#éˆÇ^J’ÆÅ÷GGxÍ@+ÿ·ô�ñþ;îlÝIDATb<‡�%y5ð‰Ò;$Iî–€�¸>×–2ž €�Ø<ƒ&ügé’¤ s]ßÏ8­�€4^ €�˜wYncÍ€Ko‘$�³ä_æÌ¡yØÒÜRzÊDð.€]°¼Ç6àv`ré-’¤1·-ƒó祥‡L$Ï삹­¼ƒàƒ¥wH’ÆÜúHN©ÛÁ<°[V,ŒK#y_é’¤1±&œ6¸(W•R‚gvêäà¦Ò;$I{íËU/G×õàžØmËN‹}úûù:pté-’¤Ý¶>à/–p95?{`Õ‚8 êáà·Jo‘$íšH®Ú|ð­\WzK;0öÐp3¾Ì(½E’ôÜîlÀ‡ZùµÒ[Ú‰×ì¡�VWpP‹ûE%©ÝÉÎá(þ¿Î3{iåPœEp ¥·H’ àÁ .Þw>yÈgrsé=íÊÃÍø›„—Þ!I$+¾œÁy@oé9luÿØH®håÖÒcÚ�0F†‡âÓ¼³ôIµöÀ{d+\~f¼¬§Á?%œZzÔ8«€¯6‚OÎàó\”UéA�Â#KšÑ3;¹&‚fé-’ê'`]ÕàµÏ¼¯}x(^Gp!prBO¡yãá'À�Q®˜}]Þ_zL'2ÆÐp3&WpCÀüÒ[$ÕGÀãÑà¤Ù‹òÎçúš»ÄKz&ñ’w‡Lܺ1õÁ�QqýÊàö¡VŽ–ÔÉ €1vG3¦Lƒ/_z‹¤ZØÉÉKò›»ôÕ1<ÄQUpz$§³ÇwÞ^©€»#ùj7 ò]Oñ�`,kÆ~}ðµ€W–Þ"©«mŽä÷–äm{ú¬>+åõÀ«#8>á 1Ü·»F€a‚o_ëíá‡_“�ÜÓÕ €q²üì˜Ñ³�[æ•Þ"©+m%8sÎâ¼y,ÿл›qhŽŽ`�d˜0kŒ¯¨Øþþ½À�"¹3{¸sß),÷¶½‰cŒ##@Ò8Ù04ÐÊÏOÄÿlÍüèÙ�F+J8(*Œ`ÿ*è�d0•ø•[GIž ÙFðh�6*Í�T£Ü?e?>liú!j…ãì®fÌìƒÛæ–Þ"©+l�¤9°$}2©öŠ<Î^ÑÊu[àuËKo‘Ôñ¶5‚…ü5 € ðt$<ç-:’ôl&X0{qÞXzˆºƒ0AvDÀIÀ·Ko‘Ôq6&œ6Öü©Þ¼`‚-;-ö™ÒÏ� o(½ERGØ�É©ƒKò;¥‡¨»¬™}[§ò¹Üþ8aIz.kÞ8ÐÊ”¢îã[¶4·¬]G“àS¥·Hj[÷�Âñü5^<PRD¬hrQ$•ž"©}$¬¨F9åˆëò'¥·¨{m`x(ÎÍà_ñŒŒ$¸}3œ>¯•�—¢îf´‰ £É•@_é-’ÊȤտ‘·ù)yš¾âlƒ‹³•ÉIÀÚÒ[$M¼H>68È[=øk¢x Í,?3f5|�ö~D§¤±3’Á¹ƒ‹óÒÒCT/@ºçÍ1m[‹æ—Þ"i\=¶ã‰~_/=Dõã[mè¥7å“[fpz—•Þ"i|ÜÓ¨8ƃ¿Jñ @›nÆ{>L.½EÒØHX:²�³_~Cn(½Eõå€67ÐÊÿÈäDà§¥·HÚkIòÑÁ9¼Éƒ¿Jó @‡¸«3'C 8¡ôI{äÉLÞ>¸$¯/=DÏtŒW´r]ÀI.)½EÒn[YUíÁ_íÄ3hÕÂ8½J®f”Þ"iç>;ÒÏŸqen,½Eúe@‡Zµ ~k´‡EÇ”Þ"é×<•Áùsç奷HÏÆè`kæGß–}¹˜àœÒ[$ýBÀòªÁÂÁE¹ªôé¹]`åÂx#Ég€Jo‘j.�Ë7oæÂyŸÏM¥ÇH;ct‰w | 8­ô©¦Nx×`+¿Xzˆ´+ €.³r(ÞFp 0µô©F®ïá½/»>-=DÚU@Z}V>Zqp\é-R—{,á‚ÁV~¶ôiwÝ*"†‡xOÂÅx6@_�?9²•–"í  Ë­~k22Êå¯/½EêkI>4gI^Yzˆ´7 €:ˆˆ•MÞMòQüð iOe$WOêåÂïÉGJ�‘ö–P#ÃÍx>ÉE|?ZÚÿ�pÎ`+o-=D+@ Åk.I˜[z‹ÔΞª‚è’¿?lin)½GK@M-{_ôö­ç‚€¿ö)½Gj7_lôð�—}.ï+½E@Í­:3~§jp0§ô©MlMxÿ`+?]zˆ4ž 1ÜŒç'|øíÒ[¤Â2“3}l¯êÀ ÁÄ@+Ëä‚Ò;¤Ònô௺0@ÿFn -½C*)ƒ/•Þ M@l�J¦ßª¹¨üP}øÍ.ªä Jï�JÊ'”Þ M@üEéRqÉ‚»›ñÒÒ3¤‰`ˆMÎN*½Cj½“àêáfL.=Do@Í Ÿ¯ŠíÏ�$ÌËðgBÝϨ±å͘› ¾ô—Þ"µ•ä‚•Cñ×¥gHãɨ©UgÅ`n^Pz‹Ô–‚�¬hƇJÏ�Æ‹ŸXC«ÎŠcªŠ›�ýKo‘Ú]$äB.ʪôi,5³b(ÞÒ®J˜Rz‹Ô)"¹jòFÞíÕM €YÑŒóþßú‘öÄwFG8ãˆësmé!ÒX0j`¸“.Þ^z‹Ôáî xÓ@+‡K‘ö–¯»Üê·Ä ¾‚i,ÌJøîÊ…ñ¦ÒC¤½et±UgÅ`5‰ÿ?ÞTCÓ"¹aåÂðÓ3ÕÑ|  K 7ãd`QÂ~¥·H]+øT$ç ´rké)Òîò @ZÑŒó�/xð—ÆYòî„ÛîjÆÌÒS¤Ýå€.rû‰1é…3¹4á]¥·H5³&à”�V®)=DÚU@—X3?ú¶Låj`Aé-RM=Üh0ö¢¼³ôiW]`ùÙ1£±�›�ãJo‘jîÉHÎX’·•"ý&@‡[ÖŒýúáVà¨Ò[$°µœ1{q.-=DÚ/ì`w¿-ö퇛ñà/µ“É™\»raœXzˆ´3žèPkæGßÖ©|%áµ¥·HzV? xÝ@+¿Wzˆôl<С¶ìËÇ=øKmmjÂM?lÆA¥‡HÏÆè@+Æyï)½CÒoôâ¸vÍüè+=Dz& Ã 7ãå‘\\z‡¤]pÌæiü]éÒ3�äÃÑþ˜TzФ]ÉùÃÍxyéÒ/3:Èʼ3áØÒ;$í¶I —ìˆx©-øÍØ!–½/z .*½CÒûݕÜZz„ô4 Cô?Æà%¥wHÚs‘œ[zƒô4 SC¥'HÚ; 'þèbÿÒ;$0:‰÷üK�oÒÈ6ŸÙ¡ö`t€U âà¥wHÚ{U0Xzƒ@GÈàù¥7Hø€Ú‚ж5ØPzƒ¤±ÉúÒ$0:‘­|ø~é’ö^Uác‚Õ €Nü9P•ž!i/W^›Æ¼Ú‚Ð!æ,ίœøüf©|c´�÷—Þ!=Íè sç%g?+½EÒ®Ëàê‘~N=âÊÜXz‹ô´Èôe§Y}V>ZqpBé-’vjm6¸8¯*=Dz& SEÄŠ&C‘üpDé9’~Å‘|‚àâ�V>VzŒôl €.°ja¼~4ùHÀ1¥·H5÷hŸÈIüÛÜ«ÓÛýÔÖ €.²jaŸœÁ™ÀóJï‘j"¾Ég#X4ÐJ¯ÑQG0ºÐ}ïˆþ�›xðG$§½¥7I]è~’EÙÃ僋òJ�‘v—ÐåîjÆÌ^89‚ù$¿~¬°´'Fîˆd)Á—ZùƒÒ›¤½aÔÈ’fôÌ�c«`~$§°ýâAo•žÛ÷d²4‚[¼ OÝĨ±{ÞÓª~^5 ¯&9®Ç%L)½K*è§ߊä«T|{à:†ñIu)@?·f~ôm�ÊQÌ#y%0 ˆÂÓ¤ñ°¸3ƒ»¨ø½|{ðš|¸ô(i¢Ú©{ÞÓFû8²‚y ˜ $Ì&—Þ&í†õÀp$Ë–E²ÌW÷ª;@»m¸“G+^Òèa0¹ýׄÙÀ>…ç©ÞÖÃÀÊ„áž`åÈ(÷ν6ï-=Lj7€ÆÌŽ‹ Í`vTž f‘Ì 84á ¯ôFu…‡€{~\÷keu£ÁjïÁ—v� ‰ñáhÜ}7öNbV&³ÝìˆÚq«ÝÃÀerßÏô î�:…ò™Ü\z§Ô µ�ågÇŒI£”£\58 QqpÂA˜ð"àEû ©Ö�k#y0<”ð É= ~ºµâ�Áÿ µr´ðV© uœáfL­¼(+^Ø3+˜ ¼¸3«`ÿF2=a:0ƒí¿NÇkÆÌŽWéëÙ~ý†€õlˆä‘„u‘Sö#Ø7`JÏ#™ L ˜–ÛŸ­ÐÃö˜ˆ€þN8±ã`ýÄŽÿÜlžxª‚��GòT›6$<›"ØP›Éle½¬ïÝĆ—Þ”Oü+I#€´—~pFLïÙ‡˜´™þ‘Ø f<óë&ůÿÞ/™šÕög6TÁ†žàY0G+6e°åW~³Ú~`ïí¥ÚÖàq€žmlhåÖ=ûIª@’¤òsà%Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤2$Iª!@’¤úÓæÉX“îIEND®B`‚qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/icons/qtea64.png000066400000000000000000000041611525155022500231040ustar00rootroot00000000000000‰PNG  IHDR@@ªiqÞ pHYsØØú\¦rtEXtSoftwarewww.inkscape.org›î<þIDATxœí›}ŒTW‡ŸßÝÙ]°Ph°¦-�™å+Š]ØX(…Ö4iJ)3ƒMP)¨� …4RS¤)JâGµÕb¤*ìì‚’(h n¥¸´Rl,3»TKÉÒ¤@ÁÊÇ~ÍÜ×?†ÝîÎÎîÎ.3sÑîóßœóžs~ï›{Ï=÷}ïÈÌø0ãx-Àkú൯é€×¼¦?^ ðšþä}Åõº®‚®ÞžO.Ñ€†&' ¿cø$ꉿËÞNµ=ÒÀ!ÆÄ*3Y0I5óÙnbQJ=ð7`^ïüÈ#ƉÙÃRÚ·*ì= ×ësZäãAÛr&Ò#̸?çàäߨ¿»²ñRi0:ŸÂò…ÄS……¼Üו�·äMU~™¨;Gp:Ob<Á’ûX—8®q"_b€}�\w‡\h”E™� DlÀ›è¹–bª‡ 'ìpa±àå¢K̳ךbA}Qš¡�À¡«Z?�FïécppBJ{íÙâPÕ�‰Ûí²ŒŠ.¬+‰ØŒf�2»|M,¯»OÅc÷ØE›0ž« i«àiĆVçëéF‰/f4­±¹¥…�"6‹dz¬³¼ŒX"µÝu˜ÖÞ,gÇ ­øy.ކµ¹ÎÊm)Æ– ÄNnÄ�š�æÇÂ*“(•ñÛ<¼h0#VYMH_hl毷÷4¡`­¿ÂÖ j¢!Ö6àÞ4f®ãv‘Üq:d¶ª&î²úðGì ðZÚÅ�Gýp"ÔFÞZz ŒvE©Ó] ŽO¨ *ã-S ¦¹¢T02ƒ¹.a´Ä‚ú^Ó Þ’±$­NØ7¾ÒŽwêX/ãî¶ßÆO“~¥d…k‚Zhâ—ê‰w ËêjÚë» ö f›QVRaÕGçkœãpˆ,ÇeÌöWØþÔö”³Î¹âKŒ³×š:)Μ£èÁ^b°µÕy$¹Æ2ĺ’ˆÍ~(‡e­¶*í˜,+�ÆêtθíöO¶î?�Nc3«, ê ÄŽ l  Ê€�´v8ƨšù àp“äQæ`œ›ÝNÆÂBÆ�\—F‰[SæþðŠ`°ÁÔtZS1ãñtíÑÝî–9Öp3?iÓ™n@ „ˆàH7k]‘±Ò×İ@Ä>+‡'”’Ë7±Ü¢/ æÍþ .8qÎ'�xØàU9üñùöã…æ°Ê±én!ÃM<tY2Ø[Ra/¥¶Y¦B¹l'ùø6ĪO=kmûWú:Ý:s°LÐéQ"8+˜ê¯°ŒÝckÚíºì1(è2\I�kCÉM(QÌýÝÙ¶ÚËe_í•Nø•]()·ïÈåND§ì… Á\V¤¶ i`ñ"Àô«†›åöÇc»+�ÅÂÚ‚±*EØ· \"&&›Ã<Œ0=d^Û =íÂÁSd^9Š›xÁqÙƒˆ™¨Ä˜ÔÑ Öú+ì»íÛjBšeð}’Yo€ª³g¹gf•Å;Ží&'—hÀåËTS2ë.𢌨Áû‚[MÌƵü½ÈǽŸüµ�KÜcq´&¤1–ÜÒDÿ8,øœ?bçÓuöX«÷G¬ÎŒ…@¼'Û<Óm&S�0ñlbwuå<ô¢<~õ€´�ëã«’×!è$&1×`,É"� Ž"ª ÊSóéèÕ±°–b?qg™Âb`|Fž=ư ~�¶SÁÇ‘öF6Wå±ù=pF1•�PcÜð©26çÕ·è«…>0 �5r3ùFWãœÂÐ�0É6¬ŽZâ+´pioän_ß‹ØL*Fa–›ýjð‡šõ×nlü KãÎ¡Úø%c”;T«Ê?¸µñ Vøb%…�Îìÿ{È­�Qx¯r’F'>›ƒnó�×+)f¢]½îÛÔ ü¾’jF!û6êQ·™�-¼VI5£�‚:tõ (7ZX‡6v‚X¥´ŒR jOsÖ:=¼‘7gW(¼\H~ÿßíÀ§Ê/gÔa×ø-ÀÞË%Ð{ÓÕÇ4±1j8Ò×ËÎÙëõpª�¨*íMò/(?ðFóñƒÀn~Œr%p!P—q>¡ð’î¨oÖç¡ß1K.QxÆ ÑÇBêLuæC…åáf½ST•–L¨s^ŸGÌ$ýñ€.5 ýèðXÏÈGù¹Úœm×0)3¾ šÿN’Pn˜�‰5Ê=*î¿âUIG•ÃÂÉ�M¤¦ÇʹjØÌÇžTÞ¸åØðt¥E–Àû K�Í^ É…¿Él|€`‹nSá§9Ì& 8 ¦—M@_¥‹@†«Ã} »›Ëvy­)2D6 Îq*>à€3Óž+·°RQxrVD74lÔ£*,÷ZS´þ;×É®“ø-ГåÔ;i£Ö—[Y©¨ð|êq��M^iɅ¶³#úV®ó +µOœµL:Ò ¾l?aø‡£ üJ«ÀæSa òm€£]Äk>i÷¿Ra0E”+€?>Ù"lÈ—G�ߘÉÎ4Ô¯Õýí–¼„—9lˆrW0ª·'�wÜ 5�Ã,åÛ¢œ›š·ÖÏ_öÿ’W`�Ñ�É�¶Er†Ø kh! &Áº¡2ìž'ã SåÙÁ=]øO•¾+° aðBf/-NO=nX©}áf½ åç W·/’³ž»Xü*ܼ]ãgnjã`3­¯ < °l¨k [òÅõÕ2‹ÁAlGëþÄ–AÔÐ ä›Ñ9›_‡šõ¡ˆ~!a3hq!6+W·.�Añ›êç{€›ÇÛ,¹tòdÖsî›ñˆšw¸µ ¯ Ì F9#Ñ¥]¹K�˜ ¡QV¹(ûsYÒ^œþ¤ö rÀôÕzD%ïÃXÔðHÌ’)³ZôµPDUøf^ÁYPã÷±¡c�LMM?ªo ìǹ¯ß„ú ¶§°\LÌ’ïWS?°¹ >ŒèFTó>÷gç±;É[º0?3I…Ç wpî…ÆÝ�t¯Ú|9Ü¢¯$Ú-ù1p‹ ÛlRa•À±©C¸La�Àœ`D_~îbñOžÌ+âÌä=¤†}¢|ʆkÎ)²Î?ˆÓø‡ö.–{{¸W…Åù UXnÖ¯•§íù„‰ó–BjÔ\<çÔ³Öé�œáém–ìpù£l„µj³Ævú�O®ÿK‘£�×v*Ôçv3¡ÆÏää-§Ý’�À—¶xCá4à<й)Ü„Ÿu’`ºØ\ŽðµŒõ9MÕfv¾0ö˜%×(ƒ^ÄžEôJÈþ}"É põ@6(�"4úÈ>Örɇ*Ü òHrÅÊîy2>`wâÜN¼¼[žqµ†@¹ óñk„{þŸËÎ@3ð¶{I¥¡ðåp³®N].t(@˜¨ðààzGãRmÏŠèîn¸†uº"_†¨%>®HMSh«�|<÷’ÓÁˆö*Ü]šF×¼Žè Wù °¨S¸9Ñ¥&Á¹ÀA–²\Ò´7Dôî±;ÂQžÌ—/ätŠÓÒ•e¤Ü÷‡¼oÖ}ÄýÀŠÔéQ^ÈLëX$ç)üØŽèOê×ê(Ë€ócíü‘´‹Ûhúg‹J¡Âí¸XÛ¥ðÏIÛÃ-é#̼kÄÚšä«¢gYÑU Ô¢ük(ªßOfl] Ÿôùx³ÿðE…•ÆfÂ5,BY”CK Ê›"œ¨ÆY5Ô30+›‚½(_¾˜%W)ÎP³ÛæÔ¯Ñ­©ùò èP Â?õnE*üF„;CÍúb2m×B™i _Éa2S…û ƒâ"¤E0–÷S>k͘£Éëx¨¾¤t„¢ú�äaÇ™ª†[TøG2&χ*ÅVnË—)fÉ”þ¥^©ü"³ñÁÅЭ1¢ UnÂÝ'ŽpK8¢—¦5þµ2ÑÖedL=ðw÷¿Œˆ·µ5Ê—’Çõku0ª·‹s%¸zx«ð`8ª/ •'fÉ8…(0%%ùµ@mö—TWcçpTŸÊ«Oùz¨YïMMì\$3L›)à J+µÎ—�Ov‘Ó¦ >ZÚeijz0¢±D‚‹Éþ½>•ƒµ¾A÷ô4:çËI O‘þ1³Ol®™¾Z�d³q½NxÏ5rr_œr,¢eu0ªK’Ç1K¦ÛÂ�¢ÜBq=?•͉8 |5\_¦ø¥gîn‡§“ÓˆmMò�(×å´þ6Ô¬9;a{“\&Ê™ËvE¹1ÕÌÛQÊùj·YÒ$°&ÇéN…×€Z�¤¯–/�.uV+–“�€ß)gpð™•oïîâ¢Ì°ó–L—õw² ²Ø­5ë7†PðJù¶&¹_” 2:>èSgË…8 [¦ª³b4ë@F”_Ã|-ß>;`ïåèÇK%|ü:þ~ rƒ›M@ŠÚ+¢c¡|Ú6¼ŒÓÇ8*pg0¢ßukPÔÄú}Õæ*Æ~$PÄGÅVU.)¤ñ¡„É÷ú5ºU�·Îc.–¨d”Gý>.VØÀÃS�¢Š2»¸^%ïÔfÉ�9~{ŸêžÈ¼†•Ú°ïz©ëêb¶ÚL³a‚q濉¡óÝwé,e§(Ó†Mm–\màá ‡›–±cY’ºEM¥)K¯ Gt½.‘¼è[”…B4 gã;õ–qϸÎE2#aó8΋ØH¡WàÖ`DæEåe½oÏ\£{ŽÀl”<ÛÏ- mbsžW�Ú5 fÉçVÓ+RAiÄQþC„ï#Úë¥�Š9œ�ž^ÖãÌç+|$6lÑm^ � ûƒ¼ ÚÓsèÅPðÖb•¢¢ˆYò-Q®­dE0IáñÎùr’×B R· åbÚÛøÂÍå/¼ltú|Ì�ù¨îóRDÙ°÷r ôŒãa`AY ® o«ÍÜáÚ¤5e¿õŒã‡ŒŒÆøs1<±ëZ™è•€²:`ÇUrðõr–9 œæëÅòªò²:`L޹QÏ�$lá€Wõ—ÕÁˆ~$NÐÓw�}å,»EˆÚ6ç„#êÙâÄŠ¾ˆí²¤Á(`8å³§gÄÉ'~'Ê65líîâ™Böv«u@&1Kj6Ó|ƉšPá §åNg‹àä?7Æ£8{18¢pX…wÄæ€À[À;¯{“ 0Ž5†ÕÅÒz�Œ•„³Åý¬G8ì&0v¤0"p All rights reserved. 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 in this position and unchanged. 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. THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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(S) 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. qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/shaders/000077500000000000000000000000001525155022500216065ustar00rootroot00000000000000qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/shaders/crtea.fs000066400000000000000000000237271525155022500232510ustar00rootroot00000000000000/* MIT License CRTea - Configurable CRT Fragment Shader Copyright (c) 2020-2022 Rupert Carmichael 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. */ // Based on Public Domain work by Timothy Lottes precision highp float; uniform sampler2D source; uniform vec4 sourceSize; uniform vec4 targetSize; uniform int masktype; // Mask Type uniform float maskstr; // Mask Strength uniform float scanstr; // Scanline Strength uniform float sharpness; // Pixel Sharpness uniform float curve; // Screen Curvature uniform float corner; // Screen Curvature uniform float tcurve; // Trinitron Curve in vec2 texCoord; out vec4 FragColor; //#define CRTS_DEBUG 1 // Define to see on/off split screen //#define CRTS_2_TAP 1 // Faster very pixely 2-tap filter (off is 8) #define CRTS_WARP 1 // Apply screen warp #define INPUT_MASK (1.0 - maskstr) #define INPUT_SCAN (0.5 + (0.5 * scanstr)) #define INPUT_SHRP (-1.0 * sharpness) #define INPUT_X sourceSize.x #define INPUT_Y sourceSize.y #define CURVATURE curve #define TRINITRON_CURVE tcurve #define CORNER corner #define CRT_GAMMA 2.4 #define CRTS_TONE 1 // Normalize mid-level and process color #define CRTS_CONTRAST 0 // Process color - enable contrast control #define CRTS_SATURATION 0 // Process color - enable saturation control #define CrtsRcpF1(x) (1.0/(x)) #define CrtsSatF1(x) clamp((x),0.0,1.0) // sRGB-Linear Conversions float FromSrgb1(float c) { return (c <= 0.04045) ? c * (1.0 / 12.92) : pow(c * (1.0 / 1.055) + (0.055 / 1.055), CRT_GAMMA); } vec3 FromSrgb(vec3 c) { return vec3(FromSrgb1(c.r), FromSrgb1(c.g), FromSrgb1(c.b)); } float ToSrgb1(float c) { return (c < 0.0031308 ? c * 12.92 : 1.055 * pow(c, 0.41666) - 0.055); } vec3 ToSrgb(vec3 c) { return vec3(ToSrgb1(c.r), ToSrgb1(c.g), ToSrgb1(c.b)); } // Fetch the input image colour vec3 CrtsFetch(vec2 uv) { // Scale to get native texels in the image uv *= vec2(INPUT_X, INPUT_Y) / sourceSize.xy; return FromSrgb(texture(source, uv.xy, -16.0).rgb); } // Get the maximum of 3 floats float CrtsMax3F1(float a, float b, float c) { return max(a, max(b, c)); } // Tonal Control vec4 CrtsTone(float contrast, float saturation, float thin, float mask) { if (masktype == 0) mask = 1.0; if (masktype == 1) { // Normal R mask is {1.0,mask,mask} // LITE R mask is {mask,1.0,1.0} mask = 0.5 + mask * 0.5; } vec4 ret; float midOut = 0.18 / ((1.5 - thin) * (0.5 * mask + 0.5)); float pMidIn = pow(0.18, contrast); ret.x = contrast; ret.y = ((-pMidIn) + midOut) / ((1.0 - pMidIn) * midOut); ret.z = ((-pMidIn) * midOut + pMidIn) / (midOut * (-pMidIn) + midOut); ret.w = contrast + saturation; return ret; } // Apply the mask vec3 CrtsMask(vec2 pos, float dark) { if (masktype == 0) { // Scanlines (No Mask) return vec3(1.0, 1.0, 1.0); } if (masktype == 1) { // Aperture Grille Lite vec3 m = vec3(1.0, 1.0, 1.0); float x = fract(pos.x * (1.0 / 3.0)); if (x < (1.0 / 3.0)) m.r = dark; else if (x < (2.0 / 3.0)) m.g = dark; else m.b = dark; return m; } if (masktype == 2) { // Aperture Grille vec3 m = vec3(dark, dark, dark); float x = fract(pos.x * (1.0 / 3.0)); if (x < (1.0 / 3.0)) m.r = 1.0; else if (x < (2.0 / 3.0)) m.g = 1.0; else m.b = 1.0; return m; } if (masktype == 3) { // Shadow Mask pos.x += pos.y * 2.9999; vec3 m = vec3(dark, dark, dark); float x = fract(pos.x * (1.0 / 6.0)); if (x < (1.0 / 3.0)) m.r = 1.0; else if (x < (2.0 / 3.0)) m.g = 1.0; else m.b = 1.0; return m; } } // The filter function itself // SV_POSITION, fragCoord.xy // sourceSize / targetSize (in pixels) // 0.5 * sourceSize (in pixels) // 1.0 / sourceSize (in pixels) // 1.0 / targetSize (in pixels) // 2.0 / targetSize (in pixels) // Warp scanlines but not phosphor mask // Tonal curve parameters generated by CrtsTone() vec3 CrtsFilter(vec2 ipos, vec2 inputSizeDivOutputSize, vec2 halfInputSize, vec2 rcpInputSize, vec2 rcpOutputSize, vec2 twoDivOutputSize, vec2 warp, vec4 tone) { #ifdef CRTS_DEBUG vec2 uv = ipos * rcpOutputSize; // Show second half processed, and first half un-processed if (uv.x < 0.5) { // Force nearest to get squares uv *= 1.0 / rcpInputSize; uv = floor(uv) + vec2(0.5, 0.5); uv *= rcpInputSize; vec3 color = CrtsFetch(uv); return color; } #endif // Optional apply warp vec2 pos; #ifdef CRTS_WARP // Convert to {-1 to 1} range pos = ipos * twoDivOutputSize - vec2(1.0, 1.0); // Distort pushes image outside {-1 to 1} range pos *= vec2(1.0 + (pos.y * pos.y) * warp.x, 1.0 + (pos.x * pos.x) * warp.y); // TODO: Vignette needs optimization float vin = (1.0 - ((1.0 - CrtsSatF1(pos.x * pos.x)) * (1.0 - CrtsSatF1(pos.y * pos.y)))) * (0.998 + (0.001 * CORNER)); vin = CrtsSatF1((-vin) * sourceSize.y + sourceSize.y); // Leave in {0 to inputSize} pos = pos * halfInputSize + halfInputSize; #else pos = ipos * inputSizeDivOutputSize; #endif // Snap to center of first scanline float y0 = floor(pos.y - 0.5) + 0.5; #ifdef CRTS_2_TAP // Using Inigo's "Improved Texture Interpolation" // http://iquilezles.org/www/articles/texture/texture.htm pos.x += 0.5; float xi = floor(pos.x); float xf = pos.x - xi; xf = xf * xf * xf * (xf * (xf * 6.0 - 15.0) + 10.0); float x0 = xi + xf - 0.5; vec2 p = vec2(x0 * rcpInputSize.x, y0 * rcpInputSize.y); // Coordinate adjusted bilinear fetch from 2 nearest scanlines vec3 colA = CrtsFetch(p); p.y += rcpInputSize.y; vec3 colB = CrtsFetch(p); #else // Snap to center of one of four pixels float x0 = floor(pos.x - 1.5) + 0.5; // Inital UV position vec2 p = vec2(x0 * rcpInputSize.x, y0 * rcpInputSize.y); // Fetch 4 nearest texels from 2 nearest scanlines vec3 colA0 = CrtsFetch(p); p.x += rcpInputSize.x; vec3 colA1 = CrtsFetch(p); p.x += rcpInputSize.x; vec3 colA2 = CrtsFetch(p); p.x += rcpInputSize.x; vec3 colA3 = CrtsFetch(p); p.y += rcpInputSize.y; vec3 colB3 = CrtsFetch(p); p.x -= rcpInputSize.x; vec3 colB2 = CrtsFetch(p); p.x -= rcpInputSize.x; vec3 colB1 = CrtsFetch(p); p.x -= rcpInputSize.x; vec3 colB0 = CrtsFetch(p); #endif // Vertical filter // Scanline intensity is using sine wave // Easy filter window and integral used later in exposure float off = pos.y - y0; float pi2 = 6.28318530717958; float hlf = 0.5; float scanA = cos(min(0.5, off * INPUT_SCAN) * pi2) * hlf + hlf; float scanB = cos(min(0.5, (-off) * INPUT_SCAN + INPUT_SCAN) * pi2) * hlf + hlf; #ifdef CRTS_2_TAP #ifdef CRTS_WARP // Get rid of wrong pixels on edge scanA *= vin; scanB *= vin; #endif // Apply vertical filter vec3 color = (colA * scanA) + (colB * scanB); #else // Horizontal kernel is simple gaussian filter float off0 = pos.x - x0; float off1 = off0 - 1.0; float off2 = off0 - 2.0; float off3 = off0 - 3.0; float pix0 = exp2(INPUT_SHRP * off0 * off0); float pix1 = exp2(INPUT_SHRP * off1 * off1); float pix2 = exp2(INPUT_SHRP * off2 * off2); float pix3 = exp2(INPUT_SHRP * off3 * off3); float pixT = CrtsRcpF1(pix0 + pix1 + pix2 + pix3); #ifdef CRTS_WARP // Get rid of wrong pixels on edge pixT *= vin; #endif scanA *= pixT; scanB *= pixT; // Apply horizontal and vertical filters vec3 color = (colA0 * pix0 + colA1 * pix1 + colA2 * pix2 + colA3 * pix3) * scanA + (colB0 * pix0 + colB1 * pix1 + colB2 * pix2 + colB3 * pix3) * scanB; #endif // Apply phosphor mask color *= CrtsMask(gl_FragCoord.xy, INPUT_MASK); // Optional color processing #ifdef CRTS_TONE // Tonal control, start by protecting from /0 float peak = max(1.0 / (256.0 * 65536.0), CrtsMax3F1(color.r, color.g, color.b)); // Compute the ratios of {R,G,B} vec3 ratio = color * CrtsRcpF1(peak); // Apply tonal curve to peak value #ifdef CRTS_CONTRAST peak = pow(peak, tone.x); #endif peak = peak * CrtsRcpF1(peak * tone.y + tone.z); // Apply saturation #ifdef CRTS_SATURATION ratio = pow(ratio, vec3(tone.w, tone.w, tone.w)); #endif // Reconstruct color return ratio * peak; #else return color; #endif } void main() { vec2 warp_factor; warp_factor.x = CURVATURE; warp_factor.y = (3.0 / 4.0) * warp_factor.x; // assume 4:3 aspect warp_factor.x *= (1.0 - TRINITRON_CURVE); FragColor.rgb = CrtsFilter(texCoord.xy * targetSize.xy, sourceSize.xy * targetSize.zw, sourceSize.xy * vec2(0.5, 0.5), sourceSize.zw, targetSize.zw, 2.0 * targetSize.zw, warp_factor, CrtsTone(1.0, 0.0, INPUT_SCAN, INPUT_MASK)); // Output non-linear color FragColor.rgb = ToSrgb(FragColor.rgb); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/shaders/default.fs000066400000000000000000000023241525155022500235650ustar00rootroot00000000000000/* MIT License Copyright (c) 2020-2022 Rupert Carmichael 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. */ precision highp float; in vec2 texCoord; out vec4 fragColor; uniform sampler2D source; void main() { fragColor = texture(source, texCoord); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/shaders/default.vs000066400000000000000000000023141525155022500236040ustar00rootroot00000000000000/* MIT License Copyright (c) 2020-2022 Rupert Carmichael 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. */ in vec2 position; in vec2 vtxCoord; out vec2 texCoord; void main() { texCoord = vtxCoord; gl_Position = vec4(position, 0.0, 1.0); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/shaders/lcd.fs000066400000000000000000000035751525155022500227140ustar00rootroot00000000000000/* MIT License Copyright (c) 2020-2022 Rupert Carmichael 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. */ precision highp float; uniform sampler2D source; uniform vec4 sourceSize; in vec2 texCoord; out vec4 fragColor; #define maskstr 0.5 void main() { // Find out where in the LCD screen we are vec2 lcdCoord = texCoord * sourceSize.xy * 3.0; // Find out which column of the pixel we're in float col = floor(mod(lcdCoord.x, 3.0)); // Shade all pixels vec4 shade = vec4(maskstr, maskstr, maskstr, 1.0); // Shade stronger in red, green, or blue for each column if (col == 1.0) shade.g = 1.0; else if (col == 2.0) shade.b = 1.0; else shade.r = 1.0; // Draw a horizontal scanline at the bottom of each pixel if (floor(mod(lcdCoord.y, 3.0)) == 0.0) shade.rgba = vec4(maskstr, maskstr, maskstr, 1.0); fragColor = texture(source, texCoord) * shade; } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/shaders/mmpx.fs000066400000000000000000000245641525155022500231340ustar00rootroot00000000000000// MMPX // by Morgan McGuire and Mara Gagiu // https://casual-effects.com/research/McGuire2021PixelArt/ // License: MIT // adapted for slang by hunterk precision highp float; uniform sampler2D source; uniform vec4 sourceSize; uniform vec4 targetSize; in vec2 texCoord; out vec4 fragColor; float luma(vec3 col){ return dot(col, vec3(0.2126, 0.7152, 0.0722)); } // I tried using a hash to speed these up but it didn't really help bool same(vec3 B, vec3 A0){ return all(equal(B, A0)); } bool notsame(vec3 B, vec3 A0){ return any(notEqual(B, A0)); } bool all_eq2(vec3 B, vec3 A0, vec3 A1) { return (same(B,A0) && same(B,A1)); } bool all_eq3(vec3 B, vec3 A0, vec3 A1, vec3 A2) { return (same(B,A0) && same(B,A1) && same(B,A2)); } bool all_eq4(vec3 B, vec3 A0, vec3 A1, vec3 A2, vec3 A3) { return (same(B,A0) && same(B,A1) && same(B,A2) && same(B,A3)); } bool any_eq3(vec3 B, vec3 A0, vec3 A1, vec3 A2) { return (same(B,A0) || same(B,A1) || same(B,A2)); } bool none_eq2(vec3 B, vec3 A0, vec3 A1) { return (notsame(B,A0) && notsame(B,A1)); } bool none_eq4(vec3 B, vec3 A0, vec3 A1, vec3 A2, vec3 A3) { return (notsame(B,A0) && notsame(B,A1) && notsame(B,A2) && notsame(B,A3)); } #define src(c,d) texture(source, texCoord + vec2(c,d) * sourceSize.zw).rgb void main() { // these do nothing, but just for consistency with the original code... float srcX = 0.; float srcY = 0.; // Our current pixel vec3 E = src(srcX+0.,srcY+0.); // Input: A-I central 3x3 grid vec3 A = src(srcX-1.,srcY-1.); vec3 B = src(srcX+0.,srcY-1.); vec3 C = src(srcX+1.,srcY-1.); vec3 D = src(srcX-1.,srcY+0.); vec3 F = src(srcX+1.,srcY+0.); vec3 G = src(srcX-1.,srcY+1.); vec3 H = src(srcX+0.,srcY+1.); vec3 I = src(srcX+1.,srcY+1.); // Default to Nearest magnification vec3 J = E; vec3 K = E; vec3 L = E; vec3 M = E; // Go ahead and put this here so we can use an early return on the next // line to save some cycles fragColor = vec4(E, 1.0); // Skip constant 3x3 centers and just use nearest-neighbor // them. This gives a good speedup on spritesheets with // lots of padding and full screen images with large // constant regions such as skies. // EDIT: this is a wash for me, but we'll keep it around if(same(E,A) && same(E,B) && same(E,C) && same(E,D) && same(E,F) && same(E,G) && same(E,H) && same(E,I)) return; // Read additional values at the tips of the diamond pattern vec3 P = src(srcX+0.,srcY-2.); vec3 Q = src(srcX-2.,srcY+0.); vec3 R = src(srcX+2.,srcY+0.); vec3 S = src(srcX+0.,srcY+2.); // Precompute luminances float Bl = luma(B); float Dl = luma(D); float El = luma(E); float Fl = luma(F); float Hl = luma(H); // Round some corners and fill in 1:1 slopes, but preserve // sharp right angles. // // In each expression, the left clause is from // EPX and the others are new. EPX // recognizes 1:1 single-pixel lines because it // applies the rounding only to the LINE, and not // to the background (it looks at the mirrored // side). It thus fails on thick 1:1 edges // because it rounds *both* sides and produces an // aliased edge shifted by 1 dst pixel. (This // also yields the mushroom-shaped arrow heads, // where that 1-pixel offset runs up against the // 2-pixel aligned end; this is an inherent // problem with 2X in-palette scaling.) // // The 2nd clause clauses avoid *double* diagonal // filling on 1:1 slopes to prevent them becoming // aliased again. It does this by breaking // symmetry ties using luminance when working with // thick features (it allows thin and transparent // features to pass always). // // The 3rd clause seeks to preserve square corners // by considering the center value before // rounding. // // The 4th clause identifies 1-pixel bumps on // straight lines that are darker than their // background, such as the tail on a pixel art // "4", and prevents them from being rounded. This // corrects for asymmetry in this case that the // luminance tie breaker introduced. // .------------ 1st ------------. .----- 2nd ---------. .------ 3rd -----. .--------------- 4th -----------------------. if (((same(D,B) && notsame(D,H) && notsame(D,F))) && ((El>=Dl) || same(E,A)) && any_eq3(E,A,C,G) && ((El=Bl) || same(E,C)) && any_eq3(E,A,C,I) && ((El=Hl) || same(E,G)) && any_eq3(E,A,G,I) && ((El=Fl) || same(E,I)) && any_eq3(E,C,G,I) && ((El // .--------------------- 1st ------------------------. .--------- 2nd -----------. if ((notsame(E,F) && all_eq4(E,C,I,D,Q) && all_eq2(F,B,H)) && notsame(F,src(srcX+3.,srcY))) K=M=F; if ((notsame(E,D) && all_eq4(E,A,G,F,R) && all_eq2(D,B,H)) && notsame(D,src(srcX-3.,srcY))) J=L=D; if ((notsame(E,H) && all_eq4(E,G,I,B,P) && all_eq2(H,D,F)) && notsame(H,src(srcX,srcY+3.))) L=M=H; if ((notsame(E,B) && all_eq4(E,A,C,H,S) && all_eq2(B,D,F)) && notsame(B,src(srcX,srcY-3.))) J=K=B; // Remove tips of bright triangles on dark // backgrounds. The luminance tie breaker for 1:1 // pixel lines leaves these as sticking up squared // off, which makes bright triangles and diamonds // look bad. if ((Bl 0.125 || diff.y > 0.027 || diff.z > 0.031; } #define P(m, r) ((pattern & (m)) == (r)) #define uResolution targetSize.xy #define textureDimensions sourceSize.xy vec4 scale(sampler2D image, vec2 coord) { // o = offset, the width of a pixel vec2 o = 1.0 / textureDimensions; vec2 texCoord = coord; /* We always calculate the top left quarter. If we need a different quarter, we flip our co-ordinates */ // p = the position within a pixel [0...1] vec2 p = fract(texCoord * textureDimensions); if (p.x > 0.5) { o.x = -o.x; p.x = 1.0 - p.x; } if (p.y > 0.5) { o.y = -o.y; p.y = 1.0 - p.y; } vec4 w0 = texture(image, texCoord + vec2( -o.x, -o.y)); vec4 w1 = texture(image, texCoord + vec2( 0, -o.y)); vec4 w2 = texture(image, texCoord + vec2( o.x, -o.y)); vec4 w3 = texture(image, texCoord + vec2( -o.x, 0)); vec4 w4 = texture(image, texCoord + vec2( 0, 0)); vec4 w5 = texture(image, texCoord + vec2( o.x, 0)); vec4 w6 = texture(image, texCoord + vec2( -o.x, o.y)); vec4 w7 = texture(image, texCoord + vec2( 0, o.y)); vec4 w8 = texture(image, texCoord + vec2( o.x, o.y)); int pattern = 0; if (is_different(w0, w4)) pattern |= 1 << 0; if (is_different(w1, w4)) pattern |= 1 << 1; if (is_different(w2, w4)) pattern |= 1 << 2; if (is_different(w3, w4)) pattern |= 1 << 3; if (is_different(w5, w4)) pattern |= 1 << 4; if (is_different(w6, w4)) pattern |= 1 << 5; if (is_different(w7, w4)) pattern |= 1 << 6; if (is_different(w8, w4)) pattern |= 1 << 7; if ((P(0xbf,0x37) || P(0xdb,0x13)) && is_different(w1, w5)) return mix(w4, w3, 0.5 - p.x); if ((P(0xdb,0x49) || P(0xef,0x6d)) && is_different(w7, w3)) return mix(w4, w1, 0.5 - p.y); if ((P(0x0b,0x0b) || P(0xfe,0x4a) || P(0xfe,0x1a)) && is_different(w3, w1)) return w4; if ((P(0x6f,0x2a) || P(0x5b,0x0a) || P(0xbf,0x3a) || P(0xdf,0x5a) || P(0x9f,0x8a) || P(0xcf,0x8a) || P(0xef,0x4e) || P(0x3f,0x0e) || P(0xfb,0x5a) || P(0xbb,0x8a) || P(0x7f,0x5a) || P(0xaf,0x8a) || P(0xeb,0x8a)) && is_different(w3, w1)) return mix(w4, mix(w4, w0, 0.5 - p.x), 0.5 - p.y); if (P(0x0b,0x08)) return mix(mix(w0 * 0.375 + w1 * 0.25 + w4 * 0.375, w4 * 0.5 + w1 * 0.5, p.x * 2.0), w4, p.y * 2.0); if (P(0x0b,0x02)) return mix(mix(w0 * 0.375 + w3 * 0.25 + w4 * 0.375, w4 * 0.5 + w3 * 0.5, p.y * 2.0), w4, p.x * 2.0); if (P(0x2f,0x2f)) { float dist = length(p - vec2(0.5)); float pixel_size = length(1.0 / (uResolution / textureDimensions)); if (dist < 0.5 - pixel_size / 2.0) { return w4; } vec4 r; if (is_different(w0, w1) || is_different(w0, w3)) { r = mix(w1, w3, p.y - p.x + 0.5); } else { r = mix(mix(w1 * 0.375 + w0 * 0.25 + w3 * 0.375, w3, p.y * 2.0), w1, p.x * 2.0); } if (dist > 0.5 + pixel_size / 2.0) { return r; } return mix(w4, r, (dist - 0.5 + pixel_size / 2.0) / pixel_size); } if (P(0xbf,0x37) || P(0xdb,0x13)) { float dist = p.x - 2.0 * p.y; float pixel_size = length(1.0 / (uResolution / textureDimensions)) * sqrt(5.0); if (dist > pixel_size / 2.0) { return w1; } vec4 r = mix(w3, w4, p.x + 0.5); if (dist < -pixel_size / 2.0) { return r; } return mix(r, w1, (dist + pixel_size / 2.0) / pixel_size); } if (P(0xdb,0x49) || P(0xef,0x6d)) { float dist = p.y - 2.0 * p.x; float pixel_size = length(1.0 / (uResolution / textureDimensions)) * sqrt(5.0); if (p.y - 2.0 * p.x > pixel_size / 2.0) { return w3; } vec4 r = mix(w1, w4, p.x + 0.5); if (dist < -pixel_size / 2.0) { return r; } return mix(r, w3, (dist + pixel_size / 2.0) / pixel_size); } if (P(0xbf,0x8f) || P(0x7e,0x0e)) { float dist = p.x + 2.0 * p.y; float pixel_size = length(1.0 / (uResolution / textureDimensions)) * sqrt(5.0); if (dist > 1.0 + pixel_size / 2.0) { return w4; } vec4 r; if (is_different(w0, w1) || is_different(w0, w3)) { r = mix(w1, w3, p.y - p.x + 0.5); } else { r = mix(mix(w1 * 0.375 + w0 * 0.25 + w3 * 0.375, w3, p.y * 2.0), w1, p.x * 2.0); } if (dist < 1.0 - pixel_size / 2.0) { return r; } return mix(r, w4, (dist + pixel_size / 2.0 - 1.0) / pixel_size); } if (P(0x7e,0x2a) || P(0xef,0xab)) { float dist = p.y + 2.0 * p.x; float pixel_size = length(1.0 / (uResolution / textureDimensions)) * sqrt(5.0); if (p.y + 2.0 * p.x > 1.0 + pixel_size / 2.0) { return w4; } vec4 r; if (is_different(w0, w1) || is_different(w0, w3)) { r = mix(w1, w3, p.y - p.x + 0.5); } else { r = mix(mix(w1 * 0.375 + w0 * 0.25 + w3 * 0.375, w3, p.y * 2.0), w1, p.x * 2.0); } if (dist < 1.0 - pixel_size / 2.0) { return r; } return mix(r, w4, (dist + pixel_size / 2.0 - 1.0) / pixel_size); } if (P(0x1b,0x03) || P(0x4f,0x43) || P(0x8b,0x83) || P(0x6b,0x43)) return mix(w4, w3, 0.5 - p.x); if (P(0x4b,0x09) || P(0x8b,0x89) || P(0x1f,0x19) || P(0x3b,0x19)) return mix(w4, w1, 0.5 - p.y); if (P(0xfb,0x6a) || P(0x6f,0x6e) || P(0x3f,0x3e) || P(0xfb,0xfa) || P(0xdf,0xde) || P(0xdf,0x1e)) return mix(w4, w0, (1.0 - p.x - p.y) / 2.0); if (P(0x4f,0x4b) || P(0x9f,0x1b) || P(0x2f,0x0b) || P(0xbe,0x0a) || P(0xee,0x0a) || P(0x7e,0x0a) || P(0xeb,0x4b) || P(0x3b,0x1b)) { float dist = p.x + p.y; float pixel_size = length(1.0 / (uResolution / textureDimensions)); if (dist > 0.5 + pixel_size / 2.0) { return w4; } vec4 r; if (is_different(w0, w1) || is_different(w0, w3)) { r = mix(w1, w3, p.y - p.x + 0.5); } else { r = mix(mix(w1 * 0.375 + w0 * 0.25 + w3 * 0.375, w3, p.y * 2.0), w1, p.x * 2.0); } if (dist < 0.5 - pixel_size / 2.0) { return r; } return mix(r, w4, (dist + pixel_size / 2.0 - 0.5) / pixel_size); } if (P(0x0b,0x01)) return mix(mix(w4, w3, 0.5 - p.x), mix(w1, (w1 + w3) / 2.0, 0.5 - p.x), 0.5 - p.y); if (P(0x0b,0x00)) return mix(mix(w4, w3, 0.5 - p.x), mix(w1, w0, 0.5 - p.x), 0.5 - p.y); float dist = p.x + p.y; float pixel_size = length(1.0 / (uResolution / textureDimensions)); if (dist > 0.5 + pixel_size / 2.0) return w4; /* We need more samples to "solve" this diagonal */ vec4 x0 = texture(image, texCoord + vec2( -o.x * 2.0, -o.y * 2.0)); vec4 x1 = texture(image, texCoord + vec2( -o.x , -o.y * 2.0)); vec4 x2 = texture(image, texCoord + vec2( 0.0 , -o.y * 2.0)); vec4 x3 = texture(image, texCoord + vec2( o.x , -o.y * 2.0)); vec4 x4 = texture(image, texCoord + vec2( -o.x * 2.0, -o.y )); vec4 x5 = texture(image, texCoord + vec2( -o.x * 2.0, 0.0 )); vec4 x6 = texture(image, texCoord + vec2( -o.x * 2.0, o.y )); if (is_different(x0, w4)) pattern |= 1 << 8; if (is_different(x1, w4)) pattern |= 1 << 9; if (is_different(x2, w4)) pattern |= 1 << 10; if (is_different(x3, w4)) pattern |= 1 << 11; if (is_different(x4, w4)) pattern |= 1 << 12; if (is_different(x5, w4)) pattern |= 1 << 13; if (is_different(x6, w4)) pattern |= 1 << 14; int diagonal_bias = -7; while (pattern != 0) { diagonal_bias += pattern & 1; pattern >>= 1; } if (diagonal_bias <= 0) { vec4 r = mix(w1, w3, p.y - p.x + 0.5); if (dist < 0.5 - pixel_size / 2.0) { return r; } return mix(r, w4, (dist + pixel_size / 2.0 - 0.5) / pixel_size); } return w4; } void main() { fragColor = scale(source, texCoord); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/shaders/sharp-bilinear.fs000066400000000000000000000037161525155022500250470ustar00rootroot00000000000000/* MIT License Sharp Bilinear (Modified) Copyright (c) 2020-2022 Rupert Carmichael 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. */ // Based on Public Domain work by Themaister precision highp float; uniform sampler2D source; uniform vec4 sourceSize; uniform vec4 targetSize; in vec2 texCoord; out vec4 fragColor; void main() { float prescale = floor(targetSize.y / sourceSize.y + 0.01); if (prescale == 0.0) prescale = 1.0; vec2 texel = texCoord.xy * sourceSize.xy; vec2 texel_floored = floor(texel); vec2 s = fract(texel); float region_range = 0.5 - 0.5 / prescale; /* Figure out where in the texel to sample to get correct pre-scaled bilinear. Uses the hardware bilinear interpolator to avoid having to sample 4 times manually. */ vec2 center_dist = s - 0.5; vec2 f = (center_dist - clamp(center_dist, -region_range, region_range)) * prescale + 0.5; vec2 mod_texel = texel_floored + f; fragColor = texture(source, mod_texel / sourceSize.xy); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/000077500000000000000000000000001525155022500207445ustar00rootroot00000000000000qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/audiomanager.cpp000066400000000000000000000277461525155022500241240ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 __APPLE__ #define _POSIX_C_SOURCE 200112L #endif #include #include #include #include #include #include #include #include "audiomanager.h" #include "jgmanager.h" #include "logdriver.h" namespace { constexpr size_t BUFSIZE = 12800; // Longest wait for the device to drain; it comes out of the frame. constexpr int64_t MAX_BACKPRESSURE_US = 2000; jg_audioinfo_t micinfo{JG_SAMPFMT_INT16, 48000, 1, 800, nullptr}; }; AudioManager::AudioManager(JGManager& jgm_, SettingManager& setmgr_) : jgm(nullptr), setmgr(setmgr_) { // Program-lifetime scratch, as jgrf's. buf_in_ = new int16_t[BUFSIZE]; std::fill(buf_in_, buf_in_ + BUFSIZE, 0); fltbuf_in_ = new float[BUFSIZE]; std::fill(fltbuf_in_, fltbuf_in_ + BUFSIZE, 0.0f); rsbuf_ = new int16_t[BUFSIZE]; std::fill(rsbuf_, rsbuf_ + BUFSIZE, 0); outbuf_ = new int16_t[BUFSIZE]; std::fill(outbuf_, outbuf_ + BUFSIZE, 0); rbuf_storage_ = new int16_t[BUFSIZE]; std::fill(rbuf_storage_, rbuf_storage_ + BUFSIZE, 0); rbuf_in_.buffer = rbuf_storage_; rbuf_in_.bufsize = BUFSIZE; rbuf_in_.head = rbuf_in_.tail = rbuf_in_.cursize = 0; resampler_ = nullptr; audiostream_ = nullptr; audinfo_ = nullptr; // 1/10 ms. req_.tv_sec = 0; req_.tv_nsec = 100000; attach(jgm_); } AudioManager::~AudioManager() { if (audiostream_in_) SDL_DestroyAudioStream(audiostream_in_); if (audiostream_) SDL_DestroyAudioStream(audiostream_); if (resampler_) speex_resampler_destroy(resampler_); delete[] buf_in_; delete[] fltbuf_in_; delete[] rsbuf_; delete[] outbuf_; delete[] rbuf_storage_; } // Moving average, as jgrf. void AudioManager::mavg_update(MAvg &mavg, size_t newval) { mavg.buf[mavg.pos++] = newval; if (mavg.pos == MAVGSIZE) mavg.pos = 0; double sum = 0.0; for (uint32_t i = 0; i < MAVGSIZE; ++i) sum += mavg.buf[i]; mavg.avg = sum / (double)MAVGSIZE; } void AudioManager::mavg_seed(MAvg &mavg, size_t seed) { for (uint32_t i = 0; i < MAVGSIZE; ++i) mavg.buf[i] = seed; mavg.pos = 0; mavg_update(mavg, seed); } // Ring buffer, as jgrf. int16_t AudioManager::rbuf_deq(RingBuf &rbuf) { if (rbuf.cursize == 0) return 0; int16_t sample = rbuf.buffer[rbuf.head]; rbuf.head = (rbuf.head + 1) % rbuf.bufsize; --rbuf.cursize; return sample; } void AudioManager::rbuf_enq(RingBuf &rbuf, int16_t *data, size_t size) { for (uint32_t i = 0; i < size; ++i) { rbuf.buffer[rbuf.tail] = data[i]; rbuf.tail = (rbuf.tail + 1) % rbuf.bufsize; ++rbuf.cursize; if (rbuf.cursize >= rbuf.bufsize - 1) break; } } void AudioManager::rbuf_enqf(RingBuf &rbuf, float *data, size_t size) { for (uint32_t i = 0; i < size; ++i) { float v = data[i] * 32768.0f; if (v >= 32767.0f) rbuf.buffer[rbuf.tail] = 32767; else if (v <= -32768.0f) rbuf.buffer[rbuf.tail] = -32768; else rbuf.buffer[rbuf.tail] = (int16_t)lrintf(v); rbuf.tail = (rbuf.tail + 1) % rbuf.bufsize; ++rbuf.cursize; if (rbuf.cursize >= rbuf.bufsize - 1) break; } } // jgrf's jgrf_audio_timing. The core's frame rate can change under a running // session, and the average would otherwise walk to the new chunk size over // MAVGSIZE frames, resampling against the wrong input rate the whole way. void AudioManager::timing(int corefps) { if (!audinfo_ || !corefps) return; const int spf = (audinfo_->rate / corefps) * audinfo_->channels; const int avg = (int)(mavg_in_.avg + 0.5); const int diff = spf > avg ? spf - avg : avg - spf; if (diff >= SPFTOLERANCE) mavg_seed(mavg_in_, spf); } void AudioManager::reset_pipeline() { rbuf_in_.head = rbuf_in_.tail = rbuf_in_.cursize = 0; ma_offset_ = 0; corefps_ = JGManager::get_frametime(); mavg_seed(mavg_in_, (audinfo_->rate / corefps_) * audinfo_->channels); } // The core's audio callback, as jgrf_audio_cb_core. void AudioManager::queue(void *userdata, size_t in_size) { auto *self = static_cast(userdata); if (!in_size) return; const int channels = self->audinfo_->channels; // From the frametime callback, not audinfo->spf, which a core may leave // stale across a restart. const uint32_t corefps = JGManager::get_frametime(); if ((int)corefps != self->corefps_) { self->corefps_ = (int)corefps; self->timing((int)corefps); } self->mavg_update(self->mavg_in_, in_size); // Ideal samples per frame. const size_t spf = (self->audinfo_->rate / corefps) * channels; self->spf_ = spf; // Moving-average input per frame, made even. uint32_t ma_insamps = (uint32_t)(self->mavg_in_.avg) + ((uint32_t)(self->mavg_in_.avg) % 2); // jgrf's stepped offset on the ring queue. if (self->rbuf_in_.cursize == 0) // buffer about half self->ma_offset_ = -((int)((in_size >> 1) + ((in_size >> 1) % channels))); else if (self->rbuf_in_.cursize < spf) self->ma_offset_ = -channels; // eat less else if (self->rbuf_in_.cursize > (spf + (spf >> 2))) self->ma_offset_ = channels; // eat more else if (self->rbuf_in_.cursize == spf) self->ma_offset_ = 0; ma_insamps += self->ma_offset_; uint32_t in_rate = (ma_insamps * corefps) / channels; uint32_t out_rate = self->audinfo_->rate / self->ffspeed_; // Queue depth as feedback, targeting 3-4 frames. int qbytes = SDL_GetAudioStreamAvailable(self->audiostream_); int qsamps = qbytes / (int)sizeof(int16_t); out_rate += (4 - (qsamps / (int)spf)) * corefps; speex_resampler_set_rate_frac(self->resampler_, in_rate, out_rate, in_rate, out_rate); uint32_t out_size = (uint32_t)((ma_insamps * (double)out_rate) / (double)in_rate); if (self->audinfo_->sampfmt == JG_SAMPFMT_INT16) self->rbuf_enq(self->rbuf_in_, self->buf_in_, in_size); else self->rbuf_enqf(self->rbuf_in_, self->fltbuf_in_, in_size); for (uint32_t i = 0; i < ma_insamps; ++i) self->rsbuf_[i] = self->rbuf_deq(self->rbuf_in_); // A null input while muted gives silence without disturbing the phase. if (channels == 2) { ma_insamps >>= 1; out_size >>= 1; speex_resampler_process_interleaved_int(self->resampler_, self->mute_ ? nullptr : self->rsbuf_, &ma_insamps, self->outbuf_, &out_size); out_size <<= 1; } else { speex_resampler_process_int(self->resampler_, 0, self->mute_ ? nullptr : self->rsbuf_, &ma_insamps, self->outbuf_, &out_size); } // Damps a burst; rate matching handles the rest. Bounded, so the frame // loop keeps its deadline. const auto deadline = std::chrono::steady_clock::now() + std::chrono::microseconds(MAX_BACKPRESSURE_US); while ((SDL_GetAudioStreamAvailable(self->audiostream_) / (int)sizeof(int16_t)) + out_size >= (uint32_t)(self->audinfo_->spf * 6)) { if (std::chrono::steady_clock::now() >= deadline) { break; } nanosleep(&self->req_, &self->rem_); } SDL_PutAudioStreamData(self->audiostream_, self->outbuf_, out_size * sizeof(int16_t)); } void AudioManager::rehash() { if (resampler_) speex_resampler_destroy(resampler_); int err; resampler_ = speex_resampler_init(audinfo_->channels, audinfo_->rate, audinfo_->rate, RSQUAL, &err); } void AudioManager::attach(JGManager& jgm_) { if (jgm) detach(); jgm = &jgm_; audinfo_ = jgm_.get_audioinfo(); if (audinfo_->sampfmt == JG_SAMPFMT_INT16) audinfo_->buf = &buf_in_[0]; else audinfo_->buf = &fltbuf_in_[0]; // Muting is mute_, so it can be undone; main() applies a_mute through // toggle_mute(). jgm_.set_audio_cb(AudioManager::queue, this); // Until queue() recomputes it. spf_ = (audinfo_->rate / JGManager::get_frametime()) * audinfo_->channels; reset_pipeline(); reconfigure_device_if_needed(); } void AudioManager::detach() { audinfo_ = nullptr; jgm = nullptr; } void AudioManager::reconfigure_device_if_needed() { if (audiostream_ && stream_sampfmt_ == (int)audinfo_->sampfmt && stream_channels_ == (unsigned)audinfo_->channels && stream_rate_ == (int)audinfo_->rate) { return; } if (resampler_) speex_resampler_destroy(resampler_); int err; resampler_ = speex_resampler_init(audinfo_->channels, audinfo_->rate, audinfo_->rate, RSQUAL, &err); reset_pipeline(); if (audiostream_) { SDL_DestroyAudioStream(audiostream_); audiostream_ = nullptr; } SDL_AudioSpec audiospec; audiospec.freq = audinfo_->rate; audiospec.format = SDL_AUDIO_S16; audiospec.channels = audinfo_->channels; audiostream_ = SDL_OpenAudioDeviceStream( SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audiospec, nullptr, nullptr); if (!audiostream_) LogDriver::log(LogLevel::Warn, "Error opening audio device"); stream_sampfmt_ = (int)audinfo_->sampfmt; stream_channels_ = audinfo_->channels; stream_rate_ = (int)audinfo_->rate; if (audiostream_) SDL_ResumeAudioStreamDevice(audiostream_); } void AudioManager::set_speed(int speed) { ffspeed_ = speed; } void AudioManager::pause(bool p) { if (audiostream_) { if (p) SDL_PauseAudioStreamDevice(audiostream_); else SDL_ResumeAudioStreamDevice(audiostream_); } if (audiostream_in_ && jgm->get_coreinfo()->hints & JG_HINT_INPUT_AUDIO) { if (p) SDL_PauseAudioStreamDevice(audiostream_in_); else SDL_ResumeAudioStreamDevice(audiostream_in_); } else if (!p && jgm->get_coreinfo()->hints & JG_HINT_INPUT_AUDIO) { SDL_AudioSpec capspec; capspec.channels = micinfo.channels; capspec.freq = micinfo.rate; capspec.format = SDL_AUDIO_S16; audiostream_in_ = SDL_OpenAudioDeviceStream( SDL_AUDIO_DEVICE_DEFAULT_RECORDING, &capspec, nullptr, nullptr); if (audiostream_in_) { SDL_ResumeAudioStreamDevice(audiostream_in_); LogDriver::log(LogLevel::Debug, "Microphone: capture enabled"); } } } void AudioManager::mute(bool m) { mute_ = m ? 1 : 0; } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/audiomanager.h000066400000000000000000000076721525155022500235650ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include #include #include "jgmanager.h" #include "setmanager.h" // jgrf's audio.c rate matching. The core feeds a variable number of samples // per frame; a moving average of that size plus a ring buffer decouple the // jittery producer from a smooth dequeue. The resample ratio is the averaged // input rate against an output rate nudged by the SDL queue depth. class AudioManager { public: AudioManager() = delete; AudioManager(JGManager& jgm_, SettingManager& setmgr_); ~AudioManager(); void set_speed(int speed); void pause(bool p); void mute(bool m); void attach(JGManager& jgm); void detach(); static void queue(void *userdata, size_t in_size); void rehash(); private: void reconfigure_device_if_needed(); void reset_pipeline(); void timing(int corefps); static constexpr int RSQUAL = 2; // Divergence tolerated between the ideal and averaged input chunk size. static constexpr int SPFTOLERANCE = 28; // Of core output chunk sizes. static constexpr uint32_t MAVGSIZE = 60 * 2; struct MAvg { double avg{0.0}; uint32_t pos{0}; size_t buf[MAVGSIZE]{}; }; void mavg_update(MAvg &mavg, size_t newval); void mavg_seed(MAvg &mavg, size_t seed); struct RingBuf { uint32_t head{0}; uint32_t tail{0}; uint32_t cursize{0}; uint32_t bufsize{0}; int16_t *buffer{nullptr}; }; int16_t rbuf_deq(RingBuf &rbuf); void rbuf_enq(RingBuf &rbuf, int16_t *data, size_t size); void rbuf_enqf(RingBuf &rbuf, float *data, size_t size); JGManager *jgm; SettingManager &setmgr; jg_audioinfo_t *audinfo_{nullptr}; SDL_AudioStream *audiostream_{nullptr}; int stream_sampfmt_{-1}; unsigned stream_channels_{0}; int stream_rate_{0}; SDL_AudioStream *audiostream_in_{nullptr}; SpeexResamplerState *resampler_{nullptr}; int16_t *buf_in_{nullptr}; // the core writes here, S16 cores float *fltbuf_in_{nullptr}; // or here, float cores int16_t *rsbuf_{nullptr}; // dequeued, awaiting resample int16_t *outbuf_{nullptr}; // resampled, pushed to SDL int16_t *rbuf_storage_{nullptr}; // ring backing MAvg mavg_in_{}; RingBuf rbuf_in_{}; int ma_offset_{0}; int corefps_{0}; size_t spf_{0}; int ffspeed_{1}; int mute_{0}; struct timespec req_{}, rem_{}; }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/chtmanager.cpp000066400000000000000000000167671525155022500236020ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "jg/jg.h" extern "C" { #include "parson.h" } #include "chtmanager.h" #include "logdriver.h" namespace { // json_value_free frees the whole tree. struct JsonValueDeleter { void operator()(JSON_Value *v) const noexcept { if (v) json_value_free(v); } }; using JsonValuePtr = std::unique_ptr; } // namespace CheatManager::CheatManager(JGManager& jgm_, SettingManager& setmgr_) : jgm(jgm_), setmgr(setmgr_) { } void CheatManager::clear() { jgm.cheat_clear(); } bool CheatManager::load(const std::string& gamename) { cheats_.clear(); // The master switch follows the setting on every load, before the // file checks so a game without one still gets a fresh gate. The // file's per-cheat flags are kept either way. jg_setting_t *autoset = setmgr.get_setting("m_cheatauto"); gate_ = autoset && autoset->val; if (gamename.empty()) { return false; } // jgrf's scheme, so files work in both frontends. const std::filesystem::path path = std::filesystem::path(jgm.get_cheatpath()) / (gamename + ".json"); std::error_code ec; if (!std::filesystem::exists(path, ec)) { LogDriver::jg_log(JG_LOG_DBG, "No cheat file: %s\n", path.string().c_str()); return false; } if (!load_path(path.string())) { return false; } apply(); return true; } bool CheatManager::load_path(const std::string& path) { cheats_.clear(); if (path.empty()) { return false; } // The format documents // comments as the way to disable a cheat. JsonValuePtr root(json_parse_file_with_comments(path.c_str())); if (!root || json_value_get_type(root.get()) != JSONObject) { LogDriver::jg_log(JG_LOG_WRN, "Failed to parse cheat file: %s\n", path.c_str()); return false; } JSON_Object *parent = json_value_get_object(root.get()); JSON_Array *arr = json_object_get_array(parent, "cheats"); if (!arr) { // Well-formed but empty. return true; } const size_t count = json_array_get_count(arr); cheats_.reserve(count); for (size_t i = 0; i < count; ++i) { JSON_Object *entry = json_array_get_object(arr, i); if (!entry) continue; Cheat c; // NULL or 0 for missing keys. const char *desc = json_object_get_string(entry, "desc"); c.desc = desc ? desc : ""; c.enabled = json_object_get_boolean(entry, "enabled") != 0; JSON_Array *codes = json_object_get_array(entry, "codes"); if (codes) { const size_t ncodes = json_array_get_count(codes); c.codes.reserve(ncodes); for (size_t j = 0; j < ncodes; ++j) { const char *code = json_array_get_string(codes, j); if (code) c.codes.emplace_back(code); } } cheats_.push_back(std::move(c)); } LogDriver::jg_log(JG_LOG_DBG, "Cheat file loaded: %s (%zu entries)\n", path.c_str(), cheats_.size()); return true; } bool CheatManager::save(const std::string& gamename) { if (gamename.empty()) { return false; } const std::filesystem::path path = std::filesystem::path(jgm.get_cheatpath()) / (gamename + ".json"); return save_path(path.string()); } bool CheatManager::save_path(const std::string& path) { if (path.empty()) { return false; } // parson owns each object once set into a parent. JsonValuePtr root(json_value_init_object()); if (!root) return false; JSON_Object *parent = json_value_get_object(root.get()); JSON_Value *cheats_val = json_value_init_array(); JSON_Array *cheats_arr = json_value_get_array(cheats_val); json_object_set_value(parent, "cheats", cheats_val); for (const Cheat &c : cheats_) { JSON_Value *entry_val = json_value_init_object(); JSON_Object *entry = json_value_get_object(entry_val); JSON_Value *codes_val = json_value_init_array(); JSON_Array *codes_arr = json_value_get_array(codes_val); for (const std::string &code : c.codes) { json_array_append_string(codes_arr, code.c_str()); } // README field order, for stable diffs. json_object_set_value (entry, "codes", codes_val); json_object_set_boolean(entry, "enabled", c.enabled ? 1 : 0); json_object_set_string (entry, "desc", c.desc.c_str()); json_array_append_value(cheats_arr, entry_val); } // A save-as path may be anywhere. std::error_code ec; std::filesystem::create_directories( std::filesystem::path(path).parent_path(), ec); JSON_Status st = json_serialize_to_file_pretty(root.get(), path.c_str()); if (st != JSONSuccess) { LogDriver::jg_log(JG_LOG_WRN, "Failed to write cheat file: %s\n", path.c_str()); return false; } LogDriver::jg_log(JG_LOG_DBG, "Cheat file saved: %s\n", path.c_str()); return true; } void CheatManager::apply() { // Clear first, so a cheat since disabled or removed drops out. jgm.cheat_clear(); // Gate off: the model is kept, nothing reaches the core. if (!gate_) { return; } for (const Cheat &c : cheats_) { if (!c.enabled) continue; for (const std::string &code : c.codes) { jgm.cheat_set(code.c_str()); } } } void CheatManager::add(Cheat c) { cheats_.push_back(std::move(c)); } void CheatManager::remove(size_t index) { if (index >= cheats_.size()) return; cheats_.erase(cheats_.begin() + index); } void CheatManager::replace(size_t index, Cheat c) { if (index >= cheats_.size()) return; cheats_[index] = std::move(c); } void CheatManager::set_enabled(size_t index, bool enabled) { if (index >= cheats_.size()) return; cheats_[index].enabled = enabled; } bool CheatManager::any_enabled() const { for (const Cheat &c : cheats_) { if (c.enabled) return true; } return false; } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/chtmanager.h000066400000000000000000000062261525155022500232340ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include #include "jgmanager.h" #include "setmanager.h" // The JG cheat JSON schema, so the load/save round-trip is identity. struct Cheat { std::string desc; std::vector codes; bool enabled{false}; }; // The per-game cheat list, bridged to the running core. Editing goes // through the accessors; the dialog never touches cheats_. class CheatManager { public: CheatManager() = delete; CheatManager(JGManager& jgm_, SettingManager& setmgr_); ~CheatManager() {} // Wipe core-side state, leaving the model alone. void clear(); // Load /.json, replacing cheats_ wholesale. False // means no file was found, the common case. Resets the gate from // m_cheatauto; the file's enabled flags are kept and applied. bool load(const std::string& gamename); bool save(const std::string& gamename); // For the dialog's Load/Save; load_path() does not auto-apply. bool load_path(const std::string& path); bool save_path(const std::string& path); // Clear the core, then push every enabled entry. Idempotent. void apply(); const std::vector& cheats() const { return cheats_; } // Out-of-range indexes are no-ops. void add(Cheat c); void remove(size_t index); void replace(size_t index, Cheat c); void set_enabled(size_t index, bool enabled); bool any_enabled() const; // Off, apply() clears the core and keeps the model. bool gate() const { return gate_; } void set_gate(bool on) { gate_ = on; } private: JGManager& jgm; SettingManager& setmgr; std::vector cheats_; bool gate_{true}; }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/crc32.cpp000066400000000000000000000073161525155022500223730ustar00rootroot00000000000000/*- * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or * code or tables extracted from it, as desired without restriction. * * Table and function from FreeBSD's sys/libkern/crc32.c. */ #include #include #include "crc32.h" static uint32_t crc32_tab[] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; uint32_t crc32(uint32_t crc, const void *buf, size_t size) { const uint8_t *p = static_cast(buf); crc = crc ^ ~0U; while (size--) crc = crc32_tab[(crc ^ *p++) & 0xff] ^ (crc >> 8); return crc ^ ~0U; } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/crc32.h000066400000000000000000000001131525155022500220240ustar00rootroot00000000000000#pragma once uint32_t crc32(uint32_t crc, const void *data, size_t size); qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/font/000077500000000000000000000000001525155022500217125ustar00rootroot00000000000000qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/font/6x8.h000066400000000000000000000203421525155022500225110ustar00rootroot00000000000000// U+0000 - U+007F - Public Domain 6x8 console font static uint8_t sixbyeight[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // U+0000 (nul) 0x38, 0x44, 0x6c, 0x44, 0x54, 0x44, 0x38, 0x00, // U+0001 0x38, 0x7c, 0x54, 0x7c, 0x44, 0x7c, 0x38, 0x00, // U+0002 0x00, 0x28, 0x7c, 0x7c, 0x7c, 0x38, 0x10, 0x00, // U+0003 0x00, 0x10, 0x38, 0x7c, 0x7c, 0x38, 0x10, 0x00, // U+0004 0x10, 0x38, 0x38, 0x10, 0x7c, 0x7c, 0x10, 0x00, // U+0005 0x00, 0x10, 0x38, 0x7c, 0x7c, 0x10, 0x38, 0x00, // U+0006 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x00, // U+0007 0xfc, 0xfc, 0xfc, 0xcc, 0xcc, 0xfc, 0xfc, 0xfc, // U+0008 0x00, 0x00, 0x78, 0x48, 0x48, 0x78, 0x00, 0x00, // U+0009 0xfc, 0xfc, 0x84, 0xb4, 0xb4, 0x84, 0xfc, 0xfc, // U+000A 0x00, 0x1c, 0x0c, 0x34, 0x48, 0x48, 0x30, 0x00, // U+000B 0x38, 0x44, 0x44, 0x38, 0x10, 0x38, 0x10, 0x00, // U+000C 0x10, 0x18, 0x14, 0x10, 0x30, 0x70, 0x60, 0x00, // U+000D 0x0c, 0x34, 0x2c, 0x34, 0x2c, 0x6c, 0x60, 0x00, // U+000E 0x00, 0x54, 0x38, 0x6c, 0x38, 0x54, 0x00, 0x00, // U+000F 0x20, 0x30, 0x38, 0x3c, 0x38, 0x30, 0x20, 0x00, // U+0010 0x08, 0x18, 0x38, 0x78, 0x38, 0x18, 0x08, 0x00, // U+0011 0x10, 0x38, 0x7c, 0x10, 0x7c, 0x38, 0x10, 0x00, // U+0012 0x28, 0x28, 0x28, 0x28, 0x28, 0x00, 0x28, 0x00, // U+0013 0x3c, 0x54, 0x54, 0x34, 0x14, 0x14, 0x14, 0x00, // U+0014 0x38, 0x44, 0x30, 0x28, 0x18, 0x44, 0x38, 0x00, // U+0015 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x78, 0x00, // U+0016 0x10, 0x38, 0x7c, 0x10, 0x7c, 0x38, 0x10, 0x38, // U+0017 0x10, 0x38, 0x7c, 0x10, 0x10, 0x10, 0x10, 0x00, // U+0018 0x10, 0x10, 0x10, 0x10, 0x7c, 0x38, 0x10, 0x00, // U+0019 0x00, 0x10, 0x18, 0x7c, 0x18, 0x10, 0x00, 0x00, // U+001A 0x00, 0x10, 0x30, 0x7c, 0x30, 0x10, 0x00, 0x00, // U+001B 0x00, 0x00, 0x00, 0x40, 0x40, 0x40, 0x7c, 0x00, // U+001C 0x00, 0x28, 0x28, 0x7c, 0x28, 0x28, 0x00, 0x00, // U+001D 0x10, 0x10, 0x38, 0x38, 0x7c, 0x7c, 0x00, 0x00, // U+001E 0x7c, 0x7c, 0x38, 0x38, 0x10, 0x10, 0x00, 0x00, // U+001F 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // U+0020 (space) 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x10, 0x00, // U+0021 (!) 0x28, 0x28, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, // U+0022 (") 0x00, 0x28, 0x7c, 0x28, 0x28, 0x7c, 0x28, 0x00, // U+0023 (#) 0x10, 0x3c, 0x50, 0x38, 0x14, 0x78, 0x10, 0x00, // U+0024 ($) 0x44, 0x44, 0x08, 0x10, 0x20, 0x44, 0x44, 0x00, // U+0025 (%) 0x30, 0x48, 0x48, 0x3c, 0x48, 0x48, 0x34, 0x00, // U+0026 (&) 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, // U+0027 (') 0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x08, 0x00, // U+0028 (() 0x20, 0x10, 0x10, 0x10, 0x10, 0x10, 0x20, 0x00, // U+0029 ()) 0x00, 0x10, 0x54, 0x38, 0x54, 0x10, 0x00, 0x00, // U+002A (*) 0x00, 0x10, 0x10, 0x7c, 0x10, 0x10, 0x00, 0x00, // U+002B (+) 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x20, // U+002C (,) 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x00, 0x00, // U+002D (-) 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, // U+002E (.) 0x04, 0x04, 0x08, 0x10, 0x20, 0x40, 0x40, 0x00, // U+002F (/) 0x38, 0x44, 0x4c, 0x54, 0x64, 0x44, 0x38, 0x00, // U+0030 (0) 0x10, 0x30, 0x10, 0x10, 0x10, 0x10, 0x7c, 0x00, // U+0031 (1) 0x38, 0x44, 0x04, 0x08, 0x10, 0x20, 0x7c, 0x00, // U+0032 (2) 0x38, 0x44, 0x04, 0x18, 0x04, 0x44, 0x38, 0x00, // U+0033 (3) 0x24, 0x24, 0x44, 0x7c, 0x04, 0x04, 0x04, 0x00, // U+0034 (4) 0x7c, 0x40, 0x78, 0x04, 0x04, 0x44, 0x38, 0x00, // U+0035 (5) 0x38, 0x40, 0x40, 0x78, 0x44, 0x44, 0x38, 0x00, // U+0036 (6) 0x7c, 0x04, 0x04, 0x08, 0x10, 0x10, 0x10, 0x00, // U+0037 (7) 0x38, 0x44, 0x44, 0x38, 0x44, 0x44, 0x38, 0x00, // U+0038 (8) 0x38, 0x44, 0x44, 0x3c, 0x04, 0x44, 0x38, 0x00, // U+0039 (9) 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, // U+003A (:) 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x20, // U+003B (;) 0x00, 0x0c, 0x30, 0x40, 0x30, 0x0c, 0x00, 0x00, // U+003C (<) 0x00, 0x00, 0x7c, 0x00, 0x7c, 0x00, 0x00, 0x00, // U+003D (=) 0x00, 0x60, 0x18, 0x04, 0x18, 0x60, 0x00, 0x00, // U+003E (>) 0x38, 0x44, 0x04, 0x08, 0x10, 0x00, 0x10, 0x00, // U+003F (?) 0x38, 0x4c, 0x54, 0x54, 0x4c, 0x40, 0x38, 0x00, // U+0040 (@) 0x38, 0x44, 0x44, 0x44, 0x7c, 0x44, 0x44, 0x00, // U+0041 (A) 0x78, 0x44, 0x44, 0x78, 0x44, 0x44, 0x78, 0x00, // U+0042 (B) 0x38, 0x44, 0x40, 0x40, 0x40, 0x44, 0x38, 0x00, // U+0043 (C) 0x78, 0x44, 0x44, 0x44, 0x44, 0x44, 0x78, 0x00, // U+0044 (D) 0x7c, 0x40, 0x40, 0x78, 0x40, 0x40, 0x7c, 0x00, // U+0045 (E) 0x7c, 0x40, 0x40, 0x78, 0x40, 0x40, 0x40, 0x00, // U+0046 (F) 0x38, 0x44, 0x40, 0x5c, 0x44, 0x44, 0x38, 0x00, // U+0047 (G) 0x44, 0x44, 0x44, 0x7c, 0x44, 0x44, 0x44, 0x00, // U+0048 (H) 0x7c, 0x10, 0x10, 0x10, 0x10, 0x10, 0x7c, 0x00, // U+0049 (I) 0x04, 0x04, 0x04, 0x04, 0x44, 0x44, 0x38, 0x00, // U+004A (J) 0x44, 0x48, 0x50, 0x60, 0x50, 0x48, 0x44, 0x00, // U+004B (K) 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x7c, 0x00, // U+004C (L) 0x44, 0x6c, 0x54, 0x44, 0x44, 0x44, 0x44, 0x00, // U+004D (M) 0x44, 0x44, 0x64, 0x54, 0x4c, 0x44, 0x44, 0x00, // U+004E (N) 0x38, 0x44, 0x44, 0x44, 0x44, 0x44, 0x38, 0x00, // U+004F (O) 0x78, 0x44, 0x44, 0x78, 0x40, 0x40, 0x40, 0x00, // U+0050 (P) 0x38, 0x44, 0x44, 0x44, 0x44, 0x44, 0x38, 0x0c, // U+0051 (Q) 0x78, 0x44, 0x44, 0x78, 0x44, 0x44, 0x44, 0x00, // U+0052 (R) 0x38, 0x44, 0x40, 0x38, 0x04, 0x44, 0x38, 0x00, // U+0053 (S) 0x7c, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, // U+0054 (T) 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x38, 0x00, // U+0055 (U) 0x44, 0x44, 0x44, 0x44, 0x28, 0x28, 0x10, 0x00, // U+0056 (V) 0x44, 0x44, 0x44, 0x44, 0x54, 0x6c, 0x44, 0x00, // U+0057 (W) 0x44, 0x44, 0x28, 0x10, 0x28, 0x44, 0x44, 0x00, // U+0058 (X) 0x44, 0x44, 0x28, 0x10, 0x10, 0x10, 0x10, 0x00, // U+0059 (Y) 0x7c, 0x04, 0x08, 0x10, 0x20, 0x40, 0x7c, 0x00, // U+005A (Z) 0x18, 0x10, 0x10, 0x10, 0x10, 0x10, 0x18, 0x00, // U+005B ([) 0x40, 0x40, 0x20, 0x10, 0x08, 0x04, 0x04, 0x00, // U+005C (\) 0x30, 0x10, 0x10, 0x10, 0x10, 0x10, 0x30, 0x00, // U+005D (]) 0x10, 0x28, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, // U+005E (^) 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x00, // U+005F (_) 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // U+0060 (`) 0x00, 0x00, 0x3c, 0x44, 0x44, 0x44, 0x3c, 0x00, // U+0061 (a) 0x40, 0x40, 0x78, 0x44, 0x44, 0x44, 0x78, 0x00, // U+0062 (b) 0x00, 0x00, 0x38, 0x44, 0x40, 0x44, 0x38, 0x00, // U+0063 (c) 0x04, 0x04, 0x3c, 0x44, 0x44, 0x44, 0x3c, 0x00, // U+0064 (d) 0x00, 0x00, 0x38, 0x44, 0x7c, 0x40, 0x38, 0x00, // U+0065 (e) 0x18, 0x24, 0x20, 0x78, 0x20, 0x20, 0x20, 0x00, // U+0066 (f) 0x00, 0x00, 0x3c, 0x44, 0x44, 0x3c, 0x04, 0x38, // U+0067 (g) 0x40, 0x40, 0x78, 0x44, 0x44, 0x44, 0x44, 0x00, // U+0068 (h) 0x10, 0x00, 0x30, 0x10, 0x10, 0x10, 0x7c, 0x00, // U+0069 (i) 0x08, 0x00, 0x18, 0x08, 0x08, 0x08, 0x48, 0x30, // U+006A (j) 0x40, 0x40, 0x44, 0x48, 0x70, 0x48, 0x44, 0x00, // U+006B (k) 0x60, 0x20, 0x20, 0x20, 0x20, 0x20, 0x1c, 0x00, // U+006C (l) 0x00, 0x00, 0x78, 0x54, 0x54, 0x54, 0x54, 0x00, // U+006D (m) 0x00, 0x00, 0x78, 0x44, 0x44, 0x44, 0x44, 0x00, // U+006E (n) 0x00, 0x00, 0x38, 0x44, 0x44, 0x44, 0x38, 0x00, // U+006F (o) 0x00, 0x00, 0x78, 0x44, 0x44, 0x44, 0x78, 0x40, // U+0070 (p) 0x00, 0x00, 0x3c, 0x44, 0x44, 0x44, 0x3c, 0x04, // U+0071 (q) 0x00, 0x00, 0x58, 0x64, 0x40, 0x40, 0x40, 0x00, // U+0072 (r) 0x00, 0x00, 0x3c, 0x40, 0x38, 0x04, 0x78, 0x00, // U+0073 (s) 0x20, 0x20, 0x78, 0x20, 0x20, 0x20, 0x1c, 0x00, // U+0074 (t) 0x00, 0x00, 0x44, 0x44, 0x44, 0x44, 0x3c, 0x00, // U+0075 (u) 0x00, 0x00, 0x44, 0x44, 0x44, 0x28, 0x10, 0x00, // U+0076 (v) 0x00, 0x00, 0x44, 0x44, 0x54, 0x54, 0x28, 0x00, // U+0077 (w) 0x00, 0x00, 0x44, 0x28, 0x10, 0x28, 0x44, 0x00, // U+0078 (x) 0x00, 0x00, 0x44, 0x44, 0x44, 0x3C, 0x08, 0x70, // U+0079 (y) 0x00, 0x00, 0x7c, 0x08, 0x10, 0x20, 0x7c, 0x00, // U+007A (z) 0x08, 0x10, 0x10, 0x20, 0x10, 0x10, 0x08, 0x00, // U+007B ({) 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, // U+007C (|) 0x20, 0x10, 0x10, 0x08, 0x10, 0x10, 0x20, 0x00, // U+007D (}) 0x00, 0x00, 0x24, 0x58, 0x00, 0x00, 0x00, 0x00, // U+007E (~) 0x10, 0x38, 0x6c, 0x44, 0x44, 0x7c, 0x00, 0x00 // U+007F (©) }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/hasher.cpp000066400000000000000000000044361525155022500227310ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "hasher.h" #include "crc32.h" #include "md5.h" uint32_t Hasher::crc(void *data, size_t size) { return crc32(0, data, size); } std::string Hasher::md5(void *data, size_t size) { MD5_CTX c; size_t md5len = size; uint8_t *dataptr = static_cast(data); uint8_t digest[16]; char md5buf[33]; MD5_Init(&c); MD5_Update(&c, dataptr, md5len); MD5_Final(digest, &c); auto nyb_hexchar = [](uint8_t nyb) -> char { nyb &= 0xf; if (nyb >= 10) nyb += 'a' - 10; else nyb += '0'; return (char)nyb; }; for (int i = 0; i < 16; ++i) { md5buf[i * 2] = nyb_hexchar(digest[i] >> 4); md5buf[(i * 2) + 1] =nyb_hexchar(digest[i]); } md5buf[32] = '\0'; return std::string{md5buf}; } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/hasher.h000066400000000000000000000032471525155022500223750ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include class Hasher { public: static uint32_t crc(void *data, size_t size); static std::string md5(void *data, size_t size); }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/ini.h000066400000000000000000000460271525155022500217050ustar00rootroot00000000000000/* * The MIT License (MIT) * Copyright (c) 2018 Danijel Durakovic * * 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. * */ /////////////////////////////////////////////////////////////////////////////// // // /mINI/ v0.9.15 // An INI file reader and writer for the modern age. // /////////////////////////////////////////////////////////////////////////////// // // A tiny utility library for manipulating INI files with a straightforward // API and a minimal footprint. It conforms to the (somewhat) standard INI // format - sections and keys are case insensitive and all leading and // trailing whitespace is ignored. Comments are lines that begin with a // semicolon. Trailing comments are allowed on section lines. // // Files are read on demand, upon which data is kept in memory and the file // is closed. This utility supports lazy writing, which only writes changes // and updates to a file and preserves custom formatting and comments. A lazy // write invoked by a write() call will read the output file, find what // changes have been made and update the file accordingly. If you only need to // generate files, use generate() instead. Section and key order is preserved // on read, write and insert. // /////////////////////////////////////////////////////////////////////////////// // // /* BASIC USAGE EXAMPLE: */ // // /* read from file */ // mINI::INIFile file("myfile.ini"); // mINI::INIStructure ini; // file.read(ini); // // /* read value; gets a reference to actual value in the structure. // if key or section don't exist, a new empty value will be created */ // std::string& value = ini["section"]["key"]; // // /* read value safely; gets a copy of value in the structure. // does not alter the structure */ // std::string value = ini.get("section").get("key"); // // /* set or update values */ // ini["section"]["key"] = "value"; // // /* set multiple values */ // ini["section2"].set({ // {"key1", "value1"}, // {"key2", "value2"} // }); // // /* write updates back to file, preserving comments and formatting */ // file.write(ini); // // /* or generate a file (overwrites the original) */ // file.generate(ini); // /////////////////////////////////////////////////////////////////////////////// // // Long live the INI file!!! // /////////////////////////////////////////////////////////////////////////////// #ifndef MINI_INI_H_ #define MINI_INI_H_ #include #include #include #include #include #include #include #include #include #include namespace mINI { namespace INIStringUtil { const char* const whitespaceDelimiters = " \t\n\r\f\v"; inline void trim(std::string& str) { str.erase(str.find_last_not_of(whitespaceDelimiters) + 1); str.erase(0, str.find_first_not_of(whitespaceDelimiters)); } #ifndef MINI_CASE_SENSITIVE inline void toLower(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](const char c) { return static_cast(std::tolower(c)); }); } #endif inline void replace(std::string& str, std::string const& a, std::string const& b) { if (!a.empty()) { std::size_t pos = 0; while ((pos = str.find(a, pos)) != std::string::npos) { str.replace(pos, a.size(), b); pos += b.size(); } } } #ifdef _WIN32 const char* const endl = "\r\n"; #else const char* const endl = "\n"; #endif } template class INIMap { private: using T_DataIndexMap = std::unordered_map; using T_DataItem = std::pair; using T_DataContainer = std::vector; using T_MultiArgs = typename std::vector>; T_DataIndexMap dataIndexMap; T_DataContainer data; inline std::size_t setEmpty(std::string& key) { std::size_t index = data.size(); dataIndexMap[key] = index; data.emplace_back(key, T()); return index; } public: using const_iterator = typename T_DataContainer::const_iterator; INIMap() { } INIMap(INIMap const& other) : dataIndexMap(other.dataIndexMap), data(other.data) { } INIMap& operator=(INIMap const& other) { std::size_t data_size = other.data.size(); for (std::size_t i = 0; i < data_size; ++i) { auto const& key = other.data[i].first; auto const& obj = other.data[i].second; data.emplace_back(key, obj); } dataIndexMap = T_DataIndexMap(other.dataIndexMap); return *this; } T& operator[](std::string key) { INIStringUtil::trim(key); #ifndef MINI_CASE_SENSITIVE INIStringUtil::toLower(key); #endif auto it = dataIndexMap.find(key); bool hasIt = (it != dataIndexMap.end()); std::size_t index = (hasIt) ? it->second : setEmpty(key); return data[index].second; } T get(std::string key) const { INIStringUtil::trim(key); #ifndef MINI_CASE_SENSITIVE INIStringUtil::toLower(key); #endif auto it = dataIndexMap.find(key); if (it == dataIndexMap.end()) { return T(); } return T(data[it->second].second); } bool has(std::string key) const { INIStringUtil::trim(key); #ifndef MINI_CASE_SENSITIVE INIStringUtil::toLower(key); #endif return (dataIndexMap.count(key) == 1); } void set(std::string key, T obj) { INIStringUtil::trim(key); #ifndef MINI_CASE_SENSITIVE INIStringUtil::toLower(key); #endif auto it = dataIndexMap.find(key); if (it != dataIndexMap.end()) { data[it->second].second = obj; } else { dataIndexMap[key] = data.size(); data.emplace_back(key, obj); } } void set(T_MultiArgs const& multiArgs) { for (auto const& it : multiArgs) { auto const& key = it.first; auto const& obj = it.second; set(key, obj); } } bool remove(std::string key) { INIStringUtil::trim(key); #ifndef MINI_CASE_SENSITIVE INIStringUtil::toLower(key); #endif auto it = dataIndexMap.find(key); if (it != dataIndexMap.end()) { std::size_t index = it->second; data.erase(data.begin() + index); dataIndexMap.erase(it); for (auto& it2 : dataIndexMap) { auto& vi = it2.second; if (vi > index) { vi--; } } return true; } return false; } void clear() { data.clear(); dataIndexMap.clear(); } std::size_t size() const { return data.size(); } const_iterator begin() const { return data.begin(); } const_iterator end() const { return data.end(); } }; using INIStructure = INIMap>; namespace INIParser { using T_ParseValues = std::pair; enum class PDataType : char { PDATA_NONE, PDATA_COMMENT, PDATA_SECTION, PDATA_KEYVALUE, PDATA_UNKNOWN }; inline PDataType parseLine(std::string line, T_ParseValues& parseData) { parseData.first.clear(); parseData.second.clear(); INIStringUtil::trim(line); if (line.empty()) { return PDataType::PDATA_NONE; } char firstCharacter = line[0]; if (firstCharacter == ';') { return PDataType::PDATA_COMMENT; } if (firstCharacter == '[') { auto commentAt = line.find_first_of(';'); if (commentAt != std::string::npos) { line = line.substr(0, commentAt); } auto closingBracketAt = line.find_last_of(']'); if (closingBracketAt != std::string::npos) { auto section = line.substr(1, closingBracketAt - 1); INIStringUtil::trim(section); parseData.first = section; return PDataType::PDATA_SECTION; } } auto lineNorm = line; INIStringUtil::replace(lineNorm, "\\=", " "); auto equalsAt = lineNorm.find_first_of('='); if (equalsAt != std::string::npos) { auto key = line.substr(0, equalsAt); INIStringUtil::trim(key); INIStringUtil::replace(key, "\\=", "="); auto value = line.substr(equalsAt + 1); INIStringUtil::trim(value); parseData.first = key; parseData.second = value; return PDataType::PDATA_KEYVALUE; } return PDataType::PDATA_UNKNOWN; } } class INIReader { public: using T_LineData = std::vector; using T_LineDataPtr = std::shared_ptr; bool isBOM = false; private: std::ifstream fileReadStream; T_LineDataPtr lineData; T_LineData readFile() { fileReadStream.seekg(0, std::ios::end); const std::size_t fileSize = static_cast(fileReadStream.tellg()); fileReadStream.seekg(0, std::ios::beg); if (fileSize >= 3) { const char header[3] = { static_cast(fileReadStream.get()), static_cast(fileReadStream.get()), static_cast(fileReadStream.get()) }; isBOM = ( header[0] == static_cast(0xEF) && header[1] == static_cast(0xBB) && header[2] == static_cast(0xBF) ); } else { isBOM = false; } std::string fileContents; fileContents.resize(fileSize); fileReadStream.seekg(isBOM ? 3 : 0, std::ios::beg); fileReadStream.read(&fileContents[0], fileSize); fileReadStream.close(); T_LineData output; if (fileSize == 0) { return output; } std::string buffer; buffer.reserve(50); for (std::size_t i = 0; i < fileSize; ++i) { char& c = fileContents[i]; if (c == '\n') { output.emplace_back(buffer); buffer.clear(); continue; } if (c != '\0' && c != '\r') { buffer += c; } } output.emplace_back(buffer); return output; } public: INIReader(std::string const& filename, bool keepLineData = false) { fileReadStream.open(filename, std::ios::in | std::ios::binary); if (keepLineData) { lineData = std::make_shared(); } } ~INIReader() { } bool operator>>(INIStructure& data) { if (!fileReadStream.is_open()) { return false; } T_LineData fileLines = readFile(); std::string section; bool inSection = false; INIParser::T_ParseValues parseData; for (auto const& line : fileLines) { auto parseResult = INIParser::parseLine(line, parseData); if (parseResult == INIParser::PDataType::PDATA_SECTION) { inSection = true; data[section = parseData.first]; } else if (inSection && parseResult == INIParser::PDataType::PDATA_KEYVALUE) { auto const& key = parseData.first; auto const& value = parseData.second; data[section][key] = value; } if (lineData && parseResult != INIParser::PDataType::PDATA_UNKNOWN) { if (parseResult == INIParser::PDataType::PDATA_KEYVALUE && !inSection) { continue; } lineData->emplace_back(line); } } return true; } T_LineDataPtr getLines() { return lineData; } }; class INIGenerator { private: std::ofstream fileWriteStream; public: bool prettyPrint = false; INIGenerator(std::string const& filename) { fileWriteStream.open(filename, std::ios::out | std::ios::binary); } ~INIGenerator() { } bool operator<<(INIStructure const& data) { if (!fileWriteStream.is_open()) { return false; } if (!data.size()) { return true; } auto it = data.begin(); for (;;) { auto const& section = it->first; auto const& collection = it->second; fileWriteStream << "[" << section << "]"; if (collection.size()) { fileWriteStream << INIStringUtil::endl; auto it2 = collection.begin(); for (;;) { auto key = it2->first; INIStringUtil::replace(key, "=", "\\="); auto value = it2->second; INIStringUtil::trim(value); fileWriteStream << key << ((prettyPrint) ? " = " : "=") << value; if (++it2 == collection.end()) { break; } fileWriteStream << INIStringUtil::endl; } } if (++it == data.end()) { break; } fileWriteStream << INIStringUtil::endl; if (prettyPrint) { fileWriteStream << INIStringUtil::endl; } } return true; } }; class INIWriter { private: using T_LineData = std::vector; using T_LineDataPtr = std::shared_ptr; std::string filename; T_LineData getLazyOutput(T_LineDataPtr const& lineData, INIStructure& data, INIStructure& original) { T_LineData output; INIParser::T_ParseValues parseData; std::string sectionCurrent; bool parsingSection = false; bool continueToNextSection = false; bool discardNextEmpty = false; bool writeNewKeys = false; std::size_t lastKeyLine = 0; for (auto line = lineData->begin(); line != lineData->end(); ++line) { if (!writeNewKeys) { auto parseResult = INIParser::parseLine(*line, parseData); if (parseResult == INIParser::PDataType::PDATA_SECTION) { if (parsingSection) { writeNewKeys = true; parsingSection = false; --line; continue; } sectionCurrent = parseData.first; if (data.has(sectionCurrent)) { parsingSection = true; continueToNextSection = false; discardNextEmpty = false; output.emplace_back(*line); lastKeyLine = output.size(); } else { continueToNextSection = true; discardNextEmpty = true; continue; } } else if (parseResult == INIParser::PDataType::PDATA_KEYVALUE) { if (continueToNextSection) { continue; } if (data.has(sectionCurrent)) { auto& collection = data[sectionCurrent]; auto const& key = parseData.first; auto const& value = parseData.second; if (collection.has(key)) { auto outputValue = collection[key]; if (value == outputValue) { output.emplace_back(*line); } else { INIStringUtil::trim(outputValue); auto lineNorm = *line; INIStringUtil::replace(lineNorm, "\\=", " "); auto equalsAt = lineNorm.find_first_of('='); auto valueAt = lineNorm.find_first_not_of( INIStringUtil::whitespaceDelimiters, equalsAt + 1 ); std::string outputLine = line->substr(0, valueAt); if (prettyPrint && equalsAt + 1 == valueAt) { outputLine += " "; } outputLine += outputValue; output.emplace_back(outputLine); } lastKeyLine = output.size(); } } } else { if (discardNextEmpty && line->empty()) { discardNextEmpty = false; } else if (parseResult != INIParser::PDataType::PDATA_UNKNOWN) { output.emplace_back(*line); } } } if (writeNewKeys || std::next(line) == lineData->end()) { T_LineData linesToAdd; if (data.has(sectionCurrent) && original.has(sectionCurrent)) { auto const& collection = data[sectionCurrent]; auto const& collectionOriginal = original[sectionCurrent]; for (auto const& it : collection) { auto key = it.first; if (collectionOriginal.has(key)) { continue; } auto value = it.second; INIStringUtil::replace(key, "=", "\\="); INIStringUtil::trim(value); linesToAdd.emplace_back( key + ((prettyPrint) ? " = " : "=") + value ); } } if (!linesToAdd.empty()) { output.insert( output.begin() + lastKeyLine, linesToAdd.begin(), linesToAdd.end() ); } if (writeNewKeys) { writeNewKeys = false; --line; } } } for (auto const& it : data) { auto const& section = it.first; if (original.has(section)) { continue; } if (prettyPrint && output.size() > 0 && !output.back().empty()) { output.emplace_back(); } output.emplace_back("[" + section + "]"); auto const& collection = it.second; for (auto const& it2 : collection) { auto key = it2.first; auto value = it2.second; INIStringUtil::replace(key, "=", "\\="); INIStringUtil::trim(value); output.emplace_back( key + ((prettyPrint) ? " = " : "=") + value ); } } return output; } public: bool prettyPrint = false; INIWriter(std::string const& filename) : filename(filename) { } ~INIWriter() { } bool operator<<(INIStructure& data) { struct stat buf; bool fileExists = (stat(filename.c_str(), &buf) == 0); if (!fileExists) { INIGenerator generator(filename); generator.prettyPrint = prettyPrint; return generator << data; } INIStructure originalData; T_LineDataPtr lineData; bool readSuccess = false; bool fileIsBOM = false; { INIReader reader(filename, true); if ((readSuccess = reader >> originalData)) { lineData = reader.getLines(); fileIsBOM = reader.isBOM; } } if (!readSuccess) { return false; } T_LineData output = getLazyOutput(lineData, data, originalData); std::ofstream fileWriteStream(filename, std::ios::out | std::ios::binary); if (fileWriteStream.is_open()) { if (fileIsBOM) { const char utf8_BOM[3] = { static_cast(0xEF), static_cast(0xBB), static_cast(0xBF) }; fileWriteStream.write(utf8_BOM, 3); } if (output.size()) { auto line = output.begin(); for (;;) { fileWriteStream << *line; if (++line == output.end()) { break; } fileWriteStream << INIStringUtil::endl; } } return true; } return false; } }; class INIFile { private: std::string filename; public: INIFile(std::string const& filename) : filename(filename) { } ~INIFile() { } bool read(INIStructure& data) const { if (data.size()) { data.clear(); } if (filename.empty()) { return false; } INIReader reader(filename); return reader >> data; } bool generate(INIStructure const& data, bool pretty = false) const { if (filename.empty()) { return false; } INIGenerator generator(filename); generator.prettyPrint = pretty; return generator << data; } bool write(INIStructure& data, bool pretty = false) const { if (filename.empty()) { return false; } INIWriter writer(filename); writer.prettyPrint = pretty; return writer << data; } }; } #endif // MINI_INI_H_ qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/inputmanager.cpp000066400000000000000000000671171525155022500241560ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 #include #include "uiadapter.h" #include "inputmanager.h" #include "logdriver.h" #include "qtea_parse.h" namespace { // Axes as buttons, and the threshold for binding an axis. Fixed: binding // must not go hair-trigger at a zero deadzone. constexpr int BDEADZONE = 16384; // Axis magnitude at full deflection; i_deadzone is a percentage of it. constexpr int AXIS_MAX = 32767; // From i_deadzone, via rehash(). int deadzone = 15 * AXIS_MAX / 100; constexpr size_t MAXPORTS = 12; jg_inputstate_t coreinput[MAXPORTS]{}; jg_inputinfo_t *inputinfo[MAXPORTS]{nullptr}; jg_inputstate_t hkstate; jg_inputinfo_t hkinfo; constexpr size_t NDEFS_HK = 12; const char *defs_hk[NDEFS_HK] = { "ResetSoft", "ResetHard", "QuickSave1", "QuickSave2", "QuickLoad1", "QuickLoad2", "Fullscreen", "Pause", "Mute", "FastForward", "Screenshot", "Quit" }; // Qt::Key_* values, keeping this TU free of Qt headers. The defaults share // e->key()'s code space, which reports letters uppercase. constexpr int QtKey_F1 = 0x01000030; constexpr int QtKey_F2 = 0x01000031; constexpr int QtKey_F5 = 0x01000034; constexpr int QtKey_F6 = 0x01000035; constexpr int QtKey_F7 = 0x01000036; constexpr int QtKey_F8 = 0x01000037; constexpr int QtKey_F9 = 0x01000038; const int hk_defaults[NDEFS_HK - 1] = { QtKey_F1, QtKey_F2, // ResetSoft, ResetHard, QtKey_F5, QtKey_F6, QtKey_F7, QtKey_F8, // QuickSave1/2, QuickLoad1/2 'F', 'P', 'M', '`', QtKey_F9 // Fullscreen, Pause, Mute, FastForward, Screenshot }; bool hkprev[NDEFS_HK]{}; SDL_Joystick *joystick[MAXPORTS]{nullptr}; int jsports[MAXPORTS]{}; SDL_JoystickID jsiid[MAXPORTS]{}; unsigned jstrig[MAXPORTS]{}; // Per-port bitmask of axes the gamepad mapping reports inverted. unsigned axisinv[MAXPORTS]{}; // Instance id to port. Tracked here: SDL_GetJoystickPlayerIndex() can be // reassigned asynchronously after open. int input_port(SDL_JoystickID which) { for (size_t i = 0; i < MAXPORTS; ++i) { if (jsports[i] && jsiid[i] == which) { return static_cast(i); } } return -1; } bool conflict{false}; // Look up without inserting; the event paths miss on every unmapped input. template typename Map::mapped_type map_lookup(const Map &map, int key) { auto it = map.find(key); return it == map.end() ? nullptr : it->second; } // "j", kind 'a' axis, 'b' button, 'h' hat. Validated: // it comes from a hand-editable file. bool parse_joydef(const std::string &val, int &port, char &kind, int &inum) { if (val.size() < 4 || val[0] != 'j') { return false; } if (val[1] < '0' || val[1] > '9') { return false; } if (val[2] != 'a' && val[2] != 'b' && val[2] != 'h') { return false; } for (size_t i = 3; i < val.size(); ++i) { if (val[i] < '0' || val[i] > '9') { return false; } } port = val[1] - '0'; kind = val[2]; return qtea::parse_int(val.substr(3), inum); } void log_malformed(const std::string &val) { LogDriver::log(LogLevel::Warn, "Malformed input code: " + val); } } size_t InputManager::num_ports() const { const size_t n = static_cast(jgm->get_coreinfo()->numinputs); return n > MAXPORTS ? MAXPORTS : n; } InputManager::InputManager(JGManager& jgm_, SettingManager& setmgr_) : jgm(&jgm_), setmgr(setmgr_) { for (size_t i = 0; i < num_ports(); ++i) { jg_set_inputstate(&coreinput[i], i); } hkinfo.type = JG_INPUT_EXTERNAL; hkinfo.index = 21; hkinfo.name = "hotkeys"; hkinfo.fname = "Hotkeys"; hkinfo.defs = defs_hk; hkinfo.numaxes = 0; hkinfo.numbuttons = NDEFS_HK; hkbuttons_.assign(NDEFS_HK, 0); hkstate.button = hkbuttons_.data(); // Defaults for anything input.ini left empty, seeded now so the // settings dialog shows them before reassign(). Quit stays undefined so // it can't fight a global shortcut. for (size_t i = 0; i < NDEFS_HK - 1; ++i) { if (setmgr.get_input(hkinfo.name, hkinfo.defs[i]).empty()) { setmgr.set_input(hkinfo.name, hkinfo.defs[i], std::to_string(hk_defaults[i])); } } rehash(); jgm->set_rumble_cb(InputManager::rumble_cb, this); } InputManager::~InputManager() { unassign(); hkstate.button = nullptr; // REMOVED only fires for devices unplugged while the process runs. for (size_t i = 0; i < MAXPORTS; ++i) { if (joystick[i]) { SDL_CloseJoystick(joystick[i]); joystick[i] = nullptr; } jsports[i] = 0; jsiid[i] = 0; } } void InputManager::rehash() { deadzone = setmgr.get_setting("i_deadzone")->val * AXIS_MAX / 100; } // Triggers rest at minimum, sticks at centre; otherwise a trigger bound to // an emulated axis reads half-pressed until first pulled. void InputManager::normalize_axes(int port) { if (port < 0 || static_cast(port) >= MAXPORTS || !joystick[port]) { return; } const int naxes = SDL_GetNumJoystickAxes(joystick[port]); for (int j = 0; j < naxes && j < 32; ++j) { if (int16_t *p = map_lookup(jxmap, (port * 100) + j)) { *p = (jstrig[port] & (1u << j)) ? INT16_MIN : 0; } } } void InputManager::rumble_cb(void *userdata, int port, float strength, size_t len) { auto *self = static_cast(userdata); if (port < 0 || static_cast(port) >= MAXPORTS) return; unsigned js_port = self->rumblemap_[port]; if (js_port >= MAXPORTS || !joystick[js_port]) return; uint16_t str = static_cast(strength * 0xFFFF); if (len == 0) SDL_RumbleJoystick(joystick[js_port], 0, 0, 0); else SDL_RumbleJoystick(joystick[js_port], str, str, len); } void InputManager::reassign() { unassign(); assign(); } void InputManager::assign() { const size_t numinputs = num_ports(); portbufs_.assign(numinputs, PortBuffers{}); for (size_t i = 0; i < numinputs; ++i) { inputinfo[i] = jgm->get_inputinfo(i); PortBuffers &pb = portbufs_[i]; // Never empty: some cores read button[0] before checking numbuttons. const size_t naxes = inputinfo[i]->numaxes ? inputinfo[i]->numaxes : 1; const size_t nbtns = inputinfo[i]->numbuttons ? inputinfo[i]->numbuttons : 1; pb.axis.assign(naxes, 0); pb.button.assign(nbtns, 0); pb.coord.assign(3, 0); pb.rel.assign(2, 0); coreinput[i].axis = pb.axis.data(); coreinput[i].button = pb.button.data(); coreinput[i].coord = pb.coord.data(); coreinput[i].rel = pb.rel.data(); jg_set_inputstate(&coreinput[i], i); } remap_kb(); remap_js(); } void InputManager::unassign() { jxmap.clear(); jamap.clear(); jbmap.clear(); jhmap.clear(); kbmap.clear(); msmap.clear(); lightgun = false; // Rebuilt by remap_js(). std::fill(std::begin(rumblemap_), std::end(rumblemap_), 0u); // Every port: a restart can change numinputs between assign and here. for (size_t i = 0; i < MAXPORTS; ++i) { coreinput[i].axis = nullptr; coreinput[i].button = nullptr; coreinput[i].coord = nullptr; coreinput[i].rel = nullptr; } portbufs_.clear(); } void InputManager::remap_kb() { kbmap.clear(); msmap.clear(); // Quit has no default. for (size_t i = 0; i < NDEFS_HK - 1; ++i) { std::string val = setmgr.get_input(hkinfo.name, hkinfo.defs[i]); if (val.empty()) { setmgr.set_input(hkinfo.name, hkinfo.defs[i], std::to_string(hk_defaults[i])); kbmap[hk_defaults[i]] = &hkstate.button[i]; } else { int code; if (!qtea::parse_int(val, code)) { log_malformed(val); } else if (map_lookup(kbmap, code) == nullptr) { kbmap[code] = &hkstate.button[i]; } else { LogDriver::log(LogLevel::Warn, std::string{"Input configuration conflict: "} + hkinfo.name + ", " + hkinfo.defs[i]); } } } std::string quitdef = setmgr.get_input(hkinfo.name, hkinfo.defs[NDEFS_HK - 1]); if (!quitdef.empty()) { int code; if (qtea::parse_int(quitdef, code)) { kbmap[code] = &hkstate.button[NDEFS_HK - 1]; } else { log_malformed(quitdef); } } for (size_t i = 0; i < num_ports(); ++i) { inputinfo[i] = jgm->get_inputinfo(i); if (inputinfo[i]->type == JG_INPUT_POINTER || inputinfo[i]->type == JG_INPUT_GUN) { msmap[0] = &coreinput[i].coord[0]; msmap[1] = &coreinput[i].coord[1]; } if (inputinfo[i]->type == JG_INPUT_GUN) { lightgun = true; } for (int j = 0; j < inputinfo[i]->numbuttons; ++j) { const char *idef = inputinfo[i]->defs[j + inputinfo[i]->numaxes]; std::string val = setmgr.get_input(inputinfo[i]->name, idef); if (val.empty()) { continue; } int code; if (!qtea::parse_int(val, code)) { log_malformed(val); } else if (map_lookup(kbmap, code) == nullptr) { kbmap[code] = &coreinput[i].button[j]; } else { LogDriver::log(LogLevel::Warn, std::string{"Input configuration conflict: "} + inputinfo[i]->name + ", " + idef); } } } } void InputManager::remap_js() { jxmap.clear(); jamap.clear(); jbmap.clear(); jhmap.clear(); for (size_t i = 0; i < num_ports(); ++i) { inputinfo[i] = jgm->get_inputinfo(i); for (int j = 0; j < inputinfo[i]->numaxes; ++j) { std::string val = setmgr.get_input(std::string(inputinfo[i]->name) + "j", inputinfo[i]->defs[j]); if (val.empty()) { continue; } int port, inum; char kind; if (parse_joydef(val, port, kind, inum) && kind == 'a') { jxmap[(port * 100) + (inum / 2)] = &coreinput[i].axis[j]; // Force feedback follows the axes. rumblemap_[i] = port; } else { log_malformed(val); } } for (int j = 0; j < inputinfo[i]->numbuttons; ++j) { std::string val = setmgr.get_input(std::string(inputinfo[i]->name) + "j", inputinfo[i]->defs[j + inputinfo[i]->numaxes]); if (val.empty()) { continue; } int port, inum; char kind; if (!parse_joydef(val, port, kind, inum)) { log_malformed(val); continue; } const int code = (port * 100) + inum; switch (kind) { case 'b': jbmap[code] = &coreinput[i].button[j]; break; case 'h': jhmap[code] = &coreinput[i].button[j]; break; case 'a': jamap[code] = &coreinput[i].button[j]; break; } } } for (size_t i = 0; i < NDEFS_HK; ++i) { std::string val = setmgr.get_input(std::string(hkinfo.name) + "j", hkinfo.defs[i]); if (val.empty()) { continue; } int port, inum; char kind; if (!parse_joydef(val, port, kind, inum)) { log_malformed(val); continue; } const int code = (port * 100) + inum; switch (kind) { case 'b': jbmap[code] = &hkstate.button[i]; break; case 'h': jhmap[code] = &hkstate.button[i]; break; case 'a': jamap[code] = &hkstate.button[i]; break; } } // Re-seat every connected device: a pad plugged in before the game // loaded had no mapping to write through at hotplug. for (size_t i = 0; i < MAXPORTS; ++i) { if (jsports[i]) { normalize_axes(static_cast(i)); } } } void InputManager::set_inputdef(SDL_Event& evt) { const bool axis = cfg_axis; switch (evt.type) { case SDL_EVENT_JOYSTICK_BUTTON_DOWN: { if (axis) { LogDriver::log(LogLevel::Warn, "Tried to configure an axis as a button"); break; } int port = input_port(evt.jbutton.which); if (port < 0) break; int btn = evt.jbutton.button; if (map_lookup(jbmap, (port * 100) + btn) == nullptr) { std::string bstr{"j" + std::to_string(port) + "b" + std::to_string(btn)}; setmgr.set_input(cfg_name + "j", cfg_def, bstr); } else { conflict = true; } set_cfg_running(false); break; } case SDL_EVENT_JOYSTICK_HAT_MOTION: { if (axis) { LogDriver::log(LogLevel::Warn, "Tried to configure an axis as a hat"); break; } int port = input_port(evt.jhat.which); if (port < 0) break; int hat = 0; if (evt.jhat.value & SDL_HAT_UP) { hat = 0; } else if (evt.jhat.value & SDL_HAT_DOWN) { hat = 1; } else if (evt.jhat.value & SDL_HAT_LEFT) { hat = 2; } else if (evt.jhat.value & SDL_HAT_RIGHT) { hat = 3; } if (map_lookup(jhmap, (port * 100) + hat) == nullptr) { std::string hstr{"j" + std::to_string(port) + "h" + std::to_string(hat)}; setmgr.set_input(cfg_name + "j", cfg_def, hstr); } else { conflict = true; } set_cfg_running(false); break; } case SDL_EVENT_JOYSTICK_AXIS_MOTION: { int port = input_port(evt.jaxis.which); if (port < 0) break; int jaxis = evt.jaxis.axis * 2 + (evt.jaxis.value > 0 ? 1 : 0); if (jstrig[port] & (1u << evt.jaxis.axis) && evt.jaxis.value < 0) { break; } if (std::abs(evt.jaxis.value) >= BDEADZONE) { if (map_lookup(jamap, (port * 100) + jaxis) == nullptr) { std::string astr{"j" + std::to_string(port) + "a" + std::to_string(jaxis)}; setmgr.set_input(cfg_name + "j", cfg_def, astr); } else { conflict = true; } set_cfg_running(false); } break; } } if (cfg_running) { return; } remap_js(); } void InputManager::event(SDL_Event& evt) { // Inverted axes (MFi Y on macOS) are corrected once, before either // configuration or gameplay sees the event. if (evt.type == SDL_EVENT_JOYSTICK_AXIS_MOTION) { int port = input_port(evt.jaxis.which); if (port >= 0 && (axisinv[port] & (1 << evt.jaxis.axis))) { evt.jaxis.value = (evt.jaxis.value == INT16_MIN) ? INT16_MAX : -evt.jaxis.value; } } if (cfg_running) { set_inputdef(evt); return; } switch (evt.type) { case SDL_EVENT_JOYSTICK_ADDED: { SDL_JoystickID which = evt.jdevice.which; // A duplicate ADDED must not open the device twice. if (input_port(which) != -1) { break; } for (size_t i = 0; i < MAXPORTS; ++i) { if (!jsports[i]) { joystick[i] = SDL_OpenJoystick(which); if (!joystick[i]) { // macOS permissions, for one LogDriver::log(LogLevel::Warn, std::string("Failed to open joystick: ") + SDL_GetError()); break; } SDL_SetJoystickPlayerIndex(joystick[i], i); jsports[i] = 1; jsiid[i] = SDL_GetJoystickID(joystick[i]); int port = i; LogDriver::log(LogLevel::Info, std::string("Joystick ") + std::to_string(port + 1) + " Connected: " + SDL_GetJoystickName(joystick[port]) + " (Instance ID: " + std::to_string(jsiid[port]) + ")"); jstrig[port] = 0; axisinv[port] = 0; // Triggers and inverted axes from the gamepad mapping: // sampling at open time misreads a stick held off // centre, and gating inversion on platform would // double-invert pads that are already correct. if (SDL_IsGamepad(which)) { SDL_Gamepad *gp = SDL_OpenGamepad(which); if (gp) { int nbindings = 0; SDL_GamepadBinding **bindings = SDL_GetGamepadBindings(gp, &nbindings); if (bindings) { for (int b = 0; b < nbindings; ++b) { SDL_GamepadBinding *bind = bindings[b]; if (bind->input_type != SDL_GAMEPAD_BINDTYPE_AXIS || bind->output_type != SDL_GAMEPAD_BINDTYPE_AXIS) { continue; } // External data: bound the shift. const int in_axis = bind->input.axis.axis; if (in_axis < 0 || in_axis >= 32) { continue; } if (bind->output.axis.axis == SDL_GAMEPAD_AXIS_LEFT_TRIGGER || bind->output.axis.axis == SDL_GAMEPAD_AXIS_RIGHT_TRIGGER) { jstrig[port] |= 1u << in_axis; continue; } bool in_desc = bind->input.axis.axis_min > bind->input.axis.axis_max; bool out_desc = bind->output.axis.axis_min > bind->output.axis.axis_max; if (in_desc != out_desc) { axisinv[port] |= 1u << in_axis; LogDriver::log(LogLevel::Debug, std::string("Axis ") + std::to_string(in_axis) + " inverted"); } } SDL_free(bindings); } SDL_CloseGamepad(gp); } } normalize_axes(port); break; } } break; } case SDL_EVENT_JOYSTICK_REMOVED: { SDL_JoystickID id = evt.jdevice.which; for (size_t i = 0; i < MAXPORTS; ++i) { // jsports too: a released slot keeps a stale id SDL may // reuse. if (jsports[i] && jsiid[i] == id) { jsports[i] = 0; LogDriver::log(LogLevel::Info, std::string("Joystick ") + std::to_string(i + 1) + " Disconnected (Instance ID: " + std::to_string(id) + ")"); SDL_CloseJoystick(joystick[i]); joystick[i] = nullptr; jsiid[i] = 0; jstrig[i] = 0; axisinv[i] = 0; break; } } break; } case SDL_EVENT_JOYSTICK_BUTTON_UP: { int port = input_port(evt.jbutton.which); if (port < 0) break; int btn = (port * 100) + evt.jbutton.button; if (uint8_t *p = map_lookup(jbmap, btn)) { *p = 0; } break; } case SDL_EVENT_JOYSTICK_BUTTON_DOWN: { int port = input_port(evt.jbutton.which); if (port < 0) break; int btn = (port * 100) + evt.jbutton.button; if (uint8_t *p = map_lookup(jbmap, btn)) { *p = 1; } break; } case SDL_EVENT_JOYSTICK_HAT_MOTION: { int port = input_port(evt.jhat.which); if (port < 0) break; int hat = (port * 100); if (uint8_t *p = map_lookup(jhmap, hat + 0)) { *p = evt.jhat.value & SDL_HAT_UP; } if (uint8_t *p = map_lookup(jhmap, hat + 1)) { *p = (evt.jhat.value & SDL_HAT_DOWN) >> 2; } if (uint8_t *p = map_lookup(jhmap, hat + 2)) { *p = (evt.jhat.value & SDL_HAT_LEFT) >> 3; } if (uint8_t *p = map_lookup(jhmap, hat + 3)) { *p = (evt.jhat.value & SDL_HAT_RIGHT) >> 1; } break; } case SDL_EVENT_JOYSTICK_AXIS_MOTION: { int port = input_port(evt.jaxis.which); if (port < 0) break; int axis = (port * 100) + (evt.jaxis.axis * 2); if (uint8_t *p = map_lookup(jamap, axis)) { *p = evt.jaxis.value < -BDEADZONE; } if (uint8_t *p = map_lookup(jamap, axis + 1)) { *p = evt.jaxis.value > BDEADZONE; } axis = (port * 100) + evt.jaxis.axis; if (int16_t *p = map_lookup(jxmap, axis)) { *p = std::abs(evt.jaxis.value) > deadzone ? evt.jaxis.value : 0; } break; } } hk_events(); } void InputManager::event(int key, bool pressed) { uint8_t *state = map_lookup(kbmap, key); if (!state) { return; } // Auto-repeat. if (*state && pressed) { return; } *state = pressed; } void InputManager::event(int x, int y) { int32_t *cx = map_lookup(msmap, 0); int32_t *cy = map_lookup(msmap, 1); if (cx && cy) { *cx = x; *cy = y; } } void InputManager::hk_events() { // On release, so holding doesn't repeat. for (size_t i = 0; i < NDEFS_HK; ++i) { if (hkprev[i] && !hkstate.button[i]) { switch (i) { case 0: // ResetSoft jgm->reset(0); break; case 1: // ResetHard jgm->reset(1); break; case 2: // QuickSave1 jgm->state_qsave(0); break; case 3: // QuickSave2 jgm->state_qsave(1); break; case 4: // QuickLoad1 jgm->state_qload(0); break; case 5: // QuickLoad2 jgm->state_qload(1); break; case 6: // Fullscreen UiAdapter::fullscreen(); break; case 7: // Pause UiAdapter::pause(); break; case 8: // Mute UiAdapter::mute(); break; case 9: // FastForward UiAdapter::fastforward(false); break; case 10: // Screenshot UiAdapter::screenshot(); break; case 11: // Quit UiAdapter::quit(); break; } } hkprev[i] = hkstate.button[i]; } if (hkstate.button[9]) { UiAdapter::fastforward(true); } } std::vector InputManager::get_inputinfo() { std::vector input_info{}; size_t n = 0; jg_inputinfo_t *list = jgm->get_inputlist(&n); if (list) { input_info.assign(list, list + n); } input_info.push_back(hkinfo); return input_info; } std::string InputManager::get_inputdef(std::string device, std::string def) { std::string ret = setmgr.get_input(device, def); return ret; } void InputManager::clear_inputdef() { setmgr.set_input(cfg_name, cfg_def, std::string{}); setmgr.set_input(cfg_name + "j", cfg_def, std::string{}); remap_kb(); remap_js(); } void InputManager::set_inputcfg(std::string name, std::string def, int defnum) { set_cfg_running(true); cfg_name = name; cfg_def = def; // Axes lead the defs list. The hotkey device has none. cfg_axis = false; size_t n = 0; jg_inputinfo_t *list = jgm->get_inputlist(&n); for (size_t i = 0; list && i < n; ++i) { if (list[i].name && name == list[i].name) { cfg_axis = defnum < list[i].numaxes; break; } } } void InputManager::set_inputdef(int val) { if (map_lookup(kbmap, val) != nullptr) { conflict = true; return; } setmgr.set_input(cfg_name, cfg_def, std::to_string(val)); remap_kb(); } void InputManager::set_cfg_running(bool running) { cfg_running = running; if (!running) { // Conflicts only; the row cleans up a successful rebind itself. if (conflict) { UiAdapter::show_inputmsg(2); conflict = false; } } } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/inputmanager.h000066400000000000000000000073531525155022500236170ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include #include #include #include #include "jgmanager.h" #include "setmanager.h" class InputManager { public: InputManager() = delete; InputManager(JGManager& jgm_, SettingManager& setmgr_); ~InputManager(); void reassign(); // Re-read the cached settings. From QTeaWindow::rehash(). void rehash(); void event(SDL_Event& evt); // Joystick void event(int key, bool pressed); // Keyboard void event(int x, int y); // Mouse void hk_events(); std::vector get_inputinfo(); std::string get_inputdef(std::string device, std::string def); void set_inputdef(int val); void clear_inputdef(); void set_inputcfg(std::string device, std::string def, int defnum); bool get_lightgun() { return lightgun; } bool get_cfg_running() { return cfg_running; } void set_cfg_running(bool running); // JG rumble callback; userdata is the InputManager*. static void rumble_cb(void *userdata, int port, float strength, size_t len); private: // The core's port count, clamped to the port arrays. size_t num_ports() const; void assign(); void unassign(); void normalize_axes(int port); void remap_kb(); void remap_js(); void set_inputdef(SDL_Event& evt); // The jg_inputstate_t buffers, living exactly as long as the assignment. struct PortBuffers { std::vector axis; std::vector button; std::vector coord; std::vector rel; }; std::vector portbufs_; // Parallel to defs_hk. std::vector hkbuttons_; JGManager *jgm; SettingManager &setmgr; std::unordered_map jxmap; std::unordered_map jamap; std::unordered_map jbmap; std::unordered_map jhmap; std::unordered_map kbmap; std::unordered_map msmap; bool lightgun{false}; // Core port to joystick, for force feedback. Sized to MAXPORTS. unsigned rumblemap_[12]{}; bool cfg_running{false}; std::string cfg_name; std::string cfg_def; bool cfg_axis{false}; }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/jgmanager.cpp000066400000000000000000000367461525155022500234230ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 #include #include #include #include "jgmanager.h" #include "qtea_parse.h" #include "hasher.h" // Vendored; its accessors shadow members. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #include "ini.h" #pragma GCC diagnostic pop #include "logdriver.h" #include "qtea_paths.h" namespace { int frametime{60}; void jg_frametime(void* /*userdata*/, double interval) { frametime = interval + 0.5; } void jg_rumble_noop(void*, int, float, size_t) { } size_t pxsize_for(unsigned pixfmt) { switch (pixfmt) { case JG_PIXFMT_XRGB8888: case JG_PIXFMT_XBGR8888: return 4; case JG_PIXFMT_RGBX5551: case JG_PIXFMT_RGB565: return 2; default: return 4; } } } // namespace JGManager::JGManager(const char *sys) { system = sys ? sys : ""; // Its side effects (Geolith's cdmode) are wanted. coreinfo_ = jg_get_coreinfo(system.c_str()); set_paths(); rebuild_settings(); register_callbacks(); } JGManager::~JGManager() { // Unload before deinit: jg_game_unload touches per-session state. switch (stage_) { case Stage::GameLoaded: dip_write(); jg_game_unload(); [[fallthrough]]; case Stage::Initialised: jg_deinit(); [[fallthrough]]; case Stage::Nothing: break; } } bool JGManager::restart(const char *sys) { // Unload before deinit, as the destructor. if (stage_ == Stage::GameLoaded) { dip_write(); jg_game_unload(); loaded = false; stage_ = Stage::Initialised; } if (stage_ == Stage::Initialised) { jg_deinit(); stage_ = Stage::Nothing; } // Everything cached points into the freed session. settings.clear(); dips_ = nullptr; dips_num_ = 0; dips_default_.clear(); for (int i = 0; i < NUM_AUX; ++i) { auxinfo[i] = jg_fileinfo_t{}; auxpath[i].clear(); auxname[i].clear(); auxfname[i].clear(); auxmd5[i].clear(); } loaded = false; vidinfo_ = nullptr; audinfo_ = nullptr; videobuf_.clear(); audiobuf_.clear(); // Only a core off the 60Hz default reports a frame time, so the previous // system's would carry over. frametime = 60; system = sys ? sys : ""; // Re-triggers Geolith's cdmode, deliberately. coreinfo_ = jg_get_coreinfo(system.c_str()); set_paths(); rebuild_settings(); register_callbacks(); if (!jg_init()) { return false; } stage_ = Stage::Initialised; // At once, so sub-managers never see old pointers. alloc_buffers(); return true; } void JGManager::alloc_buffers() { vidinfo_ = jg_get_videoinfo(); audinfo_ = jg_get_audioinfo(); if (vidinfo_) { size_t vbytes = static_cast(vidinfo_->wmax) * static_cast(vidinfo_->hmax) * pxsize_for(vidinfo_->pixfmt); videobuf_.assign(vbytes, 0); vidinfo_->buf = videobuf_.data(); } // A guard for cores without JG_HINT_AUDIO_INTERNAL, which may touch // audinfo->buf in jg_setup_audio; AudioManager::attach() replaces it. if (audinfo_ && coreinfo_ && !(coreinfo_->hints & JG_HINT_AUDIO_INTERNAL)) { // A second of 8-channel float at 96kHz. const size_t guard_bytes = static_cast(96000) * 8 * 4; audiobuf_.assign(guard_bytes, 0); audinfo_->buf = audiobuf_.data(); } } void JGManager::rebuild_settings() { settings.clear(); size_t numsettings = 0; jg_setting_t *jg_settings = jg_get_settings(&numsettings); for (size_t i = 0; i < numsettings; ++i) { settings.push_back(&jg_settings[i]); } } void JGManager::register_callbacks() { jg_set_cb_frametime(jg_frametime, nullptr); jg_set_cb_log(&LogDriver::jg_log); jg_set_cb_rumble(rumble_cb_ ? rumble_cb_ : jg_rumble_noop, rumble_userdata_); } int JGManager::init() { if (!jg_init()) { return 0; } stage_ = Stage::Initialised; alloc_buffers(); return 1; } void JGManager::unload_game() { if (loaded) { dip_write(); dips_ = nullptr; dips_num_ = 0; dips_default_.clear(); jg_game_unload(); loaded = false; stage_ = Stage::Initialised; clear_auxinfo(); } } void JGManager::load_game(const char *filepath, const char *namepath, std::vector& game) { unload_game(); gameinfo.data = game.data(); gameinfo.size = game.size(); gameinfo.crc = Hasher::crc(game.data(), game.size()); gamemd5 = Hasher::md5(game.data(), game.size()); gameinfo.md5 = gamemd5.c_str(); // A real file: the archive itself for archived media. gamepath = qtea::paths::long_path(filepath); gameinfo.path = gamepath.c_str(); // Names the save files: the inner entry for archives. gamename = std::filesystem::path(namepath).stem().string(); gameinfo.name = gamename.c_str(); gamefname = std::filesystem::path(namepath).filename().string(); gameinfo.fname = gamefname.c_str(); jg_set_gameinfo(gameinfo); if (!jg_game_load()) { unload_game(); return; } loaded = true; stage_ = Stage::GameLoaded; dip_read(); } void JGManager::set_auxinfo(int idx, const char *filepath, const char *namepath, std::vector& data) { if (idx < 0 || idx >= NUM_AUX) { return; } auxinfo[idx].data = data.data(); auxinfo[idx].size = data.size(); auxinfo[idx].crc = Hasher::crc(data.data(), data.size()); auxmd5[idx] = Hasher::md5(data.data(), data.size()); auxinfo[idx].md5 = auxmd5[idx].c_str(); auxpath[idx] = std::string(filepath); auxinfo[idx].path = auxpath[idx].c_str(); auxname[idx] = std::filesystem::path(namepath).stem().string(); auxinfo[idx].name = auxname[idx].c_str(); auxfname[idx] = std::filesystem::path(namepath).filename().string(); auxinfo[idx].fname = auxfname[idx].c_str(); jg_set_auxinfo(auxinfo[idx], idx); } void JGManager::clear_auxinfo() { for (int i = 0; i < NUM_AUX; ++i) { auxinfo[i] = jg_fileinfo_t{}; auxpath[i].clear(); auxname[i].clear(); auxfname[i].clear(); auxmd5[i].clear(); jg_set_auxinfo(auxinfo[i], i); } } void JGManager::set_paths() { // Names the installed and per-user directories. qtea::paths::set_core_name(get_coreinfo()->name); basepath = qtea::paths::user_data_dir(); pathinfo.base = basepath.c_str(); biospath = basepath + "/bios"; pathinfo.bios = biospath.c_str(); pathinfo.user = basepath.c_str(); savepath = basepath + "/save"; pathinfo.save = savepath.c_str(); cheatpath = basepath + "/cheats"; shotpath = basepath + "/screenshots"; statepath = basepath + "/state"; // Logged and carried: the session runs, it just can't write saves. qtea::paths::make_dir(savepath); qtea::paths::make_dir(cheatpath); qtea::paths::make_dir(biospath); qtea::paths::make_dir(statepath); qtea::paths::make_dir(shotpath); // Where the core's declared assets are. corepath = qtea::paths::data_root(); pathinfo.core = corepath.c_str(); jg_set_paths(pathinfo); } bool JGManager::is_loaded() { return loaded; } std::string &JGManager::get_basepath() { return basepath; } std::string &JGManager::get_cheatpath() { return cheatpath; } std::string &JGManager::get_shotpath() { return shotpath; } std::string &JGManager::get_statepath() { return statepath; } std::string &JGManager::get_gamename() { return gamename; } std::vector *JGManager::get_settings() { return &settings; } jg_setting_t *JGManager::get_setting(std::string name) { for (size_t i = 0; i < settings.size(); ++i ) { if (std::string(settings[i]->name) == name) { return settings[i]; } } return nullptr; } void JGManager::exec_frame() { jg_exec_frame(); } void JGManager::reset(int hard) { if (loaded) { jg_reset(hard); } } int JGManager::state_load(std::string &filename) { if (!loaded) { return 2; } return jg_state_load(filename.c_str()); } int JGManager::state_qload(int slot) { if (!loaded) { return 2; } std::string slotpath = statepath + "/" + gamename + ".st" + std::to_string(slot); int result = state_load(slotpath); switch (result) { case 0: LogDriver::log(LogLevel::OSD, "State Load Failed"); break; case 1: LogDriver::log(LogLevel::OSD, "State Loaded"); break; default: LogDriver::log(LogLevel::OSD, "State Load Unknown"); break; } return result; } int JGManager::state_save(std::string &filename) { if (!loaded) { return 2; } return jg_state_save(filename.c_str()); } int JGManager::state_qsave(int slot) { if (!loaded) { return 2; } std::string slotpath = statepath + "/" + gamename + ".st" + std::to_string(slot); int result = state_save(slotpath); switch (result) { case 0: LogDriver::log(LogLevel::OSD, "State Save Failed"); break; case 1: LogDriver::log(LogLevel::OSD, "State Saved"); break; default: LogDriver::log(LogLevel::OSD, "State Save Unknown"); break; } return result; } void JGManager::media_set(unsigned index) { if (!loaded) { return; } jg_media_set(index); } void JGManager::media_mount(unsigned state) { if (!loaded) { return; } jg_media_mount(state); } jg_mediainfo_t *JGManager::get_mediainfo() { if (!loaded) { return nullptr; } return jg_get_mediainfo(); } void JGManager::cheat_clear() { jg_cheat_clear(); } void JGManager::cheat_set(const char *code) { jg_cheat_set(code); } jg_setting_t *JGManager::get_dips(size_t *num) { if (dips_) { *num = dips_num_; return dips_; } return jg_get_dips(num); } void JGManager::dip_read() { dips_ = nullptr; dips_num_ = 0; dips_default_.clear(); size_t num = 0; jg_setting_t *dips = jg_get_dips(&num); if (!dips || !num) { return; } dips_ = dips; dips_num_ = num; dips_default_.reserve(num); for (size_t i = 0; i < num; ++i) { dips_default_.push_back(dips_[i].val); } std::string path = savepath + "/" + gamename + ".dip"; mINI::INIFile file(path); mINI::INIStructure ini; if (!file.read(ini)) { return; } for (size_t i = 0; i < num; ++i) { std::string key = std::to_string(i); std::string &strval = ini["dipswitch"][key]; if (strval.empty()) { continue; } int val; if (!qtea::parse_int(strval, val)) { LogDriver::log(LogLevel::Warn, "Ignoring malformed DIP value at index " + std::to_string(i)); continue; } if (val >= dips_[i].min && val <= dips_[i].max) { dips_[i].val = val; } else { LogDriver::log(LogLevel::Warn, "DIP value out of range at index " + std::to_string(i) + ": " + std::to_string(val)); } } } void JGManager::dip_write() { if (!dips_ || !dips_num_) { return; } std::string path = savepath + "/" + gamename + ".dip"; mINI::INIFile file(path); mINI::INIStructure ini; for (size_t i = 0; i < dips_num_; ++i) { std::string key = std::to_string(i); ini["dipswitch"][key] = std::to_string(dips_[i].val); } file.generate(ini, true); } void JGManager::dip_default() { if (!dips_ || !dips_num_ || dips_default_.empty()) { return; } for (size_t i = 0; i < dips_num_; ++i) { dips_[i].val = dips_default_[i]; } jg_rehash(); } int JGManager::get_frametime() { return frametime; } void JGManager::rehash() { if (loaded) { jg_rehash(); } } jg_coreinfo_t *JGManager::get_coreinfo() { return coreinfo_; } jg_inputinfo_t *JGManager::get_inputinfo(int port) { return jg_get_inputinfo(port); } jg_inputinfo_t *JGManager::get_inputlist(size_t *num) { return jg_get_inputlist(num); } jg_audioinfo_t *JGManager::get_audioinfo() { // Cached, refreshed before restart() returns; jg_get_audioinfo() itself // could be stale in the gap. return audinfo_; } jg_videoinfo_t *JGManager::get_videoinfo() { return vidinfo_; } void JGManager::set_audio_cb(jg_cb_audio_t cb, void *userdata) { jg_set_cb_audio(cb, userdata); setup_audio(); } void JGManager::set_rumble_cb(jg_cb_rumble_t cb, void *userdata) { rumble_cb_ = cb; rumble_userdata_ = userdata; jg_set_cb_rumble(cb, userdata); } void JGManager::data_push(uint32_t type, int port, const void *p, size_t sz) { jg_data_push(type, port, p, sz); } void JGManager::setup_audio() { jg_setup_audio(); // audinfo->buf is AudioManager's. } void JGManager::setup_video() { // Regrow before the call, not after: cores cache vidinfo->buf during // jg_setup_video, so a reallocation here would leave them holding a // freed pointer to write frames into. if (vidinfo_) { size_t want_bytes = static_cast(vidinfo_->wmax) * static_cast(vidinfo_->hmax) * pxsize_for(vidinfo_->pixfmt); if (videobuf_.size() < want_bytes) { videobuf_.assign(want_bytes, 0); } vidinfo_->buf = videobuf_.data(); } jg_setup_video(); // Re-pointed, which setup_video may have zeroed. if (vidinfo_) { vidinfo_->buf = videobuf_.data(); } } jg_biosinfo_t *JGManager::get_bioslist(size_t *num) { return jg_get_bioslist(num); } jg_systeminfo_t *JGManager::get_systemlist(size_t *num) { return jg_get_systemlist(num); } std::string &JGManager::get_biospath() { return biospath; } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/jgmanager.h000066400000000000000000000131521525155022500230520ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include #include #include #include class JGManager { public: // Selects per-subsystem coreinfo and BIOS/path layout on cores that // distinguish modes. Needed before set_paths() runs in the constructor, // hence the parameter. "" for single-system cores. explicit JGManager(const char *sys); JGManager() : JGManager("") {} ~JGManager(); void exec_frame(); void reset(int hard); void rehash(); int init(); void unload_game(); void load_game(const char *filepath, const char *namepath, std::vector& game); bool is_loaded(); // Aux files (BIOS, addon, link-cable peer, second cart); slot meaning is // the core's. Paths split as for load_game(): the file, and the name. static constexpr int NUM_AUX = 3; void set_auxinfo(int idx, const char *filepath, const char *namepath, std::vector& data); void clear_auxinfo(); int state_load(std::string &filename); int state_save(std::string &filename); int state_qload(int slot); int state_qsave(int slot); void media_set(unsigned index); void media_mount(unsigned state); jg_mediainfo_t* get_mediainfo(); void cheat_clear(); void cheat_set(const char *code); // Per-game. jg_setting_t *get_dips(size_t *num); void dip_read(); void dip_write(); void dip_default(); // Tear down and bring back up against `sys`. On success sub-managers // must refresh cached pointers and the caller re-reads settings; on // failure the session is dead. bool restart(const char *sys); static int get_frametime(); std::string& get_basepath(); std::string& get_cheatpath(); std::string& get_shotpath(); std::string& get_statepath(); std::string& get_gamename(); std::vector* get_settings(); jg_setting_t* get_setting(std::string name); jg_coreinfo_t* get_coreinfo(); jg_inputinfo_t* get_inputinfo(int port); jg_inputinfo_t* get_inputlist(size_t *num); jg_audioinfo_t* get_audioinfo(); jg_videoinfo_t* get_videoinfo(); jg_biosinfo_t* get_bioslist(size_t *num); jg_systeminfo_t* get_systemlist(size_t *num); std::string& get_biospath(); void set_audio_cb(jg_cb_audio_t cb, void *userdata); void set_rumble_cb(jg_cb_rumble_t cb, void *userdata); void data_push(uint32_t type, int port, const void *p, size_t sz); void setup_audio(); void setup_video(); private: void set_paths(); void rebuild_settings(); void register_callbacks(); // After every jg_init. Input state is InputManager's: multi-system cores // populate inputinfo only during jg_game_load. void alloc_buffers(); jg_fileinfo_t gameinfo; jg_pathinfo_t pathinfo; bool loaded{false}; std::string system; std::string basepath; std::string biospath; std::string cheatpath; std::string corepath; std::string savepath; std::string shotpath; std::string statepath; std::string gamepath; std::string gamename; std::string gamefname; std::string gamemd5; std::array auxinfo{}; std::array auxpath; std::array auxname; std::array auxfname; std::array auxmd5; jg_setting_t *dips_{nullptr}; size_t dips_num_{0}; std::vector dips_default_; jg_coreinfo_t *coreinfo_{nullptr}; jg_videoinfo_t *vidinfo_{nullptr}; jg_audioinfo_t *audinfo_{nullptr}; // Re-registered on every restart(). jg_cb_rumble_t rumble_cb_{nullptr}; void *rumble_userdata_{nullptr}; // wmax * hmax * bytes per pixel, held by the core via vidinfo->buf. std::vector videobuf_; // Guard only; see alloc_buffers(). std::vector audiobuf_; // So the destructor unwinds only what was set up. enum class Stage { Nothing, Initialised, GameLoaded, }; Stage stage_{Stage::Nothing}; std::vector settings; }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/lodepng.cpp000066400000000000000000011160211525155022500231020ustar00rootroot00000000000000/* LodePNG version 20230410 Copyright (c) 2005-2023 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. */ /* The manual and changelog are in the header file "lodepng.h" Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C. */ #include "lodepng.h" #ifdef LODEPNG_COMPILE_DISK #include /* LONG_MAX */ #include /* file handling */ #endif /* LODEPNG_COMPILE_DISK */ #ifdef LODEPNG_COMPILE_ALLOCATORS #include /* allocations */ #endif /* LODEPNG_COMPILE_ALLOCATORS */ #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 */ const char* LODEPNG_VERSION_STRING = "20230410"; /* This source file is divided into 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 */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* // Tools for C, and common code for PNG and Zlib. // */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /*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) { #ifdef LODEPNG_MAX_ALLOC if(size > LODEPNG_MAX_ALLOC) return 0; #endif return malloc(size); } /* NOTE: when realloc returns NULL, it leaves the original memory untouched */ static void* lodepng_realloc(void* ptr, size_t new_size) { #ifdef LODEPNG_MAX_ALLOC if(new_size > LODEPNG_MAX_ALLOC) return 0; #endif return realloc(ptr, new_size); } static void lodepng_free(void* ptr) { free(ptr); } #else /*LODEPNG_COMPILE_ALLOCATORS*/ /* TODO: support giving additional void* payload to the custom 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*/ /* convince the compiler to inline a function, for use when this measurably improves performance */ /* inline is not available in C90, but use it when supported by the compiler */ #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(__cplusplus) && (__cplusplus >= 199711L)) #define LODEPNG_INLINE inline #else #define LODEPNG_INLINE /* not available */ #endif /* restrict is not available in C90, but use it when supported by the compiler */ #if (defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) ||\ (defined(_MSC_VER) && (_MSC_VER >= 1400)) || \ (defined(__WATCOMC__) && (__WATCOMC__ >= 1250) && !defined(__cplusplus)) #define LODEPNG_RESTRICT __restrict #else #define LODEPNG_RESTRICT /* not available */ #endif /* Replacements for C library functions such as memcpy and strlen, to support platforms where a full C library is not available. The compiler can recognize them and compile to something as fast. */ static void lodepng_memcpy(void* LODEPNG_RESTRICT dst, const void* LODEPNG_RESTRICT src, size_t size) { size_t i; for(i = 0; i < size; i++) ((char*)dst)[i] = ((const char*)src)[i]; } static void lodepng_memset(void* LODEPNG_RESTRICT dst, int value, size_t num) { size_t i; for(i = 0; i < num; i++) ((char*)dst)[i] = (char)value; } /* does not check memory out of bounds, do not use on untrusted data */ static size_t lodepng_strlen(const char* a) { const char* orig = a; /* avoid warning about unused function in case of disabled COMPILE... macros */ (void)(&lodepng_strlen); while(*a) a++; return (size_t)(a - orig); } #define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b)) #if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER) /* Safely check if adding two integers will overflow (no undefined behavior, compiler removing the code, etc...) and output result. */ static int lodepng_addofl(size_t a, size_t b, size_t* result) { *result = a + b; /* Unsigned addition is well defined and safe in C90 */ return *result < a; } #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_DECODER)*/ #ifdef LODEPNG_COMPILE_DECODER /* Safely check if multiplying two integers will overflow (no undefined behavior, compiler removing the code, etc...) and output result. */ static int lodepng_mulofl(size_t a, size_t b, size_t* result) { *result = a * b; /* Unsigned multiplication is well defined and safe in C90 */ return (a != 0 && *result / a != b); } #ifdef LODEPNG_COMPILE_ZLIB /* Safely check if a + b > c, even if overflow could happen. */ static int lodepng_gtofl(size_t a, size_t b, size_t c) { size_t d; if(lodepng_addofl(a, b, &d)) return 1; return d > c; } #endif /*LODEPNG_COMPILE_ZLIB*/ #endif /*LODEPNG_COMPILE_DECODER*/ /* 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_resize(&lz77_encoded, datasize)) 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 #ifdef LODEPNG_COMPILE_ENCODER /*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_resize(uivector* p, size_t size) { size_t allocsize = size * sizeof(unsigned); if(allocsize > p->allocsize) { size_t newsize = allocsize + (p->allocsize >> 1u); void* data = lodepng_realloc(p->data, newsize); if(data) { p->allocsize = newsize; p->data = (unsigned*)data; } else return 0; /*error: not enough memory*/ } p->size = size; return 1; /*success*/ } static void uivector_init(uivector* p) { p->data = NULL; p->size = p->allocsize = 0; } /*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; } #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 size) { if(size > p->allocsize) { size_t newsize = size + (p->allocsize >> 1u); 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; /*success*/ } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned ucvector_resize(ucvector* p, size_t size) { p->size = size; return ucvector_reserve(p, size); } static ucvector ucvector_init(unsigned char* buffer, size_t size) { ucvector v; v.data = buffer; v.allocsize = v.size = size; return v; } /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_PNG #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*free string pointer and set it to NULL*/ static void string_cleanup(char** out) { lodepng_free(*out); *out = NULL; } /*also appends null termination character*/ static char* alloc_string_sized(const char* in, size_t insize) { char* out = (char*)lodepng_malloc(insize + 1); if(out) { lodepng_memcpy(out, in, insize); out[insize] = 0; } return out; } /* dynamically allocates a new string with a copy of the null terminated input text */ static char* alloc_string(const char* in) { return alloc_string_sized(in, lodepng_strlen(in)); } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ #endif /*LODEPNG_COMPILE_PNG*/ /* ////////////////////////////////////////////////////////////////////////// */ #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG) static unsigned lodepng_read32bitInt(const unsigned char* buffer) { return (((unsigned)buffer[0] << 24u) | ((unsigned)buffer[1] << 16u) | ((unsigned)buffer[2] << 8u) | (unsigned)buffer[3]); } #endif /*defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_PNG)*/ #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)*/ /* ////////////////////////////////////////////////////////////////////////// */ /* / File IO / */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_DISK /* returns negative value on error. This should be pure C compatible, so no fstat. */ static long lodepng_filesize(const char* filename) { FILE* file; long size; file = fopen(filename, "rb"); if(!file) return -1; if(fseek(file, 0, SEEK_END) != 0) { fclose(file); return -1; } size = ftell(file); /* It may give LONG_MAX as directory size, this is invalid for us. */ if(size == LONG_MAX) size = -1; fclose(file); return size; } /* load file into buffer that already has the correct allocated size. Returns error code.*/ static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename) { FILE* file; size_t readsize; file = fopen(filename, "rb"); if(!file) return 78; readsize = fread(out, 1, size, file); fclose(file); if(readsize != size) return 78; return 0; } unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) { long size = lodepng_filesize(filename); if(size < 0) return 78; *outsize = (size_t)size; *out = (unsigned char*)lodepng_malloc((size_t)size); if(!(*out) && size > 0) return 83; /*the above malloc failed*/ return lodepng_buffer_file(*out, (size_t)size, filename); } /*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(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 typedef struct { ucvector* data; unsigned char bp; /*ok to overflow, indicates bit pos inside byte*/ } LodePNGBitWriter; static void LodePNGBitWriter_init(LodePNGBitWriter* writer, ucvector* data) { writer->data = data; writer->bp = 0; } /*TODO: this ignores potential out of memory errors*/ #define WRITEBIT(writer, bit){\ /* append new byte */\ if(((writer->bp) & 7u) == 0) {\ if(!ucvector_resize(writer->data, writer->data->size + 1)) return;\ writer->data->data[writer->data->size - 1] = 0;\ }\ (writer->data->data[writer->data->size - 1]) |= (bit << ((writer->bp) & 7u));\ ++writer->bp;\ } /* LSB of value is written first, and LSB of bytes is used first */ static void writeBits(LodePNGBitWriter* writer, unsigned value, size_t nbits) { if(nbits == 1) { /* compiler should statically compile this case if nbits == 1 */ WRITEBIT(writer, value); } else { /* TODO: increase output size only once here rather than in each WRITEBIT */ size_t i; for(i = 0; i != nbits; ++i) { WRITEBIT(writer, (unsigned char)((value >> i) & 1)); } } } /* This one is to use for adding huffman symbol, the value bits are written MSB first */ static void writeBitsReversed(LodePNGBitWriter* writer, unsigned value, size_t nbits) { size_t i; for(i = 0; i != nbits; ++i) { /* TODO: increase output size only once here rather than in each WRITEBIT */ WRITEBIT(writer, (unsigned char)((value >> (nbits - 1u - i)) & 1u)); } } #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_DECODER typedef struct { const unsigned char* data; size_t size; /*size of data in bytes*/ size_t bitsize; /*size of data in bits, end of valid bp values, should be 8*size*/ size_t bp; unsigned buffer; /*buffer for reading bits. NOTE: 'unsigned' must support at least 32 bits*/ } LodePNGBitReader; /* data size argument is in bytes. Returns error if size too large causing overflow */ static unsigned LodePNGBitReader_init(LodePNGBitReader* reader, const unsigned char* data, size_t size) { size_t temp; reader->data = data; reader->size = size; /* size in bits, return error if overflow (if size_t is 32 bit this supports up to 500MB) */ if(lodepng_mulofl(size, 8u, &reader->bitsize)) return 105; /*ensure incremented bp can be compared to bitsize without overflow even when it would be incremented 32 too much and trying to ensure 32 more bits*/ if(lodepng_addofl(reader->bitsize, 64u, &temp)) return 105; reader->bp = 0; reader->buffer = 0; return 0; /*ok*/ } /* ensureBits functions: Ensures the reader can at least read nbits bits in one or more readBits calls, safely even if not enough bits are available. The nbits parameter is unused but is given for documentation purposes, error checking for amount of bits must be done beforehand. */ /*See ensureBits documentation above. This one ensures up to 9 bits */ static LODEPNG_INLINE void ensureBits9(LodePNGBitReader* reader, size_t nbits) { size_t start = reader->bp >> 3u; size_t size = reader->size; if(start + 1u < size) { reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u); reader->buffer >>= (reader->bp & 7u); } else { reader->buffer = 0; if(start + 0u < size) reader->buffer = reader->data[start + 0]; reader->buffer >>= (reader->bp & 7u); } (void)nbits; } /*See ensureBits documentation above. This one ensures up to 17 bits */ static LODEPNG_INLINE void ensureBits17(LodePNGBitReader* reader, size_t nbits) { size_t start = reader->bp >> 3u; size_t size = reader->size; if(start + 2u < size) { reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | ((unsigned)reader->data[start + 2] << 16u); reader->buffer >>= (reader->bp & 7u); } else { reader->buffer = 0; if(start + 0u < size) reader->buffer |= reader->data[start + 0]; if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u); reader->buffer >>= (reader->bp & 7u); } (void)nbits; } /*See ensureBits documentation above. This one ensures up to 25 bits */ static LODEPNG_INLINE void ensureBits25(LodePNGBitReader* reader, size_t nbits) { size_t start = reader->bp >> 3u; size_t size = reader->size; if(start + 3u < size) { reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u); reader->buffer >>= (reader->bp & 7u); } else { reader->buffer = 0; if(start + 0u < size) reader->buffer |= reader->data[start + 0]; if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u); if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u); reader->buffer >>= (reader->bp & 7u); } (void)nbits; } /*See ensureBits documentation above. This one ensures up to 32 bits */ static LODEPNG_INLINE void ensureBits32(LodePNGBitReader* reader, size_t nbits) { size_t start = reader->bp >> 3u; size_t size = reader->size; if(start + 4u < size) { reader->buffer = (unsigned)reader->data[start + 0] | ((unsigned)reader->data[start + 1] << 8u) | ((unsigned)reader->data[start + 2] << 16u) | ((unsigned)reader->data[start + 3] << 24u); reader->buffer >>= (reader->bp & 7u); reader->buffer |= (((unsigned)reader->data[start + 4] << 24u) << (8u - (reader->bp & 7u))); } else { reader->buffer = 0; if(start + 0u < size) reader->buffer |= reader->data[start + 0]; if(start + 1u < size) reader->buffer |= ((unsigned)reader->data[start + 1] << 8u); if(start + 2u < size) reader->buffer |= ((unsigned)reader->data[start + 2] << 16u); if(start + 3u < size) reader->buffer |= ((unsigned)reader->data[start + 3] << 24u); reader->buffer >>= (reader->bp & 7u); } (void)nbits; } /* Get bits without advancing the bit pointer. Must have enough bits available with ensureBits. Max nbits is 31. */ static LODEPNG_INLINE unsigned peekBits(LodePNGBitReader* reader, size_t nbits) { /* The shift allows nbits to be only up to 31. */ return reader->buffer & ((1u << nbits) - 1u); } /* Must have enough bits available with ensureBits */ static LODEPNG_INLINE void advanceBits(LodePNGBitReader* reader, size_t nbits) { reader->buffer >>= nbits; reader->bp += nbits; } /* Must have enough bits available with ensureBits */ static LODEPNG_INLINE unsigned readBits(LodePNGBitReader* reader, size_t nbits) { unsigned result = peekBits(reader, nbits); advanceBits(reader, nbits); return result; } #endif /*LODEPNG_COMPILE_DECODER*/ static unsigned reverseBits(unsigned bits, unsigned num) { /*TODO: implement faster lookup table based version when needed*/ unsigned i, result = 0; for(i = 0; i < num; i++) result |= ((bits >> (num - i - 1u)) & 1u) << i; return result; } /* ////////////////////////////////////////////////////////////////////////// */ /* / 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 as specified by deflate, 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* codes; /*the huffman codes (bit patterns representing the symbols)*/ unsigned* lengths; /*the lengths of the huffman codes*/ unsigned maxbitlen; /*maximum number of bits a single code can get*/ unsigned numcodes; /*number of symbols in the alphabet = number of codes*/ /* for reading only */ unsigned char* table_len; /*length of symbol from lookup table, or max length if secondary lookup needed*/ unsigned short* table_value; /*value of symbol from lookup table, or pointer to secondary table if needed*/ } HuffmanTree; static void HuffmanTree_init(HuffmanTree* tree) { tree->codes = 0; tree->lengths = 0; tree->table_len = 0; tree->table_value = 0; } static void HuffmanTree_cleanup(HuffmanTree* tree) { lodepng_free(tree->codes); lodepng_free(tree->lengths); lodepng_free(tree->table_len); lodepng_free(tree->table_value); } /* amount of bits for first huffman table lookup (aka root bits), see HuffmanTree_makeTable and huffmanDecodeSymbol.*/ /* values 8u and 9u work the fastest */ #define FIRSTBITS 9u /* a symbol value too big to represent any valid symbol, to indicate reading disallowed huffman bits combination, which is possible in case of only 0 or 1 present symbols. */ #define INVALIDSYMBOL 65535u /* make table for huffman decoding */ static unsigned HuffmanTree_makeTable(HuffmanTree* tree) { static const unsigned headsize = 1u << FIRSTBITS; /*size of the first table*/ static const unsigned mask = (1u << FIRSTBITS) /*headsize*/ - 1u; size_t i, numpresent, pointer, size; /*total table size*/ unsigned* maxlens = (unsigned*)lodepng_malloc(headsize * sizeof(unsigned)); if(!maxlens) return 83; /*alloc fail*/ /* compute maxlens: max total bit length of symbols sharing prefix in the first table*/ lodepng_memset(maxlens, 0, headsize * sizeof(*maxlens)); for(i = 0; i < tree->numcodes; i++) { unsigned symbol = tree->codes[i]; unsigned l = tree->lengths[i]; unsigned index; if(l <= FIRSTBITS) continue; /*symbols that fit in first table don't increase secondary table size*/ /*get the FIRSTBITS MSBs, the MSBs of the symbol are encoded first. See later comment about the reversing*/ index = reverseBits(symbol >> (l - FIRSTBITS), FIRSTBITS); maxlens[index] = LODEPNG_MAX(maxlens[index], l); } /* compute total table size: size of first table plus all secondary tables for symbols longer than FIRSTBITS */ size = headsize; for(i = 0; i < headsize; ++i) { unsigned l = maxlens[i]; if(l > FIRSTBITS) size += (((size_t)1) << (l - FIRSTBITS)); } tree->table_len = (unsigned char*)lodepng_malloc(size * sizeof(*tree->table_len)); tree->table_value = (unsigned short*)lodepng_malloc(size * sizeof(*tree->table_value)); if(!tree->table_len || !tree->table_value) { lodepng_free(maxlens); /* freeing tree->table values is done at a higher scope */ return 83; /*alloc fail*/ } /*initialize with an invalid length to indicate unused entries*/ for(i = 0; i < size; ++i) tree->table_len[i] = 16; /*fill in the first table for long symbols: max prefix size and pointer to secondary tables*/ pointer = headsize; for(i = 0; i < headsize; ++i) { unsigned l = maxlens[i]; if(l <= FIRSTBITS) continue; tree->table_len[i] = l; tree->table_value[i] = (unsigned short)pointer; pointer += (((size_t)1) << (l - FIRSTBITS)); } lodepng_free(maxlens); /*fill in the first table for short symbols, or secondary table for long symbols*/ numpresent = 0; for(i = 0; i < tree->numcodes; ++i) { unsigned l = tree->lengths[i]; unsigned symbol, reverse; if(l == 0) continue; symbol = tree->codes[i]; /*the huffman bit pattern. i itself is the value.*/ /*reverse bits, because the huffman bits are given in MSB first order but the bit reader reads LSB first*/ reverse = reverseBits(symbol, l); numpresent++; if(l <= FIRSTBITS) { /*short symbol, fully in first table, replicated num times if l < FIRSTBITS*/ unsigned num = 1u << (FIRSTBITS - l); unsigned j; for(j = 0; j < num; ++j) { /*bit reader will read the l bits of symbol first, the remaining FIRSTBITS - l bits go to the MSB's*/ unsigned index = reverse | (j << l); if(tree->table_len[index] != 16) return 55; /*invalid tree: long symbol shares prefix with short symbol*/ tree->table_len[index] = l; tree->table_value[index] = (unsigned short)i; } } else { /*long symbol, shares prefix with other long symbols in first lookup table, needs second lookup*/ /*the FIRSTBITS MSBs of the symbol are the first table index*/ unsigned index = reverse & mask; unsigned maxlen = tree->table_len[index]; /*log2 of secondary table length, should be >= l - FIRSTBITS*/ unsigned tablelen = maxlen - FIRSTBITS; unsigned start = tree->table_value[index]; /*starting index in secondary table*/ unsigned num = 1u << (tablelen - (l - FIRSTBITS)); /*amount of entries of this symbol in secondary table*/ unsigned j; if(maxlen < l) return 55; /*invalid tree: long symbol shares prefix with short symbol*/ for(j = 0; j < num; ++j) { unsigned reverse2 = reverse >> FIRSTBITS; /* l - FIRSTBITS bits */ unsigned index2 = start + (reverse2 | (j << (l - FIRSTBITS))); tree->table_len[index2] = l; tree->table_value[index2] = (unsigned short)i; } } } if(numpresent < 2) { /* In case of exactly 1 symbol, in theory the huffman symbol needs 0 bits, but deflate uses 1 bit instead. In case of 0 symbols, no symbols can appear at all, but such huffman tree could still exist (e.g. if distance codes are never used). In both cases, not all symbols of the table will be filled in. Fill them in with an invalid symbol value so returning them from huffmanDecodeSymbol will cause error. */ for(i = 0; i < size; ++i) { if(tree->table_len[i] == 16) { /* As length, use a value smaller than FIRSTBITS for the head table, and a value larger than FIRSTBITS for the secondary table, to ensure valid behavior for advanceBits when reading this symbol. */ tree->table_len[i] = (i < headsize) ? 1 : (FIRSTBITS + 1); tree->table_value[i] = INVALIDSYMBOL; } } } else { /* A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. If that is not the case (due to too long length codes), the table will not have been fully used, and this is an error (not all bit combinations can be decoded): an oversubscribed huffman tree, indicated by error 55. */ for(i = 0; i < size; ++i) { if(tree->table_len[i] == 16) return 55; } } 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) { unsigned* blcount; unsigned* nextcode; unsigned error = 0; unsigned bits, n; tree->codes = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned)); blcount = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned)); nextcode = (unsigned*)lodepng_malloc((tree->maxbitlen + 1) * sizeof(unsigned)); if(!tree->codes || !blcount || !nextcode) error = 83; /*alloc fail*/ if(!error) { for(n = 0; n != tree->maxbitlen + 1; n++) blcount[n] = nextcode[n] = 0; /*step 1: count number of instances of each code length*/ for(bits = 0; bits != tree->numcodes; ++bits) ++blcount[tree->lengths[bits]]; /*step 2: generate the nextcode values*/ for(bits = 1; bits <= tree->maxbitlen; ++bits) { nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1u; } /*step 3: generate all the codes*/ for(n = 0; n != tree->numcodes; ++n) { if(tree->lengths[n] != 0) { tree->codes[n] = nextcode[tree->lengths[n]]++; /*remove superfluous bits from the code*/ tree->codes[n] &= ((1u << tree->lengths[n]) - 1u); } } } lodepng_free(blcount); lodepng_free(nextcode); if(!error) error = HuffmanTree_makeTable(tree); 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 /*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding", Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/ /*chain node for boundary package merge*/ typedef struct BPMNode { int weight; /*the sum of all weights in this chain*/ unsigned index; /*index of this leaf node (called "count" in the paper)*/ struct BPMNode* tail; /*the next nodes in this chain (null if last)*/ int in_use; } BPMNode; /*lists of chains*/ typedef struct BPMLists { /*memory pool*/ unsigned memsize; BPMNode* memory; unsigned numfree; unsigned nextfree; BPMNode** freelist; /*two heads of lookahead chains per list*/ unsigned listsize; BPMNode** chains0; BPMNode** chains1; } BPMLists; /*creates a new chain node with the given parameters, from the memory in the lists */ static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) { unsigned i; BPMNode* result; /*memory full, so garbage collect*/ if(lists->nextfree >= lists->numfree) { /*mark only those that are in use*/ for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0; for(i = 0; i != lists->listsize; ++i) { BPMNode* node; for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1; for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1; } /*collect those that are free*/ lists->numfree = 0; for(i = 0; i != lists->memsize; ++i) { if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i]; } lists->nextfree = 0; } result = lists->freelist[lists->nextfree++]; result->weight = weight; result->index = index; result->tail = tail; return result; } /*sort the leaves with stable mergesort*/ static void bpmnode_sort(BPMNode* leaves, size_t num) { BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num); size_t width, counter = 0; for(width = 1; width < num; width *= 2) { BPMNode* a = (counter & 1) ? mem : leaves; BPMNode* b = (counter & 1) ? leaves : mem; size_t p; for(p = 0; p < num; p += 2 * width) { size_t q = (p + width > num) ? num : (p + width); size_t r = (p + 2 * width > num) ? num : (p + 2 * width); size_t i = p, j = q, k; for(k = p; k < r; k++) { if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++]; else b[k] = a[j++]; } } counter++; } if(counter & 1) lodepng_memcpy(leaves, mem, sizeof(*leaves) * num); lodepng_free(mem); } /*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/ static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) { unsigned lastindex = lists->chains1[c]->index; if(c == 0) { if(lastindex >= numpresent) return; lists->chains0[c] = lists->chains1[c]; lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0); } else { /*sum of the weights of the head nodes of the previous lookahead chains.*/ int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight; lists->chains0[c] = lists->chains1[c]; if(lastindex < numpresent && sum > leaves[lastindex].weight) { lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail); return; } lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]); /*in the end we are only interested in the chain of the last list, so no need to recurse if we're at the last one (this gives measurable speedup)*/ if(num + 1 < (int)(2 * numpresent - 2)) { boundaryPM(lists, leaves, numpresent, c - 1, num); boundaryPM(lists, leaves, numpresent, c - 1, num); } } } unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, size_t numcodes, unsigned maxbitlen) { unsigned error = 0; unsigned i; size_t numpresent = 0; /*number of symbols with non-zero frequency*/ BPMNode* leaves; /*the symbols, only those with > 0 frequency*/ if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/ leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves)); if(!leaves) return 83; /*alloc fail*/ for(i = 0; i != numcodes; ++i) { if(frequencies[i] > 0) { leaves[numpresent].weight = (int)frequencies[i]; leaves[numpresent].index = i; ++numpresent; } } lodepng_memset(lengths, 0, numcodes * sizeof(*lengths)); /*ensure at least two present symbols. There should be at least one symbol according to RFC 1951 section 3.2.7. Some 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 theoretical 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) { lengths[leaves[0].index] = 1; lengths[leaves[0].index == 0 ? 1 : 0] = 1; } else { BPMLists lists; BPMNode* node; bpmnode_sort(leaves, numpresent); lists.listsize = maxbitlen; lists.memsize = 2 * maxbitlen * (maxbitlen + 1); lists.nextfree = 0; lists.numfree = lists.memsize; lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory)); lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*)); lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/ if(!error) { for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i]; bpmnode_create(&lists, leaves[0].weight, 1, 0); bpmnode_create(&lists, leaves[1].weight, 2, 0); for(i = 0; i != lists.listsize; ++i) { lists.chains0[i] = &lists.memory[0]; lists.chains1[i] = &lists.memory[1]; } /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/ for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i); for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) { for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index]; } } lodepng_free(lists.memory); lodepng_free(lists.freelist); lodepng_free(lists.chains0); lodepng_free(lists.chains1); } lodepng_free(leaves); 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->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); if(!tree->lengths) return 83; /*alloc fail*/ tree->maxbitlen = maxbitlen; tree->numcodes = (unsigned)numcodes; /*number of symbols*/ error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); if(!error) error = HuffmanTree_makeFromLengths2(tree); return error; } #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. The bit reader must already have been ensured at least 15 bits */ static unsigned huffmanDecodeSymbol(LodePNGBitReader* reader, const HuffmanTree* codetree) { unsigned short code = peekBits(reader, FIRSTBITS); unsigned short l = codetree->table_len[code]; unsigned short value = codetree->table_value[code]; if(l <= FIRSTBITS) { advanceBits(reader, l); return value; } else { advanceBits(reader, FIRSTBITS); value += peekBits(reader, l - FIRSTBITS); advanceBits(reader, codetree->table_len[value] - FIRSTBITS); return codetree->table_value[value]; } } #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 Returns error code.*/ static unsigned getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) { unsigned error = generateFixedLitLenTree(tree_ll); if(error) return error; return 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, LodePNGBitReader* reader) { /*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; /*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(reader->bitsize - reader->bp < 14) return 49; /*error: the bit pointer is or will go past the memory*/ ensureBits17(reader, 14); /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/ HLIT = readBits(reader, 5) + 257; /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/ HDIST = readBits(reader, 5) + 1; /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/ HCLEN = readBits(reader, 4) + 4; bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); if(!bitlen_cl) return 83 /*alloc fail*/; HuffmanTree_init(&tree_cl); while(!error) { /*read the code length codes out of 3 * (amount of code length codes) bits*/ if(lodepng_gtofl(reader->bp, HCLEN * 3, reader->bitsize)) { ERROR_BREAK(50); /*error: the bit pointer is or will go past the memory*/ } for(i = 0; i != HCLEN; ++i) { ensureBits9(reader, 3); /*out of bounds already checked above */ bitlen_cl[CLCL_ORDER[i]] = readBits(reader, 3); } for(i = HCLEN; i != NUM_CODE_LENGTH_CODES; ++i) { bitlen_cl[CLCL_ORDER[i]] = 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*/); lodepng_memset(bitlen_ll, 0, NUM_DEFLATE_CODE_SYMBOLS * sizeof(*bitlen_ll)); lodepng_memset(bitlen_d, 0, NUM_DISTANCE_SYMBOLS * sizeof(*bitlen_d)); /*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; ensureBits25(reader, 22); /* up to 15 bits for huffman code, up to 7 extra bits below*/ code = huffmanDecodeSymbol(reader, &tree_cl); 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*/ replength += readBits(reader, 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*/ replength += readBits(reader, 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*/ replength += readBits(reader, 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 == INVALIDSYMBOL)*/ { ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/ } /*check if any of the ensureBits above went out of bounds*/ if(reader->bp > reader->bitsize) { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ /* TODO: revise error codes 10,11,50: the above comment is no longer valid */ ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ } } 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. btype must be 1 or 2.*/ static unsigned inflateHuffmanBlock(ucvector* out, LodePNGBitReader* reader, unsigned btype, size_t max_output_size) { unsigned error = 0; HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ HuffmanTree tree_d; /*the huffman tree for distance codes*/ const size_t reserved_size = 260; /* must be at least 258 for max length, and a few extra for adding a few extra literals */ int done = 0; if(!ucvector_reserve(out, out->size + reserved_size)) return 83; /*alloc fail*/ HuffmanTree_init(&tree_ll); HuffmanTree_init(&tree_d); if(btype == 1) error = getTreeInflateFixed(&tree_ll, &tree_d); else /*if(btype == 2)*/ error = getTreeInflateDynamic(&tree_ll, &tree_d, reader); while(!error && !done) /*decode all symbols until end reached, breaks at end code*/ { /*code_ll is literal, length or end code*/ unsigned code_ll; /* ensure enough bits for 2 huffman code reads (15 bits each): if the first is a literal, a second literal is read at once. This appears to be slightly faster, than ensuring 20 bits here for 1 huffman symbol and the potential 5 extra bits for the length symbol.*/ ensureBits32(reader, 30); code_ll = huffmanDecodeSymbol(reader, &tree_ll); if(code_ll <= 255) { /*slightly faster code path if multiple literals in a row*/ out->data[out->size++] = (unsigned char)code_ll; code_ll = huffmanDecodeSymbol(reader, &tree_ll); } if(code_ll <= 255) /*literal symbol*/ { out->data[out->size++] = (unsigned char)code_ll; } 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, 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(numextrabits_l != 0) { /* bits already ensured above */ ensureBits25(reader, 5); length += readBits(reader, numextrabits_l); } /*part 3: get distance code*/ ensureBits32(reader, 28); /* up to 15 for the huffman symbol, up to 13 for the extra bits */ code_d = huffmanDecodeSymbol(reader, &tree_d); if(code_d > 29) { if(code_d <= 31) { ERROR_BREAK(18); /*error: invalid distance code (30-31 are never used)*/ } else /* if(code_d == INVALIDSYMBOL) */{ ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/ } } distance = DISTANCEBASE[code_d]; /*part 4: get extra bits from distance*/ numextrabits_d = DISTANCEEXTRA[code_d]; if(numextrabits_d != 0) { /* bits already ensured above */ distance += readBits(reader, numextrabits_d); } /*part 5: fill in all the out[n] values based on the length and dist*/ start = out->size; if(distance > start) ERROR_BREAK(52); /*too long backward distance*/ backward = start - distance; out->size += length; if(distance < length) { size_t forward; lodepng_memcpy(out->data + start, out->data + backward, distance); start += distance; for(forward = distance; forward < length; ++forward) { out->data[start++] = out->data[backward++]; } } else { lodepng_memcpy(out->data + start, out->data + backward, length); } } else if(code_ll == 256) { done = 1; /*end code, finish the loop*/ } else /*if(code_ll == INVALIDSYMBOL)*/ { ERROR_BREAK(16); /*error: tried to read disallowed huffman symbol*/ } if(out->allocsize - out->size < reserved_size) { if(!ucvector_reserve(out, out->size + reserved_size)) ERROR_BREAK(83); /*alloc fail*/ } /*check if any of the ensureBits above went out of bounds*/ if(reader->bp > reader->bitsize) { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ /* TODO: revise error codes 10,11,50: the above comment is no longer valid */ ERROR_BREAK(51); /*error, bit pointer jumps past memory*/ } if(max_output_size && out->size > max_output_size) { ERROR_BREAK(109); /*error, larger than max size*/ } } HuffmanTree_cleanup(&tree_ll); HuffmanTree_cleanup(&tree_d); return error; } static unsigned inflateNoCompression(ucvector* out, LodePNGBitReader* reader, const LodePNGDecompressSettings* settings) { size_t bytepos; size_t size = reader->size; unsigned LEN, NLEN, error = 0; /*go to first boundary of byte*/ bytepos = (reader->bp + 7u) >> 3u; /*read LEN (2 bytes) and NLEN (2 bytes)*/ if(bytepos + 4 >= size) return 52; /*error, bit pointer will jump past memory*/ LEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2; NLEN = (unsigned)reader->data[bytepos] + ((unsigned)reader->data[bytepos + 1] << 8u); bytepos += 2; /*check if 16-bit NLEN is really the one's complement of LEN*/ if(!settings->ignore_nlen && LEN + NLEN != 65535) { return 21; /*error: NLEN is not one's complement of LEN*/ } if(!ucvector_resize(out, out->size + LEN)) return 83; /*alloc fail*/ /*read the literal data: LEN bytes are now stored in the out buffer*/ if(bytepos + LEN > size) return 23; /*error: reading outside of in buffer*/ /*out->data can be NULL (when LEN is zero), and arithmetics on NULL ptr is undefined*/ if (LEN) { lodepng_memcpy(out->data + out->size - LEN, reader->data + bytepos, LEN); bytepos += LEN; } reader->bp = bytepos << 3u; return error; } static unsigned lodepng_inflatev(ucvector* out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { unsigned BFINAL = 0; LodePNGBitReader reader; unsigned error = LodePNGBitReader_init(&reader, in, insize); if(error) return error; while(!BFINAL) { unsigned BTYPE; if(reader.bitsize - reader.bp < 3) return 52; /*error, bit pointer will jump past memory*/ ensureBits9(&reader, 3); BFINAL = readBits(&reader, 1); BTYPE = readBits(&reader, 2); if(BTYPE == 3) return 20; /*error: invalid BTYPE*/ else if(BTYPE == 0) error = inflateNoCompression(out, &reader, settings); /*no compression*/ else error = inflateHuffmanBlock(out, &reader, BTYPE, settings->max_output_size); /*compression, BTYPE 01 or 10*/ if(!error && settings->max_output_size && out->size > settings->max_output_size) error = 109; if(error) break; } return error; } unsigned lodepng_inflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { ucvector v = ucvector_init(*out, *outsize); unsigned error = lodepng_inflatev(&v, in, insize, settings); *out = v.data; *outsize = v.size; return error; } static unsigned inflatev(ucvector* out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { if(settings->custom_inflate) { unsigned error = settings->custom_inflate(&out->data, &out->size, in, insize, settings); out->allocsize = out->size; if(error) { /*the custom inflate is allowed to have its own error codes, however, we translate it to code 110*/ error = 110; /*if there's a max output size, and the custom zlib returned error, then indicate that error instead*/ if(settings->max_output_size && out->size > settings->max_output_size) error = 109; } return error; } else { return lodepng_inflatev(out, in, insize, settings); } } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* ////////////////////////////////////////////////////////////////////////// */ /* / Deflator (Compressor) / */ /* ////////////////////////////////////////////////////////////////////////// */ static const unsigned MAX_SUPPORTED_DEFLATE_LENGTH = 258; /*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) { /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/ size_t left = 1; size_t right = array_size - 1; while(left <= right) { size_t mid = (left + right) >> 1; if(array[mid] >= value) right = mid - 1; else left = mid + 1; } if(left >= array_size || array[left] > value) left--; return left; } 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]); size_t pos = values->size; /*TODO: return error when this fails (out of memory)*/ unsigned ok = uivector_resize(values, values->size + 4); if(ok) { values->data[pos + 0] = length_code + FIRST_LENGTH_CODE_INDEX; values->data[pos + 1] = extra_length; values->data[pos + 2] = dist_code; values->data[pos + 3] = 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] = (int)wpos; hash->zeros[wpos] = numzeros; if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; hash->headz[numzeros] = (int)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 / 8u; 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 = (unsigned)(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, numdeflateblocks = (datasize + 65534u) / 65535u; unsigned datapos = 0; for(i = 0; i != numdeflateblocks; ++i) { unsigned BFINAL, BTYPE, LEN, NLEN; unsigned char firstbyte; size_t pos = out->size; BFINAL = (i == numdeflateblocks - 1); BTYPE = 0; LEN = 65535; if(datasize - datapos < 65535u) LEN = (unsigned)datasize - datapos; NLEN = 65535 - LEN; if(!ucvector_resize(out, out->size + LEN + 5)) return 83; /*alloc fail*/ firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1u) << 1u) + ((BTYPE & 2u) << 1u)); out->data[pos + 0] = firstbyte; out->data[pos + 1] = (unsigned char)(LEN & 255); out->data[pos + 2] = (unsigned char)(LEN >> 8u); out->data[pos + 3] = (unsigned char)(NLEN & 255); out->data[pos + 4] = (unsigned char)(NLEN >> 8u); lodepng_memcpy(out->data + pos + 5, data + datapos, LEN); datapos += LEN; } 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(LodePNGBitWriter* writer, 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]; writeBitsReversed(writer, tree_ll->codes[val], tree_ll->lengths[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]; writeBits(writer, length_extra_bits, n_length_extra_bits); writeBitsReversed(writer, tree_d->codes[distance_code], tree_d->lengths[distance_code]); writeBits(writer, 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(LodePNGBitWriter* writer, 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 lengths 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*/ unsigned* frequencies_ll = 0; /*frequency of lit,len codes*/ unsigned* frequencies_d = 0; /*frequency of dist codes*/ unsigned* frequencies_cl = 0; /*frequency of code length codes*/ unsigned* bitlen_lld = 0; /*lit,len,dist code lengths (int bits), literally (without repeat codes).*/ unsigned* bitlen_lld_e = 0; /*bitlen_lld encoded with repeat codes (this is a rudimentary run length compression)*/ size_t datasize = dataend - datapos; /* If we could call "bitlen_cl" the the code length code lengths ("clcl"), that is the bit lengths of codes to represent tree_cl in CLCL_ORDER, then due to the huffman compression of huffman tree representations ("two levels"), there are some analogies: 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 i; size_t numcodes_ll, numcodes_d, numcodes_lld, numcodes_lld_e, numcodes_cl; unsigned HLIT, HDIST, HCLEN; uivector_init(&lz77_encoded); HuffmanTree_init(&tree_ll); HuffmanTree_init(&tree_d); HuffmanTree_init(&tree_cl); /* could fit on stack, but >1KB is on the larger side so allocate instead */ frequencies_ll = (unsigned*)lodepng_malloc(286 * sizeof(*frequencies_ll)); frequencies_d = (unsigned*)lodepng_malloc(30 * sizeof(*frequencies_d)); frequencies_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl)); if(!frequencies_ll || !frequencies_d || !frequencies_cl) error = 83; /*alloc fail*/ /*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) { lodepng_memset(frequencies_ll, 0, 286 * sizeof(*frequencies_ll)); lodepng_memset(frequencies_d, 0, 30 * sizeof(*frequencies_d)); lodepng_memset(frequencies_cl, 0, NUM_CODE_LENGTH_CODES * sizeof(*frequencies_cl)); 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 - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/ } /*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[symbol]; if(symbol > 256) { unsigned dist = lz77_encoded.data[i + 2]; ++frequencies_d[dist]; i += 3; } } frequencies_ll[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, 257, 286, 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, 2, 30, 15); if(error) break; numcodes_ll = LODEPNG_MIN(tree_ll.numcodes, 286); numcodes_d = LODEPNG_MIN(tree_d.numcodes, 30); /*store the code lengths of both generated trees in bitlen_lld*/ numcodes_lld = numcodes_ll + numcodes_d; bitlen_lld = (unsigned*)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld)); /*numcodes_lld_e never needs more size than bitlen_lld*/ bitlen_lld_e = (unsigned*)lodepng_malloc(numcodes_lld * sizeof(*bitlen_lld_e)); if(!bitlen_lld || !bitlen_lld_e) ERROR_BREAK(83); /*alloc fail*/ numcodes_lld_e = 0; for(i = 0; i != numcodes_ll; ++i) bitlen_lld[i] = tree_ll.lengths[i]; for(i = 0; i != numcodes_d; ++i) bitlen_lld[numcodes_ll + i] = tree_d.lengths[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 != numcodes_lld; ++i) { unsigned j = 0; /*amount of repetitions*/ while(i + j + 1 < numcodes_lld && bitlen_lld[i + j + 1] == bitlen_lld[i]) ++j; if(bitlen_lld[i] == 0 && j >= 2) /*repeat code for zeroes*/ { ++j; /*include the first zero*/ if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ { bitlen_lld_e[numcodes_lld_e++] = 17; bitlen_lld_e[numcodes_lld_e++] = j - 3; } else /*repeat code 18 supports max 138 zeroes*/ { if(j > 138) j = 138; bitlen_lld_e[numcodes_lld_e++] = 18; bitlen_lld_e[numcodes_lld_e++] = j - 11; } i += (j - 1); } else if(j >= 3) /*repeat code for value other than zero*/ { size_t k; unsigned num = j / 6u, rest = j % 6u; bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i]; for(k = 0; k < num; ++k) { bitlen_lld_e[numcodes_lld_e++] = 16; bitlen_lld_e[numcodes_lld_e++] = 6 - 3; } if(rest >= 3) { bitlen_lld_e[numcodes_lld_e++] = 16; bitlen_lld_e[numcodes_lld_e++] = rest - 3; } else j -= rest; i += j; } else /*too short to benefit from repeat code*/ { bitlen_lld_e[numcodes_lld_e++] = bitlen_lld[i]; } } /*generate tree_cl, the huffmantree of huffmantrees*/ for(i = 0; i != numcodes_lld_e; ++i) { ++frequencies_cl[bitlen_lld_e[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[i] >= 16) ++i; } error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl, NUM_CODE_LENGTH_CODES, NUM_CODE_LENGTH_CODES, 7); if(error) break; /*compute amount of code-length-code-lengths to output*/ numcodes_cl = NUM_CODE_LENGTH_CODES; /*trim zeros at the end (using CLCL_ORDER), but minimum size must be 4 (see HCLEN below)*/ while(numcodes_cl > 4u && tree_cl.lengths[CLCL_ORDER[numcodes_cl - 1u]] == 0) { numcodes_cl--; } /* 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 lengths 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*/ writeBits(writer, BFINAL, 1); writeBits(writer, 0, 1); /*first bit of BTYPE "dynamic"*/ writeBits(writer, 1, 1); /*second bit of BTYPE "dynamic"*/ /*write the HLIT, HDIST and HCLEN values*/ /*all three sizes take trimmed ending zeroes into account, done either by HuffmanTree_makeFromFrequencies or in the loop for numcodes_cl above, which saves space. */ HLIT = (unsigned)(numcodes_ll - 257); HDIST = (unsigned)(numcodes_d - 1); HCLEN = (unsigned)(numcodes_cl - 4); writeBits(writer, HLIT, 5); writeBits(writer, HDIST, 5); writeBits(writer, HCLEN, 4); /*write the code lengths of the code length alphabet ("bitlen_cl")*/ for(i = 0; i != numcodes_cl; ++i) writeBits(writer, tree_cl.lengths[CLCL_ORDER[i]], 3); /*write the lengths of the lit/len AND the dist alphabet*/ for(i = 0; i != numcodes_lld_e; ++i) { writeBitsReversed(writer, tree_cl.codes[bitlen_lld_e[i]], tree_cl.lengths[bitlen_lld_e[i]]); /*extra bits of repeat codes*/ if(bitlen_lld_e[i] == 16) writeBits(writer, bitlen_lld_e[++i], 2); else if(bitlen_lld_e[i] == 17) writeBits(writer, bitlen_lld_e[++i], 3); else if(bitlen_lld_e[i] == 18) writeBits(writer, bitlen_lld_e[++i], 7); } /*write the compressed data symbols*/ writeLZ77data(writer, &lz77_encoded, &tree_ll, &tree_d); /*error: the length of the end code 256 must be larger than 0*/ if(tree_ll.lengths[256] == 0) ERROR_BREAK(64); /*write the end code*/ writeBitsReversed(writer, tree_ll.codes[256], tree_ll.lengths[256]); break; /*end of error-while*/ } /*cleanup*/ uivector_cleanup(&lz77_encoded); HuffmanTree_cleanup(&tree_ll); HuffmanTree_cleanup(&tree_d); HuffmanTree_cleanup(&tree_cl); lodepng_free(frequencies_ll); lodepng_free(frequencies_d); lodepng_free(frequencies_cl); lodepng_free(bitlen_lld); lodepng_free(bitlen_lld_e); return error; } static unsigned deflateFixed(LodePNGBitWriter* writer, 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); error = generateFixedLitLenTree(&tree_ll); if(!error) error = generateFixedDistanceTree(&tree_d); if(!error) { writeBits(writer, BFINAL, 1); writeBits(writer, 1, 1); /*first bit of BTYPE*/ writeBits(writer, 0, 1); /*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(writer, &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) { writeBitsReversed(writer, tree_ll.codes[data[i]], tree_ll.lengths[data[i]]); } } /*add END code*/ if(!error) writeBitsReversed(writer,tree_ll.codes[256], tree_ll.lengths[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; Hash hash; LodePNGBitWriter writer; LodePNGBitWriter_init(&writer, out); 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)*/ { /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/ blocksize = insize / 8u + 8; if(blocksize < 65536) blocksize = 65536; if(blocksize > 262144) blocksize = 262144; } numdeflateblocks = (insize + blocksize - 1) / blocksize; if(numdeflateblocks == 0) numdeflateblocks = 1; error = hash_init(&hash, settings->windowsize); if(!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(&writer, &hash, in, start, end, settings, final); else if(settings->btype == 2) error = deflateDynamic(&writer, &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) { ucvector v = ucvector_init(*out, *outsize); unsigned 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) { unsigned error = settings->custom_deflate(out, outsize, in, insize, settings); /*the custom deflate is allowed to have its own error codes, however, we translate it to code 111*/ return error ? 111 : 0; } 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 & 0xffffu; unsigned s2 = (adler >> 16u) & 0xffffu; while(len != 0u) { unsigned i; /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/ unsigned amount = len > 5552u ? 5552u : len; len -= amount; for(i = 0; i != amount; ++i) { s1 += (*data++); s2 += s1; } s1 %= 65521u; s2 %= 65521u; } return (s2 << 16u) | s1; } /*Return the adler32 of the bytes data[0..len-1]*/ static unsigned adler32(const unsigned char* data, unsigned len) { return update_adler32(1u, data, len); } /* ////////////////////////////////////////////////////////////////////////// */ /* / Zlib / */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_DECODER static unsigned lodepng_zlib_decompressv(ucvector* out, 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 = inflatev(out, in + 2, insize - 2, settings); if(error) return error; if(!settings->ignore_adler32) { unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); unsigned checksum = adler32(out->data, (unsigned)(out->size)); if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ } return 0; /*no error*/ } unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { ucvector v = ucvector_init(*out, *outsize); unsigned error = lodepng_zlib_decompressv(&v, in, insize, settings); *out = v.data; *outsize = v.size; return error; } /*expected_size is expected output size, to avoid intermediate allocations. Set to 0 if not known. */ static unsigned zlib_decompress(unsigned char** out, size_t* outsize, size_t expected_size, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { unsigned error; if(settings->custom_zlib) { error = settings->custom_zlib(out, outsize, in, insize, settings); if(error) { /*the custom zlib is allowed to have its own error codes, however, we translate it to code 110*/ error = 110; /*if there's a max output size, and the custom zlib returned error, then indicate that error instead*/ if(settings->max_output_size && *outsize > settings->max_output_size) error = 109; } } else { ucvector v = ucvector_init(*out, *outsize); if(expected_size) { /*reserve the memory to avoid intermediate reallocations*/ ucvector_resize(&v, *outsize + expected_size); v.size = *outsize; } error = lodepng_zlib_decompressv(&v, in, insize, settings); *out = v.data; *outsize = v.size; } return error; } #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) { size_t i; unsigned error; unsigned char* deflatedata = 0; size_t deflatesize = 0; error = deflate(&deflatedata, &deflatesize, in, insize, settings); *out = NULL; *outsize = 0; if(!error) { *outsize = deflatesize + 6; *out = (unsigned char*)lodepng_malloc(*outsize); if(!*out) error = 83; /*alloc fail*/ } if(!error) { unsigned ADLER32 = adler32(in, (unsigned)insize); /*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; (*out)[0] = (unsigned char)(CMFFLG >> 8); (*out)[1] = (unsigned char)(CMFFLG & 255); for(i = 0; i != deflatesize; ++i) (*out)[i + 2] = deflatedata[i]; lodepng_set32bitInt(&(*out)[*outsize - 4], ADLER32); } lodepng_free(deflatedata); 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) { unsigned error = settings->custom_zlib(out, outsize, in, insize, settings); /*the custom zlib is allowed to have its own error codes, however, we translate it to code 111*/ return error ? 111 : 0; } 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, size_t expected_size, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ (void)expected_size; 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->ignore_nlen = 0; settings->max_output_size = 0; settings->custom_zlib = 0; settings->custom_inflate = 0; settings->custom_context = 0; } const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0, 0, 0}; #endif /*LODEPNG_COMPILE_DECODER*/ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* // End of Zlib related code. Begin of PNG related code. // */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_PNG /* ////////////////////////////////////////////////////////////////////////// */ /* / CRC32 / */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_CRC static const unsigned lodepng_crc32_table0[256] = { 0x00000000u, 0x77073096u, 0xee0e612cu, 0x990951bau, 0x076dc419u, 0x706af48fu, 0xe963a535u, 0x9e6495a3u, 0x0edb8832u, 0x79dcb8a4u, 0xe0d5e91eu, 0x97d2d988u, 0x09b64c2bu, 0x7eb17cbdu, 0xe7b82d07u, 0x90bf1d91u, 0x1db71064u, 0x6ab020f2u, 0xf3b97148u, 0x84be41deu, 0x1adad47du, 0x6ddde4ebu, 0xf4d4b551u, 0x83d385c7u, 0x136c9856u, 0x646ba8c0u, 0xfd62f97au, 0x8a65c9ecu, 0x14015c4fu, 0x63066cd9u, 0xfa0f3d63u, 0x8d080df5u, 0x3b6e20c8u, 0x4c69105eu, 0xd56041e4u, 0xa2677172u, 0x3c03e4d1u, 0x4b04d447u, 0xd20d85fdu, 0xa50ab56bu, 0x35b5a8fau, 0x42b2986cu, 0xdbbbc9d6u, 0xacbcf940u, 0x32d86ce3u, 0x45df5c75u, 0xdcd60dcfu, 0xabd13d59u, 0x26d930acu, 0x51de003au, 0xc8d75180u, 0xbfd06116u, 0x21b4f4b5u, 0x56b3c423u, 0xcfba9599u, 0xb8bda50fu, 0x2802b89eu, 0x5f058808u, 0xc60cd9b2u, 0xb10be924u, 0x2f6f7c87u, 0x58684c11u, 0xc1611dabu, 0xb6662d3du, 0x76dc4190u, 0x01db7106u, 0x98d220bcu, 0xefd5102au, 0x71b18589u, 0x06b6b51fu, 0x9fbfe4a5u, 0xe8b8d433u, 0x7807c9a2u, 0x0f00f934u, 0x9609a88eu, 0xe10e9818u, 0x7f6a0dbbu, 0x086d3d2du, 0x91646c97u, 0xe6635c01u, 0x6b6b51f4u, 0x1c6c6162u, 0x856530d8u, 0xf262004eu, 0x6c0695edu, 0x1b01a57bu, 0x8208f4c1u, 0xf50fc457u, 0x65b0d9c6u, 0x12b7e950u, 0x8bbeb8eau, 0xfcb9887cu, 0x62dd1ddfu, 0x15da2d49u, 0x8cd37cf3u, 0xfbd44c65u, 0x4db26158u, 0x3ab551ceu, 0xa3bc0074u, 0xd4bb30e2u, 0x4adfa541u, 0x3dd895d7u, 0xa4d1c46du, 0xd3d6f4fbu, 0x4369e96au, 0x346ed9fcu, 0xad678846u, 0xda60b8d0u, 0x44042d73u, 0x33031de5u, 0xaa0a4c5fu, 0xdd0d7cc9u, 0x5005713cu, 0x270241aau, 0xbe0b1010u, 0xc90c2086u, 0x5768b525u, 0x206f85b3u, 0xb966d409u, 0xce61e49fu, 0x5edef90eu, 0x29d9c998u, 0xb0d09822u, 0xc7d7a8b4u, 0x59b33d17u, 0x2eb40d81u, 0xb7bd5c3bu, 0xc0ba6cadu, 0xedb88320u, 0x9abfb3b6u, 0x03b6e20cu, 0x74b1d29au, 0xead54739u, 0x9dd277afu, 0x04db2615u, 0x73dc1683u, 0xe3630b12u, 0x94643b84u, 0x0d6d6a3eu, 0x7a6a5aa8u, 0xe40ecf0bu, 0x9309ff9du, 0x0a00ae27u, 0x7d079eb1u, 0xf00f9344u, 0x8708a3d2u, 0x1e01f268u, 0x6906c2feu, 0xf762575du, 0x806567cbu, 0x196c3671u, 0x6e6b06e7u, 0xfed41b76u, 0x89d32be0u, 0x10da7a5au, 0x67dd4accu, 0xf9b9df6fu, 0x8ebeeff9u, 0x17b7be43u, 0x60b08ed5u, 0xd6d6a3e8u, 0xa1d1937eu, 0x38d8c2c4u, 0x4fdff252u, 0xd1bb67f1u, 0xa6bc5767u, 0x3fb506ddu, 0x48b2364bu, 0xd80d2bdau, 0xaf0a1b4cu, 0x36034af6u, 0x41047a60u, 0xdf60efc3u, 0xa867df55u, 0x316e8eefu, 0x4669be79u, 0xcb61b38cu, 0xbc66831au, 0x256fd2a0u, 0x5268e236u, 0xcc0c7795u, 0xbb0b4703u, 0x220216b9u, 0x5505262fu, 0xc5ba3bbeu, 0xb2bd0b28u, 0x2bb45a92u, 0x5cb36a04u, 0xc2d7ffa7u, 0xb5d0cf31u, 0x2cd99e8bu, 0x5bdeae1du, 0x9b64c2b0u, 0xec63f226u, 0x756aa39cu, 0x026d930au, 0x9c0906a9u, 0xeb0e363fu, 0x72076785u, 0x05005713u, 0x95bf4a82u, 0xe2b87a14u, 0x7bb12baeu, 0x0cb61b38u, 0x92d28e9bu, 0xe5d5be0du, 0x7cdcefb7u, 0x0bdbdf21u, 0x86d3d2d4u, 0xf1d4e242u, 0x68ddb3f8u, 0x1fda836eu, 0x81be16cdu, 0xf6b9265bu, 0x6fb077e1u, 0x18b74777u, 0x88085ae6u, 0xff0f6a70u, 0x66063bcau, 0x11010b5cu, 0x8f659effu, 0xf862ae69u, 0x616bffd3u, 0x166ccf45u, 0xa00ae278u, 0xd70dd2eeu, 0x4e048354u, 0x3903b3c2u, 0xa7672661u, 0xd06016f7u, 0x4969474du, 0x3e6e77dbu, 0xaed16a4au, 0xd9d65adcu, 0x40df0b66u, 0x37d83bf0u, 0xa9bcae53u, 0xdebb9ec5u, 0x47b2cf7fu, 0x30b5ffe9u, 0xbdbdf21cu, 0xcabac28au, 0x53b39330u, 0x24b4a3a6u, 0xbad03605u, 0xcdd70693u, 0x54de5729u, 0x23d967bfu, 0xb3667a2eu, 0xc4614ab8u, 0x5d681b02u, 0x2a6f2b94u, 0xb40bbe37u, 0xc30c8ea1u, 0x5a05df1bu, 0x2d02ef8du }; static const unsigned lodepng_crc32_table1[256] = { 0x00000000u, 0x191b3141u, 0x32366282u, 0x2b2d53c3u, 0x646cc504u, 0x7d77f445u, 0x565aa786u, 0x4f4196c7u, 0xc8d98a08u, 0xd1c2bb49u, 0xfaefe88au, 0xe3f4d9cbu, 0xacb54f0cu, 0xb5ae7e4du, 0x9e832d8eu, 0x87981ccfu, 0x4ac21251u, 0x53d92310u, 0x78f470d3u, 0x61ef4192u, 0x2eaed755u, 0x37b5e614u, 0x1c98b5d7u, 0x05838496u, 0x821b9859u, 0x9b00a918u, 0xb02dfadbu, 0xa936cb9au, 0xe6775d5du, 0xff6c6c1cu, 0xd4413fdfu, 0xcd5a0e9eu, 0x958424a2u, 0x8c9f15e3u, 0xa7b24620u, 0xbea97761u, 0xf1e8e1a6u, 0xe8f3d0e7u, 0xc3de8324u, 0xdac5b265u, 0x5d5daeaau, 0x44469febu, 0x6f6bcc28u, 0x7670fd69u, 0x39316baeu, 0x202a5aefu, 0x0b07092cu, 0x121c386du, 0xdf4636f3u, 0xc65d07b2u, 0xed705471u, 0xf46b6530u, 0xbb2af3f7u, 0xa231c2b6u, 0x891c9175u, 0x9007a034u, 0x179fbcfbu, 0x0e848dbau, 0x25a9de79u, 0x3cb2ef38u, 0x73f379ffu, 0x6ae848beu, 0x41c51b7du, 0x58de2a3cu, 0xf0794f05u, 0xe9627e44u, 0xc24f2d87u, 0xdb541cc6u, 0x94158a01u, 0x8d0ebb40u, 0xa623e883u, 0xbf38d9c2u, 0x38a0c50du, 0x21bbf44cu, 0x0a96a78fu, 0x138d96ceu, 0x5ccc0009u, 0x45d73148u, 0x6efa628bu, 0x77e153cau, 0xbabb5d54u, 0xa3a06c15u, 0x888d3fd6u, 0x91960e97u, 0xded79850u, 0xc7cca911u, 0xece1fad2u, 0xf5facb93u, 0x7262d75cu, 0x6b79e61du, 0x4054b5deu, 0x594f849fu, 0x160e1258u, 0x0f152319u, 0x243870dau, 0x3d23419bu, 0x65fd6ba7u, 0x7ce65ae6u, 0x57cb0925u, 0x4ed03864u, 0x0191aea3u, 0x188a9fe2u, 0x33a7cc21u, 0x2abcfd60u, 0xad24e1afu, 0xb43fd0eeu, 0x9f12832du, 0x8609b26cu, 0xc94824abu, 0xd05315eau, 0xfb7e4629u, 0xe2657768u, 0x2f3f79f6u, 0x362448b7u, 0x1d091b74u, 0x04122a35u, 0x4b53bcf2u, 0x52488db3u, 0x7965de70u, 0x607eef31u, 0xe7e6f3feu, 0xfefdc2bfu, 0xd5d0917cu, 0xcccba03du, 0x838a36fau, 0x9a9107bbu, 0xb1bc5478u, 0xa8a76539u, 0x3b83984bu, 0x2298a90au, 0x09b5fac9u, 0x10aecb88u, 0x5fef5d4fu, 0x46f46c0eu, 0x6dd93fcdu, 0x74c20e8cu, 0xf35a1243u, 0xea412302u, 0xc16c70c1u, 0xd8774180u, 0x9736d747u, 0x8e2de606u, 0xa500b5c5u, 0xbc1b8484u, 0x71418a1au, 0x685abb5bu, 0x4377e898u, 0x5a6cd9d9u, 0x152d4f1eu, 0x0c367e5fu, 0x271b2d9cu, 0x3e001cddu, 0xb9980012u, 0xa0833153u, 0x8bae6290u, 0x92b553d1u, 0xddf4c516u, 0xc4eff457u, 0xefc2a794u, 0xf6d996d5u, 0xae07bce9u, 0xb71c8da8u, 0x9c31de6bu, 0x852aef2au, 0xca6b79edu, 0xd37048acu, 0xf85d1b6fu, 0xe1462a2eu, 0x66de36e1u, 0x7fc507a0u, 0x54e85463u, 0x4df36522u, 0x02b2f3e5u, 0x1ba9c2a4u, 0x30849167u, 0x299fa026u, 0xe4c5aeb8u, 0xfdde9ff9u, 0xd6f3cc3au, 0xcfe8fd7bu, 0x80a96bbcu, 0x99b25afdu, 0xb29f093eu, 0xab84387fu, 0x2c1c24b0u, 0x350715f1u, 0x1e2a4632u, 0x07317773u, 0x4870e1b4u, 0x516bd0f5u, 0x7a468336u, 0x635db277u, 0xcbfad74eu, 0xd2e1e60fu, 0xf9ccb5ccu, 0xe0d7848du, 0xaf96124au, 0xb68d230bu, 0x9da070c8u, 0x84bb4189u, 0x03235d46u, 0x1a386c07u, 0x31153fc4u, 0x280e0e85u, 0x674f9842u, 0x7e54a903u, 0x5579fac0u, 0x4c62cb81u, 0x8138c51fu, 0x9823f45eu, 0xb30ea79du, 0xaa1596dcu, 0xe554001bu, 0xfc4f315au, 0xd7626299u, 0xce7953d8u, 0x49e14f17u, 0x50fa7e56u, 0x7bd72d95u, 0x62cc1cd4u, 0x2d8d8a13u, 0x3496bb52u, 0x1fbbe891u, 0x06a0d9d0u, 0x5e7ef3ecu, 0x4765c2adu, 0x6c48916eu, 0x7553a02fu, 0x3a1236e8u, 0x230907a9u, 0x0824546au, 0x113f652bu, 0x96a779e4u, 0x8fbc48a5u, 0xa4911b66u, 0xbd8a2a27u, 0xf2cbbce0u, 0xebd08da1u, 0xc0fdde62u, 0xd9e6ef23u, 0x14bce1bdu, 0x0da7d0fcu, 0x268a833fu, 0x3f91b27eu, 0x70d024b9u, 0x69cb15f8u, 0x42e6463bu, 0x5bfd777au, 0xdc656bb5u, 0xc57e5af4u, 0xee530937u, 0xf7483876u, 0xb809aeb1u, 0xa1129ff0u, 0x8a3fcc33u, 0x9324fd72u }; static const unsigned lodepng_crc32_table2[256] = { 0x00000000u, 0x01c26a37u, 0x0384d46eu, 0x0246be59u, 0x0709a8dcu, 0x06cbc2ebu, 0x048d7cb2u, 0x054f1685u, 0x0e1351b8u, 0x0fd13b8fu, 0x0d9785d6u, 0x0c55efe1u, 0x091af964u, 0x08d89353u, 0x0a9e2d0au, 0x0b5c473du, 0x1c26a370u, 0x1de4c947u, 0x1fa2771eu, 0x1e601d29u, 0x1b2f0bacu, 0x1aed619bu, 0x18abdfc2u, 0x1969b5f5u, 0x1235f2c8u, 0x13f798ffu, 0x11b126a6u, 0x10734c91u, 0x153c5a14u, 0x14fe3023u, 0x16b88e7au, 0x177ae44du, 0x384d46e0u, 0x398f2cd7u, 0x3bc9928eu, 0x3a0bf8b9u, 0x3f44ee3cu, 0x3e86840bu, 0x3cc03a52u, 0x3d025065u, 0x365e1758u, 0x379c7d6fu, 0x35dac336u, 0x3418a901u, 0x3157bf84u, 0x3095d5b3u, 0x32d36beau, 0x331101ddu, 0x246be590u, 0x25a98fa7u, 0x27ef31feu, 0x262d5bc9u, 0x23624d4cu, 0x22a0277bu, 0x20e69922u, 0x2124f315u, 0x2a78b428u, 0x2bbade1fu, 0x29fc6046u, 0x283e0a71u, 0x2d711cf4u, 0x2cb376c3u, 0x2ef5c89au, 0x2f37a2adu, 0x709a8dc0u, 0x7158e7f7u, 0x731e59aeu, 0x72dc3399u, 0x7793251cu, 0x76514f2bu, 0x7417f172u, 0x75d59b45u, 0x7e89dc78u, 0x7f4bb64fu, 0x7d0d0816u, 0x7ccf6221u, 0x798074a4u, 0x78421e93u, 0x7a04a0cau, 0x7bc6cafdu, 0x6cbc2eb0u, 0x6d7e4487u, 0x6f38fadeu, 0x6efa90e9u, 0x6bb5866cu, 0x6a77ec5bu, 0x68315202u, 0x69f33835u, 0x62af7f08u, 0x636d153fu, 0x612bab66u, 0x60e9c151u, 0x65a6d7d4u, 0x6464bde3u, 0x662203bau, 0x67e0698du, 0x48d7cb20u, 0x4915a117u, 0x4b531f4eu, 0x4a917579u, 0x4fde63fcu, 0x4e1c09cbu, 0x4c5ab792u, 0x4d98dda5u, 0x46c49a98u, 0x4706f0afu, 0x45404ef6u, 0x448224c1u, 0x41cd3244u, 0x400f5873u, 0x4249e62au, 0x438b8c1du, 0x54f16850u, 0x55330267u, 0x5775bc3eu, 0x56b7d609u, 0x53f8c08cu, 0x523aaabbu, 0x507c14e2u, 0x51be7ed5u, 0x5ae239e8u, 0x5b2053dfu, 0x5966ed86u, 0x58a487b1u, 0x5deb9134u, 0x5c29fb03u, 0x5e6f455au, 0x5fad2f6du, 0xe1351b80u, 0xe0f771b7u, 0xe2b1cfeeu, 0xe373a5d9u, 0xe63cb35cu, 0xe7fed96bu, 0xe5b86732u, 0xe47a0d05u, 0xef264a38u, 0xeee4200fu, 0xeca29e56u, 0xed60f461u, 0xe82fe2e4u, 0xe9ed88d3u, 0xebab368au, 0xea695cbdu, 0xfd13b8f0u, 0xfcd1d2c7u, 0xfe976c9eu, 0xff5506a9u, 0xfa1a102cu, 0xfbd87a1bu, 0xf99ec442u, 0xf85cae75u, 0xf300e948u, 0xf2c2837fu, 0xf0843d26u, 0xf1465711u, 0xf4094194u, 0xf5cb2ba3u, 0xf78d95fau, 0xf64fffcdu, 0xd9785d60u, 0xd8ba3757u, 0xdafc890eu, 0xdb3ee339u, 0xde71f5bcu, 0xdfb39f8bu, 0xddf521d2u, 0xdc374be5u, 0xd76b0cd8u, 0xd6a966efu, 0xd4efd8b6u, 0xd52db281u, 0xd062a404u, 0xd1a0ce33u, 0xd3e6706au, 0xd2241a5du, 0xc55efe10u, 0xc49c9427u, 0xc6da2a7eu, 0xc7184049u, 0xc25756ccu, 0xc3953cfbu, 0xc1d382a2u, 0xc011e895u, 0xcb4dafa8u, 0xca8fc59fu, 0xc8c97bc6u, 0xc90b11f1u, 0xcc440774u, 0xcd866d43u, 0xcfc0d31au, 0xce02b92du, 0x91af9640u, 0x906dfc77u, 0x922b422eu, 0x93e92819u, 0x96a63e9cu, 0x976454abu, 0x9522eaf2u, 0x94e080c5u, 0x9fbcc7f8u, 0x9e7eadcfu, 0x9c381396u, 0x9dfa79a1u, 0x98b56f24u, 0x99770513u, 0x9b31bb4au, 0x9af3d17du, 0x8d893530u, 0x8c4b5f07u, 0x8e0de15eu, 0x8fcf8b69u, 0x8a809decu, 0x8b42f7dbu, 0x89044982u, 0x88c623b5u, 0x839a6488u, 0x82580ebfu, 0x801eb0e6u, 0x81dcdad1u, 0x8493cc54u, 0x8551a663u, 0x8717183au, 0x86d5720du, 0xa9e2d0a0u, 0xa820ba97u, 0xaa6604ceu, 0xaba46ef9u, 0xaeeb787cu, 0xaf29124bu, 0xad6fac12u, 0xacadc625u, 0xa7f18118u, 0xa633eb2fu, 0xa4755576u, 0xa5b73f41u, 0xa0f829c4u, 0xa13a43f3u, 0xa37cfdaau, 0xa2be979du, 0xb5c473d0u, 0xb40619e7u, 0xb640a7beu, 0xb782cd89u, 0xb2cddb0cu, 0xb30fb13bu, 0xb1490f62u, 0xb08b6555u, 0xbbd72268u, 0xba15485fu, 0xb853f606u, 0xb9919c31u, 0xbcde8ab4u, 0xbd1ce083u, 0xbf5a5edau, 0xbe9834edu }; static const unsigned lodepng_crc32_table3[256] = { 0x00000000u, 0xb8bc6765u, 0xaa09c88bu, 0x12b5afeeu, 0x8f629757u, 0x37def032u, 0x256b5fdcu, 0x9dd738b9u, 0xc5b428efu, 0x7d084f8au, 0x6fbde064u, 0xd7018701u, 0x4ad6bfb8u, 0xf26ad8ddu, 0xe0df7733u, 0x58631056u, 0x5019579fu, 0xe8a530fau, 0xfa109f14u, 0x42acf871u, 0xdf7bc0c8u, 0x67c7a7adu, 0x75720843u, 0xcdce6f26u, 0x95ad7f70u, 0x2d111815u, 0x3fa4b7fbu, 0x8718d09eu, 0x1acfe827u, 0xa2738f42u, 0xb0c620acu, 0x087a47c9u, 0xa032af3eu, 0x188ec85bu, 0x0a3b67b5u, 0xb28700d0u, 0x2f503869u, 0x97ec5f0cu, 0x8559f0e2u, 0x3de59787u, 0x658687d1u, 0xdd3ae0b4u, 0xcf8f4f5au, 0x7733283fu, 0xeae41086u, 0x525877e3u, 0x40edd80du, 0xf851bf68u, 0xf02bf8a1u, 0x48979fc4u, 0x5a22302au, 0xe29e574fu, 0x7f496ff6u, 0xc7f50893u, 0xd540a77du, 0x6dfcc018u, 0x359fd04eu, 0x8d23b72bu, 0x9f9618c5u, 0x272a7fa0u, 0xbafd4719u, 0x0241207cu, 0x10f48f92u, 0xa848e8f7u, 0x9b14583du, 0x23a83f58u, 0x311d90b6u, 0x89a1f7d3u, 0x1476cf6au, 0xaccaa80fu, 0xbe7f07e1u, 0x06c36084u, 0x5ea070d2u, 0xe61c17b7u, 0xf4a9b859u, 0x4c15df3cu, 0xd1c2e785u, 0x697e80e0u, 0x7bcb2f0eu, 0xc377486bu, 0xcb0d0fa2u, 0x73b168c7u, 0x6104c729u, 0xd9b8a04cu, 0x446f98f5u, 0xfcd3ff90u, 0xee66507eu, 0x56da371bu, 0x0eb9274du, 0xb6054028u, 0xa4b0efc6u, 0x1c0c88a3u, 0x81dbb01au, 0x3967d77fu, 0x2bd27891u, 0x936e1ff4u, 0x3b26f703u, 0x839a9066u, 0x912f3f88u, 0x299358edu, 0xb4446054u, 0x0cf80731u, 0x1e4da8dfu, 0xa6f1cfbau, 0xfe92dfecu, 0x462eb889u, 0x549b1767u, 0xec277002u, 0x71f048bbu, 0xc94c2fdeu, 0xdbf98030u, 0x6345e755u, 0x6b3fa09cu, 0xd383c7f9u, 0xc1366817u, 0x798a0f72u, 0xe45d37cbu, 0x5ce150aeu, 0x4e54ff40u, 0xf6e89825u, 0xae8b8873u, 0x1637ef16u, 0x048240f8u, 0xbc3e279du, 0x21e91f24u, 0x99557841u, 0x8be0d7afu, 0x335cb0cau, 0xed59b63bu, 0x55e5d15eu, 0x47507eb0u, 0xffec19d5u, 0x623b216cu, 0xda874609u, 0xc832e9e7u, 0x708e8e82u, 0x28ed9ed4u, 0x9051f9b1u, 0x82e4565fu, 0x3a58313au, 0xa78f0983u, 0x1f336ee6u, 0x0d86c108u, 0xb53aa66du, 0xbd40e1a4u, 0x05fc86c1u, 0x1749292fu, 0xaff54e4au, 0x322276f3u, 0x8a9e1196u, 0x982bbe78u, 0x2097d91du, 0x78f4c94bu, 0xc048ae2eu, 0xd2fd01c0u, 0x6a4166a5u, 0xf7965e1cu, 0x4f2a3979u, 0x5d9f9697u, 0xe523f1f2u, 0x4d6b1905u, 0xf5d77e60u, 0xe762d18eu, 0x5fdeb6ebu, 0xc2098e52u, 0x7ab5e937u, 0x680046d9u, 0xd0bc21bcu, 0x88df31eau, 0x3063568fu, 0x22d6f961u, 0x9a6a9e04u, 0x07bda6bdu, 0xbf01c1d8u, 0xadb46e36u, 0x15080953u, 0x1d724e9au, 0xa5ce29ffu, 0xb77b8611u, 0x0fc7e174u, 0x9210d9cdu, 0x2aacbea8u, 0x38191146u, 0x80a57623u, 0xd8c66675u, 0x607a0110u, 0x72cfaefeu, 0xca73c99bu, 0x57a4f122u, 0xef189647u, 0xfdad39a9u, 0x45115eccu, 0x764dee06u, 0xcef18963u, 0xdc44268du, 0x64f841e8u, 0xf92f7951u, 0x41931e34u, 0x5326b1dau, 0xeb9ad6bfu, 0xb3f9c6e9u, 0x0b45a18cu, 0x19f00e62u, 0xa14c6907u, 0x3c9b51beu, 0x842736dbu, 0x96929935u, 0x2e2efe50u, 0x2654b999u, 0x9ee8defcu, 0x8c5d7112u, 0x34e11677u, 0xa9362eceu, 0x118a49abu, 0x033fe645u, 0xbb838120u, 0xe3e09176u, 0x5b5cf613u, 0x49e959fdu, 0xf1553e98u, 0x6c820621u, 0xd43e6144u, 0xc68bceaau, 0x7e37a9cfu, 0xd67f4138u, 0x6ec3265du, 0x7c7689b3u, 0xc4caeed6u, 0x591dd66fu, 0xe1a1b10au, 0xf3141ee4u, 0x4ba87981u, 0x13cb69d7u, 0xab770eb2u, 0xb9c2a15cu, 0x017ec639u, 0x9ca9fe80u, 0x241599e5u, 0x36a0360bu, 0x8e1c516eu, 0x866616a7u, 0x3eda71c2u, 0x2c6fde2cu, 0x94d3b949u, 0x090481f0u, 0xb1b8e695u, 0xa30d497bu, 0x1bb12e1eu, 0x43d23e48u, 0xfb6e592du, 0xe9dbf6c3u, 0x516791a6u, 0xccb0a91fu, 0x740cce7au, 0x66b96194u, 0xde0506f1u }; static const unsigned lodepng_crc32_table4[256] = { 0x00000000u, 0x3d6029b0u, 0x7ac05360u, 0x47a07ad0u, 0xf580a6c0u, 0xc8e08f70u, 0x8f40f5a0u, 0xb220dc10u, 0x30704bc1u, 0x0d106271u, 0x4ab018a1u, 0x77d03111u, 0xc5f0ed01u, 0xf890c4b1u, 0xbf30be61u, 0x825097d1u, 0x60e09782u, 0x5d80be32u, 0x1a20c4e2u, 0x2740ed52u, 0x95603142u, 0xa80018f2u, 0xefa06222u, 0xd2c04b92u, 0x5090dc43u, 0x6df0f5f3u, 0x2a508f23u, 0x1730a693u, 0xa5107a83u, 0x98705333u, 0xdfd029e3u, 0xe2b00053u, 0xc1c12f04u, 0xfca106b4u, 0xbb017c64u, 0x866155d4u, 0x344189c4u, 0x0921a074u, 0x4e81daa4u, 0x73e1f314u, 0xf1b164c5u, 0xccd14d75u, 0x8b7137a5u, 0xb6111e15u, 0x0431c205u, 0x3951ebb5u, 0x7ef19165u, 0x4391b8d5u, 0xa121b886u, 0x9c419136u, 0xdbe1ebe6u, 0xe681c256u, 0x54a11e46u, 0x69c137f6u, 0x2e614d26u, 0x13016496u, 0x9151f347u, 0xac31daf7u, 0xeb91a027u, 0xd6f18997u, 0x64d15587u, 0x59b17c37u, 0x1e1106e7u, 0x23712f57u, 0x58f35849u, 0x659371f9u, 0x22330b29u, 0x1f532299u, 0xad73fe89u, 0x9013d739u, 0xd7b3ade9u, 0xead38459u, 0x68831388u, 0x55e33a38u, 0x124340e8u, 0x2f236958u, 0x9d03b548u, 0xa0639cf8u, 0xe7c3e628u, 0xdaa3cf98u, 0x3813cfcbu, 0x0573e67bu, 0x42d39cabu, 0x7fb3b51bu, 0xcd93690bu, 0xf0f340bbu, 0xb7533a6bu, 0x8a3313dbu, 0x0863840au, 0x3503adbau, 0x72a3d76au, 0x4fc3fedau, 0xfde322cau, 0xc0830b7au, 0x872371aau, 0xba43581au, 0x9932774du, 0xa4525efdu, 0xe3f2242du, 0xde920d9du, 0x6cb2d18du, 0x51d2f83du, 0x167282edu, 0x2b12ab5du, 0xa9423c8cu, 0x9422153cu, 0xd3826fecu, 0xeee2465cu, 0x5cc29a4cu, 0x61a2b3fcu, 0x2602c92cu, 0x1b62e09cu, 0xf9d2e0cfu, 0xc4b2c97fu, 0x8312b3afu, 0xbe729a1fu, 0x0c52460fu, 0x31326fbfu, 0x7692156fu, 0x4bf23cdfu, 0xc9a2ab0eu, 0xf4c282beu, 0xb362f86eu, 0x8e02d1deu, 0x3c220dceu, 0x0142247eu, 0x46e25eaeu, 0x7b82771eu, 0xb1e6b092u, 0x8c869922u, 0xcb26e3f2u, 0xf646ca42u, 0x44661652u, 0x79063fe2u, 0x3ea64532u, 0x03c66c82u, 0x8196fb53u, 0xbcf6d2e3u, 0xfb56a833u, 0xc6368183u, 0x74165d93u, 0x49767423u, 0x0ed60ef3u, 0x33b62743u, 0xd1062710u, 0xec660ea0u, 0xabc67470u, 0x96a65dc0u, 0x248681d0u, 0x19e6a860u, 0x5e46d2b0u, 0x6326fb00u, 0xe1766cd1u, 0xdc164561u, 0x9bb63fb1u, 0xa6d61601u, 0x14f6ca11u, 0x2996e3a1u, 0x6e369971u, 0x5356b0c1u, 0x70279f96u, 0x4d47b626u, 0x0ae7ccf6u, 0x3787e546u, 0x85a73956u, 0xb8c710e6u, 0xff676a36u, 0xc2074386u, 0x4057d457u, 0x7d37fde7u, 0x3a978737u, 0x07f7ae87u, 0xb5d77297u, 0x88b75b27u, 0xcf1721f7u, 0xf2770847u, 0x10c70814u, 0x2da721a4u, 0x6a075b74u, 0x576772c4u, 0xe547aed4u, 0xd8278764u, 0x9f87fdb4u, 0xa2e7d404u, 0x20b743d5u, 0x1dd76a65u, 0x5a7710b5u, 0x67173905u, 0xd537e515u, 0xe857cca5u, 0xaff7b675u, 0x92979fc5u, 0xe915e8dbu, 0xd475c16bu, 0x93d5bbbbu, 0xaeb5920bu, 0x1c954e1bu, 0x21f567abu, 0x66551d7bu, 0x5b3534cbu, 0xd965a31au, 0xe4058aaau, 0xa3a5f07au, 0x9ec5d9cau, 0x2ce505dau, 0x11852c6au, 0x562556bau, 0x6b457f0au, 0x89f57f59u, 0xb49556e9u, 0xf3352c39u, 0xce550589u, 0x7c75d999u, 0x4115f029u, 0x06b58af9u, 0x3bd5a349u, 0xb9853498u, 0x84e51d28u, 0xc34567f8u, 0xfe254e48u, 0x4c059258u, 0x7165bbe8u, 0x36c5c138u, 0x0ba5e888u, 0x28d4c7dfu, 0x15b4ee6fu, 0x521494bfu, 0x6f74bd0fu, 0xdd54611fu, 0xe03448afu, 0xa794327fu, 0x9af41bcfu, 0x18a48c1eu, 0x25c4a5aeu, 0x6264df7eu, 0x5f04f6ceu, 0xed242adeu, 0xd044036eu, 0x97e479beu, 0xaa84500eu, 0x4834505du, 0x755479edu, 0x32f4033du, 0x0f942a8du, 0xbdb4f69du, 0x80d4df2du, 0xc774a5fdu, 0xfa148c4du, 0x78441b9cu, 0x4524322cu, 0x028448fcu, 0x3fe4614cu, 0x8dc4bd5cu, 0xb0a494ecu, 0xf704ee3cu, 0xca64c78cu }; static const unsigned lodepng_crc32_table5[256] = { 0x00000000u, 0xcb5cd3a5u, 0x4dc8a10bu, 0x869472aeu, 0x9b914216u, 0x50cd91b3u, 0xd659e31du, 0x1d0530b8u, 0xec53826du, 0x270f51c8u, 0xa19b2366u, 0x6ac7f0c3u, 0x77c2c07bu, 0xbc9e13deu, 0x3a0a6170u, 0xf156b2d5u, 0x03d6029bu, 0xc88ad13eu, 0x4e1ea390u, 0x85427035u, 0x9847408du, 0x531b9328u, 0xd58fe186u, 0x1ed33223u, 0xef8580f6u, 0x24d95353u, 0xa24d21fdu, 0x6911f258u, 0x7414c2e0u, 0xbf481145u, 0x39dc63ebu, 0xf280b04eu, 0x07ac0536u, 0xccf0d693u, 0x4a64a43du, 0x81387798u, 0x9c3d4720u, 0x57619485u, 0xd1f5e62bu, 0x1aa9358eu, 0xebff875bu, 0x20a354feu, 0xa6372650u, 0x6d6bf5f5u, 0x706ec54du, 0xbb3216e8u, 0x3da66446u, 0xf6fab7e3u, 0x047a07adu, 0xcf26d408u, 0x49b2a6a6u, 0x82ee7503u, 0x9feb45bbu, 0x54b7961eu, 0xd223e4b0u, 0x197f3715u, 0xe82985c0u, 0x23755665u, 0xa5e124cbu, 0x6ebdf76eu, 0x73b8c7d6u, 0xb8e41473u, 0x3e7066ddu, 0xf52cb578u, 0x0f580a6cu, 0xc404d9c9u, 0x4290ab67u, 0x89cc78c2u, 0x94c9487au, 0x5f959bdfu, 0xd901e971u, 0x125d3ad4u, 0xe30b8801u, 0x28575ba4u, 0xaec3290au, 0x659ffaafu, 0x789aca17u, 0xb3c619b2u, 0x35526b1cu, 0xfe0eb8b9u, 0x0c8e08f7u, 0xc7d2db52u, 0x4146a9fcu, 0x8a1a7a59u, 0x971f4ae1u, 0x5c439944u, 0xdad7ebeau, 0x118b384fu, 0xe0dd8a9au, 0x2b81593fu, 0xad152b91u, 0x6649f834u, 0x7b4cc88cu, 0xb0101b29u, 0x36846987u, 0xfdd8ba22u, 0x08f40f5au, 0xc3a8dcffu, 0x453cae51u, 0x8e607df4u, 0x93654d4cu, 0x58399ee9u, 0xdeadec47u, 0x15f13fe2u, 0xe4a78d37u, 0x2ffb5e92u, 0xa96f2c3cu, 0x6233ff99u, 0x7f36cf21u, 0xb46a1c84u, 0x32fe6e2au, 0xf9a2bd8fu, 0x0b220dc1u, 0xc07ede64u, 0x46eaaccau, 0x8db67f6fu, 0x90b34fd7u, 0x5bef9c72u, 0xdd7beedcu, 0x16273d79u, 0xe7718facu, 0x2c2d5c09u, 0xaab92ea7u, 0x61e5fd02u, 0x7ce0cdbau, 0xb7bc1e1fu, 0x31286cb1u, 0xfa74bf14u, 0x1eb014d8u, 0xd5ecc77du, 0x5378b5d3u, 0x98246676u, 0x852156ceu, 0x4e7d856bu, 0xc8e9f7c5u, 0x03b52460u, 0xf2e396b5u, 0x39bf4510u, 0xbf2b37beu, 0x7477e41bu, 0x6972d4a3u, 0xa22e0706u, 0x24ba75a8u, 0xefe6a60du, 0x1d661643u, 0xd63ac5e6u, 0x50aeb748u, 0x9bf264edu, 0x86f75455u, 0x4dab87f0u, 0xcb3ff55eu, 0x006326fbu, 0xf135942eu, 0x3a69478bu, 0xbcfd3525u, 0x77a1e680u, 0x6aa4d638u, 0xa1f8059du, 0x276c7733u, 0xec30a496u, 0x191c11eeu, 0xd240c24bu, 0x54d4b0e5u, 0x9f886340u, 0x828d53f8u, 0x49d1805du, 0xcf45f2f3u, 0x04192156u, 0xf54f9383u, 0x3e134026u, 0xb8873288u, 0x73dbe12du, 0x6eded195u, 0xa5820230u, 0x2316709eu, 0xe84aa33bu, 0x1aca1375u, 0xd196c0d0u, 0x5702b27eu, 0x9c5e61dbu, 0x815b5163u, 0x4a0782c6u, 0xcc93f068u, 0x07cf23cdu, 0xf6999118u, 0x3dc542bdu, 0xbb513013u, 0x700de3b6u, 0x6d08d30eu, 0xa65400abu, 0x20c07205u, 0xeb9ca1a0u, 0x11e81eb4u, 0xdab4cd11u, 0x5c20bfbfu, 0x977c6c1au, 0x8a795ca2u, 0x41258f07u, 0xc7b1fda9u, 0x0ced2e0cu, 0xfdbb9cd9u, 0x36e74f7cu, 0xb0733dd2u, 0x7b2fee77u, 0x662adecfu, 0xad760d6au, 0x2be27fc4u, 0xe0beac61u, 0x123e1c2fu, 0xd962cf8au, 0x5ff6bd24u, 0x94aa6e81u, 0x89af5e39u, 0x42f38d9cu, 0xc467ff32u, 0x0f3b2c97u, 0xfe6d9e42u, 0x35314de7u, 0xb3a53f49u, 0x78f9ececu, 0x65fcdc54u, 0xaea00ff1u, 0x28347d5fu, 0xe368aefau, 0x16441b82u, 0xdd18c827u, 0x5b8cba89u, 0x90d0692cu, 0x8dd55994u, 0x46898a31u, 0xc01df89fu, 0x0b412b3au, 0xfa1799efu, 0x314b4a4au, 0xb7df38e4u, 0x7c83eb41u, 0x6186dbf9u, 0xaada085cu, 0x2c4e7af2u, 0xe712a957u, 0x15921919u, 0xdececabcu, 0x585ab812u, 0x93066bb7u, 0x8e035b0fu, 0x455f88aau, 0xc3cbfa04u, 0x089729a1u, 0xf9c19b74u, 0x329d48d1u, 0xb4093a7fu, 0x7f55e9dau, 0x6250d962u, 0xa90c0ac7u, 0x2f987869u, 0xe4c4abccu }; static const unsigned lodepng_crc32_table6[256] = { 0x00000000u, 0xa6770bb4u, 0x979f1129u, 0x31e81a9du, 0xf44f2413u, 0x52382fa7u, 0x63d0353au, 0xc5a73e8eu, 0x33ef4e67u, 0x959845d3u, 0xa4705f4eu, 0x020754fau, 0xc7a06a74u, 0x61d761c0u, 0x503f7b5du, 0xf64870e9u, 0x67de9cceu, 0xc1a9977au, 0xf0418de7u, 0x56368653u, 0x9391b8ddu, 0x35e6b369u, 0x040ea9f4u, 0xa279a240u, 0x5431d2a9u, 0xf246d91du, 0xc3aec380u, 0x65d9c834u, 0xa07ef6bau, 0x0609fd0eu, 0x37e1e793u, 0x9196ec27u, 0xcfbd399cu, 0x69ca3228u, 0x582228b5u, 0xfe552301u, 0x3bf21d8fu, 0x9d85163bu, 0xac6d0ca6u, 0x0a1a0712u, 0xfc5277fbu, 0x5a257c4fu, 0x6bcd66d2u, 0xcdba6d66u, 0x081d53e8u, 0xae6a585cu, 0x9f8242c1u, 0x39f54975u, 0xa863a552u, 0x0e14aee6u, 0x3ffcb47bu, 0x998bbfcfu, 0x5c2c8141u, 0xfa5b8af5u, 0xcbb39068u, 0x6dc49bdcu, 0x9b8ceb35u, 0x3dfbe081u, 0x0c13fa1cu, 0xaa64f1a8u, 0x6fc3cf26u, 0xc9b4c492u, 0xf85cde0fu, 0x5e2bd5bbu, 0x440b7579u, 0xe27c7ecdu, 0xd3946450u, 0x75e36fe4u, 0xb044516au, 0x16335adeu, 0x27db4043u, 0x81ac4bf7u, 0x77e43b1eu, 0xd19330aau, 0xe07b2a37u, 0x460c2183u, 0x83ab1f0du, 0x25dc14b9u, 0x14340e24u, 0xb2430590u, 0x23d5e9b7u, 0x85a2e203u, 0xb44af89eu, 0x123df32au, 0xd79acda4u, 0x71edc610u, 0x4005dc8du, 0xe672d739u, 0x103aa7d0u, 0xb64dac64u, 0x87a5b6f9u, 0x21d2bd4du, 0xe47583c3u, 0x42028877u, 0x73ea92eau, 0xd59d995eu, 0x8bb64ce5u, 0x2dc14751u, 0x1c295dccu, 0xba5e5678u, 0x7ff968f6u, 0xd98e6342u, 0xe86679dfu, 0x4e11726bu, 0xb8590282u, 0x1e2e0936u, 0x2fc613abu, 0x89b1181fu, 0x4c162691u, 0xea612d25u, 0xdb8937b8u, 0x7dfe3c0cu, 0xec68d02bu, 0x4a1fdb9fu, 0x7bf7c102u, 0xdd80cab6u, 0x1827f438u, 0xbe50ff8cu, 0x8fb8e511u, 0x29cfeea5u, 0xdf879e4cu, 0x79f095f8u, 0x48188f65u, 0xee6f84d1u, 0x2bc8ba5fu, 0x8dbfb1ebu, 0xbc57ab76u, 0x1a20a0c2u, 0x8816eaf2u, 0x2e61e146u, 0x1f89fbdbu, 0xb9fef06fu, 0x7c59cee1u, 0xda2ec555u, 0xebc6dfc8u, 0x4db1d47cu, 0xbbf9a495u, 0x1d8eaf21u, 0x2c66b5bcu, 0x8a11be08u, 0x4fb68086u, 0xe9c18b32u, 0xd82991afu, 0x7e5e9a1bu, 0xefc8763cu, 0x49bf7d88u, 0x78576715u, 0xde206ca1u, 0x1b87522fu, 0xbdf0599bu, 0x8c184306u, 0x2a6f48b2u, 0xdc27385bu, 0x7a5033efu, 0x4bb82972u, 0xedcf22c6u, 0x28681c48u, 0x8e1f17fcu, 0xbff70d61u, 0x198006d5u, 0x47abd36eu, 0xe1dcd8dau, 0xd034c247u, 0x7643c9f3u, 0xb3e4f77du, 0x1593fcc9u, 0x247be654u, 0x820cede0u, 0x74449d09u, 0xd23396bdu, 0xe3db8c20u, 0x45ac8794u, 0x800bb91au, 0x267cb2aeu, 0x1794a833u, 0xb1e3a387u, 0x20754fa0u, 0x86024414u, 0xb7ea5e89u, 0x119d553du, 0xd43a6bb3u, 0x724d6007u, 0x43a57a9au, 0xe5d2712eu, 0x139a01c7u, 0xb5ed0a73u, 0x840510eeu, 0x22721b5au, 0xe7d525d4u, 0x41a22e60u, 0x704a34fdu, 0xd63d3f49u, 0xcc1d9f8bu, 0x6a6a943fu, 0x5b828ea2u, 0xfdf58516u, 0x3852bb98u, 0x9e25b02cu, 0xafcdaab1u, 0x09baa105u, 0xfff2d1ecu, 0x5985da58u, 0x686dc0c5u, 0xce1acb71u, 0x0bbdf5ffu, 0xadcafe4bu, 0x9c22e4d6u, 0x3a55ef62u, 0xabc30345u, 0x0db408f1u, 0x3c5c126cu, 0x9a2b19d8u, 0x5f8c2756u, 0xf9fb2ce2u, 0xc813367fu, 0x6e643dcbu, 0x982c4d22u, 0x3e5b4696u, 0x0fb35c0bu, 0xa9c457bfu, 0x6c636931u, 0xca146285u, 0xfbfc7818u, 0x5d8b73acu, 0x03a0a617u, 0xa5d7ada3u, 0x943fb73eu, 0x3248bc8au, 0xf7ef8204u, 0x519889b0u, 0x6070932du, 0xc6079899u, 0x304fe870u, 0x9638e3c4u, 0xa7d0f959u, 0x01a7f2edu, 0xc400cc63u, 0x6277c7d7u, 0x539fdd4au, 0xf5e8d6feu, 0x647e3ad9u, 0xc209316du, 0xf3e12bf0u, 0x55962044u, 0x90311ecau, 0x3646157eu, 0x07ae0fe3u, 0xa1d90457u, 0x579174beu, 0xf1e67f0au, 0xc00e6597u, 0x66796e23u, 0xa3de50adu, 0x05a95b19u, 0x34414184u, 0x92364a30u }; static const unsigned lodepng_crc32_table7[256] = { 0x00000000u, 0xccaa009eu, 0x4225077du, 0x8e8f07e3u, 0x844a0efau, 0x48e00e64u, 0xc66f0987u, 0x0ac50919u, 0xd3e51bb5u, 0x1f4f1b2bu, 0x91c01cc8u, 0x5d6a1c56u, 0x57af154fu, 0x9b0515d1u, 0x158a1232u, 0xd92012acu, 0x7cbb312bu, 0xb01131b5u, 0x3e9e3656u, 0xf23436c8u, 0xf8f13fd1u, 0x345b3f4fu, 0xbad438acu, 0x767e3832u, 0xaf5e2a9eu, 0x63f42a00u, 0xed7b2de3u, 0x21d12d7du, 0x2b142464u, 0xe7be24fau, 0x69312319u, 0xa59b2387u, 0xf9766256u, 0x35dc62c8u, 0xbb53652bu, 0x77f965b5u, 0x7d3c6cacu, 0xb1966c32u, 0x3f196bd1u, 0xf3b36b4fu, 0x2a9379e3u, 0xe639797du, 0x68b67e9eu, 0xa41c7e00u, 0xaed97719u, 0x62737787u, 0xecfc7064u, 0x205670fau, 0x85cd537du, 0x496753e3u, 0xc7e85400u, 0x0b42549eu, 0x01875d87u, 0xcd2d5d19u, 0x43a25afau, 0x8f085a64u, 0x562848c8u, 0x9a824856u, 0x140d4fb5u, 0xd8a74f2bu, 0xd2624632u, 0x1ec846acu, 0x9047414fu, 0x5ced41d1u, 0x299dc2edu, 0xe537c273u, 0x6bb8c590u, 0xa712c50eu, 0xadd7cc17u, 0x617dcc89u, 0xeff2cb6au, 0x2358cbf4u, 0xfa78d958u, 0x36d2d9c6u, 0xb85dde25u, 0x74f7debbu, 0x7e32d7a2u, 0xb298d73cu, 0x3c17d0dfu, 0xf0bdd041u, 0x5526f3c6u, 0x998cf358u, 0x1703f4bbu, 0xdba9f425u, 0xd16cfd3cu, 0x1dc6fda2u, 0x9349fa41u, 0x5fe3fadfu, 0x86c3e873u, 0x4a69e8edu, 0xc4e6ef0eu, 0x084cef90u, 0x0289e689u, 0xce23e617u, 0x40ace1f4u, 0x8c06e16au, 0xd0eba0bbu, 0x1c41a025u, 0x92cea7c6u, 0x5e64a758u, 0x54a1ae41u, 0x980baedfu, 0x1684a93cu, 0xda2ea9a2u, 0x030ebb0eu, 0xcfa4bb90u, 0x412bbc73u, 0x8d81bcedu, 0x8744b5f4u, 0x4beeb56au, 0xc561b289u, 0x09cbb217u, 0xac509190u, 0x60fa910eu, 0xee7596edu, 0x22df9673u, 0x281a9f6au, 0xe4b09ff4u, 0x6a3f9817u, 0xa6959889u, 0x7fb58a25u, 0xb31f8abbu, 0x3d908d58u, 0xf13a8dc6u, 0xfbff84dfu, 0x37558441u, 0xb9da83a2u, 0x7570833cu, 0x533b85dau, 0x9f918544u, 0x111e82a7u, 0xddb48239u, 0xd7718b20u, 0x1bdb8bbeu, 0x95548c5du, 0x59fe8cc3u, 0x80de9e6fu, 0x4c749ef1u, 0xc2fb9912u, 0x0e51998cu, 0x04949095u, 0xc83e900bu, 0x46b197e8u, 0x8a1b9776u, 0x2f80b4f1u, 0xe32ab46fu, 0x6da5b38cu, 0xa10fb312u, 0xabcaba0bu, 0x6760ba95u, 0xe9efbd76u, 0x2545bde8u, 0xfc65af44u, 0x30cfafdau, 0xbe40a839u, 0x72eaa8a7u, 0x782fa1beu, 0xb485a120u, 0x3a0aa6c3u, 0xf6a0a65du, 0xaa4de78cu, 0x66e7e712u, 0xe868e0f1u, 0x24c2e06fu, 0x2e07e976u, 0xe2ade9e8u, 0x6c22ee0bu, 0xa088ee95u, 0x79a8fc39u, 0xb502fca7u, 0x3b8dfb44u, 0xf727fbdau, 0xfde2f2c3u, 0x3148f25du, 0xbfc7f5beu, 0x736df520u, 0xd6f6d6a7u, 0x1a5cd639u, 0x94d3d1dau, 0x5879d144u, 0x52bcd85du, 0x9e16d8c3u, 0x1099df20u, 0xdc33dfbeu, 0x0513cd12u, 0xc9b9cd8cu, 0x4736ca6fu, 0x8b9ccaf1u, 0x8159c3e8u, 0x4df3c376u, 0xc37cc495u, 0x0fd6c40bu, 0x7aa64737u, 0xb60c47a9u, 0x3883404au, 0xf42940d4u, 0xfeec49cdu, 0x32464953u, 0xbcc94eb0u, 0x70634e2eu, 0xa9435c82u, 0x65e95c1cu, 0xeb665bffu, 0x27cc5b61u, 0x2d095278u, 0xe1a352e6u, 0x6f2c5505u, 0xa386559bu, 0x061d761cu, 0xcab77682u, 0x44387161u, 0x889271ffu, 0x825778e6u, 0x4efd7878u, 0xc0727f9bu, 0x0cd87f05u, 0xd5f86da9u, 0x19526d37u, 0x97dd6ad4u, 0x5b776a4au, 0x51b26353u, 0x9d1863cdu, 0x1397642eu, 0xdf3d64b0u, 0x83d02561u, 0x4f7a25ffu, 0xc1f5221cu, 0x0d5f2282u, 0x079a2b9bu, 0xcb302b05u, 0x45bf2ce6u, 0x89152c78u, 0x50353ed4u, 0x9c9f3e4au, 0x121039a9u, 0xdeba3937u, 0xd47f302eu, 0x18d530b0u, 0x965a3753u, 0x5af037cdu, 0xff6b144au, 0x33c114d4u, 0xbd4e1337u, 0x71e413a9u, 0x7b211ab0u, 0xb78b1a2eu, 0x39041dcdu, 0xf5ae1d53u, 0x2c8e0fffu, 0xe0240f61u, 0x6eab0882u, 0xa201081cu, 0xa8c40105u, 0x646e019bu, 0xeae10678u, 0x264b06e6u }; /* Computes the cyclic redundancy check as used by PNG chunks*/ unsigned lodepng_crc32(const unsigned char* data, size_t length) { /*Using the Slicing by Eight algorithm*/ unsigned r = 0xffffffffu; while(length >= 8) { r = lodepng_crc32_table7[(data[0] ^ (r & 0xffu))] ^ lodepng_crc32_table6[(data[1] ^ ((r >> 8) & 0xffu))] ^ lodepng_crc32_table5[(data[2] ^ ((r >> 16) & 0xffu))] ^ lodepng_crc32_table4[(data[3] ^ ((r >> 24) & 0xffu))] ^ lodepng_crc32_table3[data[4]] ^ lodepng_crc32_table2[data[5]] ^ lodepng_crc32_table1[data[6]] ^ lodepng_crc32_table0[data[7]]; data += 8; length -= 8; } while(length--) { r = lodepng_crc32_table0[(r ^ *data++) & 0xffu] ^ (r >> 8); } return r ^ 0xffffffffu; } #else /* LODEPNG_COMPILE_CRC */ /*in this case, the function is only declared here, and must be defined externally so that it will be linked in. Example implementation that uses a much smaller lookup table for memory constrained cases: unsigned lodepng_crc32(const unsigned char* data, size_t length) { unsigned r = 0xffffffffu; static const unsigned table[16] = { 0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; while(length--) { r = table[(r ^ *data) & 0xf] ^ (r >> 4); r = table[(r ^ (*data >> 4)) & 0xf] ^ (r >> 4); data++; } return r ^ 0xffffffffu; } */ unsigned lodepng_crc32(const unsigned char* data, size_t length); #endif /* LODEPNG_COMPILE_CRC */ /* ////////////////////////////////////////////////////////////////////////// */ /* / Reading and writing PNG color channel bits / */ /* ////////////////////////////////////////////////////////////////////////// */ /* The color channel bits of less-than-8-bit pixels are read with the MSB of bytes first, so LodePNGBitWriter and LodePNGBitReader can't be used for those. */ 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; } /* TODO: make this faster */ static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) { unsigned result = 0; size_t i; for(i = 0 ; i < nbits; ++i) { result <<= 1u; result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream); } return result; } 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) >> 3u] &= (unsigned char)(~(1u << (7u - ((*bitpointer) & 7u)))); else bitstream[(*bitpointer) >> 3u] |= (1u << (7u - ((*bitpointer) & 7u))); ++(*bitpointer); } /* ////////////////////////////////////////////////////////////////////////// */ /* / PNG chunks / */ /* ////////////////////////////////////////////////////////////////////////// */ unsigned lodepng_chunk_length(const unsigned char* chunk) { return lodepng_read32bitInt(chunk); } 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(lodepng_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 char* end) { size_t available_size = (size_t)(end - chunk); if(chunk >= end || available_size < 12) return end; /*too small to contain a chunk*/ if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47 && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) { /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */ return chunk + 8; } else { size_t total_chunk_length; if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end; if(total_chunk_length > available_size) return end; /*outside of range*/ return chunk + total_chunk_length; } } const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end) { size_t available_size = (size_t)(end - chunk); if(chunk >= end || available_size < 12) return end; /*too small to contain a chunk*/ if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47 && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) { /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */ return chunk + 8; } else { size_t total_chunk_length; if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return end; if(total_chunk_length > available_size) return end; /*outside of range*/ return chunk + total_chunk_length; } } unsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]) { for(;;) { if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */ if(lodepng_chunk_type_equals(chunk, type)) return chunk; chunk = lodepng_chunk_next(chunk, end); } } const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]) { for(;;) { if(chunk >= end || end - chunk < 12) return 0; /* past file end: chunk + 12 > end */ if(lodepng_chunk_type_equals(chunk, type)) return chunk; chunk = lodepng_chunk_next_const(chunk, end); } } unsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk) { unsigned i; size_t total_chunk_length, new_length; unsigned char *chunk_start, *new_buffer; if(lodepng_addofl(lodepng_chunk_length(chunk), 12, &total_chunk_length)) return 77; if(lodepng_addofl(*outsize, total_chunk_length, &new_length)) return 77; new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); if(!new_buffer) return 83; /*alloc fail*/ (*out) = new_buffer; (*outsize) = 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; } /*Sets length and name and allocates the space for data and crc but does not set data or crc yet. Returns the start of the chunk in chunk. The start of the data is at chunk + 8. To finalize chunk, add the data, then use lodepng_chunk_generate_crc */ static unsigned lodepng_chunk_init(unsigned char** chunk, ucvector* out, size_t length, const char* type) { size_t new_length = out->size; if(lodepng_addofl(new_length, length, &new_length)) return 77; if(lodepng_addofl(new_length, 12, &new_length)) return 77; if(!ucvector_resize(out, new_length)) return 83; /*alloc fail*/ *chunk = out->data + new_length - length - 12u; /*1: length*/ lodepng_set32bitInt(*chunk, (unsigned)length); /*2: chunk name (4 letters)*/ lodepng_memcpy(*chunk + 4, type, 4); return 0; } /* like lodepng_chunk_create but with custom allocsize */ static unsigned lodepng_chunk_createv(ucvector* out, size_t length, const char* type, const unsigned char* data) { unsigned char* chunk; CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, length, type)); /*3: the data*/ lodepng_memcpy(chunk + 8, data, length); /*4: CRC (of the chunkname characters and the data)*/ lodepng_chunk_generate_crc(chunk); return 0; } unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, size_t length, const char* type, const unsigned char* data) { ucvector v = ucvector_init(*out, *outsize); unsigned error = lodepng_chunk_createv(&v, length, type, data); *out = v.data; *outsize = v.size; return error; } /* ////////////////////////////////////////////////////////////////////////// */ /* / Color types, channels, bits / */ /* ////////////////////////////////////////////////////////////////////////// */ /*checks if the colortype is valid and the bitdepth bd is allowed for this colortype. Return value is a LodePNG error code.*/ static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) { switch(colortype) { case LCT_GREY: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; case LCT_RGB: if(!( bd == 8 || bd == 16)) return 37; break; case LCT_PALETTE: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; case LCT_GREY_ALPHA: if(!( bd == 8 || bd == 16)) return 37; break; case LCT_RGBA: if(!( bd == 8 || bd == 16)) return 37; break; case LCT_MAX_OCTET_VALUE: return 31; /* invalid color type */ default: return 31; /* invalid color type */ } return 0; /*allowed color type / bits combination*/ } static unsigned getNumColorChannels(LodePNGColorType colortype) { switch(colortype) { case LCT_GREY: return 1; case LCT_RGB: return 3; case LCT_PALETTE: return 1; case LCT_GREY_ALPHA: return 2; case LCT_RGBA: return 4; case LCT_MAX_OCTET_VALUE: return 0; /* invalid color type */ default: return 0; /*invalid 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; } /*allocates palette memory if needed, and initializes all colors to black*/ static void lodepng_color_mode_alloc_palette(LodePNGColorMode* info) { size_t i; /*if the palette is already allocated, it will have size 1024 so no reallocation needed in that case*/ /*the palette must have room for up to 256 colors with 4 bytes each.*/ if(!info->palette) info->palette = (unsigned char*)lodepng_malloc(1024); if(!info->palette) return; /*alloc fail*/ for(i = 0; i != 256; ++i) { /*Initialize all unused colors with black, the value used for invalid palette indices. This is an error according to the PNG spec, but common PNG decoders make it black instead. That makes color conversion slightly faster due to no error handling needed.*/ info->palette[i * 4 + 0] = 0; info->palette[i * 4 + 1] = 0; info->palette[i * 4 + 2] = 0; info->palette[i * 4 + 3] = 255; } } void lodepng_color_mode_cleanup(LodePNGColorMode* info) { lodepng_palette_clear(info); } unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) { lodepng_color_mode_cleanup(dest); lodepng_memcpy(dest, source, sizeof(LodePNGColorMode)); if(source->palette) { dest->palette = (unsigned char*)lodepng_malloc(1024); if(!dest->palette && source->palettesize) return 83; /*alloc fail*/ lodepng_memcpy(dest->palette, source->palette, source->palettesize * 4); } return 0; } LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) { LodePNGColorMode result; lodepng_color_mode_init(&result); result.colortype = colortype; result.bitdepth = bitdepth; return result; } 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) { if(!info->palette) /*allocate palette if empty*/ { lodepng_color_mode_alloc_palette(info); if(!info->palette) return 83; /*alloc fail*/ } if(info->palettesize >= 256) { return 108; /*too many palette values*/ } 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; } /*calculate bits per pixel out of colortype and bitdepth*/ unsigned lodepng_get_bpp(const LodePNGColorMode* info) { 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); } static size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth); size_t n = (size_t)w * (size_t)h; return ((n / 8u) * bpp) + ((n & 7u) * bpp + 7u) / 8u; } size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) { return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth); } #ifdef LODEPNG_COMPILE_PNG /*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer, and in addition has one extra byte per line: the filter byte. So this gives a larger result than lodepng_get_raw_size. Set h to 1 to get the size of 1 row including filter byte. */ static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, unsigned bpp) { /* + 1 for the filter byte, and possibly plus padding bits per line. */ /* Ignoring casts, the expression is equal to (w * bpp + 7) / 8 + 1, but avoids overflow of w * bpp */ size_t line = ((size_t)(w / 8u) * bpp) + 1u + ((w & 7u) * bpp + 7u) / 8u; return (size_t)h * line; } #ifdef LODEPNG_COMPILE_DECODER /*Safely checks whether size_t overflow can be caused due to amount of pixels. This check is overcautious rather than precise. If this check indicates no overflow, you can safely compute in a size_t (but not an unsigned): -(size_t)w * (size_t)h * 8 -amount of bytes in IDAT (including filter, padding and Adam7 bytes) -amount of bytes in raw color model Returns 1 if overflow possible, 0 if not. */ static int lodepng_pixel_overflow(unsigned w, unsigned h, const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) { size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor)); size_t numpixels, total; size_t line; /* bytes per line in worst case */ if(lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1; if(lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */ /* Bytes per scanline with the expression "(w / 8u) * bpp) + ((w & 7u) * bpp + 7u) / 8u" */ if(lodepng_mulofl((size_t)(w / 8u), bpp, &line)) return 1; if(lodepng_addofl(line, ((w & 7u) * bpp + 7u) / 8u, &line)) return 1; if(lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */ if(lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */ return 0; /* no overflow */ } #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 = NULL; dest->text_strings = NULL; 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; } static unsigned lodepng_add_text_sized(LodePNGInfo* info, const char* key, const char* str, size_t size) { 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) info->text_keys = new_keys; if(new_strings) info->text_strings = new_strings; if(!new_keys || !new_strings) return 83; /*alloc fail*/ ++info->text_num; info->text_keys[info->text_num - 1] = alloc_string(key); info->text_strings[info->text_num - 1] = alloc_string_sized(str, size); if(!info->text_keys[info->text_num - 1] || !info->text_strings[info->text_num - 1]) return 83; /*alloc fail*/ return 0; } unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) { return lodepng_add_text_sized(info, key, str, lodepng_strlen(str)); } void lodepng_clear_text(LodePNGInfo* info) { LodePNGText_cleanup(info); } /******************************************************************************/ 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 = NULL; dest->itext_langtags = NULL; dest->itext_transkeys = NULL; dest->itext_strings = NULL; 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); } static unsigned lodepng_add_itext_sized(LodePNGInfo* info, const char* key, const char* langtag, const char* transkey, const char* str, size_t size) { 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) info->itext_keys = new_keys; if(new_langtags) info->itext_langtags = new_langtags; if(new_transkeys) info->itext_transkeys = new_transkeys; if(new_strings) info->itext_strings = new_strings; if(!new_keys || !new_langtags || !new_transkeys || !new_strings) return 83; /*alloc fail*/ ++info->itext_num; info->itext_keys[info->itext_num - 1] = alloc_string(key); info->itext_langtags[info->itext_num - 1] = alloc_string(langtag); info->itext_transkeys[info->itext_num - 1] = alloc_string(transkey); info->itext_strings[info->itext_num - 1] = alloc_string_sized(str, size); return 0; } unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, const char* transkey, const char* str) { return lodepng_add_itext_sized(info, key, langtag, transkey, str, lodepng_strlen(str)); } /* same as set but does not delete */ static unsigned lodepng_assign_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) { if(profile_size == 0) return 100; /*invalid ICC profile size*/ info->iccp_name = alloc_string(name); info->iccp_profile = (unsigned char*)lodepng_malloc(profile_size); if(!info->iccp_name || !info->iccp_profile) return 83; /*alloc fail*/ lodepng_memcpy(info->iccp_profile, profile, profile_size); info->iccp_profile_size = profile_size; return 0; /*ok*/ } unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) { if(info->iccp_name) lodepng_clear_icc(info); info->iccp_defined = 1; return lodepng_assign_icc(info, name, profile, profile_size); } void lodepng_clear_icc(LodePNGInfo* info) { string_cleanup(&info->iccp_name); lodepng_free(info->iccp_profile); info->iccp_profile = NULL; info->iccp_profile_size = 0; info->iccp_defined = 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; info->gama_defined = 0; info->chrm_defined = 0; info->srgb_defined = 0; info->iccp_defined = 0; info->iccp_name = NULL; info->iccp_profile = NULL; info->sbit_defined = 0; info->sbit_r = info->sbit_g = info->sbit_b = info->sbit_a = 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); lodepng_clear_icc(info); LodePNGUnknownChunks_cleanup(info); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) { lodepng_info_cleanup(dest); lodepng_memcpy(dest, source, sizeof(LodePNGInfo)); 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)); if(source->iccp_defined) { CERROR_TRY_RETURN(lodepng_assign_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size)); } LodePNGUnknownChunks_init(dest); CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source)); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ return 0; } /* ////////////////////////////////////////////////////////////////////////// */ /*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 / 8u] = in; else out[index * bits / 8u] |= 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) { lodepng_memset(tree->children, 0, 16 * sizeof(*tree->children)); 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") Returns error code, or 0 if ok*/ static unsigned 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)); if(!tree->children[i]) return 83; /*alloc fail*/ color_tree_init(tree->children[i]); } tree = tree->children[i]; } tree->index = (int)index; return 0; } /*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 gray = r; /*((unsigned short)r + g + b) / 3u;*/ if(mode->bitdepth == 8) out[i] = gray; else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = gray; else { /*take the most significant bits of gray*/ gray = ((unsigned)gray >> (8u - mode->bitdepth)) & ((1u << mode->bitdepth) - 1u); addColorBits(out, i, mode->bitdepth, gray); } } 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 gray = r; /*((unsigned short)r + g + b) / 3u;*/ if(mode->bitdepth == 8) { out[i * 2 + 0] = gray; out[i * 2 + 1] = a; } else if(mode->bitdepth == 16) { out[i * 4 + 0] = out[i * 4 + 1] = gray; 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 gray = r; /*((unsigned)r + g + b) / 3u;*/ out[i * 2 + 0] = (gray >> 8) & 255; out[i * 2 + 1] = gray & 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 gray = r; /*((unsigned)r + g + b) / 3u;*/ out[i * 4 + 0] = (gray >> 8) & 255; out[i * 4 + 1] = gray & 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); } /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ *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 the common case of RGBA with 8 bit per channel. buffer must be RGBA with enough memory.*/ static void getPixelColorsRGBA8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels, const unsigned char* LODEPNG_RESTRICT in, const LodePNGColorMode* mode) { unsigned num_channels = 4; 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]; buffer[3] = 255; } if(mode->key_defined) { buffer -= numpixels * num_channels; for(i = 0; i != numpixels; ++i, buffer += num_channels) { if(buffer[0] == mode->key_r) buffer[3] = 0; } } } else if(mode->bitdepth == 16) { for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 2]; 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; 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) { lodepng_memcpy(buffer, &in[i * 3], 3); buffer[3] = 255; } if(mode->key_defined) { buffer -= numpixels * num_channels; for(i = 0; i != numpixels; ++i, buffer += num_channels) { if(buffer[0] == mode->key_r && buffer[1]== mode->key_g && buffer[2] == mode->key_b) buffer[3] = 0; } } } 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]; 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) { if(mode->bitdepth == 8) { for(i = 0; i != numpixels; ++i, buffer += num_channels) { unsigned index = in[i]; /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ lodepng_memcpy(buffer, &mode->palette[index * 4], 4); } } else { size_t j = 0; for(i = 0; i != numpixels; ++i, buffer += num_channels) { unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth); /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ lodepng_memcpy(buffer, &mode->palette[index * 4], 4); } } } 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]; 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]; buffer[3] = in[i * 4 + 2]; } } } else if(mode->colortype == LCT_RGBA) { if(mode->bitdepth == 8) { lodepng_memcpy(buffer, in, numpixels * 4); } 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]; buffer[3] = in[i * 8 + 6]; } } } } /*Similar to getPixelColorsRGBA8, but with 3-channel RGB output.*/ static void getPixelColorsRGB8(unsigned char* LODEPNG_RESTRICT buffer, size_t numpixels, const unsigned char* LODEPNG_RESTRICT in, const LodePNGColorMode* mode) { const unsigned num_channels = 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]; } } else if(mode->bitdepth == 16) { for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 2]; } } 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; } } } else if(mode->colortype == LCT_RGB) { if(mode->bitdepth == 8) { lodepng_memcpy(buffer, in, numpixels * 3); } 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]; } } } else if(mode->colortype == LCT_PALETTE) { if(mode->bitdepth == 8) { for(i = 0; i != numpixels; ++i, buffer += num_channels) { unsigned index = in[i]; /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ lodepng_memcpy(buffer, &mode->palette[index * 4], 3); } } else { size_t j = 0; for(i = 0; i != numpixels; ++i, buffer += num_channels) { unsigned index = readBitsFromReversedStream(&j, in, mode->bitdepth); /*out of bounds of palette not checked: see lodepng_color_mode_alloc_palette.*/ lodepng_memcpy(buffer, &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]; } } else { for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; } } } else if(mode->colortype == LCT_RGBA) { if(mode->bitdepth == 8) { for(i = 0; i != numpixels; ++i, buffer += num_channels) { lodepng_memcpy(buffer, &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]; } } } } /*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 = 256u * in[i * 6 + 0] + in[i * 6 + 1]; *g = 256u * in[i * 6 + 2] + in[i * 6 + 3]; *b = 256u * 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 = 256u * in[i * 4 + 0] + in[i * 4 + 1]; *a = 256u * in[i * 4 + 2] + in[i * 4 + 3]; } else if(mode->colortype == LCT_RGBA) { *r = 256u * in[i * 8 + 0] + in[i * 8 + 1]; *g = 256u * in[i * 8 + 2] + in[i * 8 + 3]; *b = 256u * in[i * 8 + 4] + in[i * 8 + 5]; *a = 256u * in[i * 8 + 6] + in[i * 8 + 7]; } } unsigned lodepng_convert(unsigned char* out, const unsigned char* in, const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, unsigned w, unsigned h) { size_t i; ColorTree tree; size_t numpixels = (size_t)w * (size_t)h; unsigned error = 0; if(mode_in->colortype == LCT_PALETTE && !mode_in->palette) { return 107; /* error: must provide palette if input mode is palette */ } if(lodepng_color_mode_equal(mode_out, mode_in)) { size_t numbytes = lodepng_get_raw_size(w, h, mode_in); lodepng_memcpy(out, in, numbytes); return 0; } if(mode_out->colortype == LCT_PALETTE) { size_t palettesize = mode_out->palettesize; const unsigned char* palette = mode_out->palette; size_t palsize = (size_t)1u << mode_out->bitdepth; /*if the user specified output palette but did not give the values, assume they want the values of the input color type (assuming that one is palette). Note that we never create a new palette ourselves.*/ if(palettesize == 0) { palettesize = mode_in->palettesize; palette = mode_in->palette; /*if the input was also palette with same bitdepth, then the color types are also equal, so copy literally. This to preserve the exact indices that were in the PNG even in case there are duplicate colors in the palette.*/ if(mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) { size_t numbytes = lodepng_get_raw_size(w, h, mode_in); lodepng_memcpy(out, in, numbytes); return 0; } } if(palettesize < palsize) palsize = palettesize; color_tree_init(&tree); for(i = 0; i != palsize; ++i) { const unsigned char* p = &palette[i * 4]; error = color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i); if(error) break; } } if(!error) { 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, in, mode_in); } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) { getPixelColorsRGB8(out, numpixels, 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); error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); if(error) break; } } } if(mode_out->colortype == LCT_PALETTE) { color_tree_cleanup(&tree); } return error; } /* Converts a single rgb color without alpha from one type to another, color bits truncated to their bitdepth. In case of single channel (gray or palette), only the r channel is used. Slow function, do not use to process all pixels of an image. Alpha channel not supported on purpose: this is for bKGD, supporting alpha may prevent it from finding a color in the palette, from the specification it looks like bKGD should ignore the alpha values of the palette since it can use any palette index but doesn't have an alpha channel. Idem with ignoring color key. */ unsigned lodepng_convert_rgb( unsigned* r_out, unsigned* g_out, unsigned* b_out, unsigned r_in, unsigned g_in, unsigned b_in, const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) { unsigned r = 0, g = 0, b = 0; unsigned mul = 65535 / ((1u << mode_in->bitdepth) - 1u); /*65535, 21845, 4369, 257, 1*/ unsigned shift = 16 - mode_out->bitdepth; if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) { r = g = b = r_in * mul; } else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) { r = r_in * mul; g = g_in * mul; b = b_in * mul; } else if(mode_in->colortype == LCT_PALETTE) { if(r_in >= mode_in->palettesize) return 82; r = mode_in->palette[r_in * 4 + 0] * 257u; g = mode_in->palette[r_in * 4 + 1] * 257u; b = mode_in->palette[r_in * 4 + 2] * 257u; } else { return 31; } /* now convert to output format */ if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) { *r_out = r >> shift ; } else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) { *r_out = r >> shift ; *g_out = g >> shift ; *b_out = b >> shift ; } else if(mode_out->colortype == LCT_PALETTE) { unsigned i; /* a 16-bit color cannot be in the palette */ if((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82; for(i = 0; i < mode_out->palettesize; i++) { unsigned j = i * 4; if((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] && (b >> 8) == mode_out->palette[j + 2]) { *r_out = i; return 0; } } return 82; } else { return 31; } return 0; } #ifdef LODEPNG_COMPILE_ENCODER void lodepng_color_stats_init(LodePNGColorStats* stats) { /*stats*/ stats->colored = 0; stats->key = 0; stats->key_r = stats->key_g = stats->key_b = 0; stats->alpha = 0; stats->numcolors = 0; stats->bits = 1; stats->numpixels = 0; /*settings*/ stats->allow_palette = 1; stats->allow_greyscale = 1; } /*function used for debug purposes with C++*/ /*void printColorStats(LodePNGColorStats* 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; } /*stats must already have been inited. */ unsigned lodepng_compute_color_stats(LodePNGColorStats* stats, const unsigned char* in, unsigned w, unsigned h, const LodePNGColorMode* mode_in) { size_t i; ColorTree tree; size_t numpixels = (size_t)w * (size_t)h; unsigned error = 0; /* mark things as done already if it would be impossible to have a more expensive case */ unsigned colored_done = lodepng_is_greyscale_type(mode_in) ? 1 : 0; unsigned alpha_done = lodepng_can_have_alpha(mode_in) ? 0 : 1; unsigned numcolors_done = 0; unsigned bpp = lodepng_get_bpp(mode_in); unsigned bits_done = (stats->bits == 1 && bpp == 1) ? 1 : 0; unsigned sixteen = 0; /* whether the input image is 16 bit */ unsigned maxnumcolors = 257; if(bpp <= 8) maxnumcolors = LODEPNG_MIN(257, stats->numcolors + (1u << bpp)); stats->numpixels += numpixels; /*if palette not allowed, no need to compute numcolors*/ if(!stats->allow_palette) numcolors_done = 1; color_tree_init(&tree); /*If the stats was already filled in from previous data, fill its palette in tree and mark things as done already if we know they are the most expensive case already*/ if(stats->alpha) alpha_done = 1; if(stats->colored) colored_done = 1; if(stats->bits == 16) numcolors_done = 1; if(stats->bits >= bpp) bits_done = 1; if(stats->numcolors >= maxnumcolors) numcolors_done = 1; if(!numcolors_done) { for(i = 0; i < stats->numcolors; i++) { const unsigned char* color = &stats->palette[i * 4]; error = color_tree_add(&tree, color[0], color[1], color[2], color[3], (unsigned)i); if(error) goto cleanup; } } /*Check if the 16-bit input is truly 16-bit*/ if(mode_in->bitdepth == 16 && !sixteen) { unsigned short r = 0, g = 0, b = 0, a = 0; for(i = 0; i != numpixels; ++i) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); 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*/ { stats->bits = 16; sixteen = 1; bits_done = 1; numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/ break; } } } if(sixteen) { unsigned short r = 0, g = 0, b = 0, a = 0; for(i = 0; i != numpixels; ++i) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); if(!colored_done && (r != g || r != b)) { stats->colored = 1; colored_done = 1; } if(!alpha_done) { unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b); if(a != 65535 && (a != 0 || (stats->key && !matchkey))) { stats->alpha = 1; stats->key = 0; alpha_done = 1; } else if(a == 0 && !stats->alpha && !stats->key) { stats->key = 1; stats->key_r = r; stats->key_g = g; stats->key_b = b; } else if(a == 65535 && stats->key && matchkey) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ stats->alpha = 1; stats->key = 0; alpha_done = 1; } } if(alpha_done && numcolors_done && colored_done && bits_done) break; } if(stats->key && !stats->alpha) { for(i = 0; i != numpixels; ++i) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ stats->alpha = 1; stats->key = 0; alpha_done = 1; } } } } else /* < 16-bit */ { 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); if(!bits_done && stats->bits < 8) { /*only r is checked, < 8 bits is only relevant for grayscale*/ unsigned bits = getValueRequiredBits(r); if(bits > stats->bits) stats->bits = bits; } bits_done = (stats->bits >= bpp); if(!colored_done && (r != g || r != b)) { stats->colored = 1; colored_done = 1; if(stats->bits < 8) stats->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ } if(!alpha_done) { unsigned matchkey = (r == stats->key_r && g == stats->key_g && b == stats->key_b); if(a != 255 && (a != 0 || (stats->key && !matchkey))) { stats->alpha = 1; stats->key = 0; alpha_done = 1; if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } else if(a == 0 && !stats->alpha && !stats->key) { stats->key = 1; stats->key_r = r; stats->key_g = g; stats->key_b = b; } else if(a == 255 && stats->key && matchkey) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ stats->alpha = 1; stats->key = 0; alpha_done = 1; if(stats->bits < 8) stats->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)) { error = color_tree_add(&tree, r, g, b, a, stats->numcolors); if(error) goto cleanup; if(stats->numcolors < 256) { unsigned char* p = stats->palette; unsigned n = stats->numcolors; p[n * 4 + 0] = r; p[n * 4 + 1] = g; p[n * 4 + 2] = b; p[n * 4 + 3] = a; } ++stats->numcolors; numcolors_done = stats->numcolors >= maxnumcolors; } } if(alpha_done && numcolors_done && colored_done && bits_done) break; } if(stats->key && !stats->alpha) { for(i = 0; i != numpixels; ++i) { getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); if(a != 0 && r == stats->key_r && g == stats->key_g && b == stats->key_b) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ stats->alpha = 1; stats->key = 0; alpha_done = 1; if(stats->bits < 8) stats->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } } } /*make the stats's key always 16-bit for consistency - repeat each byte twice*/ stats->key_r += (stats->key_r << 8); stats->key_g += (stats->key_g << 8); stats->key_b += (stats->key_b << 8); } cleanup: color_tree_cleanup(&tree); return error; } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*Adds a single color to the color stats. The stats must already have been inited. The color must be given as 16-bit (with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for all pixels of an image but only for a few additional values. */ static unsigned lodepng_color_stats_add(LodePNGColorStats* stats, unsigned r, unsigned g, unsigned b, unsigned a) { unsigned error = 0; unsigned char image[8]; LodePNGColorMode mode; lodepng_color_mode_init(&mode); image[0] = r >> 8; image[1] = r; image[2] = g >> 8; image[3] = g; image[4] = b >> 8; image[5] = b; image[6] = a >> 8; image[7] = a; mode.bitdepth = 16; mode.colortype = LCT_RGBA; error = lodepng_compute_color_stats(stats, image, 1, 1, &mode); lodepng_color_mode_cleanup(&mode); return error; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*Computes a minimal PNG color model that can contain all colors as indicated by the stats. The stats should be computed with lodepng_compute_color_stats. mode_in is raw color profile of the image the stats were computed on, to copy palette order from when relevant. Minimal PNG color model means the color type and bit depth that gives smallest amount of bits in the output image, e.g. gray if only grayscale pixels, palette if less than 256 colors, color key if only single transparent color, ... This is used if auto_convert is enabled (it is by default). */ static unsigned auto_choose_color(LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, const LodePNGColorStats* stats) { unsigned error = 0; unsigned palettebits; size_t i, n; size_t numpixels = stats->numpixels; unsigned palette_ok, gray_ok; unsigned alpha = stats->alpha; unsigned key = stats->key; unsigned bits = stats->bits; mode_out->key_defined = 0; if(key && numpixels <= 16) { alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ key = 0; if(bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } gray_ok = !stats->colored; if(!stats->allow_greyscale) gray_ok = 0; if(!gray_ok && bits < 8) bits = 8; n = stats->numcolors; palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); palette_ok = n <= 256 && bits <= 8 && n != 0; /*n==0 means likely numcolors wasn't computed*/ if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ if(gray_ok && !alpha && bits <= palettebits) palette_ok = 0; /*gray is less overhead*/ if(!stats->allow_palette) palette_ok = 0; if(palette_ok) { const unsigned char* p = stats->palette; lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ for(i = 0; i != stats->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); /*clears palette, keeps the above set colortype and bitdepth fields as-is*/ lodepng_color_mode_copy(mode_out, mode_in); } } else /*8-bit or 16-bit per channel*/ { mode_out->bitdepth = bits; mode_out->colortype = alpha ? (gray_ok ? LCT_GREY_ALPHA : LCT_RGBA) : (gray_ok ? LCT_GREY : LCT_RGB); if(key) { unsigned mask = (1u << mode_out->bitdepth) - 1u; /*stats always uses 16-bit, mask converts it*/ mode_out->key_r = stats->key_r & mask; mode_out->key_g = stats->key_g & mask; mode_out->key_b = stats->key_b & mask; mode_out->key_defined = 1; } } return error; } #endif /* #ifdef LODEPNG_COMPILE_ENCODER */ /*Paeth predictor, used by PNG filter type 4*/ static unsigned char paethPredictor(unsigned char a, unsigned char b, unsigned char c) { /* the subtractions of unsigned char cast it to a signed type. With gcc, short is faster than int, with clang int is as fast (as of april 2023)*/ short pa = (b - c) < 0 ? -(b - c) : (b - c); short pb = (a - c) < 0 ? -(a - c) : (a - c); /* writing it out like this compiles to something faster than introducing a temp variable*/ short pc = (a + b - c - c) < 0 ? -(a + b - c - c) : (a + b - c - c); /* return input value associated with smallest of pa, pb, pc (with certain priority if equal) */ if(pb < pa) { a = b; pa = pb; } return (pc < pa) ? c : 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] * (1u + (passw[i] * bpp + 7u) / 8u) : 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 + 7u) / 8u); /*only padded at end of reduced image*/ passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7u) / 8u; } } #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) { unsigned width, height; 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*/ /* TODO: remove this. One should use a new LodePNGState for new sessions */ 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(lodepng_chunk_length(in + 8) != 13) { CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/ } if(!lodepng_chunk_type_equals(in + 8, "IHDR")) { CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ } /*read the values given in the header*/ width = lodepng_read32bitInt(&in[16]); height = lodepng_read32bitInt(&in[20]); /*TODO: remove the undocumented feature that allows to give null pointers to width or height*/ if(w) *w = width; if(h) *h = height; 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]; /*errors returned only after the parsing so other values are still output*/ /*error: invalid image size*/ if(width == 0 || height == 0) CERROR_RETURN_ERROR(state->error, 93); /*error: invalid colortype or bitdepth combination*/ state->error = checkColorValidity(info->color.colortype, info->color.bitdepth); if(state->error) return state->error; /*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); 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*/ } } 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: { size_t j = 0; for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; for(i = bytewidth; i != length; ++i, ++j) recon[i] = scanline[i] + recon[j]; 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) { size_t j = 0; for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1u); /* Unroll independent paths of this predictor. A 6x and 8x version is also possible but that adds too much code. Whether this speeds up anything depends on compiler and settings. */ if(bytewidth >= 4) { for(; i + 3 < length; i += 4, j += 4) { unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2], s3 = scanline[i + 3]; unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2], r3 = recon[j + 3]; unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2], p3 = precon[i + 3]; recon[i + 0] = s0 + ((r0 + p0) >> 1u); recon[i + 1] = s1 + ((r1 + p1) >> 1u); recon[i + 2] = s2 + ((r2 + p2) >> 1u); recon[i + 3] = s3 + ((r3 + p3) >> 1u); } } else if(bytewidth >= 3) { for(; i + 2 < length; i += 3, j += 3) { unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1], s2 = scanline[i + 2]; unsigned char r0 = recon[j + 0], r1 = recon[j + 1], r2 = recon[j + 2]; unsigned char p0 = precon[i + 0], p1 = precon[i + 1], p2 = precon[i + 2]; recon[i + 0] = s0 + ((r0 + p0) >> 1u); recon[i + 1] = s1 + ((r1 + p1) >> 1u); recon[i + 2] = s2 + ((r2 + p2) >> 1u); } } else if(bytewidth >= 2) { for(; i + 1 < length; i += 2, j += 2) { unsigned char s0 = scanline[i + 0], s1 = scanline[i + 1]; unsigned char r0 = recon[j + 0], r1 = recon[j + 1]; unsigned char p0 = precon[i + 0], p1 = precon[i + 1]; recon[i + 0] = s0 + ((r0 + p0) >> 1u); recon[i + 1] = s1 + ((r1 + p1) >> 1u); } } for(; i != length; ++i, ++j) recon[i] = scanline[i] + ((recon[j] + precon[i]) >> 1u); } else { size_t j = 0; for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; for(i = bytewidth; i != length; ++i, ++j) recon[i] = scanline[i] + (recon[j] >> 1u); } break; case 4: if(precon) { /* Unroll independent paths of this predictor. Whether this speeds up anything depends on compiler and settings. */ if(bytewidth == 8) { unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0; unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0; unsigned char a4, b4 = 0, c4, d4 = 0, a5, b5 = 0, c5, d5 = 0; unsigned char a6, b6 = 0, c6, d6 = 0, a7, b7 = 0, c7, d7 = 0; for(i = 0; i + 7 < length; i += 8) { c0 = b0; c1 = b1; c2 = b2; c3 = b3; c4 = b4; c5 = b5; c6 = b6; c7 = b7; b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; b3 = precon[i + 3]; b4 = precon[i + 4]; b5 = precon[i + 5]; b6 = precon[i + 6]; b7 = precon[i + 7]; a0 = d0; a1 = d1; a2 = d2; a3 = d3; a4 = d4; a5 = d5; a6 = d6; a7 = d7; d0 = scanline[i + 0] + paethPredictor(a0, b0, c0); d1 = scanline[i + 1] + paethPredictor(a1, b1, c1); d2 = scanline[i + 2] + paethPredictor(a2, b2, c2); d3 = scanline[i + 3] + paethPredictor(a3, b3, c3); d4 = scanline[i + 4] + paethPredictor(a4, b4, c4); d5 = scanline[i + 5] + paethPredictor(a5, b5, c5); d6 = scanline[i + 6] + paethPredictor(a6, b6, c6); d7 = scanline[i + 7] + paethPredictor(a7, b7, c7); recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; recon[i + 3] = d3; recon[i + 4] = d4; recon[i + 5] = d5; recon[i + 6] = d6; recon[i + 7] = d7; } } else if(bytewidth == 6) { unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0; unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0; unsigned char a4, b4 = 0, c4, d4 = 0, a5, b5 = 0, c5, d5 = 0; for(i = 0; i + 5 < length; i += 6) { c0 = b0; c1 = b1; c2 = b2; c3 = b3; c4 = b4; c5 = b5; b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; b3 = precon[i + 3]; b4 = precon[i + 4]; b5 = precon[i + 5]; a0 = d0; a1 = d1; a2 = d2; a3 = d3; a4 = d4; a5 = d5; d0 = scanline[i + 0] + paethPredictor(a0, b0, c0); d1 = scanline[i + 1] + paethPredictor(a1, b1, c1); d2 = scanline[i + 2] + paethPredictor(a2, b2, c2); d3 = scanline[i + 3] + paethPredictor(a3, b3, c3); d4 = scanline[i + 4] + paethPredictor(a4, b4, c4); d5 = scanline[i + 5] + paethPredictor(a5, b5, c5); recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; recon[i + 3] = d3; recon[i + 4] = d4; recon[i + 5] = d5; } } else if(bytewidth == 4) { unsigned char a0, b0 = 0, c0, d0 = 0, a1, b1 = 0, c1, d1 = 0; unsigned char a2, b2 = 0, c2, d2 = 0, a3, b3 = 0, c3, d3 = 0; for(i = 0; i + 3 < length; i += 4) { c0 = b0; c1 = b1; c2 = b2; c3 = b3; b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; b3 = precon[i + 3]; a0 = d0; a1 = d1; a2 = d2; a3 = d3; d0 = scanline[i + 0] + paethPredictor(a0, b0, c0); d1 = scanline[i + 1] + paethPredictor(a1, b1, c1); d2 = scanline[i + 2] + paethPredictor(a2, b2, c2); d3 = scanline[i + 3] + paethPredictor(a3, b3, c3); recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; recon[i + 3] = d3; } } else if(bytewidth == 3) { unsigned char a0, b0 = 0, c0, d0 = 0; unsigned char a1, b1 = 0, c1, d1 = 0; unsigned char a2, b2 = 0, c2, d2 = 0; for(i = 0; i + 2 < length; i += 3) { c0 = b0; c1 = b1; c2 = b2; b0 = precon[i + 0]; b1 = precon[i + 1]; b2 = precon[i + 2]; a0 = d0; a1 = d1; a2 = d2; d0 = scanline[i + 0] + paethPredictor(a0, b0, c0); d1 = scanline[i + 1] + paethPredictor(a1, b1, c1); d2 = scanline[i + 2] + paethPredictor(a2, b2, c2); recon[i + 0] = d0; recon[i + 1] = d1; recon[i + 2] = d2; } } else if(bytewidth == 2) { unsigned char a0, b0 = 0, c0, d0 = 0; unsigned char a1, b1 = 0, c1, d1 = 0; for(i = 0; i + 1 < length; i += 2) { c0 = b0; c1 = b1; b0 = precon[i + 0]; b1 = precon[i + 1]; a0 = d0; a1 = d1; d0 = scanline[i + 0] + paethPredictor(a0, b0, c0); d1 = scanline[i + 1] + paethPredictor(a1, b1, c1); recon[i + 0] = d0; recon[i + 1] = d1; } } else if(bytewidth == 1) { unsigned char a, b = 0, c, d = 0; for(i = 0; i != length; ++i) { c = b; b = precon[i]; a = d; d = scanline[i] + paethPredictor(a, b, c); recon[i] = d; } } else { /* Normally not a possible case, but this would handle it correctly */ for(i = 0; i != bytewidth; ++i) { recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ } } /* finish any remaining bytes */ for(; i != length; ++i) { recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); } } else { size_t j = 0; for(i = 0; i != bytewidth; ++i) { recon[i] = scanline[i]; } for(i = bytewidth; i != length; ++i, ++j) { /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ recon[i] = (scanline[i] + recon[j]); } } break; default: return 36; /*error: invalid 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 + 7u) / 8u; /*the width of a scanline in bytes, not including the filter type*/ size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u; 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 / 8u; 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] + (size_t)y * ADAM7_DY[i]) * (size_t)w + ADAM7_IX[i] + (size_t)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] + (size_t)y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + (size_t)x * ADAM7_DX[i]) * bpp; for(b = 0; b < bpp; ++b) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&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 (= possible 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 + 7u) / 8u) * 8u) { CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); removePaddingBits(out, in, w * bpp, ((w * bpp + 7u) / 8u) * 8u, h); } /*we can immediately 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 + 7u) / 8u) * 8u, 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; color->palettesize = chunkLength / 3u; if(color->palettesize == 0 || color->palettesize > 256) return 38; /*error: palette too small or big*/ lodepng_color_mode_alloc_palette(color); if(!color->palette && color->palettesize) { color->palettesize = 0; return 83; /*alloc fail*/ } 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 39; 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 grayscale 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; /*error: invalid palette index, or maybe this chunk appeared before PLTE*/ if(data[0] >= info->color.palettesize) return 103; 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 grayscale image*/ if(chunkLength != 2) return 44; /*the values are truncated to bitdepth in the PNG file*/ 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 grayscale image*/ if(chunkLength != 6) return 45; /*the values are truncated to bitdepth in the PNG file*/ 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; 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*/ lodepng_memcpy(key, data, length); key[length] = 0; string2_begin = length + 1; /*skip keyword null terminator*/ length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin); str = (char*)lodepng_malloc(length + 1); if(!str) CERROR_BREAK(error, 83); /*alloc fail*/ lodepng_memcpy(str, data + string2_begin, length); str[length] = 0; 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 LodePNGDecoderSettings* decoder, const unsigned char* data, size_t chunkLength) { unsigned error = 0; /*copy the object to change parameters in it*/ LodePNGDecompressSettings zlibsettings = decoder->zlibsettings; unsigned length, string2_begin; char *key = 0; unsigned char* str = 0; size_t size = 0; 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*/ lodepng_memcpy(key, data, length); key[length] = 0; 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 = (unsigned)chunkLength - string2_begin; zlibsettings.max_output_size = decoder->max_text_size; /*will fail if zlib error, e.g. if length is too small*/ error = zlib_decompress(&str, &size, 0, &data[string2_begin], length, &zlibsettings); /*error: compressed text larger than decoder->max_text_size*/ if(error && size > zlibsettings.max_output_size) error = 112; if(error) break; error = lodepng_add_text_sized(info, key, (char*)str, size); break; } lodepng_free(key); lodepng_free(str); return error; } /*international text chunk (iTXt)*/ static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecoderSettings* decoder, const unsigned char* data, size_t chunkLength) { unsigned error = 0; unsigned i; /*copy the object to change parameters in it*/ LodePNGDecompressSettings zlibsettings = decoder->zlibsettings; unsigned length, begin, compressed; char *key = 0, *langtag = 0, *transkey = 0; 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*/ lodepng_memcpy(key, data, length); key[length] = 0; /*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*/ lodepng_memcpy(langtag, data + begin, length); langtag[length] = 0; /*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*/ lodepng_memcpy(transkey, data + begin, length); transkey[length] = 0; /*read the actual text*/ begin += length + 1; length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin; if(compressed) { unsigned char* str = 0; size_t size = 0; zlibsettings.max_output_size = decoder->max_text_size; /*will fail if zlib error, e.g. if length is too small*/ error = zlib_decompress(&str, &size, 0, &data[begin], length, &zlibsettings); /*error: compressed text larger than decoder->max_text_size*/ if(error && size > zlibsettings.max_output_size) error = 112; if(!error) error = lodepng_add_itext_sized(info, key, langtag, transkey, (char*)str, size); lodepng_free(str); } else { error = lodepng_add_itext_sized(info, key, langtag, transkey, (char*)(data + begin), length); } break; } lodepng_free(key); lodepng_free(langtag); lodepng_free(transkey); 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 */ } static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(chunkLength != 4) return 96; /*invalid gAMA chunk size*/ info->gama_defined = 1; info->gama_gamma = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; return 0; /* OK */ } static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(chunkLength != 32) return 97; /*invalid cHRM chunk size*/ info->chrm_defined = 1; info->chrm_white_x = 16777216u * data[ 0] + 65536u * data[ 1] + 256u * data[ 2] + data[ 3]; info->chrm_white_y = 16777216u * data[ 4] + 65536u * data[ 5] + 256u * data[ 6] + data[ 7]; info->chrm_red_x = 16777216u * data[ 8] + 65536u * data[ 9] + 256u * data[10] + data[11]; info->chrm_red_y = 16777216u * data[12] + 65536u * data[13] + 256u * data[14] + data[15]; info->chrm_green_x = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19]; info->chrm_green_y = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23]; info->chrm_blue_x = 16777216u * data[24] + 65536u * data[25] + 256u * data[26] + data[27]; info->chrm_blue_y = 16777216u * data[28] + 65536u * data[29] + 256u * data[30] + data[31]; return 0; /* OK */ } static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/ info->srgb_defined = 1; info->srgb_intent = data[0]; return 0; /* OK */ } static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecoderSettings* decoder, const unsigned char* data, size_t chunkLength) { unsigned error = 0; unsigned i; size_t size = 0; /*copy the object to change parameters in it*/ LodePNGDecompressSettings zlibsettings = decoder->zlibsettings; unsigned length, string2_begin; info->iccp_defined = 1; if(info->iccp_name) lodepng_clear_icc(info); for(length = 0; length < chunkLength && data[length] != 0; ++length) ; if(length + 2 >= chunkLength) return 75; /*no null termination, corrupt?*/ if(length < 1 || length > 79) return 89; /*keyword too short or long*/ info->iccp_name = (char*)lodepng_malloc(length + 1); if(!info->iccp_name) return 83; /*alloc fail*/ info->iccp_name[length] = 0; for(i = 0; i != length; ++i) info->iccp_name[i] = (char)data[i]; if(data[length + 1] != 0) return 72; /*the 0 byte indicating compression must be 0*/ string2_begin = length + 2; if(string2_begin > chunkLength) return 75; /*no null termination, corrupt?*/ length = (unsigned)chunkLength - string2_begin; zlibsettings.max_output_size = decoder->max_icc_size; error = zlib_decompress(&info->iccp_profile, &size, 0, &data[string2_begin], length, &zlibsettings); /*error: ICC profile larger than decoder->max_icc_size*/ if(error && size > zlibsettings.max_output_size) error = 113; info->iccp_profile_size = (unsigned)size; if(!error && !info->iccp_profile_size) error = 100; /*invalid ICC profile size*/ return error; } /*significant bits chunk (sBIT)*/ static unsigned readChunk_sBIT(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { unsigned bitdepth = (info->color.colortype == LCT_PALETTE) ? 8 : info->color.bitdepth; if(info->color.colortype == LCT_GREY) { /*error: this chunk must be 1 bytes for grayscale image*/ if(chunkLength != 1) return 114; if(data[0] == 0 || data[0] > bitdepth) return 115; info->sbit_defined = 1; info->sbit_r = info->sbit_g = info->sbit_b = data[0]; /*setting g and b is not required, but sensible*/ } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_PALETTE) { /*error: this chunk must be 3 bytes for RGB and palette image*/ if(chunkLength != 3) return 114; if(data[0] == 0 || data[1] == 0 || data[2] == 0) return 115; if(data[0] > bitdepth || data[1] > bitdepth || data[2] > bitdepth) return 115; info->sbit_defined = 1; info->sbit_r = data[0]; info->sbit_g = data[1]; info->sbit_b = data[2]; } else if(info->color.colortype == LCT_GREY_ALPHA) { /*error: this chunk must be 2 byte for grayscale with alpha image*/ if(chunkLength != 2) return 114; if(data[0] == 0 || data[1] == 0) return 115; if(data[0] > bitdepth || data[1] > bitdepth) return 115; info->sbit_defined = 1; info->sbit_r = info->sbit_g = info->sbit_b = data[0]; /*setting g and b is not required, but sensible*/ info->sbit_a = data[1]; } else if(info->color.colortype == LCT_RGBA) { /*error: this chunk must be 4 bytes for grayscale image*/ if(chunkLength != 4) return 114; if(data[0] == 0 || data[1] == 0 || data[2] == 0 || data[3] == 0) return 115; if(data[0] > bitdepth || data[1] > bitdepth || data[2] > bitdepth || data[3] > bitdepth) return 115; info->sbit_defined = 1; info->sbit_r = data[0]; info->sbit_g = data[1]; info->sbit_b = data[2]; info->sbit_a = data[3]; } return 0; /* OK */ } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos, const unsigned char* in, size_t insize) { const unsigned char* chunk = in + pos; unsigned chunkLength; const unsigned char* data; unsigned unhandled = 0; unsigned error = 0; if(pos + 4 > insize) return 30; chunkLength = lodepng_chunk_length(chunk); if(chunkLength > 2147483647) return 63; data = lodepng_chunk_data_const(chunk); if(chunkLength + 12 > insize - pos) return 30; if(lodepng_chunk_type_equals(chunk, "PLTE")) { error = readChunk_PLTE(&state->info_png.color, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "tRNS")) { error = readChunk_tRNS(&state->info_png.color, data, chunkLength); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS } else if(lodepng_chunk_type_equals(chunk, "bKGD")) { error = readChunk_bKGD(&state->info_png, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "tEXt")) { error = readChunk_tEXt(&state->info_png, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "zTXt")) { error = readChunk_zTXt(&state->info_png, &state->decoder, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "iTXt")) { error = readChunk_iTXt(&state->info_png, &state->decoder, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "tIME")) { error = readChunk_tIME(&state->info_png, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "pHYs")) { error = readChunk_pHYs(&state->info_png, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "gAMA")) { error = readChunk_gAMA(&state->info_png, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "cHRM")) { error = readChunk_cHRM(&state->info_png, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "sRGB")) { error = readChunk_sRGB(&state->info_png, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "iCCP")) { error = readChunk_iCCP(&state->info_png, &state->decoder, data, chunkLength); } else if(lodepng_chunk_type_equals(chunk, "sBIT")) { error = readChunk_sBIT(&state->info_png, data, chunkLength); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } else { /* unhandled chunk is ok (is not an error) */ unhandled = 1; } if(!error && !unhandled && !state->decoder.ignore_crc) { if(lodepng_chunk_check_crc(chunk)) return 57; /*invalid CRC*/ } return error; } /*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; /*points to beginning of next chunk*/ unsigned char* idat; /*the data from idat chunks, zlib compressed*/ size_t idatsize = 0; unsigned char* scanlines = 0; size_t scanlines_size = 0, expected_size = 0; size_t outsize = 0; /*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*/ /* safe output values in case error happens */ *out = 0; *w = *h = 0; state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ if(state->error) return; if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) { CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/ } /*the input filesize is a safe upper bound for the sum of idat chunks size*/ idat = (unsigned char*)lodepng_malloc(insize); if(!idat) CERROR_RETURN(state->error, 83); /*alloc fail*/ 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*/ size_t pos = (size_t)(chunk - in); /*error: next chunk out of bounds of the in buffer*/ if(chunk < in || pos + 12 > insize) { if(state->decoder.ignore_end) break; /*other errors may still happen though*/ CERROR_BREAK(state->error, 30); } /*length of the data of the chunk, excluding the 12 bytes for length, chunk type and CRC*/ chunkLength = lodepng_chunk_length(chunk); /*error: chunk length larger than the max PNG chunk size*/ if(chunkLength > 2147483647) { if(state->decoder.ignore_end) break; /*other errors may still happen though*/ CERROR_BREAK(state->error, 63); } if(pos + (size_t)chunkLength + 12 > insize || pos + (size_t)chunkLength + 12 < pos) { CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk (or int overflow)*/ } data = lodepng_chunk_data_const(chunk); unknown = 0; /*IDAT chunk, containing compressed image data*/ if(lodepng_chunk_type_equals(chunk, "IDAT")) { size_t newsize; if(lodepng_addofl(idatsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95); if(newsize > insize) CERROR_BREAK(state->error, 95); lodepng_memcpy(idat + idatsize, data, chunkLength); idatsize += chunkLength; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS critical_pos = 3; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } else if(lodepng_chunk_type_equals(chunk, "IEND")) { /*IEND chunk*/ IEND = 1; } else if(lodepng_chunk_type_equals(chunk, "PLTE")) { /*palette 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*/ } else if(lodepng_chunk_type_equals(chunk, "tRNS")) { /*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that affects the alpha channel of pixels. */ 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; } else if(lodepng_chunk_type_equals(chunk, "tEXt")) { /*text chunk (tEXt)*/ if(state->decoder.read_text_chunks) { state->error = readChunk_tEXt(&state->info_png, data, chunkLength); if(state->error) break; } } else if(lodepng_chunk_type_equals(chunk, "zTXt")) { /*compressed text chunk (zTXt)*/ if(state->decoder.read_text_chunks) { state->error = readChunk_zTXt(&state->info_png, &state->decoder, data, chunkLength); if(state->error) break; } } else if(lodepng_chunk_type_equals(chunk, "iTXt")) { /*international text chunk (iTXt)*/ if(state->decoder.read_text_chunks) { state->error = readChunk_iTXt(&state->info_png, &state->decoder, 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; } else if(lodepng_chunk_type_equals(chunk, "gAMA")) { state->error = readChunk_gAMA(&state->info_png, data, chunkLength); if(state->error) break; } else if(lodepng_chunk_type_equals(chunk, "cHRM")) { state->error = readChunk_cHRM(&state->info_png, data, chunkLength); if(state->error) break; } else if(lodepng_chunk_type_equals(chunk, "sRGB")) { state->error = readChunk_sRGB(&state->info_png, data, chunkLength); if(state->error) break; } else if(lodepng_chunk_type_equals(chunk, "iCCP")) { state->error = readChunk_iCCP(&state->info_png, &state->decoder, data, chunkLength); if(state->error) break; } else if(lodepng_chunk_type_equals(chunk, "sBIT")) { state->error = readChunk_sBIT(&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(!state->decoder.ignore_critical && !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, in + insize); } if(!state->error && state->info_png.color.colortype == LCT_PALETTE && !state->info_png.color.palette) { state->error = 106; /* error: PNG file must have PLTE chunk if color type is palette */ } if(!state->error) { /*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) { unsigned bpp = lodepng_get_bpp(&state->info_png.color); expected_size = lodepng_get_raw_size_idat(*w, *h, bpp); } else { unsigned bpp = lodepng_get_bpp(&state->info_png.color); /*Adam-7 interlaced: expected size is the sum of the 7 sub-images sizes*/ expected_size = 0; expected_size += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, bpp); if(*w > 4) expected_size += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, bpp); expected_size += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, bpp); if(*w > 2) expected_size += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, bpp); expected_size += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, bpp); if(*w > 1) expected_size += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, bpp); expected_size += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, bpp); } state->error = zlib_decompress(&scanlines, &scanlines_size, expected_size, idat, idatsize, &state->decoder.zlibsettings); } if(!state->error && scanlines_size != expected_size) state->error = 91; /*decompressed size doesn't match prediction*/ lodepng_free(idat); if(!state->error) { outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color); *out = (unsigned char*)lodepng_malloc(outsize); if(!*out) state->error = 83; /*alloc fail*/ } if(!state->error) { lodepng_memset(*out, 0, outsize); state->error = postProcessScanlines(*out, scanlines, *w, *h, &state->info_png); } lodepng_free(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*/ unsigned char* data = *out; size_t outsize; /*TODO: check if this works according to the statement in the documentation: "The converter can convert from grayscale input color type, to 8-bit grayscale or grayscale 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; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*disable reading things that this function doesn't output*/ state.decoder.read_text_chunks = 0; state.decoder.remember_unknown_chunks = 0; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ 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 = 0; size_t buffersize; unsigned error; /* safe output values in case error happens */ *out = 0; *w = *h = 0; 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; settings->max_text_size = 16777216; settings->max_icc_size = 16777216; /* 16MB is much more than enough for any reasonable ICC profile */ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ settings->ignore_crc = 0; settings->ignore_critical = 0; settings->ignore_end = 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 / */ /* ////////////////////////////////////////////////////////////////////////// */ static unsigned writeSignature(ucvector* out) { size_t pos = out->size; const unsigned char signature[] = {137, 80, 78, 71, 13, 10, 26, 10}; /*8 bytes PNG signature, aka the magic bytes*/ if(!ucvector_resize(out, out->size + 8)) return 83; /*alloc fail*/ lodepng_memcpy(out->data + pos, signature, 8); return 0; } static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) { unsigned char *chunk, *data; CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 13, "IHDR")); data = chunk + 8; lodepng_set32bitInt(data + 0, w); /*width*/ lodepng_set32bitInt(data + 4, h); /*height*/ data[8] = (unsigned char)bitdepth; /*bit depth*/ data[9] = (unsigned char)colortype; /*color type*/ data[10] = 0; /*compression method*/ data[11] = 0; /*filter method*/ data[12] = interlace_method; /*interlace method*/ lodepng_chunk_generate_crc(chunk); return 0; } /* only adds the chunk if needed (there is a key or palette with alpha) */ static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) { unsigned char* chunk; size_t i, j = 8; if(info->palettesize == 0 || info->palettesize > 256) { return 68; /*invalid palette size, it is only allowed to be 1-256*/ } CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, info->palettesize * 3, "PLTE")); for(i = 0; i != info->palettesize; ++i) { /*add all channels except alpha channel*/ chunk[j++] = info->palette[i * 4 + 0]; chunk[j++] = info->palette[i * 4 + 1]; chunk[j++] = info->palette[i * 4 + 2]; } lodepng_chunk_generate_crc(chunk); return 0; } static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) { unsigned char* chunk = 0; if(info->colortype == LCT_PALETTE) { size_t i, 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) break; --amount; } if(amount) { CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, amount, "tRNS")); /*add the alpha channel values from the palette*/ for(i = 0; i != amount; ++i) chunk[8 + i] = info->palette[4 * i + 3]; } } else if(info->colortype == LCT_GREY) { if(info->key_defined) { CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "tRNS")); chunk[8] = (unsigned char)(info->key_r >> 8); chunk[9] = (unsigned char)(info->key_r & 255); } } else if(info->colortype == LCT_RGB) { if(info->key_defined) { CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "tRNS")); chunk[8] = (unsigned char)(info->key_r >> 8); chunk[9] = (unsigned char)(info->key_r & 255); chunk[10] = (unsigned char)(info->key_g >> 8); chunk[11] = (unsigned char)(info->key_g & 255); chunk[12] = (unsigned char)(info->key_b >> 8); chunk[13] = (unsigned char)(info->key_b & 255); } } if(chunk) lodepng_chunk_generate_crc(chunk); return 0; } static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; unsigned char* zlib = 0; size_t zlibsize = 0; error = zlib_compress(&zlib, &zlibsize, data, datasize, zlibsettings); if(!error) { error = lodepng_chunk_createv(out, zlibsize, "IDAT", zlib); } lodepng_free(zlib); return error; } static unsigned addChunk_IEND(ucvector* out) { return lodepng_chunk_createv(out, 0, "IEND", 0); } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) { unsigned char* chunk = 0; size_t keysize = lodepng_strlen(keyword), textsize = lodepng_strlen(textstring); size_t size = keysize + 1 + textsize; if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, size, "tEXt")); lodepng_memcpy(chunk + 8, keyword, keysize); chunk[8 + keysize] = 0; /*null termination char*/ lodepng_memcpy(chunk + 9 + keysize, textstring, textsize); lodepng_chunk_generate_crc(chunk); return 0; } static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; unsigned char* chunk = 0; unsigned char* compressed = 0; size_t compressedsize = 0; size_t textsize = lodepng_strlen(textstring); size_t keysize = lodepng_strlen(keyword); if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ error = zlib_compress(&compressed, &compressedsize, (const unsigned char*)textstring, textsize, zlibsettings); if(!error) { size_t size = keysize + 2 + compressedsize; error = lodepng_chunk_init(&chunk, out, size, "zTXt"); } if(!error) { lodepng_memcpy(chunk + 8, keyword, keysize); chunk[8 + keysize] = 0; /*null termination char*/ chunk[9 + keysize] = 0; /*compression method: 0*/ lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize); lodepng_chunk_generate_crc(chunk); } lodepng_free(compressed); return error; } static unsigned addChunk_iTXt(ucvector* out, unsigned compress, const char* keyword, const char* langtag, const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; unsigned char* chunk = 0; unsigned char* compressed = 0; size_t compressedsize = 0; size_t textsize = lodepng_strlen(textstring); size_t keysize = lodepng_strlen(keyword), langsize = lodepng_strlen(langtag), transsize = lodepng_strlen(transkey); if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ if(compress) { error = zlib_compress(&compressed, &compressedsize, (const unsigned char*)textstring, textsize, zlibsettings); } if(!error) { size_t size = keysize + 3 + langsize + 1 + transsize + 1 + (compress ? compressedsize : textsize); error = lodepng_chunk_init(&chunk, out, size, "iTXt"); } if(!error) { size_t pos = 8; lodepng_memcpy(chunk + pos, keyword, keysize); pos += keysize; chunk[pos++] = 0; /*null termination char*/ chunk[pos++] = (compress ? 1 : 0); /*compression flag*/ chunk[pos++] = 0; /*compression method: 0*/ lodepng_memcpy(chunk + pos, langtag, langsize); pos += langsize; chunk[pos++] = 0; /*null termination char*/ lodepng_memcpy(chunk + pos, transkey, transsize); pos += transsize; chunk[pos++] = 0; /*null termination char*/ if(compress) { lodepng_memcpy(chunk + pos, compressed, compressedsize); } else { lodepng_memcpy(chunk + pos, textstring, textsize); } lodepng_chunk_generate_crc(chunk); } lodepng_free(compressed); return error; } static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) { unsigned char* chunk = 0; if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "bKGD")); chunk[8] = (unsigned char)(info->background_r >> 8); chunk[9] = (unsigned char)(info->background_r & 255); } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 6, "bKGD")); chunk[8] = (unsigned char)(info->background_r >> 8); chunk[9] = (unsigned char)(info->background_r & 255); chunk[10] = (unsigned char)(info->background_g >> 8); chunk[11] = (unsigned char)(info->background_g & 255); chunk[12] = (unsigned char)(info->background_b >> 8); chunk[13] = (unsigned char)(info->background_b & 255); } else if(info->color.colortype == LCT_PALETTE) { CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 1, "bKGD")); chunk[8] = (unsigned char)(info->background_r & 255); /*palette index*/ } if(chunk) lodepng_chunk_generate_crc(chunk); return 0; } static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) { unsigned char* chunk; CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 7, "tIME")); chunk[8] = (unsigned char)(time->year >> 8); chunk[9] = (unsigned char)(time->year & 255); chunk[10] = (unsigned char)time->month; chunk[11] = (unsigned char)time->day; chunk[12] = (unsigned char)time->hour; chunk[13] = (unsigned char)time->minute; chunk[14] = (unsigned char)time->second; lodepng_chunk_generate_crc(chunk); return 0; } static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) { unsigned char* chunk; CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 9, "pHYs")); lodepng_set32bitInt(chunk + 8, info->phys_x); lodepng_set32bitInt(chunk + 12, info->phys_y); chunk[16] = info->phys_unit; lodepng_chunk_generate_crc(chunk); return 0; } static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) { unsigned char* chunk; CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "gAMA")); lodepng_set32bitInt(chunk + 8, info->gama_gamma); lodepng_chunk_generate_crc(chunk); return 0; } static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) { unsigned char* chunk; CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 32, "cHRM")); lodepng_set32bitInt(chunk + 8, info->chrm_white_x); lodepng_set32bitInt(chunk + 12, info->chrm_white_y); lodepng_set32bitInt(chunk + 16, info->chrm_red_x); lodepng_set32bitInt(chunk + 20, info->chrm_red_y); lodepng_set32bitInt(chunk + 24, info->chrm_green_x); lodepng_set32bitInt(chunk + 28, info->chrm_green_y); lodepng_set32bitInt(chunk + 32, info->chrm_blue_x); lodepng_set32bitInt(chunk + 36, info->chrm_blue_y); lodepng_chunk_generate_crc(chunk); return 0; } static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) { unsigned char data = info->srgb_intent; return lodepng_chunk_createv(out, 1, "sRGB", &data); } static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; unsigned char* chunk = 0; unsigned char* compressed = 0; size_t compressedsize = 0; size_t keysize = lodepng_strlen(info->iccp_name); if(keysize < 1 || keysize > 79) return 89; /*error: invalid keyword size*/ error = zlib_compress(&compressed, &compressedsize, info->iccp_profile, info->iccp_profile_size, zlibsettings); if(!error) { size_t size = keysize + 2 + compressedsize; error = lodepng_chunk_init(&chunk, out, size, "iCCP"); } if(!error) { lodepng_memcpy(chunk + 8, info->iccp_name, keysize); chunk[8 + keysize] = 0; /*null termination char*/ chunk[9 + keysize] = 0; /*compression method: 0*/ lodepng_memcpy(chunk + 10 + keysize, compressed, compressedsize); lodepng_chunk_generate_crc(chunk); } lodepng_free(compressed); return error; } static unsigned addChunk_sBIT(ucvector* out, const LodePNGInfo* info) { unsigned bitdepth = (info->color.colortype == LCT_PALETTE) ? 8 : info->color.bitdepth; unsigned char* chunk = 0; if(info->color.colortype == LCT_GREY) { if(info->sbit_r == 0 || info->sbit_r > bitdepth) return 115; CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 1, "sBIT")); chunk[8] = info->sbit_r; } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_PALETTE) { if(info->sbit_r == 0 || info->sbit_g == 0 || info->sbit_b == 0) return 115; if(info->sbit_r > bitdepth || info->sbit_g > bitdepth || info->sbit_b > bitdepth) return 115; CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 3, "sBIT")); chunk[8] = info->sbit_r; chunk[9] = info->sbit_g; chunk[10] = info->sbit_b; } else if(info->color.colortype == LCT_GREY_ALPHA) { if(info->sbit_r == 0 || info->sbit_a == 0) return 115; if(info->sbit_r > bitdepth || info->sbit_a > bitdepth) return 115; CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 2, "sBIT")); chunk[8] = info->sbit_r; chunk[9] = info->sbit_a; } else if(info->color.colortype == LCT_RGBA) { if(info->sbit_r == 0 || info->sbit_g == 0 || info->sbit_b == 0 || info->sbit_a == 0 || info->sbit_r > bitdepth || info->sbit_g > bitdepth || info->sbit_b > bitdepth || info->sbit_a > bitdepth) { return 115; } CERROR_TRY_RETURN(lodepng_chunk_init(&chunk, out, 4, "sBIT")); chunk[8] = info->sbit_r; chunk[9] = info->sbit_g; chunk[10] = info->sbit_b; chunk[11] = info->sbit_a; } if(chunk) lodepng_chunk_generate_crc(chunk); return 0; } #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] >> 1); for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1); } else { for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1); } 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; /*invalid filter type given*/ } } /* integer binary logarithm, max return value is 31 */ static size_t ilog2(size_t i) { size_t result = 0; if(i >= 65536) { result += 16; i >>= 16; } if(i >= 256) { result += 8; i >>= 8; } if(i >= 16) { result += 4; i >>= 4; } if(i >= 4) { result += 2; i >>= 2; } if(i >= 2) { result += 1; /*i >>= 1;*/ } return result; } /* integer approximation for i * log2(i), helper function for LFS_ENTROPY */ static size_t ilog2i(size_t i) { size_t l; if(i == 0) return 0; l = ilog2(i); /* approximate i*log2(i): l is integer logarithm, ((i - (1u << l)) << 1u) linearly approximates the missing fractional part multiplied by i */ return i * l + ((i - (((size_t)1) << l)) << 1u); } static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, const LodePNGColorMode* color, const LodePNGEncoderSettings* settings) { /* For PNG filter method 0 out must be a buffer with as size: h + (w * h * bpp + 7u) / 8u, because there are the scanlines with 1 extra byte per scanline */ unsigned bpp = lodepng_get_bpp(color); /*the width of a scanline in bytes, not including the filter type*/ size_t linebytes = lodepng_get_raw_size_idat(w, 1, bpp) - 1u; /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ size_t bytewidth = (bpp + 7u) / 8u; 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 && (color->colortype == LCT_PALETTE || color->bitdepth < 8)) strategy = LFS_ZERO; if(bpp == 0) return 31; /*error: invalid color type*/ if(strategy >= LFS_ZERO && strategy <= LFS_FOUR) { unsigned char type = (unsigned char)strategy; 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] = type; /*filter type byte*/ filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); prevline = &in[inindex]; } } else if(strategy == LFS_MINSUM) { /*adaptive filtering*/ unsigned char* 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) { attempt[type] = (unsigned char*)lodepng_malloc(linebytes); if(!attempt[type]) error = 83; /*alloc fail*/ } if(!error) { for(y = 0; y != h; ++y) { /*try the 5 filter types*/ for(type = 0; type != 5; ++type) { size_t sum = 0; filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); /*calculate the sum of the result*/ if(type == 0) { for(x = 0; x != linebytes; ++x) sum += (unsigned char)(attempt[type][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][x]; sum += 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 < smallest) { bestType = type; smallest = sum; } } 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][x]; } } for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); } else if(strategy == LFS_ENTROPY) { unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ size_t bestSum = 0; unsigned type, bestType = 0; unsigned count[256]; for(type = 0; type != 5; ++type) { attempt[type] = (unsigned char*)lodepng_malloc(linebytes); if(!attempt[type]) error = 83; /*alloc fail*/ } if(!error) { for(y = 0; y != h; ++y) { /*try the 5 filter types*/ for(type = 0; type != 5; ++type) { size_t sum = 0; filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); lodepng_memset(count, 0, 256 * sizeof(*count)); for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]]; ++count[type]; /*the filter type itself is part of the scanline*/ for(x = 0; x != 256; ++x) { sum += ilog2i(count[x]); } /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ if(type == 0 || sum > bestSum) { bestType = type; bestSum = sum; } } 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][x]; } } for(type = 0; type != 5; ++type) lodepng_free(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]; unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ size_t smallest = 0; unsigned type = 0, bestType = 0; unsigned char* dummy; LodePNGCompressSettings zlibsettings; lodepng_memcpy(&zlibsettings, &settings->zlibsettings, sizeof(LodePNGCompressSettings)); /*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) { attempt[type] = (unsigned char*)lodepng_malloc(linebytes); if(!attempt[type]) error = 83; /*alloc fail*/ } if(!error) { for(y = 0; y != h; ++y) /*try the 5 filter types*/ { for(type = 0; type != 5; ++type) { unsigned testsize = (unsigned)linebytes; /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); size[type] = 0; dummy = 0; zlib_compress(&dummy, &size[type], attempt[type], 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][x]; } } for(type = 0; type != 5; ++type) lodepng_free(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 / 8u; 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 (= possible 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 + 7u) / 8u)); /*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 + 7u) / 8u) * 8u) { unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7u) / 8u)); if(!padded) error = 83; /*alloc fail*/ if(!error) { addPaddingBits(padded, in, ((w * bpp + 7u) / 8u) * 8u, w * bpp, h); error = filter(*out, padded, w, h, &info_png->color, settings); } lodepng_free(padded); } else { /*we can immediately 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 + 7u) / 8u) * 8u, 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; } #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, data + datasize); } return 0; } static unsigned isGrayICCProfile(const unsigned char* profile, unsigned size) { /* It is a gray profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-19 are "RGB ". We do not perform any full parsing of the ICC profile here, other than check those 4 bytes to grayscale profile. Other than that, validity of the profile is not checked. This is needed only because the PNG specification requires using a non-gray color model if there is an ICC profile with "RGB " (sadly limiting compression opportunities if the input data is grayscale RGB data), and requires using a gray color model if it is "GRAY". */ if(size < 20) return 0; return profile[16] == 'G' && profile[17] == 'R' && profile[18] == 'A' && profile[19] == 'Y'; } static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) { /* See comment in isGrayICCProfile*/ if(size < 20) return 0; return profile[16] == 'R' && profile[17] == 'G' && profile[18] == 'B' && profile[19] == ' '; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ unsigned lodepng_encode(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGState* state) { unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/ size_t datasize = 0; ucvector outv = ucvector_init(NULL, 0); LodePNGInfo info; const LodePNGInfo* info_png = &state->info_png; LodePNGColorMode auto_color; lodepng_info_init(&info); lodepng_color_mode_init(&auto_color); /*provide some proper output values if error will happen*/ *out = 0; *outsize = 0; state->error = 0; /*check input values validity*/ if((info_png->color.colortype == LCT_PALETTE || state->encoder.force_palette) && (info_png->color.palettesize == 0 || info_png->color.palettesize > 256)) { /*this error is returned even if auto_convert is enabled and thus encoder could generate the palette by itself: while allowing this could be possible in theory, it may complicate the code or edge cases, and always requiring to give a palette when setting this color type is a simpler contract*/ state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/ goto cleanup; } if(state->encoder.zlibsettings.btype > 2) { state->error = 61; /*error: invalid btype*/ goto cleanup; } if(info_png->interlace_method > 1) { state->error = 71; /*error: invalid interlace mode*/ goto cleanup; } state->error = checkColorValidity(info_png->color.colortype, info_png->color.bitdepth); if(state->error) goto cleanup; /*error: invalid color type given*/ state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); if(state->error) goto cleanup; /*error: invalid color type given*/ /* color convert and compute scanline filter types */ lodepng_info_copy(&info, &state->info_png); if(state->encoder.auto_convert) { LodePNGColorStats stats; unsigned allow_convert = 1; lodepng_color_stats_init(&stats); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS if(info_png->iccp_defined && isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) { /*the PNG specification does not allow to use palette with a GRAY ICC profile, even if the palette has only gray colors, so disallow it.*/ stats.allow_palette = 0; } if(info_png->iccp_defined && isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size)) { /*the PNG specification does not allow to use grayscale color with RGB ICC profile, so disallow gray.*/ stats.allow_greyscale = 0; } #endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */ state->error = lodepng_compute_color_stats(&stats, image, w, h, &state->info_raw); if(state->error) goto cleanup; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS if(info_png->background_defined) { /*the background chunk's color must be taken into account as well*/ unsigned r = 0, g = 0, b = 0; LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGB, 16); lodepng_convert_rgb(&r, &g, &b, info_png->background_r, info_png->background_g, info_png->background_b, &mode16, &info_png->color); state->error = lodepng_color_stats_add(&stats, r, g, b, 65535); if(state->error) goto cleanup; } #endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */ state->error = auto_choose_color(&auto_color, &state->info_raw, &stats); if(state->error) goto cleanup; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS if(info_png->sbit_defined) { /*if sbit is defined, due to strict requirements of which sbit values can be present for which color modes, auto_convert can't be done in many cases. However, do support a few cases here. TODO: more conversions may be possible, and it may also be possible to get a more appropriate color type out of auto_choose_color if knowledge about sbit is used beforehand */ unsigned sbit_max = LODEPNG_MAX(LODEPNG_MAX(LODEPNG_MAX(info_png->sbit_r, info_png->sbit_g), info_png->sbit_b), info_png->sbit_a); unsigned equal = (!info_png->sbit_g || info_png->sbit_g == info_png->sbit_r) && (!info_png->sbit_b || info_png->sbit_b == info_png->sbit_r) && (!info_png->sbit_a || info_png->sbit_a == info_png->sbit_r); allow_convert = 0; if(info.color.colortype == LCT_PALETTE && auto_color.colortype == LCT_PALETTE) { /* input and output are palette, and in this case it may happen that palette data is expected to be copied from info_raw into the info_png */ allow_convert = 1; } /*going from 8-bit RGB to palette (or 16-bit as long as sbit_max <= 8) is possible since both are 8-bit RGB for sBIT's purposes*/ if(info.color.colortype == LCT_RGB && auto_color.colortype == LCT_PALETTE && sbit_max <= 8) { allow_convert = 1; } /*going from 8-bit RGBA to palette is also ok but only if sbit_a is exactly 8*/ if(info.color.colortype == LCT_RGBA && auto_color.colortype == LCT_PALETTE && info_png->sbit_a == 8 && sbit_max <= 8) { allow_convert = 1; } /*going from 16-bit RGB(A) to 8-bit RGB(A) is ok if all sbit values are <= 8*/ if((info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA) && info.color.bitdepth == 16 && auto_color.colortype == info.color.colortype && auto_color.bitdepth == 8 && sbit_max <= 8) { allow_convert = 1; } /*going to less channels is ok if all bit values are equal (all possible values in sbit, as well as the chosen bitdepth of the result). Due to how auto_convert works, we already know that auto_color.colortype has less than or equal amount of channels than info.colortype. Palette is not used here. This conversion is not allowed if info_png->sbit_r < auto_color.bitdepth, because specifically for alpha, non-presence of an sbit value heavily implies that alpha's bit depth is equal to the PNG bit depth (rather than the bit depths set in the r, g and b sbit values, by how the PNG specification describes handling tRNS chunk case with sBIT), so be conservative here about ignoring user input.*/ if(info.color.colortype != LCT_PALETTE && auto_color.colortype != LCT_PALETTE && equal && info_png->sbit_r == auto_color.bitdepth) { allow_convert = 1; } } #endif if(state->encoder.force_palette) { if(info.color.colortype != LCT_GREY && info.color.colortype != LCT_GREY_ALPHA && (auto_color.colortype == LCT_GREY || auto_color.colortype == LCT_GREY_ALPHA)) { /*user speficially forced a PLTE palette, so cannot convert to grayscale types because the PNG specification only allows writing a suggested palette in PLTE for truecolor types*/ allow_convert = 0; } } if(allow_convert) { lodepng_color_mode_copy(&info.color, &auto_color); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*also convert the background chunk*/ if(info_png->background_defined) { if(lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b, info_png->background_r, info_png->background_g, info_png->background_b, &info.color, &info_png->color)) { state->error = 104; goto cleanup; } } #endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */ } } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS if(info_png->iccp_defined) { unsigned gray_icc = isGrayICCProfile(info_png->iccp_profile, info_png->iccp_profile_size); unsigned rgb_icc = isRGBICCProfile(info_png->iccp_profile, info_png->iccp_profile_size); unsigned gray_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA; if(!gray_icc && !rgb_icc) { state->error = 100; /* Disallowed profile color type for PNG */ goto cleanup; } if(gray_icc != gray_png) { /*Not allowed to use RGB/RGBA/palette with GRAY ICC profile or vice versa, or in case of auto_convert, it wasn't possible to find appropriate model*/ state->error = state->encoder.auto_convert ? 102 : 101; goto cleanup; } } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) { unsigned char* converted; size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7u) / 8u; 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) { state->error = preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); } lodepng_free(converted); if(state->error) goto cleanup; } else { state->error = preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); if(state->error) goto cleanup; } /* output all PNG chunks */ { #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS size_t i; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*write signature and chunks*/ state->error = writeSignature(&outv); if(state->error) goto cleanup; /*IHDR*/ state->error = addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); if(state->error) goto cleanup; #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) goto cleanup; } /*color profile chunks must come before PLTE */ if(info.iccp_defined) { state->error = addChunk_iCCP(&outv, &info, &state->encoder.zlibsettings); if(state->error) goto cleanup; } if(info.srgb_defined) { state->error = addChunk_sRGB(&outv, &info); if(state->error) goto cleanup; } if(info.gama_defined) { state->error = addChunk_gAMA(&outv, &info); if(state->error) goto cleanup; } if(info.chrm_defined) { state->error = addChunk_cHRM(&outv, &info); if(state->error) goto cleanup; } if(info_png->sbit_defined) { state->error = addChunk_sBIT(&outv, &info); if(state->error) goto cleanup; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*PLTE*/ if(info.color.colortype == LCT_PALETTE) { state->error = addChunk_PLTE(&outv, &info.color); if(state->error) goto cleanup; } if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) { /*force_palette means: write suggested palette for truecolor in PLTE chunk*/ state->error = addChunk_PLTE(&outv, &info.color); if(state->error) goto cleanup; } /*tRNS (this will only add if when necessary) */ state->error = addChunk_tRNS(&outv, &info.color); if(state->error) goto cleanup; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*bKGD (must come between PLTE and the IDAt chunks*/ if(info.background_defined) { state->error = addChunk_bKGD(&outv, &info); if(state->error) goto cleanup; } /*pHYs (must come before the IDAT chunks)*/ if(info.phys_defined) { state->error = addChunk_pHYs(&outv, &info); if(state->error) goto cleanup; } /*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) goto cleanup; } #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) goto cleanup; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*tIME*/ if(info.time_defined) { state->error = addChunk_tIME(&outv, &info.time); if(state->error) goto cleanup; } /*tEXt and/or zTXt*/ for(i = 0; i != info.text_num; ++i) { if(lodepng_strlen(info.text_keys[i]) > 79) { state->error = 66; /*text chunk too large*/ goto cleanup; } if(lodepng_strlen(info.text_keys[i]) < 1) { state->error = 67; /*text chunk too small*/ goto cleanup; } if(state->encoder.text_compression) { state->error = addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); if(state->error) goto cleanup; } else { state->error = addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); if(state->error) goto cleanup; } } /*LodePNG version id in text chunk*/ if(state->encoder.add_id) { unsigned already_added_id_text = 0; for(i = 0; i != info.text_num; ++i) { const char* k = info.text_keys[i]; /* Could use strcmp, but we're not calling or reimplementing this C library function for this use only */ if(k[0] == 'L' && k[1] == 'o' && k[2] == 'd' && k[3] == 'e' && k[4] == 'P' && k[5] == 'N' && k[6] == 'G' && k[7] == '\0') { already_added_id_text = 1; break; } } if(already_added_id_text == 0) { state->error = addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ if(state->error) goto cleanup; } } /*iTXt*/ for(i = 0; i != info.itext_num; ++i) { if(lodepng_strlen(info.itext_keys[i]) > 79) { state->error = 66; /*text chunk too large*/ goto cleanup; } if(lodepng_strlen(info.itext_keys[i]) < 1) { state->error = 67; /*text chunk too small*/ goto cleanup; } state->error = 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); if(state->error) goto cleanup; } /*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) goto cleanup; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ state->error = addChunk_IEND(&outv); if(state->error) goto cleanup; } cleanup: lodepng_info_cleanup(&info); lodepng_free(data); lodepng_color_mode_cleanup(&auto_color); /*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"; /*this error could happen if there are only 0 or 1 symbols present in the huffman code:*/ case 16: return "invalid 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 small or too big"; /*0, or more than 256 colors*/ case 39: return "tRNS chunk before PLTE or has more entries than palette size"; case 40: return "tRNS chunk has wrong size for grayscale 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 grayscale image"; case 45: return "bKGD chunk has wrong size for RGB image"; case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?"; 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 lengths. 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 grayscale conversion formula to the user.*/ case 62: return "conversion from color to grayscale not supported"; /*(2^31-1)*/ case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*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 "invalid interlace mode given to encoder (must be 0 or 1)"; case 72: return "while decoding, invalid 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, or index out of bounds"; 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 "integer overflow due to too many pixels"; case 93: return "zero width or height is invalid"; case 94: return "header chunk must have a size of 13 bytes"; case 95: return "integer overflow with combined idat chunk size"; case 96: return "invalid gAMA chunk size"; case 97: return "invalid cHRM chunk size"; case 98: return "invalid sRGB chunk size"; case 99: return "invalid sRGB rendering intent"; case 100: return "invalid ICC profile color type, the PNG specification only allows RGB or GRAY"; case 101: return "PNG specification does not allow RGB ICC profile on gray color types and vice versa"; case 102: return "not allowed to set grayscale ICC profile with colored pixels by PNG specification"; case 103: return "invalid palette index in bKGD chunk. Maybe it came before PLTE chunk?"; case 104: return "invalid bKGD color while encoding (e.g. palette index out of range)"; case 105: return "integer overflow of bitsize"; case 106: return "PNG file must have PLTE chunk if color type is palette"; case 107: return "color convert from palette mode requested without setting the palette data in it"; case 108: return "tried to add more than 256 values to a palette"; /*this limit can be configured in LodePNGDecompressSettings*/ case 109: return "tried to decompress zlib or deflate data larger than desired max_output_size"; case 110: return "custom zlib or inflate decompression failed"; case 111: return "custom zlib or deflate compression failed"; /*max text size limit can be configured in LodePNGDecoderSettings. This error prevents unreasonable memory consumption when decoding due to impossibly large text sizes.*/ case 112: return "compressed text unreasonably large"; /*max ICC size limit can be configured in LodePNGDecoderSettings. This error prevents unreasonable memory consumption when decoding due to impossibly large ICC profile*/ case 113: return "ICC profile unreasonably large"; case 114: return "sBIT chunk has wrong size for the color type of the image"; case 115: return "sBIT value out of range"; } return "unknown error code"; } #endif /*LODEPNG_COMPILE_ERROR_TEXT*/ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* // C++ Wrapper // */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_CPP namespace lodepng { #ifdef LODEPNG_COMPILE_DISK unsigned load_file(std::vector& buffer, const std::string& filename) { long size = lodepng_filesize(filename.c_str()); if(size < 0) return 78; buffer.resize((size_t)size); return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str()); } /*write given buffer to the file, overwriting the file, it doesn't append to it.*/ unsigned save_file(const std::vector& buffer, const std::string& filename) { return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str()); } #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, 0, in, insize, &settings); if(buffer) { out.insert(out.end(), buffer, &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, &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 = 0; 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, &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, &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; /* safe output values in case error happens */ w = h = 0; unsigned error = load_file(buffer, filename); if(error) return error; 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, &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, &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) 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*/ qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/lodepng.h000066400000000000000000003101671525155022500225550ustar00rootroot00000000000000/* LodePNG version 20230410 Copyright (c) 2005-2023 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*/ extern const char* LODEPNG_VERSION_STRING; /* 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 or clang. */ /*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 /*pass -DLODEPNG_NO_COMPILE_ZLIB to the compiler to disable this, or comment out LODEPNG_COMPILE_ZLIB below*/ #define LODEPNG_COMPILE_ZLIB #endif /*png encoder and png decoder*/ #ifndef LODEPNG_NO_COMPILE_PNG /*pass -DLODEPNG_NO_COMPILE_PNG to the compiler to disable this, or comment out LODEPNG_COMPILE_PNG below*/ #define LODEPNG_COMPILE_PNG #endif /*deflate&zlib decoder and png decoder*/ #ifndef LODEPNG_NO_COMPILE_DECODER /*pass -DLODEPNG_NO_COMPILE_DECODER to the compiler to disable this, or comment out LODEPNG_COMPILE_DECODER below*/ #define LODEPNG_COMPILE_DECODER #endif /*deflate&zlib encoder and png encoder*/ #ifndef LODEPNG_NO_COMPILE_ENCODER /*pass -DLODEPNG_NO_COMPILE_ENCODER to the compiler to disable this, or comment out LODEPNG_COMPILE_ENCODER below*/ #define LODEPNG_COMPILE_ENCODER #endif /*the optional built in harddisk file loading and saving functions*/ #ifndef LODEPNG_NO_COMPILE_DISK /*pass -DLODEPNG_NO_COMPILE_DISK to the compiler to disable this, or comment out LODEPNG_COMPILE_DISK below*/ #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 /*pass -DLODEPNG_NO_COMPILE_ANCILLARY_CHUNKS to the compiler to disable this, or comment out LODEPNG_COMPILE_ANCILLARY_CHUNKS below*/ #define LODEPNG_COMPILE_ANCILLARY_CHUNKS #endif /*ability to convert error numerical codes to English text string*/ #ifndef LODEPNG_NO_COMPILE_ERROR_TEXT /*pass -DLODEPNG_NO_COMPILE_ERROR_TEXT to the compiler to disable this, or comment out LODEPNG_COMPILE_ERROR_TEXT below*/ #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 /*pass -DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler to disable the built-in ones, or comment out LODEPNG_COMPILE_ALLOCATORS below*/ #define LODEPNG_COMPILE_ALLOCATORS #endif /*Disable built-in CRC function, in that case a custom implementation of lodepng_crc32 must be defined externally so that it can be linked in. The default built-in CRC code comes with 8KB of lookup tables, so for memory constrained environment you may want it disabled and provide a much smaller implementation externally as said above. You can find such an example implementation in a comment in the lodepng.c(pp) file in the 'else' case of the searchable LODEPNG_COMPILE_CRC section.*/ #ifndef LODEPNG_NO_COMPILE_CRC /*pass -DLODEPNG_NO_COMPILE_CRC to the compiler to disable the built-in one, or comment out LODEPNG_COMPILE_CRC below*/ #define LODEPNG_COMPILE_CRC #endif /*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/ #ifdef __cplusplus #ifndef LODEPNG_NO_COMPILE_CPP /*pass -DLODEPNG_NO_COMPILE_CPP to the compiler to disable C++ (not needed if a C-only compiler), or comment out LODEPNG_COMPILE_CPP below*/ #define LODEPNG_COMPILE_CPP #endif #endif #ifdef LODEPNG_COMPILE_CPP #include #include #endif /*LODEPNG_COMPILE_CPP*/ #ifdef LODEPNG_COMPILE_PNG /*The PNG color types (also used for raw image).*/ typedef enum LodePNGColorType { LCT_GREY = 0, /*grayscale: 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, /*grayscale with alpha: 8,16 bit*/ LCT_RGBA = 6, /*RGB with alpha: 8,16 bit*/ /*LCT_MAX_OCTET_VALUE lets the compiler allow this enum to represent any invalid byte value from 0 to 255 that could be present in an invalid PNG file header. Do not use, compare with or set the name LCT_MAX_OCTET_VALUE, instead either use the valid color type names above, or numeric values like 1 or 7 when checking for particular disallowed color type byte values, or cast to integer to print it.*/ LCT_MAX_OCTET_VALUE = 255 } 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. NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and decode in-memory.*/ 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. NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and decode in-memory.*/ 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. NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and decode in-memory.*/ 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! NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and encode in-memory.*/ 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. NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and encode in-memory.*/ 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. NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and encode in-memory.*/ 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. NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and decode in-memory. */ 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! NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and decode in-memory. */ 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 { /* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */ unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ unsigned ignore_nlen; /*ignore complement of len checksum in uncompressed blocks*/ /*Maximum decompressed size, beyond this the decoder may (and is encouraged to) stop decoding, return an error, output a data size > max_output_size and all the data up to that point. This is not hard limit nor a guarantee, but can prevent excessive memory usage. This setting is ignored by the PNG decoder, but is used by the deflate/zlib decoder and can be used by custom ones. Set to 0 to impose no limit (the default).*/ size_t max_output_size; /*use custom zlib decoder instead of built in one (default: null). Should return 0 if success, any non-0 if error (numeric value not exposed).*/ 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 not null, custom_inflate is ignored (the zlib format uses deflate). Should return 0 if success, any non-0 if error (numeric value not exposed).*/ 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; /*minimum 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. This field may not be allocated directly, use lodepng_color_mode_init first, then lodepng_palette_add per color to correctly initialize it (to ensure size of exactly 1024 bytes). The alpha channels must be set as well, set them to 255 for opaque images. When decoding, with the default settings you can ignore this palette, since LodePNG already fills the palette colors in the pixels of the raw RGBA output, but when decoding to the original PNG color mode it is needed to reconstruct the colors. The palette is only supported for color type 3. */ unsigned char* palette; /*palette in RGBARGBA... order. Must be either 0, or when allocated must have 1024 bytes*/ size_t palettesize; /*palette size in number of colors (amount of used 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 grayscale 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/grayscale 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); /* Makes a temporary LodePNGColorMode that does not need cleanup (no palette) */ LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth); 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 grayscale 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: 0=none, 1=Adam7*/ LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /* Suggested background color chunk (bKGD) This uses the same color mode and bit depth as the PNG (except no alpha channel), with values truncated to the bit depth in the unsigned integer. For grayscale and palette PNGs, the value is stored in background_r. The values in background_g and background_b are then unused. The decoder will set them equal to background_r, the encoder ignores them in this case. When decoding, you may get these in a different color mode than the one you requested for the raw pixels: the colortype and bitdepth defined by info_png.color, that is the ones defined in the header of the PNG image, are used. When encoding with auto_convert, you must use the color model defined in info_png.color for these values. The encoder normally ignores info_png.color when auto_convert is on, but will use it to interpret these values (and convert copies of them to its chosen color model). When encoding, avoid setting this to an expensive color, such as a non-gray value when the image is gray, or the compression will be worse since it will be forced to write the PNG with a more expensive color mode (when auto_convert is on). The decoder does not use this background color to edit the color of pixels. This is a completely optional metadata feature. */ unsigned background_defined; /*is a suggested background color given?*/ unsigned background_r; /*red/gray/palette 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. All the string fields below including strings, keys, names and language tags are null terminated. The PNG specification uses null characters for the keys, names and tags, and forbids null characters to appear in the main text which is why we can use null termination everywhere here. A keyword is minimum 1 character and maximum 79 characters long (plus the additional null terminator). 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. Standard text chunk keywords and strings are encoded using Latin-1. */ 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", and the following text encodings are used: keys: Latin-1, langtags: ASCII, transkeys and strings: UTF-8. keys must be 1-79 characters (plus the additional null terminator), the other strings are any length. */ 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)*/ /* Color profile related chunks: gAMA, cHRM, sRGB, iCPP, sBIT LodePNG does not apply any color conversions on pixels in the encoder or decoder and does not interpret these color profile values. It merely passes on the information. If you wish to use color profiles and convert colors, please use these values with a color management library. See the PNG, ICC and sRGB specifications for more information about the meaning of these values. */ /* gAMA chunk: optional, overridden by sRGB or iCCP if those are present. */ unsigned gama_defined; /* Whether a gAMA chunk is present (0 = not present, 1 = present). */ unsigned gama_gamma; /* Gamma exponent times 100000 */ /* cHRM chunk: optional, overridden by sRGB or iCCP if those are present. */ unsigned chrm_defined; /* Whether a cHRM chunk is present (0 = not present, 1 = present). */ unsigned chrm_white_x; /* White Point x times 100000 */ unsigned chrm_white_y; /* White Point y times 100000 */ unsigned chrm_red_x; /* Red x times 100000 */ unsigned chrm_red_y; /* Red y times 100000 */ unsigned chrm_green_x; /* Green x times 100000 */ unsigned chrm_green_y; /* Green y times 100000 */ unsigned chrm_blue_x; /* Blue x times 100000 */ unsigned chrm_blue_y; /* Blue y times 100000 */ /* sRGB chunk: optional. May not appear at the same time as iCCP. If gAMA is also present gAMA must contain value 45455. If cHRM is also present cHRM must contain respectively 31270,32900,64000,33000,30000,60000,15000,6000. */ unsigned srgb_defined; /* Whether an sRGB chunk is present (0 = not present, 1 = present). */ unsigned srgb_intent; /* Rendering intent: 0=perceptual, 1=rel. colorimetric, 2=saturation, 3=abs. colorimetric */ /* iCCP chunk: optional. May not appear at the same time as sRGB. LodePNG does not parse or use the ICC profile (except its color space header field for an edge case), a separate library to handle the ICC data (not included in LodePNG) format is needed to use it for color management and conversions. For encoding, if iCCP is present, gAMA and cHRM are recommended to be added as well with values that match the ICC profile as closely as possible, if you wish to do this you should provide the correct values for gAMA and cHRM and enable their '_defined' flags since LodePNG will not automatically compute them from the ICC profile. For encoding, the ICC profile is required by the PNG specification to be an "RGB" profile for non-gray PNG color types and a "GRAY" profile for gray PNG color types. If you disable auto_convert, you must ensure the ICC profile type matches your requested color type, else the encoder gives an error. If auto_convert is enabled (the default), and the ICC profile is not a good match for the pixel data, this will result in an encoder error if the pixel data has non-gray pixels for a GRAY profile, or a silent less-optimal compression of the pixel data if the pixels could be encoded as grayscale but the ICC profile is RGB. To avoid this do not set an ICC profile in the image unless there is a good reason for it, and when doing so make sure you compute it carefully to avoid the above problems. */ unsigned iccp_defined; /* Whether an iCCP chunk is present (0 = not present, 1 = present). */ char* iccp_name; /* Null terminated string with profile name, 1-79 bytes */ /* The ICC profile in iccp_profile_size bytes. Don't allocate this buffer yourself. Use the init/cleanup functions correctly and use lodepng_set_icc and lodepng_clear_icc. */ unsigned char* iccp_profile; unsigned iccp_profile_size; /* The size of iccp_profile in bytes */ /* sBIT chunk: significant bits. Optional metadata, only set this if needed. If defined, these values give the bit depth of the original data. Since PNG only stores 1, 2, 4, 8 or 16-bit per channel data, the significant bits value can be used to indicate the original encoded data has another sample depth, such as 10 or 12. Encoders using this value, when storing the pixel data, should use the most significant bits of the data to store the original bits, and use a good sample depth scaling method such as "left bit replication" to fill in the least significant bits, rather than fill zeroes. Decoders using this value, if able to work with data that's e.g. 10-bit or 12-bit, should right shift the data to go back to the original bit depth, but decoders are also allowed to ignore sbit and work e.g. with the 8-bit or 16-bit data from the PNG directly, since thanks to the encoder contract, the values encoded in PNG are in valid range for the PNG bit depth. For grayscale images, sbit_g and sbit_b are not used, and for images that don't use color type RGBA or grayscale+alpha, sbit_a is not used (it's not used even for palette images with translucent palette values, or images with color key). The values that are used must be greater than zero and smaller than or equal to the PNG bit depth. The color type from the header in the PNG image defines these used and unused fields: if decoding with a color mode conversion, such as always decoding to RGBA, this metadata still only uses the color type of the original PNG, and may e.g. lack the alpha channel info if the PNG was RGB. When encoding with auto_convert (as well as without), also always the color model defined in info_png.color determines this. NOTE: enabling sbit can hurt compression, because the encoder can then not always use auto_convert to choose a more optimal color mode for the data, because the PNG format has strict requirements for the allowed sbit values in combination with color modes. For example, setting these fields to 10-bit will force the encoder to keep using a 16-bit per channel color mode, even if the pixel data would in fact fit in a more efficient 8-bit mode. */ unsigned sbit_defined; /*is significant bits given? if not, the values below are unused*/ unsigned sbit_r; /*red or gray component of significant bits*/ unsigned sbit_g; /*green component of significant bits*/ unsigned sbit_b; /*blue component of significant bits*/ unsigned sbit_a; /*alpha component of significant bits*/ /* End of color profile related chunks */ /* unknown chunks: chunks not known by LodePNG, passed on byte for byte. 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 positions are: 0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND. For encoding, do not store critical chunks or known chunks that are enabled with a "_defined" flag above in here, since the encoder will blindly follow this and could then encode an invalid PNG file (such as one with two IHDR chunks or the disallowed combination of sRGB with iCCP). But do use this if you wish to store an ancillary chunk that is not supported by LodePNG (such as sPLT or hIST), or any non-standard PNG chunk. 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 unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/ void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts 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*/ void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/ /*replaces if exists*/ unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size); void lodepng_clear_icc(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ #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, const 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*/ /* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */ unsigned ignore_crc; /*ignore CRC checksums*/ unsigned ignore_critical; /*ignore unknown critical chunks*/ unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/ /* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters in string keys, etc... */ 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; /* maximum size for decompressed text chunks. If a text chunk's text is larger than this, an error is returned, unless reading text chunks is disabled or this limit is set higher or disabled. Set to 0 to allow any size. By default it is a value that prevents unreasonably large strings from hogging memory. */ size_t max_text_size; /* maximum size for compressed ICC chunks. If the ICC profile is larger than this, an error will be returned. Set to 0 to allow any size. By default this is a value that prevents ICC profiles that would be much larger than any legitimate profile could be to hog memory. */ size_t max_icc_size; #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 = 0, /*every filter at 1, 2, 3 or 4 (paeth), unlike LFS_ZERO not a good choice, but for testing*/ LFS_ONE = 1, LFS_TWO = 2, LFS_THREE = 3, LFS_FOUR = 4, /*Use filter that gives minimum 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 integer RGBA colors of the image (count, alpha channel usage, bit depth, ...), 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 LodePNGColorStats { unsigned colored; /*not grayscale*/ unsigned key; /*image is not opaque and color key is possible instead of full alpha*/ unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/ unsigned short key_g; unsigned short key_b; unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/ unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16 or allow_palette is disabled.*/ unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order, only valid when numcolors is valid*/ unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for grayscale only. 16 if 16-bit per channel required.*/ size_t numpixels; /*user settings for computing/using the stats*/ unsigned allow_palette; /*default 1. if 0, disallow choosing palette colortype in auto_choose_color, and don't count numcolors*/ unsigned allow_greyscale; /*default 1. if 0, choose RGB or RGBA even if the image only has gray colors*/ } LodePNGColorStats; void lodepng_color_stats_init(LodePNGColorStats* stats); /*Get a LodePNGColorStats of the image. The stats must already have been inited. Returns error code (e.g. alloc fail) or 0 if ok.*/ unsigned lodepng_compute_color_stats(LodePNGColorStats* stats, 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. If color type is explicitely set to a grayscale type (1 or 4), this is not done and is ignored. If enabling this, a palette must be present in the info_png. NOTE: enabling this may worsen compression if auto_convert is used to choose optimal color mode, because it cannot use grayscale color modes in this case*/ 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; } 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 IHDR 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*/ /* Reads one metadata chunk (other than IHDR, which is handled by lodepng_inspect) of the PNG file and outputs what it read in the state. Returns error code on failure. Use lodepng_inspect first with a new state, then e.g. lodepng_chunk_find_const to find the desired chunk type, and if non null use lodepng_inspect_chunk (with chunk_pointer - start_of_file as pos). Supports most metadata chunks from the PNG standard (gAMA, bKGD, tEXt, ...). Ignores unsupported, unknown, non-metadata or IHDR chunks (without error). Requirements: &in[pos] must point to start of a chunk, must use regular lodepng_inspect first since format of most other chunks depends on IHDR, and if there is a PLTE chunk, that one must be inspected before tRNS or bKGD. */ unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos, const unsigned char* in, size_t insize); #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. The chunk pointer always points to the beginning of the chunk itself, that is the first byte of the 4 length bytes. In the PNG file format, chunks have the following format: -4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer) -4 bytes chunk type (ASCII a-z,A-Z only, see below) -length bytes of data (may be 0 bytes if length was 0) -4 bytes of CRC, computed on chunk name + data The first chunk starts at the 8th byte of the PNG file, the entire rest of the file exists out of concatenated chunks with the above format. PNG standard chunk ASCII 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, allows iterating through all chunks of the PNG file. Input must be at the beginning of a chunk (result of a previous lodepng_chunk_next call, or the 8th byte of a PNG file which always has the first chunk), or alternatively may point to the first byte of the PNG file (which is not a chunk but the magic header, the function will then skip over it and return the first real chunk). Will output pointer to the start of the next chunk, or at or beyond end of the file if there is no more chunk after this or possibly if the chunk is corrupt. Start this process at the 8th byte of the PNG file. In a non-corrupt PNG file, the last chunk should have name "IEND". */ unsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end); const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end); /*Finds the first chunk with the given type in the range [chunk, end), or returns NULL if not found.*/ unsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]); const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]); /* Appends chunk to the data in out. The given chunk should already have its chunk header. The out variable and outsize 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* outsize, 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 outsize 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* outsize, size_t 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) NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and decode in-memory. */ 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) NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and encode in-memory */ 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); ~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. return value: error code (0 means ok) NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and decode in-memory */ unsigned 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. NOTE: Wide-character filenames are not supported, you can use an external method to handle such files and encode in-memory */ unsigned 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 various compilers - done but needs to be redone for every newer version [X] converting color to 16-bit per channel types [X] support color profile chunk types (but never let them touch RGB values by default) [ ] support all public PNG chunk types (almost done except sPLT and hIST) [ ] 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" [ ] allow treating some errors like warnings, when image is recoverable (e.g. 69, 57, 58) [ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ... [ ] error messages with line numbers (and version) [ ] errors in state instead of as return code? [ ] new errors/warnings like suspiciously big decompressed ztxt or iccp chunk [ ] 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, ... [ ] allow user to give data (void*) to custom allocator [X] provide alternatives for C library functions not present on some platforms (memcpy, ...) */ #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. state settings reference 12. changes 13. 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 *) colorimetric color profile conversions: currently experimentally available in lodepng_util.cpp only, plus alternatively ability to pass on chroma/gamma/ICC profile information to other color management system. *) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks. *) the following chunks are supported 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 cHRM: RGB chromaticities gAMA: RGB gamma correction iCCP: ICC color profile sRGB: rendering intent sBIT: significant bits 1.2. features not supported --------------------------- The following features are not (yet) 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 hIST and sPLT public chunks are not (yet) supported but treated as unknown chunks 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 grayscale 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, grayscale 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 grayscale 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 beyond the scope of a PNG encoder (yes, RGB to gray 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: grayscale, bit depths 1, 2, 4, 8, 16 2: RGB, bit depths 8 and 16 3: palette, bit depths 1, 2, 4 and 8 4: grayscale 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. 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. Non supported color conversions: -color to grayscale when non-gray pixels are present: no error is thrown, but the result will look ugly because only the red channel is taken (it assumes all three channels are the same in this case so ignores green and blue). The reason no error is given is to allow converting from three-channel grayscale images to one-channel even if there are numerical imprecisions. -anything to palette when the palette does not have an exact match for a from-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 gray or gray+alpha, to gray or gray+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. 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 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. It is not recommended to use the numerical values to programmatically make different decisions based on error types as the numbers are not guaranteed to stay backwards compatible. They are for human consumption only. Programmatically only 0 or non-0 matter. 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* outsize, const unsigned char* chunk): unsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, 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 *outsize. 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 distinction 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 compliant. 10. examples ------------ This decoder example shows the most basic usage of LodePNG. More complex examples can be found on the LodePNG website. NOTE: these examples do not support wide-character filenames, you can use an external method to handle such files and encode or decode in-memory 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. state settings reference ---------------------------- A quick reference of some settings to set on the LodePNGState For decoding: state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums state.decoder.zlibsettings.custom_...: use custom inflate function state.decoder.ignore_crc: ignore CRC checksums state.decoder.ignore_critical: ignore unknown critical chunks state.decoder.ignore_end: ignore missing IEND chunk. May fail if this corruption causes other errors state.decoder.color_convert: convert internal PNG color to chosen one state.decoder.read_text_chunks: whether to read in text metadata chunks state.decoder.remember_unknown_chunks: whether to read in unknown chunks state.info_raw.colortype: desired color type for decoded image state.info_raw.bitdepth: desired bit depth for decoded image state.info_raw....: more color settings, see struct LodePNGColorMode state.info_png....: no settings for decoder but ouput, see struct LodePNGInfo For encoding: state.encoder.zlibsettings.btype: disable compression by setting it to 0 state.encoder.zlibsettings.use_lz77: use LZ77 in compression state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching state.encoder.zlibsettings.lazymatching: try one more LZ77 matching state.encoder.zlibsettings.custom_...: use custom deflate function state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png state.encoder.filter_palette_zero: PNG filter strategy for palette state.encoder.filter_strategy: PNG filter strategy to encode with state.encoder.force_palette: add palette even if not encoding to one state.encoder.add_id: add LodePNG identifier and version as a text chunk state.encoder.text_compression: use compressed text chunks for metadata state.info_raw.colortype: color type of raw input image you provide state.info_raw.bitdepth: bit depth of raw input image you provide state.info_raw: more color settings, see struct LodePNGColorMode state.info_png.color.colortype: desired color type if auto_convert is false state.info_png.color.bitdepth: desired bit depth if auto_convert is false state.info_png.color....: more color settings, see struct LodePNGColorMode state.info_png....: more PNG related settings, see struct LodePNGInfo 12. 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. Not all changes are listed here, the commit history in github lists more: https://github.com/lvandeve/lodepng *) 10 apr 2023: faster CRC32 implementation, but with larger lookup table. *) 13 jun 2022: added support for the sBIT chunk. *) 09 jan 2022: minor decoder speed improvements. *) 27 jun 2021: added warnings that file reading/writing functions don't support wide-character filenames (support for this is not planned, opening files is not the core part of PNG decoding/decoding and is platform dependent). *) 17 okt 2020: prevent decoding too large text/icc chunks by default. *) 06 mar 2020: simplified some of the dynamic memory allocations. *) 12 jan 2020: (!) added 'end' argument to lodepng_chunk_next to allow correct overflow checks. *) 14 aug 2019: around 25% faster decoding thanks to huffman lookup tables. *) 15 jun 2019: (!) auto_choose_color API changed (for bugfix: don't use palette if gray ICC profile) and non-ICC LodePNGColorProfile renamed to LodePNGColorStats. *) 30 dec 2018: code style changes only: removed newlines before opening braces. *) 10 sep 2018: added way to inspect metadata chunks without full decoding. *) 19 aug 2018: (!) fixed color mode bKGD is encoded with and made it use palette index in case of palette. *) 10 aug 2018: (!) added support for gAMA, cHRM, sRGB and iCCP chunks. This change is backwards compatible unless you relied on unknown_chunks for those. *) 11 jun 2018: less restrictive check for pixel size integer overflow *) 14 jan 2018: allow optionally ignoring a few more recoverable errors *) 17 sep 2017: fix memory leak for some encoder input error cases *) 27 nov 2016: grey+alpha auto color model detection bugfix *) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort). *) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within the limits of pure C90). *) 08 dec 2015: Made load_file function return error if file can't be opened. *) 24 okt 2015: Bugfix with decoding to palette output. *) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding. *) 24 aug 2014: Moved to github *) 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 shrunk 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 various 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) 13. 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-2022 Lode Vandevenne */ qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/logdriver.cpp000066400000000000000000000061631525155022500234530ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_osd.h" #include "logdriver.h" namespace { LogLevel minlevel{LogLevel::Info}; // OSD ticks: two seconds at any refresh rate. constexpr int OSD_MESSAGE_TICKS = 2 * QTEA_OSD_TICKS_PER_SEC; } void LogDriver::log(LogLevel level, std::string text) { if (level < minlevel) { return; } if (level == LogLevel::OSD) { qtea_osd_text(QTEA_OSD_TEXT_FRONTEND, OSD_MESSAGE_TICKS, QTEA_OSD_ANCHOR_BL, 0, 0, 0, text.c_str()); } else if (level == LogLevel::Info) { std::cout << text << std::endl; } else { std::cerr << text << std::endl; } } void LogDriver::jg_log(int level, const char *fmt, ...) { if (level < static_cast(minlevel)) { return; } va_list va; char buffer[512]; static const char *lcol[4] = { "\033[0;35m", "\033[0;36m", "\033[7;33m", "\033[1;7;31m" }; va_start(va, fmt); vsnprintf(buffer, sizeof(buffer), fmt, va); va_end(va); FILE *fout = level == 1 ? stdout : stderr; if (level == JG_LOG_SCR) { qtea_osd_text(QTEA_OSD_TEXT_CORE, OSD_MESSAGE_TICKS, QTEA_OSD_ANCHOR_BR, 0, 0, 0, buffer); return; } // The core's level; only four have a colour. const char *col = (level >= 0 && level < 4) ? lcol[level] : ""; fprintf(fout, "%s%s\033[0m", col, buffer); fflush(fout); if (level == JG_LOG_ERR) { qtea_osd_text(QTEA_OSD_TEXT_FRONTEND, OSD_MESSAGE_TICKS, QTEA_OSD_ANCHOR_TL, 0, 0, 0, buffer); } } void LogDriver::set_level(int level) { minlevel = static_cast(level); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/logdriver.h000066400000000000000000000035101525155022500231110ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include enum class LogLevel : int { Debug, Info, Warn, Error, OSD }; class LogDriver { // A log driver's waltz pleases girls completely public: static void log(LogLevel level, std::string text); static void jg_log(int level, const char *fmt, ...); static void set_level(int level); }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/md5.cpp000066400000000000000000000210471525155022500221410ustar00rootroot00000000000000/* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * (This is a heavily cut-down "BSD license".) * * This differs from Colin Plumb's older public domain implementation in that * no exactly 32-bit integer data type is required (any 32-bit or wider * unsigned integer data type will do), there's no compile-time endianness * configuration, and the function prototypes match OpenSSL's. No code from * Colin Plumb's implementation has been reused; this comment merely compares * the properties of the two independent implementations. * * The primary goals of this implementation are portability and ease of use. * It is meant to be fast, but not as fast as possible. Some known * optimizations are not included to reduce source code size and avoid * compile-time configuration. */ #ifndef HAVE_OPENSSL #include #include "md5.h" /* * The basic MD5 functions. * * F and G are optimized compared to their RFC 1321 definitions for * architectures that lack an AND-NOT instruction, just like in Colin Plumb's * implementation. */ #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) #define H(x, y, z) (((x) ^ (y)) ^ (z)) #define H2(x, y, z) ((x) ^ ((y) ^ (z))) #define I(x, y, z) ((y) ^ ((x) | ~(z))) /* * The MD5 transformation for all four rounds. */ #define STEP(f, a, b, c, d, x, t, s) \ (a) += f((b), (c), (d)) + (x) + (t); \ (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ (a) += (b); /* * SET reads 4 input bytes in little-endian byte order and stores them in a * properly aligned word in host byte order. * * The check for little-endian architectures that tolerate unaligned memory * accesses is just an optimization. Nothing will break if it fails to detect * a suitable architecture. * * Unfortunately, this optimization may be a C strict aliasing rules violation * if the caller's data buffer has effective type that cannot be aliased by * MD5_u32plus. In practice, this problem may occur if these MD5 routines are * inlined into a calling function, or with future and dangerously advanced * link-time optimizations. For the time being, keeping these MD5 routines in * their own translation unit avoids the problem. */ #if defined(__i386__) || defined(__x86_64__) || defined(__vax__) #define SET(n) \ (*(MD5_u32plus *)&ptr[(n) * 4]) #define GET(n) \ SET(n) #else #define SET(n) \ (ctx->block[(n)] = \ (MD5_u32plus)ptr[(n) * 4] | \ ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) #define GET(n) \ (ctx->block[(n)]) #endif /* * This processes one or more 64-byte data blocks, but does NOT update the bit * counters. There are no alignment requirements. */ static const void *body(MD5_CTX *ctx, const void *data, unsigned long size) { const unsigned char *ptr; MD5_u32plus a, b, c, d; MD5_u32plus saved_a, saved_b, saved_c, saved_d; ptr = (const unsigned char *)data; a = ctx->a; b = ctx->b; c = ctx->c; d = ctx->d; do { saved_a = a; saved_b = b; saved_c = c; saved_d = d; /* Round 1 */ STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) STEP(F, c, d, a, b, SET(2), 0x242070db, 17) STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) /* Round 2 */ STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) STEP(G, d, a, b, c, GET(10), 0x02441453, 9) STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) /* Round 3 */ STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11) STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23) STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11) STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23) STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11) STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23) STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11) STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23) /* Round 4 */ STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) a += saved_a; b += saved_b; c += saved_c; d += saved_d; ptr += 64; } while (size -= 64); ctx->a = a; ctx->b = b; ctx->c = c; ctx->d = d; return ptr; } void MD5_Init(MD5_CTX *ctx) { ctx->a = 0x67452301; ctx->b = 0xefcdab89; ctx->c = 0x98badcfe; ctx->d = 0x10325476; ctx->lo = 0; ctx->hi = 0; } void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size) { MD5_u32plus saved_lo; unsigned long used, available; saved_lo = ctx->lo; if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) ctx->hi++; ctx->hi += size >> 29; used = saved_lo & 0x3f; if (used) { available = 64 - used; if (size < available) { memcpy(&ctx->buffer[used], data, size); return; } memcpy(&ctx->buffer[used], data, available); data = (const unsigned char *)data + available; size -= available; body(ctx, ctx->buffer, 64); } if (size >= 64) { data = body(ctx, data, size & ~(unsigned long)0x3f); size &= 0x3f; } memcpy(ctx->buffer, data, size); } #define OUT(dst, src) \ (dst)[0] = (unsigned char)(src); \ (dst)[1] = (unsigned char)((src) >> 8); \ (dst)[2] = (unsigned char)((src) >> 16); \ (dst)[3] = (unsigned char)((src) >> 24); void MD5_Final(unsigned char *result, MD5_CTX *ctx) { unsigned long used, available; used = ctx->lo & 0x3f; ctx->buffer[used++] = 0x80; available = 64 - used; if (available < 8) { memset(&ctx->buffer[used], 0, available); body(ctx, ctx->buffer, 64); used = 0; available = 64; } memset(&ctx->buffer[used], 0, available - 8); ctx->lo <<= 3; OUT(&ctx->buffer[56], ctx->lo) OUT(&ctx->buffer[60], ctx->hi) body(ctx, ctx->buffer, 64); OUT(&result[0], ctx->a) OUT(&result[4], ctx->b) OUT(&result[8], ctx->c) OUT(&result[12], ctx->d) memset(ctx, 0, sizeof(*ctx)); } #endif qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/md5.h000066400000000000000000000026021525155022500216020ustar00rootroot00000000000000/* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * See md5.c for more information. */ #ifdef HAVE_OPENSSL #include #elif !defined(_MD5_H) #define _MD5_H /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned int MD5_u32plus; typedef struct { MD5_u32plus lo, hi; MD5_u32plus a, b, c, d; unsigned char buffer[64]; MD5_u32plus block[16]; } MD5_CTX; extern void MD5_Init(MD5_CTX *ctx); extern void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size); extern void MD5_Final(unsigned char *result, MD5_CTX *ctx); #endif qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/parson.cpp000066400000000000000000002426141525155022500227630ustar00rootroot00000000000000/* SPDX-License-Identifier: MIT Parson 1.5.3 (https://github.com/kgabis/parson) Copyright (c) 2012 - 2023 Krzysztof Gabis 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. */ #ifdef _MSC_VER #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif /* _CRT_SECURE_NO_WARNINGS */ #endif /* _MSC_VER */ #include "parson.h" #define PARSON_IMPL_VERSION_MAJOR 1 #define PARSON_IMPL_VERSION_MINOR 5 #define PARSON_IMPL_VERSION_PATCH 3 #if (PARSON_VERSION_MAJOR != PARSON_IMPL_VERSION_MAJOR)\ || (PARSON_VERSION_MINOR != PARSON_IMPL_VERSION_MINOR)\ || (PARSON_VERSION_PATCH != PARSON_IMPL_VERSION_PATCH) #error "parson version mismatch between parson.c and parson.h" #endif #include #include #include #include #include #include #include /* Apparently sscanf is not implemented in some "standard" libraries, so don't use it, if you * don't have to. */ #ifdef sscanf #undef sscanf #define sscanf THINK_TWICE_ABOUT_USING_SSCANF #endif /* strcpy is unsafe */ #ifdef strcpy #undef strcpy #endif #define strcpy USE_MEMCPY_INSTEAD_OF_STRCPY #define STARTING_CAPACITY 16 #define MAX_NESTING 2048 #ifndef PARSON_DEFAULT_FLOAT_FORMAT #define PARSON_DEFAULT_FLOAT_FORMAT "%1.17g" /* do not increase precision without incresing NUM_BUF_SIZE */ #endif #ifndef PARSON_NUM_BUF_SIZE #define PARSON_NUM_BUF_SIZE 64 /* double printed with "%1.17g" shouldn't be longer than 25 bytes so let's be paranoid and use 64 */ #endif #ifndef PARSON_INDENT_STR #define PARSON_INDENT_STR " " #endif #define SIZEOF_TOKEN(a) (sizeof(a) - 1) #define SKIP_CHAR(str) ((*str)++) #define SKIP_WHITESPACES(str) while (isspace((unsigned char)(**str))) { SKIP_CHAR(str); } #define MAX(a, b) ((a) > (b) ? (a) : (b)) #undef malloc #undef free #if defined(isnan) && defined(isinf) #define IS_NUMBER_INVALID(x) (isnan((x)) || isinf((x))) #else #define IS_NUMBER_INVALID(x) (((x) * 0.0) != 0.0) #endif #define OBJECT_INVALID_IX ((size_t)-1) static JSON_Malloc_Function parson_malloc = malloc; static JSON_Free_Function parson_free = free; static int parson_escape_slashes = 1; static char *parson_float_format = NULL; static JSON_Number_Serialization_Function parson_number_serialization_function = NULL; #define IS_CONT(b) (((unsigned char)(b) & 0xC0) == 0x80) /* is utf-8 continuation byte */ typedef int parson_bool_t; #define PARSON_TRUE 1 #define PARSON_FALSE 0 typedef struct json_string { char *chars; size_t length; } JSON_String; /* Type definitions */ typedef union json_value_value { JSON_String string; double number; JSON_Object *object; JSON_Array *array; int boolean; int null; } JSON_Value_Value; struct json_value_t { JSON_Value *parent; JSON_Value_Type type; JSON_Value_Value value; }; struct json_object_t { JSON_Value *wrapping_value; size_t *cells; unsigned long *hashes; char **names; JSON_Value **values; size_t *cell_ixs; size_t count; size_t item_capacity; size_t cell_capacity; }; struct json_array_t { JSON_Value *wrapping_value; JSON_Value **items; size_t count; size_t capacity; }; /* Various */ static char * read_file(const char *filename); static void remove_comments(char *string, const char *start_token, const char *end_token); static char * parson_strndup(const char *string, size_t n); static char * parson_strdup(const char *string); static int parson_snprintf(char * s, size_t sz, const char * format, ...); static int hex_char_to_int(char c); static JSON_Status parse_utf16_hex(const char *string, unsigned int *result); static int num_bytes_in_utf8_sequence(unsigned char c); static JSON_Status verify_utf8_sequence(const unsigned char *string, int *len); static parson_bool_t is_valid_utf8(const char *string, size_t string_len); static parson_bool_t is_decimal(const char *string, size_t length); static unsigned long hash_string(const char *string, size_t n); /* JSON Object */ static JSON_Object * json_object_make(JSON_Value *wrapping_value); static JSON_Status json_object_init(JSON_Object *object, size_t capacity); static void json_object_deinit(JSON_Object *object, parson_bool_t free_keys, parson_bool_t free_values); static JSON_Status json_object_grow_and_rehash(JSON_Object *object); static size_t json_object_get_cell_ix(const JSON_Object *object, const char *key, size_t key_len, unsigned long hash, parson_bool_t *out_found); static JSON_Status json_object_add(JSON_Object *object, char *name, JSON_Value *value); static JSON_Value * json_object_getn_value(const JSON_Object *object, const char *name, size_t name_len); static JSON_Status json_object_remove_internal(JSON_Object *object, const char *name, parson_bool_t free_value); static JSON_Status json_object_dotremove_internal(JSON_Object *object, const char *name, parson_bool_t free_value); static void json_object_free(JSON_Object *object); /* JSON Array */ static JSON_Array * json_array_make(JSON_Value *wrapping_value); static JSON_Status json_array_add(JSON_Array *array, JSON_Value *value); static JSON_Status json_array_resize(JSON_Array *array, size_t new_capacity); static void json_array_free(JSON_Array *array); /* JSON Value */ static JSON_Value * json_value_init_string_no_copy(char *string, size_t length); static const JSON_String * json_value_get_string_desc(const JSON_Value *value); /* Parser */ static JSON_Status skip_quotes(const char **string); static JSON_Status parse_utf16(const char **unprocessed, char **processed); static char * process_string(const char *input, size_t input_len, size_t *output_len); static char * get_quoted_string(const char **string, size_t *output_string_len); static JSON_Value * parse_object_value(const char **string, size_t nesting); static JSON_Value * parse_array_value(const char **string, size_t nesting); static JSON_Value * parse_string_value(const char **string); static JSON_Value * parse_boolean_value(const char **string); static JSON_Value * parse_number_value(const char **string); static JSON_Value * parse_null_value(const char **string); static JSON_Value * parse_value(const char **string, size_t nesting); /* Serialization */ static int json_serialize_to_buffer_r(const JSON_Value *value, char *buf, int level, parson_bool_t is_pretty, char *num_buf); static int json_serialize_string(const char *string, size_t len, char *buf); /* Various */ static char * read_file(const char * filename) { FILE *fp = fopen(filename, "r"); size_t size_to_read = 0; size_t size_read = 0; long pos; char *file_contents; if (!fp) { return NULL; } fseek(fp, 0L, SEEK_END); pos = ftell(fp); if (pos < 0) { fclose(fp); return NULL; } size_to_read = pos; rewind(fp); file_contents = (char*)parson_malloc(sizeof(char) * (size_to_read + 1)); if (!file_contents) { fclose(fp); return NULL; } size_read = fread(file_contents, 1, size_to_read, fp); if (size_read == 0 || ferror(fp)) { fclose(fp); parson_free(file_contents); return NULL; } fclose(fp); file_contents[size_read] = '\0'; return file_contents; } static void remove_comments(char *string, const char *start_token, const char *end_token) { parson_bool_t in_string = PARSON_FALSE, escaped = PARSON_FALSE; size_t i; char *ptr = NULL, current_char; size_t start_token_len = strlen(start_token); size_t end_token_len = strlen(end_token); if (start_token_len == 0 || end_token_len == 0) { return; } while ((current_char = *string) != '\0') { if (current_char == '\\' && !escaped) { escaped = PARSON_TRUE; string++; continue; } else if (current_char == '\"' && !escaped) { in_string = !in_string; } else if (!in_string && strncmp(string, start_token, start_token_len) == 0) { for(i = 0; i < start_token_len; i++) { string[i] = ' '; } string = string + start_token_len; ptr = strstr(string, end_token); if (!ptr) { return; } for (i = 0; i < (ptr - string) + end_token_len; i++) { string[i] = ' '; } string = ptr + end_token_len - 1; } escaped = PARSON_FALSE; string++; } } static char * parson_strndup(const char *string, size_t n) { /* We expect the caller has validated that 'n' fits within the input buffer. */ char *output_string = (char*)parson_malloc(n + 1); if (!output_string) { return NULL; } output_string[n] = '\0'; memcpy(output_string, string, n); return output_string; } static char * parson_strdup(const char *string) { return parson_strndup(string, strlen(string)); } static int parson_snprintf(char * s, size_t sz, const char * format, ...) { int result; va_list args; va_start(args, format); #if defined(__APPLE__) && defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif result = vsnprintf(s, sz, format, args); #if defined(__APPLE__) && defined(__clang__) #pragma clang diagnostic pop #endif va_end(args); return result; } static int hex_char_to_int(char c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } else if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } return -1; } static JSON_Status parse_utf16_hex(const char *s, unsigned int *result) { int x1, x2, x3, x4; if (s[0] == '\0' || s[1] == '\0' || s[2] == '\0' || s[3] == '\0') { return JSONFailure; } x1 = hex_char_to_int(s[0]); x2 = hex_char_to_int(s[1]); x3 = hex_char_to_int(s[2]); x4 = hex_char_to_int(s[3]); if (x1 == -1 || x2 == -1 || x3 == -1 || x4 == -1) { return JSONFailure; } *result = (unsigned int)((x1 << 12) | (x2 << 8) | (x3 << 4) | x4); return JSONSuccess; } static int num_bytes_in_utf8_sequence(unsigned char c) { if (c == 0xC0 || c == 0xC1 || c > 0xF4 || IS_CONT(c)) { return 0; } else if ((c & 0x80) == 0) { /* 0xxxxxxx */ return 1; } else if ((c & 0xE0) == 0xC0) { /* 110xxxxx */ return 2; } else if ((c & 0xF0) == 0xE0) { /* 1110xxxx */ return 3; } else if ((c & 0xF8) == 0xF0) { /* 11110xxx */ return 4; } return 0; /* won't happen */ } static JSON_Status verify_utf8_sequence(const unsigned char *string, int *len) { unsigned int cp = 0; *len = num_bytes_in_utf8_sequence(string[0]); if (*len == 1) { cp = string[0]; } else if (*len == 2 && IS_CONT(string[1])) { cp = string[0] & 0x1F; cp = (cp << 6) | (string[1] & 0x3F); } else if (*len == 3 && IS_CONT(string[1]) && IS_CONT(string[2])) { cp = ((unsigned char)string[0]) & 0xF; cp = (cp << 6) | (string[1] & 0x3F); cp = (cp << 6) | (string[2] & 0x3F); } else if (*len == 4 && IS_CONT(string[1]) && IS_CONT(string[2]) && IS_CONT(string[3])) { cp = string[0] & 0x7; cp = (cp << 6) | (string[1] & 0x3F); cp = (cp << 6) | (string[2] & 0x3F); cp = (cp << 6) | (string[3] & 0x3F); } else { return JSONFailure; } /* overlong encodings */ if ((cp < 0x80 && *len > 1) || (cp < 0x800 && *len > 2) || (cp < 0x10000 && *len > 3)) { return JSONFailure; } /* invalid unicode */ if (cp > 0x10FFFF) { return JSONFailure; } /* surrogate halves */ if (cp >= 0xD800 && cp <= 0xDFFF) { return JSONFailure; } return JSONSuccess; } static int is_valid_utf8(const char *string, size_t string_len) { int len = 0; const char *string_end = string + string_len; while (string < string_end) { if (verify_utf8_sequence((const unsigned char*)string, &len) != JSONSuccess) { return PARSON_FALSE; } string += len; } return PARSON_TRUE; } static parson_bool_t is_decimal(const char *string, size_t length) { if (length > 1 && string[0] == '0' && string[1] != '.') { return PARSON_FALSE; } if (length > 2 && !strncmp(string, "-0", 2) && string[2] != '.') { return PARSON_FALSE; } while (length--) { if (strchr("xX", string[length])) { return PARSON_FALSE; } } return PARSON_TRUE; } static unsigned long hash_string(const char *string, size_t n) { #ifdef PARSON_FORCE_HASH_COLLISIONS (void)string; (void)n; return 0; #else unsigned long hash = 5381; unsigned char c; size_t i = 0; for (i = 0; i < n; i++) { c = string[i]; if (c == '\0') { break; } hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } return hash; #endif } /* JSON Object */ static JSON_Object * json_object_make(JSON_Value *wrapping_value) { JSON_Status res = JSONFailure; JSON_Object *new_obj = (JSON_Object*)parson_malloc(sizeof(JSON_Object)); if (new_obj == NULL) { return NULL; } new_obj->wrapping_value = wrapping_value; res = json_object_init(new_obj, 0); if (res != JSONSuccess) { parson_free(new_obj); return NULL; } return new_obj; } static JSON_Status json_object_init(JSON_Object *object, size_t capacity) { unsigned int i = 0; object->cells = NULL; object->names = NULL; object->values = NULL; object->cell_ixs = NULL; object->hashes = NULL; object->count = 0; object->cell_capacity = capacity; object->item_capacity = (unsigned int)(capacity * 7/10); if (capacity == 0) { return JSONSuccess; } object->cells = (size_t*)parson_malloc(object->cell_capacity * sizeof(*object->cells)); object->names = (char**)parson_malloc(object->item_capacity * sizeof(*object->names)); object->values = (JSON_Value**)parson_malloc(object->item_capacity * sizeof(*object->values)); object->cell_ixs = (size_t*)parson_malloc(object->item_capacity * sizeof(*object->cell_ixs)); object->hashes = (unsigned long*)parson_malloc(object->item_capacity * sizeof(*object->hashes)); if (object->cells == NULL || object->names == NULL || object->values == NULL || object->cell_ixs == NULL || object->hashes == NULL) { goto error; } for (i = 0; i < object->cell_capacity; i++) { object->cells[i] = OBJECT_INVALID_IX; } return JSONSuccess; error: parson_free(object->cells); parson_free(object->names); parson_free(object->values); parson_free(object->cell_ixs); parson_free(object->hashes); return JSONFailure; } static void json_object_deinit(JSON_Object *object, parson_bool_t free_keys, parson_bool_t free_values) { unsigned int i = 0; for (i = 0; i < object->count; i++) { if (free_keys) { parson_free(object->names[i]); } if (free_values) { json_value_free(object->values[i]); } } object->count = 0; object->item_capacity = 0; object->cell_capacity = 0; parson_free(object->cells); parson_free(object->names); parson_free(object->values); parson_free(object->cell_ixs); parson_free(object->hashes); object->cells = NULL; object->names = NULL; object->values = NULL; object->cell_ixs = NULL; object->hashes = NULL; } static JSON_Status json_object_grow_and_rehash(JSON_Object *object) { JSON_Value *wrapping_value = NULL; JSON_Object new_object; char *key = NULL; JSON_Value *value = NULL; unsigned int i = 0; size_t new_capacity = MAX(object->cell_capacity * 2, STARTING_CAPACITY); JSON_Status res = json_object_init(&new_object, new_capacity); if (res != JSONSuccess) { return JSONFailure; } wrapping_value = json_object_get_wrapping_value(object); new_object.wrapping_value = wrapping_value; for (i = 0; i < object->count; i++) { key = object->names[i]; value = object->values[i]; res = json_object_add(&new_object, key, value); if (res != JSONSuccess) { json_object_deinit(&new_object, PARSON_FALSE, PARSON_FALSE); return JSONFailure; } value->parent = wrapping_value; } json_object_deinit(object, PARSON_FALSE, PARSON_FALSE); *object = new_object; return JSONSuccess; } static size_t json_object_get_cell_ix(const JSON_Object *object, const char *key, size_t key_len, unsigned long hash, parson_bool_t *out_found) { size_t cell_ix = hash & (object->cell_capacity - 1); size_t cell = 0; size_t ix = 0; unsigned int i = 0; unsigned long hash_to_check = 0; const char *key_to_check = NULL; size_t key_to_check_len = 0; *out_found = PARSON_FALSE; for (i = 0; i < object->cell_capacity; i++) { ix = (cell_ix + i) & (object->cell_capacity - 1); cell = object->cells[ix]; if (cell == OBJECT_INVALID_IX) { return ix; } hash_to_check = object->hashes[cell]; if (hash != hash_to_check) { continue; } key_to_check = object->names[cell]; key_to_check_len = strlen(key_to_check); if (key_to_check_len == key_len && strncmp(key, key_to_check, key_len) == 0) { *out_found = PARSON_TRUE; return ix; } } return OBJECT_INVALID_IX; } static JSON_Status json_object_add(JSON_Object *object, char *name, JSON_Value *value) { unsigned long hash = 0; parson_bool_t found = PARSON_FALSE; size_t cell_ix = 0; JSON_Status res = JSONFailure; if (!object || !name || !value) { return JSONFailure; } hash = hash_string(name, strlen(name)); found = PARSON_FALSE; cell_ix = json_object_get_cell_ix(object, name, strlen(name), hash, &found); if (found) { return JSONFailure; } if (object->count >= object->item_capacity) { res = json_object_grow_and_rehash(object); if (res != JSONSuccess) { return JSONFailure; } cell_ix = json_object_get_cell_ix(object, name, strlen(name), hash, &found); } object->names[object->count] = name; object->cells[cell_ix] = object->count; object->values[object->count] = value; object->cell_ixs[object->count] = cell_ix; object->hashes[object->count] = hash; object->count++; value->parent = json_object_get_wrapping_value(object); return JSONSuccess; } static JSON_Value * json_object_getn_value(const JSON_Object *object, const char *name, size_t name_len) { unsigned long hash = 0; parson_bool_t found = PARSON_FALSE; size_t cell_ix = 0; size_t item_ix = 0; if (!object || !name) { return NULL; } hash = hash_string(name, name_len); found = PARSON_FALSE; cell_ix = json_object_get_cell_ix(object, name, name_len, hash, &found); if (!found) { return NULL; } item_ix = object->cells[cell_ix]; return object->values[item_ix]; } static JSON_Status json_object_remove_internal(JSON_Object *object, const char *name, parson_bool_t free_value) { unsigned long hash = 0; parson_bool_t found = PARSON_FALSE; size_t cell = 0; size_t item_ix = 0; size_t last_item_ix = 0; size_t i = 0; size_t j = 0; size_t x = 0; size_t k = 0; JSON_Value *val = NULL; if (object == NULL) { return JSONFailure; } hash = hash_string(name, strlen(name)); found = PARSON_FALSE; cell = json_object_get_cell_ix(object, name, strlen(name), hash, &found); if (!found) { return JSONFailure; } item_ix = object->cells[cell]; if (free_value) { val = object->values[item_ix]; json_value_free(val); val = NULL; } parson_free(object->names[item_ix]); last_item_ix = object->count - 1; if (item_ix < last_item_ix) { object->names[item_ix] = object->names[last_item_ix]; object->values[item_ix] = object->values[last_item_ix]; object->cell_ixs[item_ix] = object->cell_ixs[last_item_ix]; object->hashes[item_ix] = object->hashes[last_item_ix]; object->cells[object->cell_ixs[item_ix]] = item_ix; } object->count--; i = cell; j = i; for (x = 0; x < (object->cell_capacity - 1); x++) { j = (j + 1) & (object->cell_capacity - 1); if (object->cells[j] == OBJECT_INVALID_IX) { break; } k = object->hashes[object->cells[j]] & (object->cell_capacity - 1); if ((j > i && (k <= i || k > j)) || (j < i && (k <= i && k > j))) { object->cell_ixs[object->cells[j]] = i; object->cells[i] = object->cells[j]; i = j; } } object->cells[i] = OBJECT_INVALID_IX; return JSONSuccess; } static JSON_Status json_object_dotremove_internal(JSON_Object *object, const char *name, parson_bool_t free_value) { JSON_Value *temp_value = NULL; JSON_Object *temp_object = NULL; const char *dot_pos = strchr(name, '.'); if (!dot_pos) { return json_object_remove_internal(object, name, free_value); } temp_value = json_object_getn_value(object, name, dot_pos - name); if (json_value_get_type(temp_value) != JSONObject) { return JSONFailure; } temp_object = json_value_get_object(temp_value); return json_object_dotremove_internal(temp_object, dot_pos + 1, free_value); } static void json_object_free(JSON_Object *object) { json_object_deinit(object, PARSON_TRUE, PARSON_TRUE); parson_free(object); } /* JSON Array */ static JSON_Array * json_array_make(JSON_Value *wrapping_value) { JSON_Array *new_array = (JSON_Array*)parson_malloc(sizeof(JSON_Array)); if (new_array == NULL) { return NULL; } new_array->wrapping_value = wrapping_value; new_array->items = (JSON_Value**)NULL; new_array->capacity = 0; new_array->count = 0; return new_array; } static JSON_Status json_array_add(JSON_Array *array, JSON_Value *value) { if (array->count >= array->capacity) { size_t new_capacity = MAX(array->capacity * 2, STARTING_CAPACITY); if (json_array_resize(array, new_capacity) != JSONSuccess) { return JSONFailure; } } value->parent = json_array_get_wrapping_value(array); array->items[array->count] = value; array->count++; return JSONSuccess; } static JSON_Status json_array_resize(JSON_Array *array, size_t new_capacity) { JSON_Value **new_items = NULL; if (new_capacity == 0) { return JSONFailure; } new_items = (JSON_Value**)parson_malloc(new_capacity * sizeof(JSON_Value*)); if (new_items == NULL) { return JSONFailure; } if (array->items != NULL && array->count > 0) { memcpy(new_items, array->items, array->count * sizeof(JSON_Value*)); } parson_free(array->items); array->items = new_items; array->capacity = new_capacity; return JSONSuccess; } static void json_array_free(JSON_Array *array) { size_t i; for (i = 0; i < array->count; i++) { json_value_free(array->items[i]); } parson_free(array->items); parson_free(array); } /* JSON Value */ static JSON_Value * json_value_init_string_no_copy(char *string, size_t length) { JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value)); if (!new_value) { return NULL; } new_value->parent = NULL; new_value->type = JSONString; new_value->value.string.chars = string; new_value->value.string.length = length; return new_value; } /* Parser */ static JSON_Status skip_quotes(const char **string) { if (**string != '\"') { return JSONFailure; } SKIP_CHAR(string); while (**string != '\"') { if (**string == '\0') { return JSONFailure; } else if (**string == '\\') { SKIP_CHAR(string); if (**string == '\0') { return JSONFailure; } } SKIP_CHAR(string); } SKIP_CHAR(string); return JSONSuccess; } static JSON_Status parse_utf16(const char **unprocessed, char **processed) { unsigned int cp, lead, trail; char *processed_ptr = *processed; const char *unprocessed_ptr = *unprocessed; JSON_Status status = JSONFailure; unprocessed_ptr++; /* skips u */ status = parse_utf16_hex(unprocessed_ptr, &cp); if (status != JSONSuccess) { return JSONFailure; } if (cp < 0x80) { processed_ptr[0] = (char)cp; /* 0xxxxxxx */ } else if (cp < 0x800) { processed_ptr[0] = ((cp >> 6) & 0x1F) | 0xC0; /* 110xxxxx */ processed_ptr[1] = ((cp) & 0x3F) | 0x80; /* 10xxxxxx */ processed_ptr += 1; } else if (cp < 0xD800 || cp > 0xDFFF) { processed_ptr[0] = ((cp >> 12) & 0x0F) | 0xE0; /* 1110xxxx */ processed_ptr[1] = ((cp >> 6) & 0x3F) | 0x80; /* 10xxxxxx */ processed_ptr[2] = ((cp) & 0x3F) | 0x80; /* 10xxxxxx */ processed_ptr += 2; } else if (cp >= 0xD800 && cp <= 0xDBFF) { /* lead surrogate (0xD800..0xDBFF) */ lead = cp; unprocessed_ptr += 4; /* should always be within the buffer, otherwise previous sscanf would fail */ if (*unprocessed_ptr++ != '\\' || *unprocessed_ptr++ != 'u') { return JSONFailure; } status = parse_utf16_hex(unprocessed_ptr, &trail); if (status != JSONSuccess || trail < 0xDC00 || trail > 0xDFFF) { /* valid trail surrogate? (0xDC00..0xDFFF) */ return JSONFailure; } cp = ((((lead - 0xD800) & 0x3FF) << 10) | ((trail - 0xDC00) & 0x3FF)) + 0x010000; processed_ptr[0] = (((cp >> 18) & 0x07) | 0xF0); /* 11110xxx */ processed_ptr[1] = (((cp >> 12) & 0x3F) | 0x80); /* 10xxxxxx */ processed_ptr[2] = (((cp >> 6) & 0x3F) | 0x80); /* 10xxxxxx */ processed_ptr[3] = (((cp) & 0x3F) | 0x80); /* 10xxxxxx */ processed_ptr += 3; } else { /* trail surrogate before lead surrogate */ return JSONFailure; } unprocessed_ptr += 3; *processed = processed_ptr; *unprocessed = unprocessed_ptr; return JSONSuccess; } /* Copies and processes passed string up to supplied length. Example: "\u006Corem ipsum" -> lorem ipsum */ static char* process_string(const char *input, size_t input_len, size_t *output_len) { const char *input_ptr = input; size_t initial_size = (input_len + 1) * sizeof(char); size_t final_size = 0; char *output = NULL, *output_ptr = NULL, *resized_output = NULL; output = (char*)parson_malloc(initial_size); if (output == NULL) { goto error; } output_ptr = output; while ((*input_ptr != '\0') && (size_t)(input_ptr - input) < input_len) { if (*input_ptr == '\\') { input_ptr++; switch (*input_ptr) { case '\"': *output_ptr = '\"'; break; case '\\': *output_ptr = '\\'; break; case '/': *output_ptr = '/'; break; case 'b': *output_ptr = '\b'; break; case 'f': *output_ptr = '\f'; break; case 'n': *output_ptr = '\n'; break; case 'r': *output_ptr = '\r'; break; case 't': *output_ptr = '\t'; break; case 'u': if (parse_utf16(&input_ptr, &output_ptr) != JSONSuccess) { goto error; } break; default: goto error; } } else if ((unsigned char)*input_ptr < 0x20) { goto error; /* 0x00-0x19 are invalid characters for json string (http://www.ietf.org/rfc/rfc4627.txt) */ } else { *output_ptr = *input_ptr; } output_ptr++; input_ptr++; } *output_ptr = '\0'; /* resize to new length */ final_size = (size_t)(output_ptr-output) + 1; /* todo: don't resize if final_size == initial_size */ resized_output = (char*)parson_malloc(final_size); if (resized_output == NULL) { goto error; } memcpy(resized_output, output, final_size); *output_len = final_size - 1; parson_free(output); return resized_output; error: parson_free(output); return NULL; } /* Return processed contents of a string between quotes and skips passed argument to a matching quote. */ static char * get_quoted_string(const char **string, size_t *output_string_len) { const char *string_start = *string; size_t input_string_len = 0; JSON_Status status = skip_quotes(string); if (status != JSONSuccess) { return NULL; } input_string_len = *string - string_start - 2; /* length without quotes */ return process_string(string_start + 1, input_string_len, output_string_len); } static JSON_Value * parse_value(const char **string, size_t nesting) { if (nesting > MAX_NESTING) { return NULL; } SKIP_WHITESPACES(string); switch (**string) { case '{': return parse_object_value(string, nesting + 1); case '[': return parse_array_value(string, nesting + 1); case '\"': return parse_string_value(string); case 'f': case 't': return parse_boolean_value(string); case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return parse_number_value(string); case 'n': return parse_null_value(string); default: return NULL; } } static JSON_Value * parse_object_value(const char **string, size_t nesting) { JSON_Status status = JSONFailure; JSON_Value *output_value = NULL, *new_value = NULL; JSON_Object *output_object = NULL; char *new_key = NULL; output_value = json_value_init_object(); if (output_value == NULL) { return NULL; } if (**string != '{') { json_value_free(output_value); return NULL; } output_object = json_value_get_object(output_value); SKIP_CHAR(string); SKIP_WHITESPACES(string); if (**string == '}') { /* empty object */ SKIP_CHAR(string); return output_value; } while (**string != '\0') { size_t key_len = 0; new_key = get_quoted_string(string, &key_len); /* We do not support key names with embedded \0 chars */ if (!new_key) { json_value_free(output_value); return NULL; } if (key_len != strlen(new_key)) { parson_free(new_key); json_value_free(output_value); return NULL; } SKIP_WHITESPACES(string); if (**string != ':') { parson_free(new_key); json_value_free(output_value); return NULL; } SKIP_CHAR(string); new_value = parse_value(string, nesting); if (new_value == NULL) { parson_free(new_key); json_value_free(output_value); return NULL; } status = json_object_add(output_object, new_key, new_value); if (status != JSONSuccess) { parson_free(new_key); json_value_free(new_value); json_value_free(output_value); return NULL; } SKIP_WHITESPACES(string); if (**string != ',') { break; } SKIP_CHAR(string); SKIP_WHITESPACES(string); if (**string == '}') { break; } } SKIP_WHITESPACES(string); if (**string != '}') { json_value_free(output_value); return NULL; } SKIP_CHAR(string); return output_value; } static JSON_Value * parse_array_value(const char **string, size_t nesting) { JSON_Value *output_value = NULL, *new_array_value = NULL; JSON_Array *output_array = NULL; output_value = json_value_init_array(); if (output_value == NULL) { return NULL; } if (**string != '[') { json_value_free(output_value); return NULL; } output_array = json_value_get_array(output_value); SKIP_CHAR(string); SKIP_WHITESPACES(string); if (**string == ']') { /* empty array */ SKIP_CHAR(string); return output_value; } while (**string != '\0') { new_array_value = parse_value(string, nesting); if (new_array_value == NULL) { json_value_free(output_value); return NULL; } if (json_array_add(output_array, new_array_value) != JSONSuccess) { json_value_free(new_array_value); json_value_free(output_value); return NULL; } SKIP_WHITESPACES(string); if (**string != ',') { break; } SKIP_CHAR(string); SKIP_WHITESPACES(string); if (**string == ']') { break; } } SKIP_WHITESPACES(string); if (**string != ']' || /* Trim array after parsing is over */ json_array_resize(output_array, json_array_get_count(output_array)) != JSONSuccess) { json_value_free(output_value); return NULL; } SKIP_CHAR(string); return output_value; } static JSON_Value * parse_string_value(const char **string) { JSON_Value *value = NULL; size_t new_string_len = 0; char *new_string = get_quoted_string(string, &new_string_len); if (new_string == NULL) { return NULL; } value = json_value_init_string_no_copy(new_string, new_string_len); if (value == NULL) { parson_free(new_string); return NULL; } return value; } static JSON_Value * parse_boolean_value(const char **string) { size_t true_token_size = SIZEOF_TOKEN("true"); size_t false_token_size = SIZEOF_TOKEN("false"); if (strncmp("true", *string, true_token_size) == 0) { *string += true_token_size; return json_value_init_boolean(1); } else if (strncmp("false", *string, false_token_size) == 0) { *string += false_token_size; return json_value_init_boolean(0); } return NULL; } static JSON_Value * parse_number_value(const char **string) { char *end; double number = 0; errno = 0; number = strtod(*string, &end); if (errno == ERANGE && (number <= -HUGE_VAL || number >= HUGE_VAL)) { return NULL; } if ((errno && errno != ERANGE) || !is_decimal(*string, end - *string)) { return NULL; } *string = end; return json_value_init_number(number); } static JSON_Value * parse_null_value(const char **string) { size_t token_size = SIZEOF_TOKEN("null"); if (strncmp("null", *string, token_size) == 0) { *string += token_size; return json_value_init_null(); } return NULL; } /* Serialization */ /* APPEND_STRING() is only called on string literals. It's a bit hacky because it makes plenty of assumptions about the external state and should eventually be tidied up into a function (same goes for APPEND_INDENT) */ #define APPEND_STRING(str) do {\ written = SIZEOF_TOKEN((str));\ if (buf != NULL) {\ memcpy(buf, (str), written);\ buf[written] = '\0';\ buf += written;\ }\ written_total += written;\ } while (0) #define APPEND_INDENT(level) do {\ int level_i = 0;\ for (level_i = 0; level_i < (level); level_i++) {\ APPEND_STRING(PARSON_INDENT_STR);\ }\ } while (0) static int json_serialize_to_buffer_r(const JSON_Value *value, char *buf, int level, parson_bool_t is_pretty, char *num_buf) { const char *key = NULL, *string = NULL; JSON_Value *temp_value = NULL; JSON_Array *array = NULL; JSON_Object *object = NULL; size_t i = 0, count = 0; double num = 0.0; int written = -1, written_total = 0; size_t len = 0; switch (json_value_get_type(value)) { case JSONArray: array = json_value_get_array(value); count = json_array_get_count(array); APPEND_STRING("["); if (count > 0 && is_pretty) { APPEND_STRING("\n"); } for (i = 0; i < count; i++) { if (is_pretty) { APPEND_INDENT(level+1); } temp_value = json_array_get_value(array, i); written = json_serialize_to_buffer_r(temp_value, buf, level+1, is_pretty, num_buf); if (written < 0) { return -1; } if (buf != NULL) { buf += written; } written_total += written; if (i < (count - 1)) { APPEND_STRING(","); } if (is_pretty) { APPEND_STRING("\n"); } } if (count > 0 && is_pretty) { APPEND_INDENT(level); } APPEND_STRING("]"); return written_total; case JSONObject: object = json_value_get_object(value); count = json_object_get_count(object); APPEND_STRING("{"); if (count > 0 && is_pretty) { APPEND_STRING("\n"); } for (i = 0; i < count; i++) { key = json_object_get_name(object, i); if (key == NULL) { return -1; } if (is_pretty) { APPEND_INDENT(level+1); } /* We do not support key names with embedded \0 chars */ written = json_serialize_string(key, strlen(key), buf); if (written < 0) { return -1; } if (buf != NULL) { buf += written; } written_total += written; APPEND_STRING(":"); if (is_pretty) { APPEND_STRING(" "); } temp_value = json_object_get_value_at(object, i); written = json_serialize_to_buffer_r(temp_value, buf, level+1, is_pretty, num_buf); if (written < 0) { return -1; } if (buf != NULL) { buf += written; } written_total += written; if (i < (count - 1)) { APPEND_STRING(","); } if (is_pretty) { APPEND_STRING("\n"); } } if (count > 0 && is_pretty) { APPEND_INDENT(level); } APPEND_STRING("}"); return written_total; case JSONString: string = json_value_get_string(value); if (string == NULL) { return -1; } len = json_value_get_string_len(value); written = json_serialize_string(string, len, buf); if (written < 0) { return -1; } if (buf != NULL) { buf += written; } written_total += written; return written_total; case JSONBoolean: if (json_value_get_boolean(value)) { APPEND_STRING("true"); } else { APPEND_STRING("false"); } return written_total; case JSONNumber: num = json_value_get_number(value); if (buf != NULL) { num_buf = buf; } if (parson_number_serialization_function) { written = parson_number_serialization_function(num, num_buf); } else { const char *float_format = parson_float_format ? parson_float_format : PARSON_DEFAULT_FLOAT_FORMAT; written = parson_snprintf(num_buf, PARSON_NUM_BUF_SIZE, float_format, num); } if (written < 0) { return -1; } if (buf != NULL) { buf += written; } written_total += written; return written_total; case JSONNull: APPEND_STRING("null"); return written_total; case JSONError: return -1; default: return -1; } } static int json_serialize_string(const char *string, size_t len, char *buf) { size_t i = 0; char c = '\0'; int written = -1, written_total = 0; APPEND_STRING("\""); for (i = 0; i < len; i++) { c = string[i]; switch (c) { case '\"': APPEND_STRING("\\\""); break; case '\\': APPEND_STRING("\\\\"); break; case '\b': APPEND_STRING("\\b"); break; case '\f': APPEND_STRING("\\f"); break; case '\n': APPEND_STRING("\\n"); break; case '\r': APPEND_STRING("\\r"); break; case '\t': APPEND_STRING("\\t"); break; case '\x00': APPEND_STRING("\\u0000"); break; case '\x01': APPEND_STRING("\\u0001"); break; case '\x02': APPEND_STRING("\\u0002"); break; case '\x03': APPEND_STRING("\\u0003"); break; case '\x04': APPEND_STRING("\\u0004"); break; case '\x05': APPEND_STRING("\\u0005"); break; case '\x06': APPEND_STRING("\\u0006"); break; case '\x07': APPEND_STRING("\\u0007"); break; /* '\x08' duplicate: '\b' */ /* '\x09' duplicate: '\t' */ /* '\x0a' duplicate: '\n' */ case '\x0b': APPEND_STRING("\\u000b"); break; /* '\x0c' duplicate: '\f' */ /* '\x0d' duplicate: '\r' */ case '\x0e': APPEND_STRING("\\u000e"); break; case '\x0f': APPEND_STRING("\\u000f"); break; case '\x10': APPEND_STRING("\\u0010"); break; case '\x11': APPEND_STRING("\\u0011"); break; case '\x12': APPEND_STRING("\\u0012"); break; case '\x13': APPEND_STRING("\\u0013"); break; case '\x14': APPEND_STRING("\\u0014"); break; case '\x15': APPEND_STRING("\\u0015"); break; case '\x16': APPEND_STRING("\\u0016"); break; case '\x17': APPEND_STRING("\\u0017"); break; case '\x18': APPEND_STRING("\\u0018"); break; case '\x19': APPEND_STRING("\\u0019"); break; case '\x1a': APPEND_STRING("\\u001a"); break; case '\x1b': APPEND_STRING("\\u001b"); break; case '\x1c': APPEND_STRING("\\u001c"); break; case '\x1d': APPEND_STRING("\\u001d"); break; case '\x1e': APPEND_STRING("\\u001e"); break; case '\x1f': APPEND_STRING("\\u001f"); break; case '/': if (parson_escape_slashes) { APPEND_STRING("\\/"); /* to make json embeddable in xml\/html */ } else { APPEND_STRING("/"); } break; default: if (buf != NULL) { buf[0] = c; buf += 1; } written_total += 1; break; } } APPEND_STRING("\""); return written_total; } #undef APPEND_STRING #undef APPEND_INDENT /* Parser API */ JSON_Value * json_parse_file(const char *filename) { char *file_contents = read_file(filename); JSON_Value *output_value = NULL; if (file_contents == NULL) { return NULL; } output_value = json_parse_string(file_contents); parson_free(file_contents); return output_value; } JSON_Value * json_parse_file_with_comments(const char *filename) { char *file_contents = read_file(filename); JSON_Value *output_value = NULL; if (file_contents == NULL) { return NULL; } output_value = json_parse_string_with_comments(file_contents); parson_free(file_contents); return output_value; } JSON_Value * json_parse_string(const char *string) { if (string == NULL) { return NULL; } if (string[0] == '\xEF' && string[1] == '\xBB' && string[2] == '\xBF') { string = string + 3; /* Support for UTF-8 BOM */ } return parse_value((const char**)&string, 0); } JSON_Value * json_parse_string_with_comments(const char *string) { JSON_Value *result = NULL; char *string_mutable_copy = NULL, *string_mutable_copy_ptr = NULL; string_mutable_copy = parson_strdup(string); if (string_mutable_copy == NULL) { return NULL; } remove_comments(string_mutable_copy, "/*", "*/"); remove_comments(string_mutable_copy, "//", "\n"); string_mutable_copy_ptr = string_mutable_copy; result = parse_value((const char**)&string_mutable_copy_ptr, 0); parson_free(string_mutable_copy); return result; } /* JSON Object API */ JSON_Value * json_object_get_value(const JSON_Object *object, const char *name) { if (object == NULL || name == NULL) { return NULL; } return json_object_getn_value(object, name, strlen(name)); } const char * json_object_get_string(const JSON_Object *object, const char *name) { return json_value_get_string(json_object_get_value(object, name)); } size_t json_object_get_string_len(const JSON_Object *object, const char *name) { return json_value_get_string_len(json_object_get_value(object, name)); } double json_object_get_number(const JSON_Object *object, const char *name) { return json_value_get_number(json_object_get_value(object, name)); } JSON_Object * json_object_get_object(const JSON_Object *object, const char *name) { return json_value_get_object(json_object_get_value(object, name)); } JSON_Array * json_object_get_array(const JSON_Object *object, const char *name) { return json_value_get_array(json_object_get_value(object, name)); } int json_object_get_boolean(const JSON_Object *object, const char *name) { return json_value_get_boolean(json_object_get_value(object, name)); } JSON_Value * json_object_dotget_value(const JSON_Object *object, const char *name) { const char *dot_position = strchr(name, '.'); if (!dot_position) { return json_object_get_value(object, name); } object = json_value_get_object(json_object_getn_value(object, name, dot_position - name)); return json_object_dotget_value(object, dot_position + 1); } const char * json_object_dotget_string(const JSON_Object *object, const char *name) { return json_value_get_string(json_object_dotget_value(object, name)); } size_t json_object_dotget_string_len(const JSON_Object *object, const char *name) { return json_value_get_string_len(json_object_dotget_value(object, name)); } double json_object_dotget_number(const JSON_Object *object, const char *name) { return json_value_get_number(json_object_dotget_value(object, name)); } JSON_Object * json_object_dotget_object(const JSON_Object *object, const char *name) { return json_value_get_object(json_object_dotget_value(object, name)); } JSON_Array * json_object_dotget_array(const JSON_Object *object, const char *name) { return json_value_get_array(json_object_dotget_value(object, name)); } int json_object_dotget_boolean(const JSON_Object *object, const char *name) { return json_value_get_boolean(json_object_dotget_value(object, name)); } size_t json_object_get_count(const JSON_Object *object) { return object ? object->count : 0; } const char * json_object_get_name(const JSON_Object *object, size_t index) { if (object == NULL || index >= json_object_get_count(object)) { return NULL; } return object->names[index]; } JSON_Value * json_object_get_value_at(const JSON_Object *object, size_t index) { if (object == NULL || index >= json_object_get_count(object)) { return NULL; } return object->values[index]; } JSON_Value *json_object_get_wrapping_value(const JSON_Object *object) { if (!object) { return NULL; } return object->wrapping_value; } int json_object_has_value (const JSON_Object *object, const char *name) { return json_object_get_value(object, name) != NULL; } int json_object_has_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type) { JSON_Value *val = json_object_get_value(object, name); return val != NULL && json_value_get_type(val) == type; } int json_object_dothas_value (const JSON_Object *object, const char *name) { return json_object_dotget_value(object, name) != NULL; } int json_object_dothas_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type) { JSON_Value *val = json_object_dotget_value(object, name); return val != NULL && json_value_get_type(val) == type; } /* JSON Array API */ JSON_Value * json_array_get_value(const JSON_Array *array, size_t index) { if (array == NULL || index >= json_array_get_count(array)) { return NULL; } return array->items[index]; } const char * json_array_get_string(const JSON_Array *array, size_t index) { return json_value_get_string(json_array_get_value(array, index)); } size_t json_array_get_string_len(const JSON_Array *array, size_t index) { return json_value_get_string_len(json_array_get_value(array, index)); } double json_array_get_number(const JSON_Array *array, size_t index) { return json_value_get_number(json_array_get_value(array, index)); } JSON_Object * json_array_get_object(const JSON_Array *array, size_t index) { return json_value_get_object(json_array_get_value(array, index)); } JSON_Array * json_array_get_array(const JSON_Array *array, size_t index) { return json_value_get_array(json_array_get_value(array, index)); } int json_array_get_boolean(const JSON_Array *array, size_t index) { return json_value_get_boolean(json_array_get_value(array, index)); } size_t json_array_get_count(const JSON_Array *array) { return array ? array->count : 0; } JSON_Value * json_array_get_wrapping_value(const JSON_Array *array) { if (!array) { return NULL; } return array->wrapping_value; } /* JSON Value API */ JSON_Value_Type json_value_get_type(const JSON_Value *value) { return value ? value->type : JSONError; } JSON_Object * json_value_get_object(const JSON_Value *value) { return json_value_get_type(value) == JSONObject ? value->value.object : NULL; } JSON_Array * json_value_get_array(const JSON_Value *value) { return json_value_get_type(value) == JSONArray ? value->value.array : NULL; } static const JSON_String * json_value_get_string_desc(const JSON_Value *value) { return json_value_get_type(value) == JSONString ? &value->value.string : NULL; } const char * json_value_get_string(const JSON_Value *value) { const JSON_String *str = json_value_get_string_desc(value); return str ? str->chars : NULL; } size_t json_value_get_string_len(const JSON_Value *value) { const JSON_String *str = json_value_get_string_desc(value); return str ? str->length : 0; } double json_value_get_number(const JSON_Value *value) { return json_value_get_type(value) == JSONNumber ? value->value.number : 0; } int json_value_get_boolean(const JSON_Value *value) { return json_value_get_type(value) == JSONBoolean ? value->value.boolean : -1; } JSON_Value * json_value_get_parent (const JSON_Value *value) { return value ? value->parent : NULL; } void json_value_free(JSON_Value *value) { switch (json_value_get_type(value)) { case JSONObject: json_object_free(value->value.object); break; case JSONString: parson_free(value->value.string.chars); break; case JSONArray: json_array_free(value->value.array); break; default: break; } parson_free(value); } JSON_Value * json_value_init_object(void) { JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value)); if (!new_value) { return NULL; } new_value->parent = NULL; new_value->type = JSONObject; new_value->value.object = json_object_make(new_value); if (!new_value->value.object) { parson_free(new_value); return NULL; } return new_value; } JSON_Value * json_value_init_array(void) { JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value)); if (!new_value) { return NULL; } new_value->parent = NULL; new_value->type = JSONArray; new_value->value.array = json_array_make(new_value); if (!new_value->value.array) { parson_free(new_value); return NULL; } return new_value; } JSON_Value * json_value_init_string(const char *string) { if (string == NULL) { return NULL; } return json_value_init_string_with_len(string, strlen(string)); } JSON_Value * json_value_init_string_with_len(const char *string, size_t length) { char *copy = NULL; JSON_Value *value; if (string == NULL) { return NULL; } if (!is_valid_utf8(string, length)) { return NULL; } copy = parson_strndup(string, length); if (copy == NULL) { return NULL; } value = json_value_init_string_no_copy(copy, length); if (value == NULL) { parson_free(copy); } return value; } JSON_Value * json_value_init_number(double number) { JSON_Value *new_value = NULL; if (IS_NUMBER_INVALID(number)) { return NULL; } new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value)); if (new_value == NULL) { return NULL; } new_value->parent = NULL; new_value->type = JSONNumber; new_value->value.number = number; return new_value; } JSON_Value * json_value_init_boolean(int boolean) { JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value)); if (!new_value) { return NULL; } new_value->parent = NULL; new_value->type = JSONBoolean; new_value->value.boolean = boolean ? 1 : 0; return new_value; } JSON_Value * json_value_init_null(void) { JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value)); if (!new_value) { return NULL; } new_value->parent = NULL; new_value->type = JSONNull; return new_value; } JSON_Value * json_value_deep_copy(const JSON_Value *value) { size_t i = 0; JSON_Value *return_value = NULL, *temp_value_copy = NULL, *temp_value = NULL; const JSON_String *temp_string = NULL; const char *temp_key = NULL; char *temp_string_copy = NULL; JSON_Array *temp_array = NULL, *temp_array_copy = NULL; JSON_Object *temp_object = NULL, *temp_object_copy = NULL; JSON_Status res = JSONFailure; char *key_copy = NULL; switch (json_value_get_type(value)) { case JSONArray: temp_array = json_value_get_array(value); return_value = json_value_init_array(); if (return_value == NULL) { return NULL; } temp_array_copy = json_value_get_array(return_value); for (i = 0; i < json_array_get_count(temp_array); i++) { temp_value = json_array_get_value(temp_array, i); temp_value_copy = json_value_deep_copy(temp_value); if (temp_value_copy == NULL) { json_value_free(return_value); return NULL; } if (json_array_add(temp_array_copy, temp_value_copy) != JSONSuccess) { json_value_free(return_value); json_value_free(temp_value_copy); return NULL; } } return return_value; case JSONObject: temp_object = json_value_get_object(value); return_value = json_value_init_object(); if (!return_value) { return NULL; } temp_object_copy = json_value_get_object(return_value); for (i = 0; i < json_object_get_count(temp_object); i++) { temp_key = json_object_get_name(temp_object, i); temp_value = json_object_get_value(temp_object, temp_key); temp_value_copy = json_value_deep_copy(temp_value); if (!temp_value_copy) { json_value_free(return_value); return NULL; } key_copy = parson_strdup(temp_key); if (!key_copy) { json_value_free(temp_value_copy); json_value_free(return_value); return NULL; } res = json_object_add(temp_object_copy, key_copy, temp_value_copy); if (res != JSONSuccess) { parson_free(key_copy); json_value_free(temp_value_copy); json_value_free(return_value); return NULL; } } return return_value; case JSONBoolean: return json_value_init_boolean(json_value_get_boolean(value)); case JSONNumber: return json_value_init_number(json_value_get_number(value)); case JSONString: temp_string = json_value_get_string_desc(value); if (temp_string == NULL) { return NULL; } temp_string_copy = parson_strndup(temp_string->chars, temp_string->length); if (temp_string_copy == NULL) { return NULL; } return_value = json_value_init_string_no_copy(temp_string_copy, temp_string->length); if (return_value == NULL) { parson_free(temp_string_copy); } return return_value; case JSONNull: return json_value_init_null(); case JSONError: return NULL; default: return NULL; } } size_t json_serialization_size(const JSON_Value *value) { char num_buf[PARSON_NUM_BUF_SIZE]; /* recursively allocating buffer on stack is a bad idea, so let's do it only once */ int res = json_serialize_to_buffer_r(value, NULL, 0, PARSON_FALSE, num_buf); return res < 0 ? 0 : (size_t)(res) + 1; } JSON_Status json_serialize_to_buffer(const JSON_Value *value, char *buf, size_t buf_size_in_bytes) { int written = -1; size_t needed_size_in_bytes = json_serialization_size(value); if (needed_size_in_bytes == 0 || buf_size_in_bytes < needed_size_in_bytes) { return JSONFailure; } written = json_serialize_to_buffer_r(value, buf, 0, PARSON_FALSE, NULL); if (written < 0) { return JSONFailure; } return JSONSuccess; } JSON_Status json_serialize_to_file(const JSON_Value *value, const char *filename) { JSON_Status return_code = JSONSuccess; FILE *fp = NULL; char *serialized_string = json_serialize_to_string(value); if (serialized_string == NULL) { return JSONFailure; } fp = fopen(filename, "w"); if (fp == NULL) { json_free_serialized_string(serialized_string); return JSONFailure; } if (fputs(serialized_string, fp) == EOF) { return_code = JSONFailure; } if (fclose(fp) == EOF) { return_code = JSONFailure; } json_free_serialized_string(serialized_string); return return_code; } char * json_serialize_to_string(const JSON_Value *value) { JSON_Status serialization_result = JSONFailure; size_t buf_size_bytes = json_serialization_size(value); char *buf = NULL; if (buf_size_bytes == 0) { return NULL; } buf = (char*)parson_malloc(buf_size_bytes); if (buf == NULL) { return NULL; } serialization_result = json_serialize_to_buffer(value, buf, buf_size_bytes); if (serialization_result != JSONSuccess) { json_free_serialized_string(buf); return NULL; } return buf; } size_t json_serialization_size_pretty(const JSON_Value *value) { char num_buf[PARSON_NUM_BUF_SIZE]; /* recursively allocating buffer on stack is a bad idea, so let's do it only once */ int res = json_serialize_to_buffer_r(value, NULL, 0, PARSON_TRUE, num_buf); return res < 0 ? 0 : (size_t)(res) + 1; } JSON_Status json_serialize_to_buffer_pretty(const JSON_Value *value, char *buf, size_t buf_size_in_bytes) { int written = -1; size_t needed_size_in_bytes = json_serialization_size_pretty(value); if (needed_size_in_bytes == 0 || buf_size_in_bytes < needed_size_in_bytes) { return JSONFailure; } written = json_serialize_to_buffer_r(value, buf, 0, PARSON_TRUE, NULL); if (written < 0) { return JSONFailure; } return JSONSuccess; } JSON_Status json_serialize_to_file_pretty(const JSON_Value *value, const char *filename) { JSON_Status return_code = JSONSuccess; FILE *fp = NULL; char *serialized_string = json_serialize_to_string_pretty(value); if (serialized_string == NULL) { return JSONFailure; } fp = fopen(filename, "w"); if (fp == NULL) { json_free_serialized_string(serialized_string); return JSONFailure; } if (fputs(serialized_string, fp) == EOF) { return_code = JSONFailure; } if (fclose(fp) == EOF) { return_code = JSONFailure; } json_free_serialized_string(serialized_string); return return_code; } char * json_serialize_to_string_pretty(const JSON_Value *value) { JSON_Status serialization_result = JSONFailure; size_t buf_size_bytes = json_serialization_size_pretty(value); char *buf = NULL; if (buf_size_bytes == 0) { return NULL; } buf = (char*)parson_malloc(buf_size_bytes); if (buf == NULL) { return NULL; } serialization_result = json_serialize_to_buffer_pretty(value, buf, buf_size_bytes); if (serialization_result != JSONSuccess) { json_free_serialized_string(buf); return NULL; } return buf; } void json_free_serialized_string(char *string) { parson_free(string); } JSON_Status json_array_remove(JSON_Array *array, size_t ix) { size_t to_move_bytes = 0; if (array == NULL || ix >= json_array_get_count(array)) { return JSONFailure; } json_value_free(json_array_get_value(array, ix)); to_move_bytes = (json_array_get_count(array) - 1 - ix) * sizeof(JSON_Value*); memmove(array->items + ix, array->items + ix + 1, to_move_bytes); array->count -= 1; return JSONSuccess; } JSON_Status json_array_replace_value(JSON_Array *array, size_t ix, JSON_Value *value) { if (array == NULL || value == NULL || value->parent != NULL || ix >= json_array_get_count(array)) { return JSONFailure; } json_value_free(json_array_get_value(array, ix)); value->parent = json_array_get_wrapping_value(array); array->items[ix] = value; return JSONSuccess; } JSON_Status json_array_replace_string(JSON_Array *array, size_t i, const char* string) { JSON_Value *value = json_value_init_string(string); if (value == NULL) { return JSONFailure; } if (json_array_replace_value(array, i, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_array_replace_string_with_len(JSON_Array *array, size_t i, const char *string, size_t len) { JSON_Value *value = json_value_init_string_with_len(string, len); if (value == NULL) { return JSONFailure; } if (json_array_replace_value(array, i, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_array_replace_number(JSON_Array *array, size_t i, double number) { JSON_Value *value = json_value_init_number(number); if (value == NULL) { return JSONFailure; } if (json_array_replace_value(array, i, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_array_replace_boolean(JSON_Array *array, size_t i, int boolean) { JSON_Value *value = json_value_init_boolean(boolean); if (value == NULL) { return JSONFailure; } if (json_array_replace_value(array, i, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_array_replace_null(JSON_Array *array, size_t i) { JSON_Value *value = json_value_init_null(); if (value == NULL) { return JSONFailure; } if (json_array_replace_value(array, i, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_array_clear(JSON_Array *array) { size_t i = 0; if (array == NULL) { return JSONFailure; } for (i = 0; i < json_array_get_count(array); i++) { json_value_free(json_array_get_value(array, i)); } array->count = 0; return JSONSuccess; } JSON_Status json_array_append_value(JSON_Array *array, JSON_Value *value) { if (array == NULL || value == NULL || value->parent != NULL) { return JSONFailure; } return json_array_add(array, value); } JSON_Status json_array_append_string(JSON_Array *array, const char *string) { JSON_Value *value = json_value_init_string(string); if (value == NULL) { return JSONFailure; } if (json_array_append_value(array, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_array_append_string_with_len(JSON_Array *array, const char *string, size_t len) { JSON_Value *value = json_value_init_string_with_len(string, len); if (value == NULL) { return JSONFailure; } if (json_array_append_value(array, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_array_append_number(JSON_Array *array, double number) { JSON_Value *value = json_value_init_number(number); if (value == NULL) { return JSONFailure; } if (json_array_append_value(array, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_array_append_boolean(JSON_Array *array, int boolean) { JSON_Value *value = json_value_init_boolean(boolean); if (value == NULL) { return JSONFailure; } if (json_array_append_value(array, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_array_append_null(JSON_Array *array) { JSON_Value *value = json_value_init_null(); if (value == NULL) { return JSONFailure; } if (json_array_append_value(array, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_object_set_value(JSON_Object *object, const char *name, JSON_Value *value) { unsigned long hash = 0; parson_bool_t found = PARSON_FALSE; size_t cell_ix = 0; size_t item_ix = 0; JSON_Value *old_value = NULL; char *key_copy = NULL; if (!object || !name || !value || value->parent) { return JSONFailure; } hash = hash_string(name, strlen(name)); found = PARSON_FALSE; cell_ix = json_object_get_cell_ix(object, name, strlen(name), hash, &found); if (found) { item_ix = object->cells[cell_ix]; old_value = object->values[item_ix]; json_value_free(old_value); object->values[item_ix] = value; value->parent = json_object_get_wrapping_value(object); return JSONSuccess; } if (object->count >= object->item_capacity) { JSON_Status res = json_object_grow_and_rehash(object); if (res != JSONSuccess) { return JSONFailure; } cell_ix = json_object_get_cell_ix(object, name, strlen(name), hash, &found); } key_copy = parson_strdup(name); if (!key_copy) { return JSONFailure; } object->names[object->count] = key_copy; object->cells[cell_ix] = object->count; object->values[object->count] = value; object->cell_ixs[object->count] = cell_ix; object->hashes[object->count] = hash; object->count++; value->parent = json_object_get_wrapping_value(object); return JSONSuccess; } JSON_Status json_object_set_string(JSON_Object *object, const char *name, const char *string) { JSON_Value *value = json_value_init_string(string); JSON_Status status = json_object_set_value(object, name, value); if (status != JSONSuccess) { json_value_free(value); } return status; } JSON_Status json_object_set_string_with_len(JSON_Object *object, const char *name, const char *string, size_t len) { JSON_Value *value = json_value_init_string_with_len(string, len); JSON_Status status = json_object_set_value(object, name, value); if (status != JSONSuccess) { json_value_free(value); } return status; } JSON_Status json_object_set_number(JSON_Object *object, const char *name, double number) { JSON_Value *value = json_value_init_number(number); JSON_Status status = json_object_set_value(object, name, value); if (status != JSONSuccess) { json_value_free(value); } return status; } JSON_Status json_object_set_boolean(JSON_Object *object, const char *name, int boolean) { JSON_Value *value = json_value_init_boolean(boolean); JSON_Status status = json_object_set_value(object, name, value); if (status != JSONSuccess) { json_value_free(value); } return status; } JSON_Status json_object_set_null(JSON_Object *object, const char *name) { JSON_Value *value = json_value_init_null(); JSON_Status status = json_object_set_value(object, name, value); if (status != JSONSuccess) { json_value_free(value); } return status; } JSON_Status json_object_dotset_value(JSON_Object *object, const char *name, JSON_Value *value) { const char *dot_pos = NULL; JSON_Value *temp_value = NULL, *new_value = NULL; JSON_Object *temp_object = NULL, *new_object = NULL; JSON_Status status = JSONFailure; size_t name_len = 0; char *name_copy = NULL; if (object == NULL || name == NULL || value == NULL) { return JSONFailure; } dot_pos = strchr(name, '.'); if (dot_pos == NULL) { return json_object_set_value(object, name, value); } name_len = dot_pos - name; temp_value = json_object_getn_value(object, name, name_len); if (temp_value) { /* Don't overwrite existing non-object (unlike json_object_set_value, but it shouldn't be changed at this point) */ if (json_value_get_type(temp_value) != JSONObject) { return JSONFailure; } temp_object = json_value_get_object(temp_value); return json_object_dotset_value(temp_object, dot_pos + 1, value); } new_value = json_value_init_object(); if (new_value == NULL) { return JSONFailure; } new_object = json_value_get_object(new_value); status = json_object_dotset_value(new_object, dot_pos + 1, value); if (status != JSONSuccess) { json_value_free(new_value); return JSONFailure; } name_copy = parson_strndup(name, name_len); if (!name_copy) { json_object_dotremove_internal(new_object, dot_pos + 1, 0); json_value_free(new_value); return JSONFailure; } status = json_object_add(object, name_copy, new_value); if (status != JSONSuccess) { parson_free(name_copy); json_object_dotremove_internal(new_object, dot_pos + 1, 0); json_value_free(new_value); return JSONFailure; } return JSONSuccess; } JSON_Status json_object_dotset_string(JSON_Object *object, const char *name, const char *string) { JSON_Value *value = json_value_init_string(string); if (value == NULL) { return JSONFailure; } if (json_object_dotset_value(object, name, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_object_dotset_string_with_len(JSON_Object *object, const char *name, const char *string, size_t len) { JSON_Value *value = json_value_init_string_with_len(string, len); if (value == NULL) { return JSONFailure; } if (json_object_dotset_value(object, name, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_object_dotset_number(JSON_Object *object, const char *name, double number) { JSON_Value *value = json_value_init_number(number); if (value == NULL) { return JSONFailure; } if (json_object_dotset_value(object, name, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_object_dotset_boolean(JSON_Object *object, const char *name, int boolean) { JSON_Value *value = json_value_init_boolean(boolean); if (value == NULL) { return JSONFailure; } if (json_object_dotset_value(object, name, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_object_dotset_null(JSON_Object *object, const char *name) { JSON_Value *value = json_value_init_null(); if (value == NULL) { return JSONFailure; } if (json_object_dotset_value(object, name, value) != JSONSuccess) { json_value_free(value); return JSONFailure; } return JSONSuccess; } JSON_Status json_object_remove(JSON_Object *object, const char *name) { return json_object_remove_internal(object, name, PARSON_TRUE); } JSON_Status json_object_dotremove(JSON_Object *object, const char *name) { return json_object_dotremove_internal(object, name, PARSON_TRUE); } JSON_Status json_object_clear(JSON_Object *object) { size_t i = 0; if (object == NULL) { return JSONFailure; } for (i = 0; i < json_object_get_count(object); i++) { parson_free(object->names[i]); object->names[i] = NULL; json_value_free(object->values[i]); object->values[i] = NULL; } object->count = 0; for (i = 0; i < object->cell_capacity; i++) { object->cells[i] = OBJECT_INVALID_IX; } return JSONSuccess; } JSON_Status json_validate(const JSON_Value *schema, const JSON_Value *value) { JSON_Value *temp_schema_value = NULL, *temp_value = NULL; JSON_Array *schema_array = NULL, *value_array = NULL; JSON_Object *schema_object = NULL, *value_object = NULL; JSON_Value_Type schema_type = JSONError, value_type = JSONError; const char *key = NULL; size_t i = 0, count = 0; if (schema == NULL || value == NULL) { return JSONFailure; } schema_type = json_value_get_type(schema); value_type = json_value_get_type(value); if (schema_type != value_type && schema_type != JSONNull) { /* null represents all values */ return JSONFailure; } switch (schema_type) { case JSONArray: schema_array = json_value_get_array(schema); value_array = json_value_get_array(value); count = json_array_get_count(schema_array); if (count == 0) { return JSONSuccess; /* Empty array allows all types */ } /* Get first value from array, rest is ignored */ temp_schema_value = json_array_get_value(schema_array, 0); for (i = 0; i < json_array_get_count(value_array); i++) { temp_value = json_array_get_value(value_array, i); if (json_validate(temp_schema_value, temp_value) != JSONSuccess) { return JSONFailure; } } return JSONSuccess; case JSONObject: schema_object = json_value_get_object(schema); value_object = json_value_get_object(value); count = json_object_get_count(schema_object); if (count == 0) { return JSONSuccess; /* Empty object allows all objects */ } else if (json_object_get_count(value_object) < count) { return JSONFailure; /* Tested object mustn't have less name-value pairs than schema */ } for (i = 0; i < count; i++) { key = json_object_get_name(schema_object, i); temp_schema_value = json_object_get_value(schema_object, key); temp_value = json_object_get_value(value_object, key); if (temp_value == NULL) { return JSONFailure; } if (json_validate(temp_schema_value, temp_value) != JSONSuccess) { return JSONFailure; } } return JSONSuccess; case JSONString: case JSONNumber: case JSONBoolean: case JSONNull: return JSONSuccess; /* equality already tested before switch */ case JSONError: default: return JSONFailure; } } int json_value_equals(const JSON_Value *a, const JSON_Value *b) { JSON_Object *a_object = NULL, *b_object = NULL; JSON_Array *a_array = NULL, *b_array = NULL; const JSON_String *a_string = NULL, *b_string = NULL; const char *key = NULL; size_t a_count = 0, b_count = 0, i = 0; JSON_Value_Type a_type, b_type; a_type = json_value_get_type(a); b_type = json_value_get_type(b); if (a_type != b_type) { return PARSON_FALSE; } switch (a_type) { case JSONArray: a_array = json_value_get_array(a); b_array = json_value_get_array(b); a_count = json_array_get_count(a_array); b_count = json_array_get_count(b_array); if (a_count != b_count) { return PARSON_FALSE; } for (i = 0; i < a_count; i++) { if (!json_value_equals(json_array_get_value(a_array, i), json_array_get_value(b_array, i))) { return PARSON_FALSE; } } return PARSON_TRUE; case JSONObject: a_object = json_value_get_object(a); b_object = json_value_get_object(b); a_count = json_object_get_count(a_object); b_count = json_object_get_count(b_object); if (a_count != b_count) { return PARSON_FALSE; } for (i = 0; i < a_count; i++) { key = json_object_get_name(a_object, i); if (!json_value_equals(json_object_get_value(a_object, key), json_object_get_value(b_object, key))) { return PARSON_FALSE; } } return PARSON_TRUE; case JSONString: a_string = json_value_get_string_desc(a); b_string = json_value_get_string_desc(b); if (a_string == NULL || b_string == NULL) { return PARSON_FALSE; /* shouldn't happen */ } return a_string->length == b_string->length && memcmp(a_string->chars, b_string->chars, a_string->length) == 0; case JSONBoolean: return json_value_get_boolean(a) == json_value_get_boolean(b); case JSONNumber: return fabs(json_value_get_number(a) - json_value_get_number(b)) < 0.000001; /* EPSILON */ case JSONError: return PARSON_TRUE; case JSONNull: return PARSON_TRUE; default: return PARSON_TRUE; } } JSON_Value_Type json_type(const JSON_Value *value) { return json_value_get_type(value); } JSON_Object * json_object (const JSON_Value *value) { return json_value_get_object(value); } JSON_Array * json_array(const JSON_Value *value) { return json_value_get_array(value); } const char * json_string(const JSON_Value *value) { return json_value_get_string(value); } size_t json_string_len(const JSON_Value *value) { return json_value_get_string_len(value); } double json_number(const JSON_Value *value) { return json_value_get_number(value); } int json_boolean(const JSON_Value *value) { return json_value_get_boolean(value); } void json_set_allocation_functions(JSON_Malloc_Function malloc_fun, JSON_Free_Function free_fun) { parson_malloc = malloc_fun; parson_free = free_fun; } void json_set_escape_slashes(int escape_slashes) { parson_escape_slashes = escape_slashes; } void json_set_float_serialization_format(const char *format) { if (parson_float_format) { parson_free(parson_float_format); parson_float_format = NULL; } if (!format) { parson_float_format = NULL; return; } parson_float_format = parson_strdup(format); } void json_set_number_serialization_function(JSON_Number_Serialization_Function func) { parson_number_serialization_function = func; } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/parson.h000066400000000000000000000336101525155022500224220ustar00rootroot00000000000000/* SPDX-License-Identifier: MIT Parson 1.5.3 (https://github.com/kgabis/parson) Copyright (c) 2012 - 2023 Krzysztof Gabis 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 parson_parson_h #define parson_parson_h #ifdef __cplusplus extern "C" { #endif #if 0 } /* unconfuse xcode */ #endif #define PARSON_VERSION_MAJOR 1 #define PARSON_VERSION_MINOR 5 #define PARSON_VERSION_PATCH 3 #define PARSON_VERSION_STRING "1.5.3" #include /* size_t */ /* Types and enums */ typedef struct json_object_t JSON_Object; typedef struct json_array_t JSON_Array; typedef struct json_value_t JSON_Value; enum json_value_type { JSONError = -1, JSONNull = 1, JSONString = 2, JSONNumber = 3, JSONObject = 4, JSONArray = 5, JSONBoolean = 6 }; typedef int JSON_Value_Type; enum json_result_t { JSONSuccess = 0, JSONFailure = -1 }; typedef int JSON_Status; typedef void * (*JSON_Malloc_Function)(size_t); typedef void (*JSON_Free_Function)(void *); /* A function used for serializing numbers (see json_set_number_serialization_function). If 'buf' is null then it should return number of bytes that would've been written (but not more than PARSON_NUM_BUF_SIZE). */ typedef int (*JSON_Number_Serialization_Function)(double num, char *buf); /* Call only once, before calling any other function from parson API. If not called, malloc and free from stdlib will be used for all allocations */ void json_set_allocation_functions(JSON_Malloc_Function malloc_fun, JSON_Free_Function free_fun); /* Sets if slashes should be escaped or not when serializing JSON. By default slashes are escaped. This function sets a global setting and is not thread safe. */ void json_set_escape_slashes(int escape_slashes); /* Sets float format used for serialization of numbers. Make sure it can't serialize to a string longer than PARSON_NUM_BUF_SIZE. If format is null then the default format is used. */ void json_set_float_serialization_format(const char *format); /* Sets a function that will be used for serialization of numbers. If function is null then the default serialization function is used. */ void json_set_number_serialization_function(JSON_Number_Serialization_Function fun); /* Parses first JSON value in a file, returns NULL in case of error */ JSON_Value * json_parse_file(const char *filename); /* Parses first JSON value in a file and ignores comments (/ * * / and //), returns NULL in case of error */ JSON_Value * json_parse_file_with_comments(const char *filename); /* Parses first JSON value in a string, returns NULL in case of error */ JSON_Value * json_parse_string(const char *string); /* Parses first JSON value in a string and ignores comments (/ * * / and //), returns NULL in case of error */ JSON_Value * json_parse_string_with_comments(const char *string); /* Serialization */ size_t json_serialization_size(const JSON_Value *value); /* returns 0 on fail */ JSON_Status json_serialize_to_buffer(const JSON_Value *value, char *buf, size_t buf_size_in_bytes); JSON_Status json_serialize_to_file(const JSON_Value *value, const char *filename); char * json_serialize_to_string(const JSON_Value *value); /* Pretty serialization */ size_t json_serialization_size_pretty(const JSON_Value *value); /* returns 0 on fail */ JSON_Status json_serialize_to_buffer_pretty(const JSON_Value *value, char *buf, size_t buf_size_in_bytes); JSON_Status json_serialize_to_file_pretty(const JSON_Value *value, const char *filename); char * json_serialize_to_string_pretty(const JSON_Value *value); void json_free_serialized_string(char *string); /* frees string from json_serialize_to_string and json_serialize_to_string_pretty */ /* Comparing */ int json_value_equals(const JSON_Value *a, const JSON_Value *b); /* Validation This is *NOT* JSON Schema. It validates json by checking if object have identically named fields with matching types. For example schema {"name":"", "age":0} will validate {"name":"Joe", "age":25} and {"name":"Joe", "age":25, "gender":"m"}, but not {"name":"Joe"} or {"name":"Joe", "age":"Cucumber"}. In case of arrays, only first value in schema is checked against all values in tested array. Empty objects ({}) validate all objects, empty arrays ([]) validate all arrays, null validates values of every type. */ JSON_Status json_validate(const JSON_Value *schema, const JSON_Value *value); /* * JSON Object */ JSON_Value * json_object_get_value (const JSON_Object *object, const char *name); const char * json_object_get_string (const JSON_Object *object, const char *name); size_t json_object_get_string_len(const JSON_Object *object, const char *name); /* doesn't account for last null character */ JSON_Object * json_object_get_object (const JSON_Object *object, const char *name); JSON_Array * json_object_get_array (const JSON_Object *object, const char *name); double json_object_get_number (const JSON_Object *object, const char *name); /* returns 0 on fail */ int json_object_get_boolean(const JSON_Object *object, const char *name); /* returns -1 on fail */ /* dotget functions enable addressing values with dot notation in nested objects, just like in structs or c++/java/c# objects (e.g. objectA.objectB.value). Because valid names in JSON can contain dots, some values may be inaccessible this way. */ JSON_Value * json_object_dotget_value (const JSON_Object *object, const char *name); const char * json_object_dotget_string (const JSON_Object *object, const char *name); size_t json_object_dotget_string_len(const JSON_Object *object, const char *name); /* doesn't account for last null character */ JSON_Object * json_object_dotget_object (const JSON_Object *object, const char *name); JSON_Array * json_object_dotget_array (const JSON_Object *object, const char *name); double json_object_dotget_number (const JSON_Object *object, const char *name); /* returns 0 on fail */ int json_object_dotget_boolean(const JSON_Object *object, const char *name); /* returns -1 on fail */ /* Functions to get available names */ size_t json_object_get_count (const JSON_Object *object); const char * json_object_get_name (const JSON_Object *object, size_t index); JSON_Value * json_object_get_value_at(const JSON_Object *object, size_t index); JSON_Value * json_object_get_wrapping_value(const JSON_Object *object); /* Functions to check if object has a value with a specific name. Returned value is 1 if object has * a value and 0 if it doesn't. dothas functions behave exactly like dotget functions. */ int json_object_has_value (const JSON_Object *object, const char *name); int json_object_has_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type); int json_object_dothas_value (const JSON_Object *object, const char *name); int json_object_dothas_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type); /* Creates new name-value pair or frees and replaces old value with a new one. * json_object_set_value does not copy passed value so it shouldn't be freed afterwards. */ JSON_Status json_object_set_value(JSON_Object *object, const char *name, JSON_Value *value); JSON_Status json_object_set_string(JSON_Object *object, const char *name, const char *string); JSON_Status json_object_set_string_with_len(JSON_Object *object, const char *name, const char *string, size_t len); /* length shouldn't include last null character */ JSON_Status json_object_set_number(JSON_Object *object, const char *name, double number); JSON_Status json_object_set_boolean(JSON_Object *object, const char *name, int boolean); JSON_Status json_object_set_null(JSON_Object *object, const char *name); /* Works like dotget functions, but creates whole hierarchy if necessary. * json_object_dotset_value does not copy passed value so it shouldn't be freed afterwards. */ JSON_Status json_object_dotset_value(JSON_Object *object, const char *name, JSON_Value *value); JSON_Status json_object_dotset_string(JSON_Object *object, const char *name, const char *string); JSON_Status json_object_dotset_string_with_len(JSON_Object *object, const char *name, const char *string, size_t len); /* length shouldn't include last null character */ JSON_Status json_object_dotset_number(JSON_Object *object, const char *name, double number); JSON_Status json_object_dotset_boolean(JSON_Object *object, const char *name, int boolean); JSON_Status json_object_dotset_null(JSON_Object *object, const char *name); /* Frees and removes name-value pair */ JSON_Status json_object_remove(JSON_Object *object, const char *name); /* Works like dotget function, but removes name-value pair only on exact match. */ JSON_Status json_object_dotremove(JSON_Object *object, const char *key); /* Removes all name-value pairs in object */ JSON_Status json_object_clear(JSON_Object *object); /* *JSON Array */ JSON_Value * json_array_get_value (const JSON_Array *array, size_t index); const char * json_array_get_string (const JSON_Array *array, size_t index); size_t json_array_get_string_len(const JSON_Array *array, size_t index); /* doesn't account for last null character */ JSON_Object * json_array_get_object (const JSON_Array *array, size_t index); JSON_Array * json_array_get_array (const JSON_Array *array, size_t index); double json_array_get_number (const JSON_Array *array, size_t index); /* returns 0 on fail */ int json_array_get_boolean(const JSON_Array *array, size_t index); /* returns -1 on fail */ size_t json_array_get_count (const JSON_Array *array); JSON_Value * json_array_get_wrapping_value(const JSON_Array *array); /* Frees and removes value at given index, does nothing and returns JSONFailure if index doesn't exist. * Order of values in array may change during execution. */ JSON_Status json_array_remove(JSON_Array *array, size_t i); /* Frees and removes from array value at given index and replaces it with given one. * Does nothing and returns JSONFailure if index doesn't exist. * json_array_replace_value does not copy passed value so it shouldn't be freed afterwards. */ JSON_Status json_array_replace_value(JSON_Array *array, size_t i, JSON_Value *value); JSON_Status json_array_replace_string(JSON_Array *array, size_t i, const char* string); JSON_Status json_array_replace_string_with_len(JSON_Array *array, size_t i, const char *string, size_t len); /* length shouldn't include last null character */ JSON_Status json_array_replace_number(JSON_Array *array, size_t i, double number); JSON_Status json_array_replace_boolean(JSON_Array *array, size_t i, int boolean); JSON_Status json_array_replace_null(JSON_Array *array, size_t i); /* Frees and removes all values from array */ JSON_Status json_array_clear(JSON_Array *array); /* Appends new value at the end of array. * json_array_append_value does not copy passed value so it shouldn't be freed afterwards. */ JSON_Status json_array_append_value(JSON_Array *array, JSON_Value *value); JSON_Status json_array_append_string(JSON_Array *array, const char *string); JSON_Status json_array_append_string_with_len(JSON_Array *array, const char *string, size_t len); /* length shouldn't include last null character */ JSON_Status json_array_append_number(JSON_Array *array, double number); JSON_Status json_array_append_boolean(JSON_Array *array, int boolean); JSON_Status json_array_append_null(JSON_Array *array); /* *JSON Value */ JSON_Value * json_value_init_object (void); JSON_Value * json_value_init_array (void); JSON_Value * json_value_init_string (const char *string); /* copies passed string */ JSON_Value * json_value_init_string_with_len(const char *string, size_t length); /* copies passed string, length shouldn't include last null character */ JSON_Value * json_value_init_number (double number); JSON_Value * json_value_init_boolean(int boolean); JSON_Value * json_value_init_null (void); JSON_Value * json_value_deep_copy (const JSON_Value *value); void json_value_free (JSON_Value *value); JSON_Value_Type json_value_get_type (const JSON_Value *value); JSON_Object * json_value_get_object (const JSON_Value *value); JSON_Array * json_value_get_array (const JSON_Value *value); const char * json_value_get_string (const JSON_Value *value); size_t json_value_get_string_len(const JSON_Value *value); /* doesn't account for last null character */ double json_value_get_number (const JSON_Value *value); int json_value_get_boolean(const JSON_Value *value); JSON_Value * json_value_get_parent (const JSON_Value *value); /* Same as above, but shorter */ JSON_Value_Type json_type (const JSON_Value *value); JSON_Object * json_object (const JSON_Value *value); JSON_Array * json_array (const JSON_Value *value); const char * json_string (const JSON_Value *value); size_t json_string_len(const JSON_Value *value); /* doesn't account for last null character */ double json_number (const JSON_Value *value); int json_boolean(const JSON_Value *value); #ifdef __cplusplus } #endif #endif qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_about.cpp000066400000000000000000000155021525155022500235770ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include "jgmanager.h" #include "version.h" #include "qtea_about.h" #include "qtea_paths.h" #include "qtea_window.h" void qtea_show_about(QWidget *parent, const jg_coreinfo_t *info) { QDialog dlg(parent); dlg.setWindowTitle("About"); dlg.setModal(true); // 80 columns of the Licenses tab's font without a horizontal scrollbar. const QFont mono = QFontDatabase::systemFont(QFontDatabase::FixedFont); const int col_w = QFontMetrics(mono).horizontalAdvance(QLatin1Char('M')); // Plus scrollbar, margins and padding. const int target_w = col_w * 84 + 48; dlg.resize(target_w, 560); QVBoxLayout *layout = new QVBoxLayout(&dlg); layout->setContentsMargins(16, 16, 16, 16); QTabWidget *tabs = new QTabWidget(&dlg); QWidget *about_tab = new QWidget; QVBoxLayout *about_layout = new QVBoxLayout(about_tab); // A core with its own icon is the JG project's and takes top billing. // A third-party core (Mednafen) is credited as a linked dependency // rather than implying an official upstream build. bool own_icon = !QTeaWindow::find_core_icon(info->name, 256, false) .isEmpty(); QString icon256 = QTeaWindow::find_core_icon(info->name, 256); if (!icon256.isEmpty()) { QLabel *iconlbl = new QLabel(about_tab); iconlbl->setPixmap(QPixmap(icon256)); iconlbl->setAlignment(Qt::AlignCenter); about_layout->addWidget(iconlbl); } if (own_icon) { QLabel *title = new QLabel( QString::fromUtf8(info->fname), about_tab); QFont titlefont = title->font(); titlefont.setBold(true); titlefont.setPointSize(titlefont.pointSize() + 2); title->setFont(titlefont); title->setAlignment(Qt::AlignCenter); about_layout->addWidget(title); QLabel *version = new QLabel( QString::fromUtf8(info->version), about_tab); version->setAlignment(Qt::AlignCenter); about_layout->addWidget(version); about_layout->addSpacing(20); QLabel *credits = new QLabel( "See the Licenses tab for core licensing information.\n\n" "The Quality Tea Frontend\n" "Licensed under the BSD 3-Clause \"New\" or \"Revised\" License", about_tab); credits->setAlignment(Qt::AlignCenter); about_layout->addWidget(credits); } else { QLabel *title = new QLabel( "The Quality Tea Frontend", about_tab); QFont titlefont = title->font(); titlefont.setBold(true); titlefont.setPointSize(titlefont.pointSize() + 2); title->setFont(titlefont); title->setAlignment(Qt::AlignCenter); about_layout->addWidget(title); QLabel *version = new QLabel(QTEA_VERSION, about_tab); version->setAlignment(Qt::AlignCenter); about_layout->addWidget(version); about_layout->addSpacing(20); QLabel *credits = new QLabel( QString("Linked against %1 %2\n" "See the Licenses tab for licensing information.\n") .arg(QString::fromUtf8(info->fname), QString::fromUtf8(info->version)), about_tab); credits->setAlignment(Qt::AlignCenter); about_layout->addWidget(credits); } QLabel *tagline = new QLabel( "Do try a cup. We find it brightens the room considerably.", about_tab); tagline->setAlignment(Qt::AlignCenter); tagline->setTextFormat(Qt::RichText); about_layout->addWidget(tagline); about_layout->addStretch(); tabs->addTab(about_tab, "About"); // QPlainTextEdit: far lighter than QTextEdit for a large file. QWidget *lic_tab = new QWidget; QVBoxLayout *lic_layout = new QVBoxLayout(lic_tab); lic_layout->setContentsMargins(0, 0, 0, 0); QPlainTextEdit *lic_view = new QPlainTextEdit(lic_tab); lic_view->setReadOnly(true); lic_view->setLineWrapMode(QPlainTextEdit::NoWrap); lic_view->setFont(mono); const std::string lic_path = qtea::paths::find_data_file("LICENSES"); if (lic_path.empty()) { lic_view->setPlainText("LICENSES file not found."); } else { QFile f(QString::fromStdString(lic_path)); if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream in(&f); // Not the system locale on Windows. in.setEncoding(QStringConverter::Utf8); lic_view->setPlainText(in.readAll()); lic_view->moveCursor(QTextCursor::Start); } else { lic_view->setPlainText( QString("Could not open %1: %2") .arg(QString::fromStdString(lic_path), f.errorString())); } } lic_layout->addWidget(lic_view); tabs->addTab(lic_tab, "Licenses"); layout->addWidget(tabs); QDialogButtonBox *bb = new QDialogButtonBox(QDialogButtonBox::Ok, &dlg); QObject::connect(bb, &QDialogButtonBox::accepted, &dlg, &QDialog::accept); layout->addWidget(bb); dlg.exec(); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_about.h000066400000000000000000000035411525155022500232440ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once class QWidget; // Modal About dialog, two tabs: About (core name, version, credits, // tagline) and Licenses (the LICENSES file, found relative to the binary // with a $QTEA_DATAROOTDIR fallback). Blocks until closed. Pure UI: the // caller pauses and resumes emulation if it needs to. void qtea_show_about(QWidget *parent, const jg_coreinfo_t *info); qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_archive.cpp000066400000000000000000000157651525155022500241210ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_archive.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "logdriver.h" #include "qtea_paths.h" namespace qtea::archive { namespace { // Per archive_read_open_filename(3). constexpr size_t BLOCK_SIZE = 10240; constexpr size_t CHUNK_SIZE = 256 * 1024; std::string lower_ext(const std::string &path) { std::string ext = std::filesystem::path(path).extension().string(); std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return std::tolower(c); }); return ext; } // `struct archive` elaborated: unqualified it is this namespace. Null with // the reason logged. format_all leaves out raw, which carries .gz and // friends. struct archive *open_read(const char *path) { struct archive *a = archive_read_new(); if (!a) { return nullptr; } archive_read_support_format_all(a); archive_read_support_format_raw(a); archive_read_support_filter_all(a); if (archive_read_open_filename(a, qtea::paths::long_path(path).c_str(), BLOCK_SIZE) != ARCHIVE_OK) { const char *err = archive_error_string(a); LogDriver::log(LogLevel::Error, std::string("Could not open archive: ") + (err ? err : "unknown error")); archive_read_free(a); return nullptr; } return a; } void close_read(struct archive *a) { archive_read_close(a); archive_read_free(a); } // The current entry. Its size is a reserve hint only; directly-compressed // files report none. bool read_current(struct archive *a, struct archive_entry *entry, std::vector &out) { if (archive_entry_size_is_set(entry)) { const la_int64_t size = archive_entry_size(entry); if (size > 0) { out.reserve(static_cast(size)); } } std::vector chunk(CHUNK_SIZE); for (;;) { const la_ssize_t got = archive_read_data(a, chunk.data(), chunk.size()); if (got == 0) { return true; } if (got < 0) { return false; } out.insert(out.end(), chunk.begin(), chunk.begin() + got); } } } // namespace const std::set &extensions() { static const std::set exts = { ".zip", ".7z", ".rar", ".tar", ".tgz", ".gz", ".bz2", ".xz", ".zst" }; return exts; } std::string raw_entry_name(const std::string &archive_path) { return std::filesystem::path(archive_path).stem().string(); } bool read_entry(const char *archive_path, const std::string &entry_name, std::vector &out) { out.clear(); struct archive *a = open_read(archive_path); if (!a) { return false; } struct archive_entry *entry = nullptr; while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { const char *pathname = archive_entry_pathname(entry); if (!pathname || entry_name != pathname) { continue; } if (!read_current(a, entry, out)) { out.clear(); } break; } close_read(a); if (out.empty()) { LogDriver::log(LogLevel::Error, "Could not read from archive: " + entry_name); return false; } return true; } bool select_entry(const char *archive_path, std::string &entry_name, const std::set &valid_exts) { struct archive *a = open_read(archive_path); if (!a) { return false; } // Filtered by the extensions the core supports. std::vector candidates; struct archive_entry *entry = nullptr; while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { const char *pathname = archive_entry_pathname(entry); if (!pathname) { continue; } if (std::string(pathname) == RAW_ENTRY && !archive_entry_size_is_set(entry)) { candidates = { pathname }; break; } if (valid_exts.count(lower_ext(pathname))) { candidates.emplace_back(pathname); } } close_read(a); if (candidates.empty()) { return false; } if (candidates.size() == 1) { entry_name = candidates.front(); return true; } QDialog dlg(QApplication::activeWindow()); dlg.setWindowTitle("Load from Archive"); dlg.setModal(true); dlg.resize(420, 260); QVBoxLayout *layout = new QVBoxLayout(&dlg); QListWidget *list = new QListWidget(&dlg); for (const std::string &c : candidates) { list->addItem(QString::fromStdString(c)); } list->setCurrentRow(0); layout->addWidget(list); QDialogButtonBox *bb = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dlg); QObject::connect(bb, &QDialogButtonBox::accepted, &dlg, &QDialog::accept); QObject::connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); layout->addWidget(bb); QObject::connect(list, &QListWidget::itemDoubleClicked, &dlg, &QDialog::accept); if (dlg.exec() != QDialog::Accepted) { return false; } QListWidgetItem *sel = list->currentItem(); if (!sel) { return false; } entry_name = sel->text().toStdString(); return true; } } // namespace qtea::archive qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_archive.h000066400000000000000000000054651525155022500235620ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include #include #include // Archive access for the loading pipeline, on libarchive. A directly // compressed file (.gz and friends) appears as one entry named "data". namespace qtea::archive { // Every extension treated as a container, lowercase and dotted. The one // list behind the file filter, read_one() and detection, so they agree. const std::set &extensions(); // libarchive's name for the single entry of a directly-compressed file. constexpr const char *RAW_ENTRY = "data"; // The name to identify such a file by: the archive's own, minus the // compression suffix, so "foo.nes.gz" is "foo.nes" for detection and // saves rather than "data". std::string raw_entry_name(const std::string &archive_path); // One named entry into `out`. False if it is missing, empty or unreadable. bool read_entry(const char *archive_path, const std::string &entry_name, std::vector &out); // Offer the archive's media candidates, filtered by `valid_exts` (lowercase // dotted, e.g. ".nes"). On success writes the chosen entry into `entry_name`. // False if cancelled, empty, or no candidates. bool select_entry(const char *archive_path, std::string &entry_name, const std::set &valid_exts); } // namespace qtea::archive qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_bios.cpp000066400000000000000000000303631525155022500234230ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_bios.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "jgmanager.h" #include "hasher.h" #include "logdriver.h" #include "setmanager.h" std::vector qtea_bios_check(JGManager &jgm) { std::vector result; size_t num = 0; jg_biosinfo_t *list = jgm.get_bioslist(&num); if (!list || !num) { return result; } const std::string &biospath = jgm.get_biospath(); result.reserve(num); for (size_t i = 0; i < num; ++i) { BiosStatus bs; bs.fname = list[i].fname ? list[i].fname : ""; bs.desc = list[i].desc ? list[i].desc : ""; bs.expected_md5 = list[i].md5 ? list[i].md5 : ""; bs.required = list[i].required != 0; bs.group = list[i].group; std::string fullpath = biospath + "/" + bs.fname; std::error_code ec; if (!std::filesystem::exists(fullpath, ec)) { bs.state = BiosStatus::Missing; } else { std::ifstream f(fullpath, std::ios::binary); if (!f.is_open()) { bs.state = BiosStatus::Missing; } else { f.seekg(0, std::ios::end); auto sz = f.tellg(); f.seekg(0, std::ios::beg); if (sz <= 0) { bs.state = BiosStatus::Missing; } else { std::vector data(static_cast(sz)); f.read(reinterpret_cast(data.data()), sz); bs.actual_md5 = Hasher::md5(data.data(), data.size()); if (!bs.expected_md5.empty() && bs.actual_md5 != bs.expected_md5) { bs.state = BiosStatus::Mismatch; } else { bs.state = BiosStatus::Found; } } } } result.push_back(std::move(bs)); } return result; } int qtea_bios_count_missing(const std::vector &entries) { // Standalone entries count one each; a group is one problem when no // member satisfies it. int missing = 0; for (const auto &e : entries) { if (e.required && e.group == 0 && e.state != BiosStatus::Found) { ++missing; } } std::map group_satisfied; std::map group_has_required; for (const auto &e : entries) { if (e.group == 0) continue; if (e.required) { group_has_required[e.group] = true; } if (e.state == BiosStatus::Found) { group_satisfied[e.group] = true; } } for (const auto &[gid, has_req] : group_has_required) { if (has_req && !group_satisfied[gid]) { ++missing; } } return missing; } int qtea_bios_count_missing(JGManager &jgm) { auto entries = qtea_bios_check(jgm); return qtea_bios_count_missing(entries); } QTeaBiosDialog::QTeaBiosDialog(JGManager &jgm, SettingManager &setmgr, QWidget *parent) : QDialog(parent), jgm_(jgm), setmgr_(setmgr) { setWindowTitle("BIOS / Firmware"); setMinimumSize(560, 400); auto *vbox = new QVBoxLayout(this); path_label_ = new QLabel(this); path_label_->setTextInteractionFlags(Qt::TextSelectableByMouse); path_label_->setWordWrap(true); vbox->addWidget(path_label_); tree_ = new QTreeWidget(this); tree_->setHeaderLabels({"Filename", "Description", "Required", "Status"}); tree_->setRootIsDecorated(false); tree_->setSelectionMode(QAbstractItemView::SingleSelection); tree_->setAlternatingRowColors(true); tree_->header()->setStretchLastSection(false); tree_->header()->setSectionResizeMode(1, QHeaderView::Stretch); vbox->addWidget(tree_); summary_label_ = new QLabel(this); vbox->addWidget(summary_label_); auto *hbox = new QHBoxLayout(); hbox->addStretch(); install_btn_ = new QPushButton("Install...", this); install_btn_->setToolTip( "Copy a BIOS file into the expected location. " "Select a missing entry above, then click Install."); connect(install_btn_, &QPushButton::clicked, this, &QTeaBiosDialog::on_install); hbox->addWidget(install_btn_); auto *close_btn = new QPushButton("Close", this); connect(close_btn, &QPushButton::clicked, this, &QDialog::close); hbox->addWidget(close_btn); vbox->addLayout(hbox); populate(); } void QTeaBiosDialog::populate() { tree_->clear(); entries_ = qtea_bios_check(jgm_); const std::string &biospath = jgm_.get_biospath(); path_label_->setText( QString("BIOS directory: %1") .arg(QString::fromStdString(biospath))); if (entries_.empty()) { summary_label_->setText("This core does not require any BIOS files."); install_btn_->setEnabled(false); return; } // A satisfied group suppresses per-member status: twelve MD5 // alternatives for one filename would report eleven mismatches. std::map group_has_found; std::map group_all_missing; for (const auto &e : entries_) { if (e.group == 0) continue; if (e.state == BiosStatus::Found) { group_has_found[e.group] = true; } if (group_all_missing.find(e.group) == group_all_missing.end()) { group_all_missing[e.group] = true; } if (e.state != BiosStatus::Missing) { group_all_missing[e.group] = false; } } // Grouped entries get a parent header. std::map group_parents; for (size_t i = 0; i < entries_.size(); ++i) { const auto &bs = entries_[i]; QTreeWidgetItem *parent_item = nullptr; if (bs.group > 0) { auto it = group_parents.find(bs.group); if (it == group_parents.end()) { auto *gi = new QTreeWidgetItem(tree_); gi->setText(0, QString::fromStdString(bs.fname)); gi->setText(1, "Alternatives (one required)"); gi->setText(2, bs.required ? "Yes" : "No"); if (group_has_found[bs.group]) { gi->setText(3, "Found"); } else if (group_all_missing[bs.group]) { gi->setText(3, "Missing"); } else { gi->setText(3, "Mismatch"); } gi->setFirstColumnSpanned(false); gi->setFlags(gi->flags() & ~Qt::ItemIsSelectable); gi->setExpanded(true); group_parents[bs.group] = gi; parent_item = gi; } else { parent_item = it->second; } } QTreeWidgetItem *item; if (parent_item) { item = new QTreeWidgetItem(parent_item); } else { item = new QTreeWidgetItem(tree_); } // For on_install. item->setData(0, Qt::UserRole, static_cast(i)); bool suppress = bs.group > 0 && group_has_found[bs.group] && bs.state != BiosStatus::Found; refresh_item(item, bs, suppress); } tree_->resizeColumnToContents(0); tree_->resizeColumnToContents(2); tree_->resizeColumnToContents(3); int nmissing = qtea_bios_count_missing(entries_); if (nmissing == 0) { summary_label_->setText("All required BIOS files are present."); } else { summary_label_->setText( QString("%1 required BIOS file%2 missing or mismatched.") .arg(nmissing) .arg(nmissing == 1 ? " is" : "s are")); } install_btn_->setEnabled(true); } void QTeaBiosDialog::refresh_item(QTreeWidgetItem *item, const BiosStatus &bs, bool suppress_status) { item->setText(0, QString::fromStdString(bs.fname)); item->setText(1, QString::fromStdString(bs.desc)); item->setText(2, bs.required ? "Yes" : "No"); if (suppress_status) { item->setText(3, QString()); return; } switch (bs.state) { case BiosStatus::Found: item->setText(3, "Found"); break; case BiosStatus::Mismatch: item->setText(3, "Mismatch"); item->setToolTip(3, QString("Expected: %1\nActual: %2") .arg(QString::fromStdString(bs.expected_md5)) .arg(QString::fromStdString(bs.actual_md5))); break; case BiosStatus::Missing: item->setText(3, "Missing"); break; } } void QTeaBiosDialog::on_install() { QTreeWidgetItem *sel = tree_->currentItem(); if (!sel) { QMessageBox::information(this, "Install BIOS", "Select a BIOS entry from the list first."); return; } QVariant v = sel->data(0, Qt::UserRole); if (!v.isValid()) { QMessageBox::information(this, "Install BIOS", "Select a specific BIOS file entry, not a group header."); return; } int idx = v.toInt(); if (idx < 0 || idx >= static_cast(entries_.size())) { return; } const BiosStatus &bs = entries_[idx]; // A filter, even permissive: the GTK and portal backends don't all cope // with the default empty one. QString title = QString("Select %1").arg(QString::fromStdString(bs.fname)); QString filename = QFileDialog::getOpenFileName(this, title, QString::fromStdString(setmgr_.get_lastdir(LASTDIR_BIOS)), "All Files (*)"); if (filename.isEmpty()) { return; } setmgr_.set_lastdir(LASTDIR_BIOS, filename.toStdString()); // Copied in under the expected filename; an unmakeable directory // surfaces as the copy error. const std::string &biospath = jgm_.get_biospath(); std::error_code ec; std::filesystem::create_directories(biospath, ec); std::string dest = biospath + "/" + bs.fname; std::filesystem::copy_file( filename.toStdString(), dest, std::filesystem::copy_options::overwrite_existing, ec); if (ec) { QMessageBox::warning(this, "Install BIOS", QString("Failed to copy file: %1") .arg(QString::fromStdString(ec.message()))); return; } LogDriver::log(LogLevel::Info, "Installed BIOS: " + bs.fname + " -> " + dest); // Wholesale, for group-level changes. populate(); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_bios.h000066400000000000000000000064521525155022500230720ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once // BIOS/firmware dialog and status checking. The dialog lists every // jg_get_bioslist() entry against what is on disk under the core's BIOS // path, and can install a missing file from a picker. The free functions // are shared with the startup OSD check in main(). #include #include #include class QLabel; class QPushButton; class QTreeWidget; class QTreeWidgetItem; class JGManager; class SettingManager; // Per-entry status, from disk state. struct BiosStatus { std::string fname; // expected filename std::string desc; // human-readable description std::string expected_md5; bool required; // required for basic functionality unsigned group; // group ID (0 = standalone) enum State { Found, Mismatch, Missing }; State state; std::string actual_md5; // when the file exists }; // One per bioslist entry, checked against get_biospath(). std::vector qtea_bios_check(JGManager &jgm); // Required entries missing or mismatched; one member satisfies a group. int qtea_bios_count_missing(const std::vector &entries); int qtea_bios_count_missing(JGManager &jgm); class QTeaBiosDialog : public QDialog { Q_OBJECT public: QTeaBiosDialog(JGManager &jgm, SettingManager &setmgr, QWidget *parent = nullptr); private slots: void on_install(); private: void populate(); void refresh_item(QTreeWidgetItem *item, const BiosStatus &bs, bool suppress_status = false); JGManager &jgm_; SettingManager &setmgr_; QTreeWidget *tree_{nullptr}; QLabel *path_label_{nullptr}; QLabel *summary_label_{nullptr}; QPushButton *install_btn_{nullptr}; // Parallel to the tree's items. std::vector entries_; }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_cheats.cpp000066400000000000000000000337121525155022500237370ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_cheats.h" #include #include #include #include #include #include #include #include #include #include #include namespace { // One code per line, trimmed, blanks dropped. std::vector codes_from_text(const QString &text) { std::vector out; const QStringList lines = text.split('\n', Qt::SkipEmptyParts); out.reserve(lines.size()); for (const QString &line : lines) { const QString trimmed = line.trimmed(); if (!trimmed.isEmpty()) { out.emplace_back(trimmed.toStdString()); } } return out; } // Inverse, for the editor. QString text_from_codes(const std::vector &codes) { QStringList lines; lines.reserve(static_cast(codes.size())); for (const std::string &c : codes) { lines.append(QString::fromStdString(c)); } return lines.join('\n'); } } // namespace QTeaCheatsDialog::QTeaCheatsDialog(JGManager &jgm, CheatManager &chtmgr, SettingManager &setmgr, QWidget *parent) : QDialog(parent), jgm_(jgm), chtmgr_(chtmgr), setmgr_(setmgr) { setWindowTitle(QString("Cheats: %1") .arg(QString::fromStdString(jgm_.get_gamename()))); resize(624, 540); build_ui(); rebuild_list(); load_detail(); } void QTeaCheatsDialog::build_ui() { QVBoxLayout *outer = new QVBoxLayout(this); chk_enabled_ = new QCheckBox("Enable Cheats", this); chk_enabled_->setChecked(chtmgr_.gate()); chk_enabled_->setToolTip( "Globally enable or disable cheats. When disabled, the list " "remains editable but no cheats reach the running game."); connect(chk_enabled_, &QCheckBox::toggled, this, &QTeaCheatsDialog::on_enabled_toggled); list_ = new QListWidget(this); list_->setSelectionMode(QAbstractItemView::SingleSelection); // Not editable in place; the detail editor is. list_->setEditTriggers(QAbstractItemView::NoEditTriggers); connect(list_, &QListWidget::itemSelectionChanged, this, &QTeaCheatsDialog::on_selection_changed); connect(list_, &QListWidget::itemChanged, this, &QTeaCheatsDialog::on_item_changed); QHBoxLayout *list_buttons = new QHBoxLayout; btn_add_ = new QPushButton("Add", this); btn_remove_ = new QPushButton("Remove", this); btn_up_ = new QPushButton("Up", this); btn_down_ = new QPushButton("Down", this); list_buttons->addWidget(btn_add_); list_buttons->addWidget(btn_remove_); list_buttons->addStretch(); list_buttons->addWidget(btn_up_); list_buttons->addWidget(btn_down_); connect(btn_add_, &QPushButton::clicked, this, &QTeaCheatsDialog::on_add_clicked); connect(btn_remove_, &QPushButton::clicked, this, &QTeaCheatsDialog::on_remove_clicked); connect(btn_up_, &QPushButton::clicked, this, &QTeaCheatsDialog::on_move_up_clicked); connect(btn_down_, &QPushButton::clicked, this, &QTeaCheatsDialog::on_move_down_clicked); QGroupBox *detail_box = new QGroupBox("Selected Cheat", this); QFormLayout *detail = new QFormLayout(detail_box); desc_edit_ = new QLineEdit(detail_box); desc_edit_->setPlaceholderText("Description"); detail->addRow("Description:", desc_edit_); codes_edit_ = new QPlainTextEdit(detail_box); codes_edit_->setPlaceholderText("One code per line"); codes_edit_->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); // Fixed, so the list keeps most of the dialog. codes_edit_->setFixedHeight(120); detail->addRow("Codes:", codes_edit_); // Inside the group box: actions on this edit, not the dialog. QHBoxLayout *detail_buttons = new QHBoxLayout; btn_dapply_ = new QPushButton("Apply", detail_box); btn_revert_ = new QPushButton("Revert", detail_box); btn_dapply_->setToolTip("Commit edits to the cheat list"); btn_revert_->setToolTip("Discard edits and restore from the cheat list"); btn_dapply_->setEnabled(false); btn_revert_->setEnabled(false); detail_buttons->addStretch(); detail_buttons->addWidget(btn_dapply_); detail_buttons->addWidget(btn_revert_); detail->addRow(detail_buttons); connect(btn_dapply_, &QPushButton::clicked, this, &QTeaCheatsDialog::on_apply_clicked); connect(btn_revert_, &QPushButton::clicked, this, &QTeaCheatsDialog::on_revert_clicked); // Enter and focus loss; textChanged would hit the model per keystroke. connect(desc_edit_, &QLineEdit::editingFinished, this, &QTeaCheatsDialog::on_desc_edited); // QPlainTextEdit has no editingFinished; suppressed while loading. connect(codes_edit_, &QPlainTextEdit::textChanged, this, &QTeaCheatsDialog::on_codes_edited); QHBoxLayout *bottom = new QHBoxLayout; btn_load_ = new QPushButton("Load...", this); btn_save_ = new QPushButton("Save...", this); btn_close_ = new QPushButton("Close", this); btn_load_->setToolTip("Read a cheat list from a JSON file"); btn_save_->setToolTip("Write the cheat list to a JSON file"); bottom->addWidget(btn_load_); bottom->addWidget(btn_save_); bottom->addStretch(); bottom->addWidget(btn_close_); connect(btn_load_, &QPushButton::clicked, this, &QTeaCheatsDialog::on_load_clicked); connect(btn_save_, &QPushButton::clicked, this, &QTeaCheatsDialog::on_save_clicked); connect(btn_close_, &QPushButton::clicked, this, &QDialog::close); outer->addWidget(chk_enabled_); outer->addWidget(list_, /*stretch=*/1); outer->addLayout(list_buttons); outer->addWidget(detail_box); outer->addLayout(bottom); } void QTeaCheatsDialog::rebuild_list() { suppress_signals_ = true; const int prev_row = list_->currentRow(); list_->clear(); const auto &cheats = chtmgr_.cheats(); for (size_t i = 0; i < cheats.size(); ++i) { const Cheat &c = cheats[i]; QListWidgetItem *item = new QListWidgetItem( c.desc.empty() ? QString("(unnamed cheat)") : QString::fromStdString(c.desc), list_); item->setFlags(item->flags() | Qt::ItemIsUserCheckable); item->setCheckState(c.enabled ? Qt::Checked : Qt::Unchecked); } // Selection restored, clamped after a remove. if (!cheats.empty()) { int row = prev_row; if (row < 0) row = 0; if (row >= static_cast(cheats.size())) row = static_cast(cheats.size()) - 1; list_->setCurrentRow(row); } suppress_signals_ = false; } void QTeaCheatsDialog::load_detail() { suppress_signals_ = true; const int row = current_row(); const auto &cheats = chtmgr_.cheats(); if (row < 0 || row >= static_cast(cheats.size())) { desc_edit_->clear(); codes_edit_->clear(); desc_edit_->setEnabled(false); codes_edit_->setEnabled(false); btn_remove_->setEnabled(false); btn_up_->setEnabled(false); btn_down_->setEnabled(false); working_desc_.clear(); working_codes_.clear(); } else { const Cheat &c = cheats[row]; desc_edit_->setText(QString::fromStdString(c.desc)); codes_edit_->setPlainText(text_from_codes(c.codes)); desc_edit_->setEnabled(true); codes_edit_->setEnabled(true); btn_remove_->setEnabled(true); btn_up_->setEnabled(row > 0); btn_down_->setEnabled(row < static_cast(cheats.size()) - 1); working_desc_ = c.desc; working_codes_ = c.codes; } dirty_ = false; update_dirty_buttons(); suppress_signals_ = false; } void QTeaCheatsDialog::update_dirty_buttons() { if (btn_dapply_) btn_dapply_->setEnabled(dirty_); if (btn_revert_) btn_revert_->setEnabled(dirty_); } int QTeaCheatsDialog::current_row() const { return list_ ? list_->currentRow() : -1; } void QTeaCheatsDialog::on_selection_changed() { if (suppress_signals_) return; load_detail(); } void QTeaCheatsDialog::on_item_changed(QListWidgetItem *item) { if (suppress_signals_ || !item) return; // Check state only; rebuild_list()'s setText is suppressed. const int row = list_->row(item); if (row < 0) return; const bool enabled = item->checkState() == Qt::Checked; chtmgr_.set_enabled(row, enabled); // Live, so re-push now. chtmgr_.apply(); } void QTeaCheatsDialog::on_add_clicked() { Cheat c; c.desc = ""; c.enabled = false; chtmgr_.add(std::move(c)); rebuild_list(); list_->setCurrentRow(static_cast(chtmgr_.cheats().size()) - 1); load_detail(); // Dirty from the start; Remove, not Revert, undoes the add. dirty_ = true; update_dirty_buttons(); desc_edit_->setFocus(); } void QTeaCheatsDialog::on_remove_clicked() { const int row = current_row(); if (row < 0) return; chtmgr_.remove(row); rebuild_list(); load_detail(); chtmgr_.apply(); } void QTeaCheatsDialog::on_move_up_clicked() { const int row = current_row(); if (row <= 0) return; Cheat a = chtmgr_.cheats()[row - 1]; Cheat b = chtmgr_.cheats()[row]; chtmgr_.replace(row - 1, std::move(b)); chtmgr_.replace(row, std::move(a)); rebuild_list(); list_->setCurrentRow(row - 1); load_detail(); chtmgr_.apply(); } void QTeaCheatsDialog::on_move_down_clicked() { const int row = current_row(); const int last = static_cast(chtmgr_.cheats().size()) - 1; if (row < 0 || row >= last) return; Cheat a = chtmgr_.cheats()[row]; Cheat b = chtmgr_.cheats()[row + 1]; chtmgr_.replace(row, std::move(b)); chtmgr_.replace(row + 1, std::move(a)); rebuild_list(); list_->setCurrentRow(row + 1); load_detail(); chtmgr_.apply(); } void QTeaCheatsDialog::on_enabled_toggled(bool on) { // The list stays editable either way; edits made while off take // effect on the next apply() after the gate reopens. chtmgr_.set_gate(on); chtmgr_.apply(); } void QTeaCheatsDialog::on_desc_edited() { if (suppress_signals_) return; if (current_row() < 0) return; working_desc_ = desc_edit_->text().toStdString(); dirty_ = true; update_dirty_buttons(); } void QTeaCheatsDialog::on_codes_edited() { if (suppress_signals_) return; if (current_row() < 0) return; working_codes_ = codes_from_text(codes_edit_->toPlainText()); dirty_ = true; update_dirty_buttons(); } void QTeaCheatsDialog::on_apply_clicked() { const int row = current_row(); if (row < 0) return; if (!dirty_) return; // enabled is the list checkbox's; Apply must not silently disable. Cheat updated = chtmgr_.cheats()[row]; updated.desc = working_desc_; updated.codes = working_codes_; chtmgr_.replace(row, std::move(updated)); suppress_signals_ = true; if (QListWidgetItem *it = list_->item(row)) { it->setText(working_desc_.empty() ? QString("(unnamed cheat)") : QString::fromStdString(working_desc_)); } suppress_signals_ = false; dirty_ = false; update_dirty_buttons(); chtmgr_.apply(); } void QTeaCheatsDialog::on_revert_clicked() { load_detail(); } void QTeaCheatsDialog::on_load_clicked() { const QString start_dir = QString::fromStdString( setmgr_.get_lastdir(LASTDIR_CHEAT, jgm_.get_cheatpath())); const QString path = QFileDialog::getOpenFileName( this, "Load Cheats", start_dir, "Cheat Files (*.json);;All Files (*)"); if (path.isEmpty()) return; setmgr_.set_lastdir(LASTDIR_CHEAT, path.toStdString()); if (!chtmgr_.load_path(path.toStdString())) { // load_path logged it and cleared the model. } rebuild_list(); load_detail(); chtmgr_.apply(); } void QTeaCheatsDialog::on_save_clicked() { // What an auto-save would write. const QString default_path = QString::fromStdString( setmgr_.get_lastdir(LASTDIR_CHEAT, jgm_.get_cheatpath())) + "/" + QString::fromStdString(jgm_.get_gamename()) + ".json"; QString path = QFileDialog::getSaveFileName( this, "Save Cheats", default_path, "Cheat Files (*.json);;All Files (*)"); if (path.isEmpty()) return; setmgr_.set_lastdir(LASTDIR_CHEAT, path.toStdString()); if (!path.contains('.')) { path += ".json"; } chtmgr_.save_path(path.toStdString()); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_cheats.h000066400000000000000000000075361525155022500234110ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include "chtmanager.h" #include "jgmanager.h" #include "setmanager.h" class QCheckBox; class QLineEdit; class QListWidget; class QListWidgetItem; class QPlainTextEdit; class QPushButton; // Modeless master/detail dialog for the per-game cheat list. List // operations are live; detail edits buffer into a working copy until Apply, // and changing selection or closing discards them. class QTeaCheatsDialog : public QDialog { Q_OBJECT public: QTeaCheatsDialog(JGManager &jgm, CheatManager &chtmgr, SettingManager &setmgr, QWidget *parent = nullptr); private slots: void on_selection_changed(); void on_item_changed(QListWidgetItem *item); void on_add_clicked(); void on_remove_clicked(); void on_move_up_clicked(); void on_move_down_clicked(); void on_enabled_toggled(bool on); // Fields into the working copy; updates dirty_. void on_desc_edited(); void on_codes_edited(); void on_apply_clicked(); void on_revert_clicked(); void on_load_clicked(); void on_save_clicked(); private: void build_ui(); // Repopulate, keeping the selection where it can. void rebuild_list(); // Selection into the detail widgets, seeding the working copy. void load_detail(); void update_dirty_buttons(); int current_row() const; JGManager &jgm_; CheatManager &chtmgr_; SettingManager &setmgr_; // One item per cheat; the checkstate is Cheat::enabled. QListWidget *list_{nullptr}; QPushButton *btn_add_{nullptr}; QPushButton *btn_remove_{nullptr}; QPushButton *btn_up_{nullptr}; QPushButton *btn_down_{nullptr}; // CheatManager keeps the state; it outlives the dialog. QCheckBox *chk_enabled_{nullptr}; QLineEdit *desc_edit_{nullptr}; QPlainTextEdit *codes_edit_{nullptr}; QPushButton *btn_dapply_{nullptr}; QPushButton *btn_revert_{nullptr}; QPushButton *btn_load_{nullptr}; QPushButton *btn_save_{nullptr}; QPushButton *btn_close_{nullptr}; // While driving widgets programmatically. bool suppress_signals_{false}; // Working copy of the selection; the list checkbox commits `enabled`. std::string working_desc_; std::vector working_codes_; bool dirty_{false}; }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_detect.cpp000066400000000000000000000241761525155022500237440ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_detect.h" #include #include #include #include #include #include #include #include #include #include #include #include "qtea_archive.h" #include "qtea_paths.h" namespace qtea::detect { namespace { struct ExtMap { std::string_view ext; std::string_view sys; }; // As jgrf's detect.c, so both frontends agree. .chd is neogeocd: Geolith is // the only core taking it. constexpr std::array kExtMap{{ {"32x", "32x"}, {"a78", "7800"}, {"bs", "snes"}, {"chd", "neogeocd"}, {"col", "coleco"}, {"dsi", "nds"}, {"fds", "nes"}, {"gb", "gb"}, {"gba", "gba"}, {"gbc", "gb"}, {"gg", "gg"}, {"lnx", "lynx"}, {"myv", "myvision"}, {"md", "md"}, {"n64", "n64"}, {"nds", "nds"}, {"neo", "neogeo"}, {"nes", "nes"}, {"ngc", "ngp"}, {"ngp", "ngp"}, {"nsf", "nes"}, {"pce", "pce"}, {"rom", "coleco"}, {"sfc", "snes"}, {"sg", "sg"}, {"sgx", "pce"}, {"smc", "snes"}, {"sms", "sms"}, {"st", "snes"}, {"vb", "vb"}, {"vec", "vectrex"}, {"ws", "wswan"}, {"wsc", "wswan"}, {"z64", "n64"}, }}; std::string to_lower(std::string_view sv) { std::string out(sv); for (char &c : out) { c = static_cast(std::tolower(static_cast(c))); } return out; } bool mem_contains(const uint8_t *haystack, size_t hlen, const char *needle, size_t nlen) { const uint8_t *nbeg = reinterpret_cast(needle); return std::search(haystack, haystack + hlen, nbeg, nbeg + nlen) != haystack + hlen; } // Disc magics in a raw-sector bin. fcount is its index in the cuesheet: the // Neo Geo CD signature is sought on track 0 only. Empty on no match. std::string inspect_bincue(const std::filesystem::path &bin, unsigned fcount) { std::ifstream f(qtea::paths::long_path(bin.string()), std::ios::binary); if (!f) { return {}; } // In jgrf's order. constexpr const char *kMcdMagic[4] = { "SEGADISCSYSTEM ", "SEGABOOTDISC ", "SEGADISC ", "SEGADATADISC ", }; constexpr size_t kMcdLen = 16; constexpr const char *kPceMagic = "PC Engine CD-ROM SYSTEM"; constexpr size_t kPceLen = 23; constexpr const char *kPcfxMagic = "PC-FX:Hu_CD-ROM "; constexpr size_t kPcfxLen = 16; constexpr const char *kPsxMagic = " Licensed by "; constexpr size_t kPsxLen = 16; constexpr const char *kSsMagic = "SEGA SEGASATURN "; constexpr size_t kSsLen = 16; constexpr const char *kNgcdMagic = "NEO-GEO"; constexpr size_t kNgcdLen = 7; // strlen, not the misleading "// 8" in C std::array buf{}; f.seekg(0x24e0, std::ios::beg); if (f.read(buf.data(), 16) && f.gcount() == 16) { if (std::memcmp(buf.data(), kPsxMagic, kPsxLen) == 0) { return "psx"; } } f.clear(); // a short read sets failbit f.seekg(0, std::ios::beg); // Saturn: offset 0 or 16. if (f.read(buf.data(), 32) && f.gcount() == 32) { if (std::memcmp(buf.data(), kSsMagic, kSsLen) == 0 || std::memcmp(buf.data() + 16, kSsMagic, kSsLen) == 0) { return "ss"; } } f.clear(); f.seekg(0, std::ios::beg); // Mega CD: offset 0 or 16. if (f.read(buf.data(), 32) && f.gcount() == 32) { for (int i = 0; i < 4; ++i) { if (std::memcmp(buf.data(), kMcdMagic[i], kMcdLen) == 0 || std::memcmp(buf.data() + 16, kMcdMagic[i], kMcdLen) == 0) { return "md"; } } } f.clear(); f.seekg(0, std::ios::beg); // Non-overlapping chunks, as jgrf: the magics are sector-aligned. auto stream_search = [&](const char *needle, size_t nlen) -> bool { f.clear(); f.seekg(0, std::ios::beg); std::array chunk{}; while (f.read(reinterpret_cast(chunk.data()), 2048) && f.gcount() == 2048) { if (mem_contains(chunk.data(), 2048, needle, nlen)) { return true; } } return false; }; if (fcount == 0 && stream_search(kNgcdMagic, kNgcdLen)) { return "neogeocd"; } if (stream_search(kPceMagic, kPceLen)) { return "pce"; } if (stream_search(kPcfxMagic, kPcfxLen)) { return "pcfx"; } return {}; } // inspect_bincue on each FILE the cuesheet names, relative to the cue. std::string inspect_cue(const std::filesystem::path &cue) { std::ifstream f(qtea::paths::long_path(cue.string())); if (!f) { return {}; } const std::filesystem::path cuedir = cue.parent_path(); std::string line; unsigned fcount = 0; while (std::getline(f, line)) { if (line.find("FILE") == std::string::npos) { continue; } // First quote opens, last closes, as jgrf. const auto q1 = line.find('"'); if (q1 == std::string::npos) { continue; } const auto q2 = line.rfind('"'); if (q2 == std::string::npos || q2 == q1) { continue; } const std::string binfile = line.substr(q1 + 1, q2 - q1 - 1); const std::filesystem::path binpath = cuedir / binfile; std::string sys = inspect_bincue(binpath, fcount); if (!sys.empty()) { return sys; } ++fcount; } return {}; } // Each cuesheet the playlist names, relative to the m3u. std::string inspect_m3u(const std::filesystem::path &m3u) { std::ifstream f(qtea::paths::long_path(m3u.string())); if (!f) { return {}; } const std::filesystem::path m3udir = m3u.parent_path(); std::string line; while (std::getline(f, line)) { // CRLF. if (!line.empty() && line.back() == '\r') { line.pop_back(); } if (line.empty()) { continue; } const std::filesystem::path cuepath = m3udir / line; std::string sys = inspect_cue(cuepath); if (!sys.empty()) { return sys; } } return {}; } // Extension detection on each member until one matches; nested archives // are not recursed into. `struct archive` elaborated: unqualified it is the // qtea::archive namespace. std::string inspect_archive(const std::filesystem::path &arc) { struct archive *a = archive_read_new(); if (!a) { return {}; } // format_all leaves out raw, which carries .gz and friends. archive_read_support_format_all(a); archive_read_support_format_raw(a); archive_read_support_filter_all(a); if (archive_read_open_filename( a, qtea::paths::long_path(arc.string()).c_str(), 10240) != ARCHIVE_OK) { archive_read_free(a); return {}; } std::string found; struct archive_entry *entry = nullptr; while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { const char *pathname = archive_entry_pathname(entry); if (!pathname) { continue; } // A directly-compressed file goes by its own name minus the suffix. const bool raw = std::string(pathname) == archive::RAW_ENTRY && !archive_entry_size_is_set(entry); Result inner = detect_sys( raw ? archive::raw_entry_name(arc.string()) : pathname); if (inner.ok()) { found = std::move(inner.sys); break; } } archive_read_close(a); archive_read_free(a); return found; } } // namespace Result detect_sys(std::string_view filename) { Result r{}; const std::filesystem::path p{std::string(filename)}; std::string ext = p.extension().string(); if (ext.empty() || ext[0] != '.') { return r; } ext.erase(0, 1); ext = to_lower(ext); // A bare .bin without its cuesheet is meaningless. if (ext == "bin") { return r; } if (ext == "cue") { r.sys = inspect_cue(p); return r; } if (ext == "m3u") { r.sys = inspect_m3u(p); return r; } // .tar.gz matches on .gz; libarchive peels the compression regardless. if (archive::extensions().count("." + ext)) { r.sys = inspect_archive(p); return r; } // Opened by path, never read into memory. if (ext == "chd") { r.path_only = true; } for (const auto &e : kExtMap) { if (ext == e.ext) { r.sys = std::string(e.sys); return r; } } return r; } } // namespace qtea::detect qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_detect.h000066400000000000000000000037061525155022500234050ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include namespace qtea::detect { // sys is the JG subsystem, empty on failure. path_only means the core opens // the file itself; only .chd sets it. struct Result { std::string sys; bool path_only{false}; bool ok() const { return !sys.empty(); } }; // By extension, then by contents for containers and playlists. Never // throws. Result detect_sys(std::string_view filename); } // namespace qtea::detect qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_dipswitches.cpp000066400000000000000000000170111525155022500250100ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 #include #include #include #include #include #include #include #include #include #include "qtea_dipswitches.h" #include "qtea_parse.h" namespace { void rstrip(std::string &s) { while (!s.empty() && std::isspace(static_cast(s.back()))) { s.pop_back(); } } void lstrip(std::string &s) { size_t i = 0; while (i < s.size() && std::isspace(static_cast(s[i]))) { ++i; } s.erase(0, i); } void strip(std::string &s) { lstrip(s); rstrip(s); } // "0 = Off, 1 = On" to labels over [min, max], the raw index where one is // missing. The "N = ..." range form is ignored: DIPs name their values. std::vector parse_opts(const char *opts, int min, int max) { std::vector out; out.resize(max - min + 1); for (int i = 0; i <= max - min; ++i) { out[i] = std::to_string(min + i); } if (!opts) { return out; } std::string s(opts); std::string item; size_t pos = 0; while (pos <= s.size()) { if (pos == s.size() || s[pos] == ',') { strip(item); size_t eq = item.find('='); if (eq != std::string::npos) { std::string num_str = item.substr(0, eq); std::string label = item.substr(eq + 1); strip(num_str); strip(label); int n; if (qtea::parse_int(num_str, n) && n >= min && n <= max) { out[n - min] = label; } } item.clear(); } else { item += s[pos]; } ++pos; } return out; } } // namespace QTeaDipswitchesDialog::QTeaDipswitchesDialog(JGManager &jgm, QWidget *parent) : QDialog(parent), jgm_(jgm) { setWindowTitle(tr("DIP Switches")); setAttribute(Qt::WA_DeleteOnClose); dips_ = jgm_.get_dips(&num_); if (!dips_ || !num_) { auto *layout = new QVBoxLayout(this); layout->addWidget(new QLabel(tr("No DIP switches available for this game."), this)); auto *btns = new QDialogButtonBox(QDialogButtonBox::Close, this); connect(btns, &QDialogButtonBox::rejected, this, &QDialog::reject); layout->addWidget(btns); return; } // For Cancel. snapshot_.reserve(num_); for (size_t i = 0; i < num_; ++i) { snapshot_.push_back(dips_[i].val); } auto *form_host = new QWidget(this); auto *form = new QFormLayout(form_host); form->setContentsMargins(8, 8, 8, 8); combos_.reserve(num_); for (size_t i = 0; i < num_; ++i) { const jg_setting_t &dip = dips_[i]; auto labels = parse_opts(dip.opts, dip.min, dip.max); auto *combo = new QComboBox(form_host); for (size_t j = 0; j < labels.size(); ++j) { combo->addItem(QString::fromStdString(labels[j]), QVariant(static_cast(j) + dip.min)); } // findData: min may be non-zero. int idx = combo->findData(QVariant(dip.val)); if (idx >= 0) { combo->setCurrentIndex(idx); } const int row = static_cast(i); connect(combo, QOverload::of(&QComboBox::currentIndexChanged), this, [this, row, combo](int /*index*/) { QVariant value = combo->currentData(); if (value.isValid()) { on_combo_changed(row, value.toInt()); } }); combos_.push_back(combo); form->addRow(QString::fromUtf8(dip.fname ? dip.fname : dip.name ? dip.name : ""), combo); } auto *scroll = new QScrollArea(this); scroll->setWidget(form_host); scroll->setWidgetResizable(true); scroll->setFrameShape(QFrame::NoFrame); // Arcade cores flag every DIP JG_SETTING_RESTART; one notice, not one // per row. auto *notice = new QLabel( tr("Some DIP switches require a hard reset " "(Emulator > Hard Reset) to take effect."), this); QFont nf = notice->font(); nf.setItalic(true); notice->setFont(nf); notice->setWordWrap(true); auto *btns = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults, this); connect(btns, &QDialogButtonBox::accepted, this, &QTeaDipswitchesDialog::on_accept); connect(btns, &QDialogButtonBox::rejected, this, &QTeaDipswitchesDialog::on_reject); connect(btns->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, this, &QTeaDipswitchesDialog::on_reset_defaults); auto *root = new QVBoxLayout(this); root->addWidget(scroll, /*stretch=*/1); root->addWidget(notice); root->addWidget(btns); resize(420, 380); } void QTeaDipswitchesDialog::refresh_combos() { // Blocked, or refreshing re-fires on_combo_changed. for (size_t i = 0; i < num_ && i < combos_.size(); ++i) { QComboBox *c = combos_[i]; const QSignalBlocker blocker(c); int idx = c->findData(QVariant(dips_[i].val)); if (idx >= 0) { c->setCurrentIndex(idx); } } } void QTeaDipswitchesDialog::on_combo_changed(int row, int value) { if (row < 0 || static_cast(row) >= num_) { return; } dips_[row].val = value; // Live where the core supports it. jgm_.rehash(); } void QTeaDipswitchesDialog::on_reset_defaults() { jgm_.dip_default(); refresh_combos(); } void QTeaDipswitchesDialog::on_accept() { // Already live; unload_game() persists them. accept(); } void QTeaDipswitchesDialog::on_reject() { for (size_t i = 0; i < num_ && i < snapshot_.size(); ++i) { dips_[i].val = snapshot_[i]; } jgm_.rehash(); reject(); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_dipswitches.h000066400000000000000000000045311525155022500244600ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include #include "jgmanager.h" class QComboBox; // Per-game DIP switch dialog. Combos write straight into the core's // jg_setting_t::val; OK keeps that, Cancel reverts to the values at open, // Reset Defaults to the load-time snapshot. unload_game() writes the file. class QTeaDipswitchesDialog : public QDialog { Q_OBJECT public: QTeaDipswitchesDialog(JGManager &jgm, QWidget *parent = nullptr); private: void refresh_combos(); void on_combo_changed(int row, int index); void on_reset_defaults(); void on_accept(); void on_reject(); JGManager &jgm_; // At open, for Cancel. std::vector snapshot_; // The core's array, captured at construction and mutated directly. jg_setting_t *dips_{nullptr}; size_t num_{0}; std::vector combos_; }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_displaylink.h000066400000000000000000000055041525155022500244560ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once // macOS-only vsync pacer on AppKit's CADisplayLink (macOS 14+). // // The macOS GL swap goes through the WindowServer compositor and does not // block on vblank, so unlike Linux and Windows it can't pace the loop. Qt's // fallback is the older CVDisplayLink marshaled to the GUI thread, which // judders in practice. The pacer calls a callback once per refresh; the // window points that at glarea->update(), so paintGL runs once per vsync. // // C++ interface, ObjC++ implementation. Never compiled on non-Apple. #include class QWindow; namespace qtea { class DisplayLinkPacer { public: DisplayLinkPacer(); ~DisplayLinkPacer(); DisplayLinkPacer(const DisplayLinkPacer &) = delete; DisplayLinkPacer &operator=(const DisplayLinkPacer &) = delete; // True only where an AppKit CADisplayLink can be vended (macOS 14+). // False leaves the caller on the self-paced paintGL loop. static bool supported(); // Call `on_vsync` on the main thread once per refresh of `win`'s // display. `win` must be realized. bool start(QWindow *win, std::function on_vsync); // Safe when not started. void stop(); // From the link's reported frame duration, 0 before the first tick. double current_hz() const; private: void *impl_{nullptr}; // ObjC state }; } // namespace qtea qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_displaylink.mm000066400000000000000000000071561525155022500246450ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE. */ // NOTE ON ARC: written for the non-ARC (manual retain/release) build that // Jolly Good's .mm files use. If you ever compile this TU with -fobjc-arc, // drop the explicit retain/release and let ARC manage the link and target. #import "qtea_displaylink.h" #import #import #include #include // Receives the CADisplayLink callback and forwards to the std::function. @interface QTeaDLTarget : NSObject { @public std::function cb; double last_duration; // link.duration, seconds } - (void)tick:(CADisplayLink *)link API_AVAILABLE(macos(14.0)); @end @implementation QTeaDLTarget - (void)tick:(CADisplayLink *)link { last_duration = link.duration; if (cb) { cb(); } } @end namespace qtea { namespace { struct Impl { CADisplayLink *link = nil; QTeaDLTarget *target = nil; }; } // namespace DisplayLinkPacer::DisplayLinkPacer() = default; DisplayLinkPacer::~DisplayLinkPacer() { stop(); } bool DisplayLinkPacer::supported() { if (@available(macOS 14.0, *)) { return true; } return false; } bool DisplayLinkPacer::start(QWindow *win, std::function on_vsync) { stop(); if (!win) { return false; } if (@available(macOS 14.0, *)) { // The backing NSView, valid once the window is realized. NSView *view = reinterpret_cast(win->winId()); if (!view) { return false; } QTeaDLTarget *t = [[QTeaDLTarget alloc] init]; t->cb = std::move(on_vsync); t->last_duration = 0.0; // Follows the view's display (ProMotion, monitor moves), suspends // offscreen. CADisplayLink *l = [view displayLinkWithTarget:t selector:@selector(tick:)]; if (!l) { [t release]; return false; } [l retain]; [l addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; impl_ = new Impl{ l, t }; return true; } return false; } void DisplayLinkPacer::stop() { if (!impl_) { return; } Impl *impl = static_cast(impl_); if (impl->link) { [impl->link invalidate]; [impl->link release]; } if (impl->target) { [impl->target release]; } delete impl; impl_ = nullptr; } double DisplayLinkPacer::current_hz() const { if (!impl_) { return 0.0; } Impl *impl = static_cast(impl_); const double d = impl->target ? impl->target->last_duration : 0.0; return d > 0.0 ? 1.0 / d : 0.0; } } // namespace qtea qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_emulator.cpp000066400000000000000000000232571525155022500243230ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_emulator.h" #include #include #include #include #include #include #include "audiomanager.h" #include "inputmanager.h" #include "jgmanager.h" #include "setmanager.h" #include "videomanager.h" #include "qtea_archive.h" #include "qtea_detect.h" #include "logdriver.h" #include "qtea_paths.h" namespace qtea { std::set collect_extensions(JGManager &jgm) { std::set exts; size_t count = 0; jg_systeminfo_t *syslist = jgm.get_systemlist(&count); if (!syslist) { return exts; } for (size_t i = 0; i < count; ++i) { if (!syslist[i].ext) { continue; } // "col,rom,bin" std::istringstream stream(syslist[i].ext); std::string token; while (std::getline(stream, token, ',')) { token.erase(0, token.find_first_not_of(' ')); token.erase(token.find_last_not_of(' ') + 1); if (token.empty()) { continue; } std::transform(token.begin(), token.end(), token.begin(), [](unsigned char c) { return std::tolower(c); }); exts.insert("." + token); } } return exts; } std::string build_file_filter(JGManager &jgm) { auto media_exts = collect_extensions(jgm); const auto &arc_exts = archive::extensions(); std::set all; all.insert(media_exts.begin(), media_exts.end()); all.insert(arc_exts.begin(), arc_exts.end()); // Cores take carts, discs and tapes. std::string filter = "Software ("; bool first = true; for (const auto &ext : all) { if (!first) { filter += ' '; } filter += '*'; filter += ext; first = false; } filter += ");;All Files (*)"; return filter; } namespace { std::string lower_ext(const std::string &path) { std::string ext = std::filesystem::path(path).extension().string(); std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return std::tolower(c); }); return ext; } // Read into `out`, extracting archives. effective_path names the game and // drives detection: the inner entry for an archive. load_path is a real // file for path-based cores: the archive itself. valid_exts filters archive // contents. A path-only file leaves `out` empty. bool read_one(const std::string &path, std::vector &out, std::string &effective_path, std::string &load_path, const std::set &valid_exts) { out.clear(); effective_path.clear(); load_path.clear(); // The core streams it; a disc image is too large to copy for nothing. if (detect::detect_sys(path).path_only) { effective_path = path; load_path = path; return true; } std::string ext = lower_ext(path); if (archive::extensions().count(ext)) { std::string arcname{}; if (!archive::select_entry(path.c_str(), arcname, valid_exts)) { LogDriver::log(LogLevel::OSD, "No valid files in archive"); return false; } if (!archive::read_entry(path.c_str(), arcname, out)) { LogDriver::log(LogLevel::OSD, "Could not read from archive"); return false; } // A directly-compressed file has no inner name. effective_path = arcname == archive::RAW_ENTRY ? archive::raw_entry_name(path) : arcname; load_path = path; return true; } std::ifstream stream(qtea::paths::long_path(path), std::ios::in | std::ios::binary); if (!stream.is_open()) { return false; } stream.seekg(0, std::ios::end); auto size = stream.tellg(); stream.seekg(0, std::ios::beg); if (size <= 0) { return false; } out.resize(static_cast(size)); stream.read(reinterpret_cast(out.data()), size); stream.close(); effective_path = path; load_path = path; return !out.empty(); } // Every load restarts the session against `sys`. Settings are written // before restart() rebuilds the array and read back after. Input is not // reassigned here: multi-system cores populate inputinfo only during // jg_game_load. bool restart_session(const char *sys, JGManager &jgm, SettingManager &setmgr, AudioManager &audiomgr, VideoManager &videomgr) { jgm.unload_game(); setmgr.write(jgm); if (!jgm.restart(sys)) { LogDriver::log(LogLevel::OSD, "JG restart failed"); return false; } audiomgr.attach(jgm); videomgr.restart(); setmgr.read(jgm); return true; } // Null `sys` detects from the file. bool load_one(const char *filename, const char *sys, std::vector &game, JGManager &jgm, SettingManager &setmgr, AudioManager &audiomgr, VideoManager &videomgr) { if (!filename) { return false; } auto valid_exts = collect_extensions(jgm); std::string effective_path; std::string load_path; if (!read_one(filename, game, effective_path, load_path, valid_exts)) { return false; } // On the inner name: read_one did the archive work. std::string detected; if (!sys) { detected = qtea::detect::detect_sys(effective_path).sys; sys = detected.c_str(); } if (!restart_session(sys, jgm, setmgr, audiomgr, videomgr)) { return false; } jgm.load_game(load_path.c_str(), effective_path.c_str(), game); return jgm.is_loaded(); } } // namespace bool load_files(const std::vector &paths, const char *sys, std::vector> &buffers, JGManager &jgm, SettingManager &setmgr, AudioManager &audiomgr, VideoManager &videomgr, InputManager &inputmgr) { (void)inputmgr; if (paths.empty()) { return false; } if (paths.size() == 1) { buffers.assign(1, std::vector{}); return load_one(paths[0].c_str(), sys, buffers[0], jgm, setmgr, audiomgr, videomgr); } auto valid_exts = collect_extensions(jgm); // Every buffer first, so a bad aux file bails out before touching the // core. buffers.assign(paths.size(), std::vector{}); std::vector effective_paths(paths.size()); std::vector load_paths(paths.size()); for (size_t i = 0; i < paths.size(); ++i) { if (!read_one(paths[i], buffers[i], effective_paths[i], load_paths[i], valid_exts)) { return false; } } // Unless forced, the game decides the system. std::string detected; if (!sys) { detected = qtea::detect::detect_sys(effective_paths.back()).sys; sys = detected.c_str(); } if (!restart_session(sys, jgm, setmgr, audiomgr, videomgr)) { return false; } // After the restart, into the new session. for (size_t i = 0; i + 1 < paths.size(); ++i) { jgm.set_auxinfo(static_cast(i), load_paths[i].c_str(), effective_paths[i].c_str(), buffers[i]); } jgm.load_game(load_paths.back().c_str(), effective_paths.back().c_str(), buffers.back()); return jgm.is_loaded(); } void take_screenshot(const std::string &filename, unsigned default_fbo, JGManager &jgm, VideoManager &videomgr) { std::string path = filename; if (path.empty()) { auto now = std::chrono::system_clock::now(); auto msecs = std::chrono::duration_cast( now.time_since_epoch()).count(); path = jgm.get_shotpath() + "/" + std::to_string(msecs) + ".png"; } videomgr.set_default_fbo(default_fbo); videomgr.screenshot(path); LogDriver::log(LogLevel::OSD, "Screenshot Saved"); } } // namespace qtea qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_emulator.h000066400000000000000000000063301525155022500237610ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once // Multi-manager coordination sequences, as free functions. The window // decides when to trigger one; the sequence lives here. No globals, no Qt. #include #include #include #include class AudioManager; class CheatManager; class InputManager; class JGManager; class SettingManager; class VideoManager; namespace qtea { // Every extension the core supports across its systems, deduplicated and // lowercased with leading dots. std::set collect_extensions(JGManager &jgm); // QFileDialog filter: core media, archive wrappers, "All Files". std::string build_file_filter(JGManager &jgm); // Load a game, extracting archives, in jgrf ordering: aux slots first, the // game last. Every load restarts the session against `sys`, or the // subsystem detected from the game when null. As jgrf, an archive becomes // gameinfo.path for path-based cores while the inner entry drives // detection and save naming. The core holds pointers into the buffers, so // they must outlive the session. On success the caller still needs // setup_audio(), setup_video(), pause(false) and reset(2). bool load_files(const std::vector &paths, const char *sys, std::vector> &buffers, JGManager &jgm, SettingManager &setmgr, AudioManager &audiomgr, VideoManager &videomgr, InputManager &inputmgr); // An empty filename writes /.png. The caller holds the GL // context. void take_screenshot(const std::string &filename, unsigned default_fbo, JGManager &jgm, VideoManager &videomgr); } // namespace qtea qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_glarea.cpp000066400000000000000000000135331525155022500237220ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_window.h" #include #include #include #include #include #include #include #include #include #include "inputmanager.h" #include "qtea_inputcodes.h" #include "jgmanager.h" #include "setmanager.h" #include "videomanager.h" QTeaGlArea::QTeaGlArea(VideoManager &videomgr, InputManager &inputmgr, SettingManager &setmgr, JGManager &jgm) : QOpenGLWindow(), videomgr_(videomgr), inputmgr_(inputmgr), setmgr_(setmgr), jgm_(&jgm) { } float QTeaGlArea::pixel_ratio() const { return static_cast(devicePixelRatio()); } void QTeaGlArea::initializeGL() { videomgr_.renderer_init(); videomgr_.set_dpiscale(pixel_ratio()); videomgr_.resize(width(), height()); } void QTeaGlArea::paintGL() { // Self-paced, this steps the core and re-arms, paced by the blocking // swap. Under a display link it only renders: the link already stepped, // and re-arming would hand pacing to Qt. if (driving_ && self_paced_ && frame_cb_) { frame_cb_(); } videomgr_.set_default_fbo(defaultFramebufferObject()); videomgr_.render(); if (driving_ && self_paced_) { update(); } } void QTeaGlArea::resizeGL(int w, int h) { videomgr_.set_dpiscale(pixel_ratio()); videomgr_.resize(w, h); } void QTeaGlArea::mousePressEvent(QMouseEvent *e) { const int code = qtea::input::mouse_keycode(e->button()); if (code) { inputmgr_.event(code, true); } e->accept(); } void QTeaGlArea::mouseReleaseEvent(QMouseEvent *e) { const int code = qtea::input::mouse_keycode(e->button()); if (code) { inputmgr_.event(code, false); } e->accept(); } void QTeaGlArea::mouseMoveEvent(QMouseEvent *e) { int xc, yc; videomgr_.get_scaled_coords(e->position().x(), e->position().y(), &xc, &yc); inputmgr_.event(xc, yc); if (e->buttons()) { // Re-send the button state while dragging. Qt::MouseButton b = Qt::NoButton; if (e->buttons() & Qt::LeftButton) b = Qt::LeftButton; else if (e->buttons() & Qt::RightButton) b = Qt::RightButton; else if (e->buttons() & Qt::MiddleButton) b = Qt::MiddleButton; const int code = qtea::input::mouse_keycode(b); if (code) { inputmgr_.event(code, true); } } e->accept(); } void QTeaGlArea::keyPressEvent(QKeyEvent *e) { // As QTeaWindow's, for platforms routing keys to the embedded QWindow. if (!e->isAutoRepeat()) { inputmgr_.event(e->key(), true); if (jgm_->is_loaded()) { inputmgr_.hk_events(); } } QOpenGLWindow::keyPressEvent(e); } void QTeaGlArea::keyReleaseEvent(QKeyEvent *e) { if (!e->isAutoRepeat()) { inputmgr_.event(e->key(), false); if (jgm_->is_loaded()) { inputmgr_.hk_events(); } } QOpenGLWindow::keyReleaseEvent(e); } bool QTeaGlArea::event(QEvent *e) { switch (e->type()) { case QEvent::Enter: if (inputmgr_.get_lightgun()) { setCursor(setmgr_.get_setting("m_hidecrosshair")->val ? Qt::BlankCursor : Qt::CrossCursor); } else if (setmgr_.get_setting("m_hidecursor")->val) { setCursor(Qt::BlankCursor); } break; case QEvent::Leave: unsetCursor(); break; case QEvent::DragEnter: { // On X11 these don't reach the containing QMainWindow. QDragEnterEvent *de = static_cast(e); if (de->mimeData() && de->mimeData()->hasUrls()) { de->acceptProposedAction(); return true; } break; } case QEvent::Drop: { QDropEvent *de = static_cast(e); if (de->mimeData() && de->mimeData()->hasUrls()) { const QList urls = de->mimeData()->urls(); if (!urls.isEmpty()) { emit file_dropped(urls.first().toLocalFile()); } de->acceptProposedAction(); return true; } break; } default: break; } return QOpenGLWindow::event(e); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_inputcodes.h000066400000000000000000000050761525155022500243140ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include // Mouse buttons reach InputManager as keycodes. They are part of the // input.ini format, so changing one invalidates saved bindings. namespace qtea::input { // [BASE + 1, BASE + 20], above every Qt::Key_*. constexpr int MOUSE_CODE_BASE = 1000; constexpr int MOUSE_CODE_LAST = MOUSE_CODE_BASE + 20; // 0 for a button the frontend doesn't bind. constexpr int mouse_keycode(Qt::MouseButton b) { switch (b) { case Qt::LeftButton: return MOUSE_CODE_BASE + 1; case Qt::RightButton: return MOUSE_CODE_BASE + 2; case Qt::MiddleButton: return MOUSE_CODE_BASE + 3; case Qt::BackButton: return MOUSE_CODE_BASE + 4; case Qt::ForwardButton: return MOUSE_CODE_BASE + 5; case Qt::TaskButton: return MOUSE_CODE_BASE + 6; default: return 0; } } constexpr bool is_mouse_keycode(int code) { return code > MOUSE_CODE_BASE && code <= MOUSE_CODE_LAST; } // 1-based, for "Mouse 1". constexpr int mouse_button_number(int code) { return code - MOUSE_CODE_BASE; } } // namespace qtea::input qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_macos.h000066400000000000000000000037031525155022500232340ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once namespace qtea { // Name the application menu after the core. AppKit and Qt both take the // menu bar's application name from the main bundle's CFBundleName, which // the plist fills from the core's .desktop Name, the jgrf plugin id. The // in-memory info dictionary is mutable, so the core's fname replaces it // before NSApplication is created. Call before constructing QApplication. void macos_set_app_name(const char *name); } // namespace qtea qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_macos.mm000066400000000000000000000041621525155022500234160ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_macos.h" #import namespace qtea { void macos_set_app_name(const char *name) { if (!name || !*name) { return; } // Returned as NSDictionary, but it is the mutable dictionary CFBundle // built from the plist; there is no public setter. NSMutableDictionary *info = (NSMutableDictionary *) [[NSBundle mainBundle] infoDictionary]; if (![info isKindOfClass:[NSMutableDictionary class]]) { return; } NSString *ns = [NSString stringWithUTF8String:name]; info[@"CFBundleName"] = ns; info[@"CFBundleDisplayName"] = ns; } } // namespace qtea qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_main.cpp000066400000000000000000000211731525155022500234120ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 #include #include #include #include #include #include #include #include "audiomanager.h" #include "chtmanager.h" #include "inputmanager.h" #include "jgmanager.h" #include "setmanager.h" #include "videomanager.h" #include "qtea_detect.h" #include "qtea_bios.h" #include "qtea_emulator.h" #include "qtea_theme.h" #include "qtea_window.h" #ifdef __APPLE__ #include "qtea_macos.h" #endif #include "uiadapter.h" #include "logdriver.h" #include "version.h" int main(int argc, char *argv[]) { // Before Qt: the settings decide QSurfaceFormat, which precedes // QApplication. Positional args as jgrf: aux files first, game last. std::vector filenames{}; std::vector flags{}; for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { flags.push_back(std::string{argv[i]}); } else { filenames.push_back(std::string{argv[i]}); } } const auto has_flag = [&](const std::string &s) { return std::find(flags.begin(), flags.end(), s) != flags.end(); }; if (has_flag("-v") || has_flag("--version")) { std::cout << "The Quality Tea Frontend " << QTEA_VERSION << std::endl; return 0; } if (has_flag("-h") || has_flag("--help")) { std::cout << "The Quality Tea Frontend " QTEA_VERSION "\n" "\n" "Usage: " QTEA_BINARY " [options] [auxfile...] [game]\n" "\n" "Options:\n" " -f, --fullscreen Start in fullscreen\n" " -m, --mute Start muted\n" " -h, --help Show this text and exit\n" " -v, --version Show version information and exit\n" "\n" "Auxiliary files are BIOS images, link cable peers and second\n" "cartridges; which slots a core uses is core-specific. The\n" "playable game is always last.\n"; return 0; } // Before JGManager: its constructor's set_paths() needs the subsystem // for a core that keys paths on it. Empty gives the generic descriptor. std::string startup_sys; if (!filenames.empty()) { auto det = qtea::detect::detect_sys(filenames.back()); startup_sys = std::move(det.sys); } // Registers the core name with qtea::paths, so lookups resolve from here. auto jgm = std::make_unique(startup_sys.c_str()); SettingManager setmgr(*jgm); setmgr.read(*jgm); LogDriver::set_level(setmgr.get_setting("l_loglevel")->val); // Before QApplication's share context. Modern is Core 3.2 for GLSL // 1.40; legacy the compatibility default. { const bool want_legacy = setmgr.get_setting("v_renderer")->val != 0; QSurfaceFormat fmt; fmt.setDepthBufferSize(0); fmt.setStencilBufferSize(0); fmt.setSwapBehavior(QSurfaceFormat::DoubleBuffer); // The default, but the self-paced loop depends on it. fmt.setSwapInterval(1); if (!want_legacy) { fmt.setVersion(3, 2); fmt.setProfile(QSurfaceFormat::CoreProfile); } QSurfaceFormat::setDefaultFormat(fmt); } #ifdef __APPLE__ qtea::macos_set_app_name(jgm->get_coreinfo()->fname); #endif QApplication app(argc, argv); // No display name: the platforms that have one append it to every // window title, and a loaded game's title is the game's alone. QCoreApplication::setApplicationName( QString::fromUtf8(jgm->get_coreinfo()->fname)); QCoreApplication::setOrganizationName("jgemu"); QTeaTheme::apply_theme(setmgr.get_setting("g_theme")->val); if (!jgm->init()) { return 1; } if (!SDL_Init(SDL_INIT_AUDIO | SDL_INIT_JOYSTICK)) { LogDriver::log(LogLevel::Error, "Failed to initialize SDL: " + std::string(SDL_GetError())); return 1; } // Only for the screensaver calls, which live in SDL's video subsystem. // SDL stands down where Qt already owns the app, so this takes no window // and no event pumping. Failure just leaves the screensaver alone. if (!SDL_InitSubSystem(SDL_INIT_VIDEO)) { LogDriver::log(LogLevel::Warn, "No SDL video, screensaver stays enabled: " + std::string(SDL_GetError())); } AudioManager audiomgr(*jgm, setmgr); VideoManager videomgr(*jgm, setmgr); InputManager inputmgr(*jgm, setmgr); CheatManager chtmgr(*jgm, setmgr); { int nmissing = qtea_bios_count_missing(*jgm); if (nmissing > 0) { std::string msg = std::to_string(nmissing) + " required BIOS file" + (nmissing == 1 ? " is" : "s are") + " missing"; LogDriver::log(LogLevel::OSD, msg); LogDriver::log(LogLevel::Warn, msg + ". Open Emulator > BIOS / Firmware for details"); } } // Loading first sizes the window from the core's real resolution. std::vector> game_buffers; if (!filenames.empty()) { bool ok = qtea::load_files(filenames, nullptr, game_buffers, *jgm, setmgr, audiomgr, videomgr, inputmgr); if (ok && jgm->is_loaded()) { setmgr.add_recent(filenames); jgm->setup_audio(); jgm->setup_video(); inputmgr.reassign(); audiomgr.pause(0); jgm->reset(2); } } int rw, rh; videomgr.set_dimensions(); videomgr.get_dimensions(&rw, &rh); QTeaWindow mainwin(*jgm, setmgr, audiomgr, videomgr, inputmgr, chtmgr, rw, rh); // The core references these all session. if (jgm->is_loaded()) { mainwin.adopt_rom_buffers(std::move(game_buffers)); } // Forwards non-UI callbacks, e.g. a gamepad pause. UiAdapter::register_window(&mainwin); if (!filenames.empty() && !jgm->is_loaded()) { LogDriver::log(LogLevel::OSD, "Failed to load file from CLI"); } if (jgm->is_loaded()) { mainwin.setWindowTitle(QString::fromStdString(jgm->get_gamename())); } else { mainwin.setWindowTitle( QString::fromUtf8(jgm->get_coreinfo()->fname)); } mainwin.update_menu_state(); // Both together still mute once. const bool want_mute = setmgr.get_setting("a_mute")->val || has_flag("-m") || has_flag("--mute"); if (want_mute) { mainwin.toggle_mute(); } mainwin.show(); mainwin.raise(); mainwin.activateWindow(); const bool want_fullscreen = setmgr.get_setting("v_fullscreen")->val || has_flag("-f") || has_flag("--fullscreen"); if (want_fullscreen && jgm->is_loaded()) { mainwin.toggle_fullscreen(); } mainwin.start_emulation(); int rc = app.exec(); // No late callback reaches a dying window. The managers then unwind in // reverse, JGManager last. UiAdapter::register_window(nullptr); setmgr.write(*jgm); return rc; } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_menu.cpp000066400000000000000000000444201525155022500234320ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_window.h" #include #include #include #include #include #include #include #include #include #include #include "jgmanager.h" #include "setmanager.h" #include "qtea_archive.h" #include "qtea_emulator.h" // The whole menu: build_menu() creates from it, update_menu_state() enables // from it. namespace { enum EnableGroup { EG_Always, EG_GameLoaded, EG_HasMedia, // the loaded game has selectable media EG_HasDips, // the loaded game has DIP switches EG_HasCheats, // a game is loaded on a core with cheats EG_HasRecent, }; // Separator: null label. Submenu header: label set, slot null; later rows // naming it as `parent` land inside it. struct MenuItem { MenuId id; // index into actions_, or M_Count const char *menu; const char *parent; const char *label; const char *shortcut; QAction::MenuRole role; // macOS relocation EnableGroup enable_group; void (QTeaWindow::*slot)(); // nullptr for separators and headers }; constexpr const char *MENU_FILE = "&File"; constexpr const char *MENU_EMU = "&Emulator"; constexpr const char *MENU_WIN = "&Window"; constexpr const char *MENU_HELP = "&Help"; constexpr const char *SUB_RECENT = "Open Recent"; constexpr const char *SUB_QLOAD = "Quick Load"; constexpr const char *SUB_QSAVE = "Quick Save"; constexpr const char *SUB_RESIZE = "Resize"; constexpr const char *SUB_MEDIA = "Switch Media"; // "Ctrl" is ⌘ on macOS. Elsewhere Alt leaves Ctrl to the core. #ifdef __APPLE__ #define MODKEY "Ctrl+" #else #define MODKEY "Alt+" #endif const MenuItem menu_items[] = { // ---------------- File ---------------- { M_Open, MENU_FILE, nullptr, "Open", MODKEY "O", QAction::NoRole, EG_Always, &QTeaWindow::on_open }, { M_OpenMultiple, MENU_FILE, nullptr, "Open Multiple...", nullptr, QAction::NoRole, EG_Always, &QTeaWindow::on_open_multiple }, // Children from rebuild_recent_menu(). { M_Count, MENU_FILE, nullptr, SUB_RECENT, nullptr, QAction::NoRole, EG_HasRecent, nullptr }, { M_Count, MENU_FILE, nullptr, nullptr, nullptr, QAction::NoRole, EG_Always, nullptr }, { M_StateLoad, MENU_FILE, nullptr, "Load State...", nullptr, QAction::NoRole, EG_GameLoaded, &QTeaWindow::on_state_load }, { M_StateSave, MENU_FILE, nullptr, "Save State...", nullptr, QAction::NoRole, EG_GameLoaded, &QTeaWindow::on_state_save }, { M_Count, MENU_FILE, nullptr, nullptr, nullptr, QAction::NoRole, EG_Always, nullptr }, // Slot children from build_menu(). { M_Count, MENU_FILE, nullptr, SUB_QLOAD, nullptr, QAction::NoRole, EG_GameLoaded, nullptr }, { M_Count, MENU_FILE, nullptr, SUB_QSAVE, nullptr, QAction::NoRole, EG_GameLoaded, nullptr }, { M_Count, MENU_FILE, nullptr, nullptr, nullptr, QAction::NoRole, EG_Always, nullptr }, { M_Screenshot, MENU_FILE, nullptr, "Screenshot...", nullptr, QAction::NoRole, EG_GameLoaded, &QTeaWindow::on_screenshot_dialog }, { M_Count, MENU_FILE, nullptr, nullptr, nullptr, QAction::NoRole, EG_Always, nullptr }, { M_Quit, MENU_FILE, nullptr, "&Quit", MODKEY "Q", QAction::QuitRole, EG_Always, &QTeaWindow::request_quit }, // ---------------- Emulator ---------------- { M_Pause, MENU_EMU, nullptr, "Pause", nullptr, QAction::NoRole, EG_GameLoaded, &QTeaWindow::toggle_pause }, { M_Count, MENU_EMU, nullptr, nullptr, nullptr, QAction::NoRole, EG_Always, nullptr }, { M_Mute, MENU_EMU, nullptr, "Mute", nullptr, QAction::NoRole, EG_Always, &QTeaWindow::toggle_mute }, { M_Count, MENU_EMU, nullptr, nullptr, nullptr, QAction::NoRole, EG_Always, nullptr }, { M_ResetSoft, MENU_EMU, nullptr, "Reset (Soft)", nullptr, QAction::NoRole, EG_GameLoaded, &QTeaWindow::on_reset_soft }, { M_ResetHard, MENU_EMU, nullptr, "Reset (Hard)", nullptr, QAction::NoRole, EG_GameLoaded, &QTeaWindow::on_reset_hard }, { M_Count, MENU_EMU, nullptr, nullptr, nullptr, QAction::NoRole, EG_Always, nullptr }, { M_Count, MENU_EMU, nullptr, SUB_MEDIA, nullptr, QAction::NoRole, EG_HasMedia, nullptr }, { M_MediaMount, MENU_EMU, nullptr, "Insert Media", nullptr, QAction::NoRole, EG_HasMedia, &QTeaWindow::on_media_mount }, { M_Dipswitches, MENU_EMU, nullptr, "DIP Switches...", nullptr, QAction::NoRole, EG_HasDips, &QTeaWindow::on_dipswitches }, { M_Count, MENU_EMU, nullptr, nullptr, nullptr, QAction::NoRole, EG_Always, nullptr }, { M_Cheats, MENU_EMU, nullptr, "Cheats...", nullptr, QAction::NoRole, EG_HasCheats, &QTeaWindow::on_cheats }, { M_Bios, MENU_EMU, nullptr, "BIOS / Firmware...",nullptr, QAction::NoRole, EG_Always, &QTeaWindow::on_bios }, { M_Count, MENU_EMU, nullptr, nullptr, nullptr, QAction::NoRole, EG_Always, nullptr }, { M_Settings, MENU_EMU, nullptr, "Settings...", nullptr, QAction::PreferencesRole, EG_Always, &QTeaWindow::on_settings }, // ---------------- Window ---------------- { M_Fullscreen, MENU_WIN, nullptr, "Fullscreen", nullptr, QAction::NoRole, EG_GameLoaded, &QTeaWindow::toggle_fullscreen }, { M_Snap, MENU_WIN, nullptr, "Snap", nullptr, QAction::NoRole, EG_Always, &QTeaWindow::snap_window }, { M_Count, MENU_WIN, nullptr, SUB_RESIZE, nullptr, QAction::NoRole, EG_Always, nullptr }, // ---------------- Help ---------------- { M_About, MENU_HELP, nullptr, "About", nullptr, QAction::AboutRole, EG_Always, &QTeaWindow::on_about }, { M_AboutQt, MENU_HELP, nullptr, "About Qt", nullptr, QAction::AboutQtRole, EG_Always, &QTeaWindow::on_about_qt }, }; constexpr size_t menu_items_count = sizeof(menu_items) / sizeof(menu_items[0]); } // namespace void QTeaWindow::build_menu() { struct MenuHandle { QString label; QMenu *m; }; std::vector top_menus; std::vector sub_menus; auto find_or_add_top = [&](const char *label) -> QMenu* { QString key(label); for (const auto &h : top_menus) { if (h.label == key) return h.m; } QMenu *m = mbar_->addMenu(label); top_menus.push_back({key, m}); return m; }; auto find_sub = [&](const char *label) -> QMenu* { QString key(label); for (const auto &h : sub_menus) { if (h.label == key) return h.m; } return nullptr; }; for (size_t i = 0; i < menu_items_count; ++i) { const MenuItem &item = menu_items[i]; QMenu *parent_menu = item.parent ? find_sub(item.parent) : find_or_add_top(item.menu); if (!parent_menu) { // A submenu named before its header: a table-ordering bug. continue; } if (!item.label) { parent_menu->addSeparator(); continue; } // Submenu header. if (!item.slot) { QMenu *sub = parent_menu->addMenu(item.label); sub_menus.push_back({QString(item.label), sub}); continue; } QAction *a = parent_menu->addAction(item.label); if (item.shortcut) { a->setShortcut(QKeySequence(item.shortcut)); } a->setMenuRole(item.role); a->setEnabled(item.enable_group == EG_Always); connect(a, &QAction::triggered, this, item.slot); actions_[item.id] = a; } // Generated: one parameterised handler per family. if (QMenu *resize_sub = find_sub(SUB_RESIZE)) { for (int s = 1; s <= 8; ++s) { QAction *a = resize_sub->addAction(QString("%1x").arg(s)); connect(a, &QAction::triggered, this, [this, s]() { resize_window(s); }); } } if (QMenu *qload_sub = find_sub(SUB_QLOAD)) { for (int s = 0; s < NUM_QUICK_SLOTS; ++s) { QAction *a = qload_sub->addAction(QString("Slot %1").arg(s)); connect(a, &QAction::triggered, this, [this, s]() { jgm_->state_qload(s); }); } } if (QMenu *qsave_sub = find_sub(SUB_QSAVE)) { for (int s = 0; s < NUM_QUICK_SLOTS; ++s) { QAction *a = qsave_sub->addAction(QString("Slot %1").arg(s)); connect(a, &QAction::triggered, this, [this, s]() { jgm_->state_qsave(s); }); } } // Filled by rebuild_*_menu(). Recent entries show the filename; the // tooltip carries the paths. media_switch_menu_ = find_sub(SUB_MEDIA); recent_menu_ = find_sub(SUB_RECENT); if (recent_menu_) { recent_menu_->setToolTipsVisible(true); } // "Open For...": a forced system, on multi-system cores. { size_t numsystems = 0; jg_systeminfo_t *syslist = jgm_->get_systemlist(&numsystems); if (numsystems > 1) { QMenu *file_menu = find_or_add_top(MENU_FILE); QMenu *open_for = new QMenu("Open For...", file_menu); // Open, Open For..., Open Multiple... QAction *before = actions_[M_OpenMultiple]; file_menu->insertMenu(before, open_for); for (size_t i = 0; i < numsystems; ++i) { QString label = QString::fromUtf8(syslist[i].fname); std::string sys_name(syslist[i].name); std::set seen; QString sys_exts; std::string extstr(syslist[i].ext ? syslist[i].ext : ""); size_t pos = 0; while (pos < extstr.size()) { size_t comma = extstr.find(',', pos); if (comma == std::string::npos) comma = extstr.size(); std::string e = extstr.substr(pos, comma - pos); if (!e.empty() && seen.insert(e).second) { sys_exts += " *." + QString::fromStdString(e); } pos = comma + 1; } for (const auto &ae : qtea::archive::extensions()) { sys_exts += " *" + QString::fromStdString(ae); } QString filter = label + " (" + sys_exts.trimmed() + ");;All Files (*)"; QAction *a = open_for->addAction(label); connect(a, &QAction::triggered, this, [this, sys_name, filter]() { open_for_system(sys_name, filter); }); } } } #ifdef __APPLE__ // Minimize and Zoom first, per the HIG. { QMenu *win = find_or_add_top(MENU_WIN); QAction *before = actions_[M_Fullscreen]; QAction *minimize = new QAction("Minimize", this); minimize->setShortcut(QKeySequence("Ctrl+M")); connect(minimize, &QAction::triggered, this, [this]() { showMinimized(); }); win->insertAction(before, minimize); QAction *zoom = new QAction("Zoom", this); connect(zoom, &QAction::triggered, this, [this]() { if (isMaximized()) showNormal(); else showMaximized(); }); win->insertAction(before, zoom); win->insertSeparator(before); } #endif } void QTeaWindow::update_menu_state() { const bool game_loaded = jgm_->is_loaded(); bool has_dips = false; if (game_loaded) { size_t ndips = 0; has_dips = jgm_->get_dips(&ndips) != nullptr && ndips > 0; } const bool has_cheats = game_loaded && (jgm_->get_coreinfo()->hints & JG_HINT_CHEATS); const bool has_media = game_loaded && jgm_->get_mediainfo() != nullptr; auto resolve_enable = [&](EnableGroup g) { switch (g) { case EG_Always: return true; case EG_GameLoaded: return game_loaded; case EG_HasMedia: return has_media; case EG_HasDips: return has_dips; case EG_HasCheats: return has_cheats; case EG_HasRecent: return !setmgr_.get_recent().empty(); } return true; }; const auto all_menus = mbar_->findChildren(); for (size_t i = 0; i < menu_items_count; ++i) { const MenuItem &item = menu_items[i]; if (item.slot) { if (item.id >= M_Count) continue; if (QAction *a = actions_[item.id]) { a->setEnabled(resolve_enable(item.enable_group)); } continue; } // Submenu header: found by title. Separators have no label. if (item.label) { for (QMenu *m : all_menus) { if (m->title() == QLatin1String(item.label)) { if (QAction *ma = m->menuAction()) { ma->setEnabled(resolve_enable(item.enable_group)); } break; } } } } rebuild_media_menu(); rebuild_recent_menu(); } void QTeaWindow::rebuild_recent_menu() { if (!recent_menu_) return; recent_menu_->clear(); const auto &recent = setmgr_.get_recent(); if (recent.empty()) return; // For a forced system's display name. size_t numsystems = 0; jg_systeminfo_t *syslist = jgm_->get_systemlist(&numsystems); for (const SettingManager::RecentEntry &entry : recent) { // The game's filename, plus what a plain Open wouldn't reproduce: // an aux file count and a forced system. An ampersand would become // an accelerator. QString label = QFileInfo(QString::fromStdString(entry.paths.back())).fileName(); QStringList extra; if (entry.paths.size() > 1) { extra << QString("+%1").arg(entry.paths.size() - 1); } if (!entry.sys.empty()) { QString sysname = QString::fromStdString(entry.sys); for (size_t i = 0; i < numsystems; ++i) { if (entry.sys == syslist[i].name) { sysname = QString::fromUtf8(syslist[i].fname); break; } } extra << sysname; } if (!extra.isEmpty()) { label += " (" + extra.join(", ") + ")"; } label.replace('&', "&&"); QStringList tip; for (const std::string &path : entry.paths) { tip << QString::fromStdString(path); } QAction *a = recent_menu_->addAction(label); a->setToolTip(tip.join('\n')); // Queued: both handlers rebuild this menu, and clear() would delete // the action mid-emission. connect(a, &QAction::triggered, this, [this, entry]() { load_paths(entry.paths, entry.sys); }, Qt::QueuedConnection); } recent_menu_->addSeparator(); QAction *clear = recent_menu_->addAction("Clear"); connect(clear, &QAction::triggered, this, [this]() { setmgr_.clear_recent(); update_menu_state(); }, Qt::QueuedConnection); } void QTeaWindow::rebuild_media_menu() { jg_mediainfo_t *mi = jgm_->get_mediainfo(); if (QAction *a = actions_[M_MediaMount]) { if (mi && mi->inserted) { a->setText("Eject Media"); } else { a->setText("Insert Media"); } } if (!media_switch_menu_) return; media_switch_menu_->clear(); if (!mi || mi->count == 0) return; // Nothing to switch between with one medium. if (QAction *ma = media_switch_menu_->menuAction()) { ma->setEnabled(mi->count > 1); } for (unsigned i = 0; i < mi->count; ++i) { QString label = QString("%1 %2") .arg(QString::fromUtf8(mi->name)) .arg(i + 1); QAction *a = media_switch_menu_->addAction(label); a->setCheckable(true); a->setChecked(mi->inserted && mi->index == i); connect(a, &QAction::triggered, this, [this, i]() { jg_mediainfo_t *cur = jgm_->get_mediainfo(); if (!cur) return; if (cur->inserted && cur->index == i) return; if (cur->inserted) { jgm_->media_mount(0); } jgm_->media_set(i); jgm_->media_mount(1); rebuild_media_menu(); }); } } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_openmultiple.cpp000066400000000000000000000160551525155022500252060ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_openmultiple.h" #include #include #include #include #include #include #include namespace { // Basename shown; the path rides in Qt::UserRole through reorders. QString format_row(const QString &path) { return QFileInfo(path).fileName(); } } // namespace QTeaOpenMultipleDialog::QTeaOpenMultipleDialog(SettingManager &setmgr, QWidget *parent) : QDialog(parent), setmgr_(setmgr) { setWindowTitle(tr("Open Multiple")); setModal(true); resize(520, 380); QVBoxLayout *outer = new QVBoxLayout(this); QLabel *help = new QLabel(this); help->setWordWrap(true); help->setText(tr("Load multiple ROMs into the emulator. This may be used " "for loading a specific BIOS, Super Game Boy/Sufami " "Turbo, lock-on carts, or multiple handheld game ROMs for " "multiplayer mode. BIOSes should always be at the top of " "the list.")); outer->addWidget(help); QHBoxLayout *row = new QHBoxLayout; outer->addLayout(row, /*stretch=*/1); list_ = new QListWidget(this); list_->setSelectionMode(QAbstractItemView::SingleSelection); list_->setDragDropMode(QAbstractItemView::InternalMove); list_->setDefaultDropAction(Qt::MoveAction); row->addWidget(list_, /*stretch=*/1); QVBoxLayout *side = new QVBoxLayout; side->setContentsMargins(0, 0, 0, 0); btn_add_ = new QPushButton(tr("Add Files..."), this); btn_up_ = new QPushButton(tr("Move Up"), this); btn_down_ = new QPushButton(tr("Move Down"), this); btn_remove_ = new QPushButton(tr("Remove"), this); side->addWidget(btn_add_); side->addWidget(btn_up_); side->addWidget(btn_down_); side->addWidget(btn_remove_); side->addStretch(1); row->addLayout(side); // Explicit buttons: Load reads better than Ok, and its enabled state // tracks the list. QHBoxLayout *bottom = new QHBoxLayout; bottom->addStretch(1); btn_cancel_ = new QPushButton(tr("Cancel"), this); btn_load_ = new QPushButton(tr("Load"), this); btn_load_->setDefault(true); bottom->addWidget(btn_cancel_); bottom->addWidget(btn_load_); outer->addLayout(bottom); connect(btn_add_, &QPushButton::clicked, this, &QTeaOpenMultipleDialog::on_add_files); connect(btn_up_, &QPushButton::clicked, this, &QTeaOpenMultipleDialog::on_move_up); connect(btn_down_, &QPushButton::clicked, this, &QTeaOpenMultipleDialog::on_move_down); connect(btn_remove_, &QPushButton::clicked, this, &QTeaOpenMultipleDialog::on_remove); connect(btn_cancel_, &QPushButton::clicked, this, &QDialog::reject); connect(btn_load_, &QPushButton::clicked, this, &QDialog::accept); connect(list_, &QListWidget::itemSelectionChanged, this, &QTeaOpenMultipleDialog::on_selection_changed); connect(list_->model(), &QAbstractItemModel::rowsMoved, this, [this]() { update_button_states(); }); update_button_states(); } QStringList QTeaOpenMultipleDialog::files() const { QStringList out; out.reserve(list_->count()); for (int i = 0; i < list_->count(); ++i) { out << list_->item(i)->data(Qt::UserRole).toString(); } return out; } void QTeaOpenMultipleDialog::on_add_files() { const int remaining = max_entries - list_->count(); if (remaining <= 0) return; // Appended in the dialog's order; the last is the game, per jgrf, which // picking BIOS then game gives naturally. QStringList picked = QFileDialog::getOpenFileNames( this, tr("Add Files"), QString::fromStdString(setmgr_.get_lastdir(LASTDIR_ROM)), tr("All Files (*)")); if (picked.isEmpty()) return; setmgr_.set_lastdir(LASTDIR_ROM, picked.first().toStdString()); // Truncate past the remaining slots; the disabled Add button says so. if (picked.size() > remaining) { picked = picked.mid(0, remaining); } for (const QString &path : picked) { QListWidgetItem *item = new QListWidgetItem(format_row(path), list_); item->setData(Qt::UserRole, path); item->setToolTip(path); // Reorders between rows, never a drop onto one. item->setFlags(item->flags() & ~Qt::ItemIsDropEnabled); } update_button_states(); } void QTeaOpenMultipleDialog::on_move_up() { int row = list_->currentRow(); if (row <= 0) return; QListWidgetItem *item = list_->takeItem(row); list_->insertItem(row - 1, item); list_->setCurrentRow(row - 1); update_button_states(); } void QTeaOpenMultipleDialog::on_move_down() { int row = list_->currentRow(); if (row < 0 || row >= list_->count() - 1) return; QListWidgetItem *item = list_->takeItem(row); list_->insertItem(row + 1, item); list_->setCurrentRow(row + 1); update_button_states(); } void QTeaOpenMultipleDialog::on_remove() { int row = list_->currentRow(); if (row < 0) return; delete list_->takeItem(row); update_button_states(); } void QTeaOpenMultipleDialog::on_selection_changed() { update_button_states(); } void QTeaOpenMultipleDialog::update_button_states() { const int total = list_->count(); const int row = list_->currentRow(); btn_add_->setEnabled(total < max_entries); btn_load_->setEnabled(total > 0); btn_up_->setEnabled(row > 0); btn_down_->setEnabled(row >= 0 && row < total - 1); btn_remove_->setEnabled(row >= 0); } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_openmultiple.h000066400000000000000000000052161525155022500246500ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include #include "jgmanager.h" #include "setmanager.h" class QListWidget; class QPushButton; // The ordered file list for "Open Multiple...": aux slots first, game last, // per the jgrf convention. Modal; paths via files() on Accepted. No I/O. class QTeaOpenMultipleDialog : public QDialog { Q_OBJECT public: explicit QTeaOpenMultipleDialog(SettingManager &setmgr, QWidget *parent = nullptr); // Top of the list is aux[0], the last index the game. Valid only after // exec() returned QDialog::Accepted. QStringList files() const; private slots: void on_add_files(); void on_move_up(); void on_move_down(); void on_remove(); void on_selection_changed(); private: void update_button_states(); SettingManager &setmgr_; QListWidget *list_{nullptr}; QPushButton *btn_add_{nullptr}; QPushButton *btn_up_{nullptr}; QPushButton *btn_down_{nullptr}; QPushButton *btn_remove_{nullptr}; QPushButton *btn_load_{nullptr}; QPushButton *btn_cancel_{nullptr}; static constexpr int max_entries = JGManager::NUM_AUX + 1; }; qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_osd.cpp000066400000000000000000001077071525155022500232630ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ // The on-screen display, ported from jgrf with one font and no settings // backend. Three layers composite on demand into a 640x480 RGBA8888 canvas: // a shade, an animated effect selected by bgfx, and text in fixed slots. // The renderer draws the canvas as one alpha-blended quad; the OSD never // sees the game pixels. #include #include #include #include #include #include "qtea_osd.h" #include "font/6x8.h" constexpr uint32_t QTEA_OSD_ORANGE = 0xd45500ff; constexpr int QTEA_OSD_TEXT_MAX = 512; constexpr int QTEA_OSD_LINE_GAP = 2; static int osdactive = 0; static int osd_bgfx = 0; // last passed to qtea_osd_toggle(1, ...) static uint32_t osd_text_rgba = QTEA_OSD_ORANGE; /* ------------------------------------------------------------------------ */ /* Helpers */ /* ------------------------------------------------------------------------ */ static inline uint32_t xorshift32(uint32_t *state) { uint32_t x = *state; x ^= x << 13; x ^= x >> 17; x ^= x << 5; *state = x; return x; } /* ------------------------------------------------------------------------ */ /* State */ /* ------------------------------------------------------------------------ */ // Packed RGBA bytes, uploaded as GL_RGBA / GL_UNSIGNED_BYTE. static uint8_t canvas[QTEA_OSD_W * QTEA_OSD_H * 4]; // Visible region static int vis_w = QTEA_OSD_W; static int vis_h = QTEA_OSD_H; static const uint8_t *font = sixbyeight; static const unsigned fwidth = 6; static const unsigned fheight = 8; /* ------------------------------------------------------------------------ */ /* Shade layer */ /* ------------------------------------------------------------------------ */ static uint32_t shade_rgba = 0; // 0 is off // Set by qtea_osd_step(), consumed by qtea_osd_composite(): an effect draws // as it advances. static int tick_pending = 0; // Display rate the timebase is spread across. static int refresh_hz = QTEA_OSD_TICKS_PER_SEC; static int refresh_frags = 0; void qtea_osd_shade_set(uint32_t rgba) { shade_rgba = rgba; } /* ------------------------------------------------------------------------ */ /* Effects layer */ /* ------------------------------------------------------------------------ */ struct qtea_osd_fx { void (*init)(); void (*step)(int vw, int vh); void (*deinit)(); }; static void fx_tea_init(); static void fx_tea_step(int vw, int vh); static void fx_tea_deinit(); static void fx_snow_init(); static void fx_snow_step(int vw, int vh); static void fx_snow_deinit(); static void fx_mush_init(); static void fx_mush_step(int vw, int vh); static void fx_mush_deinit(); static void fx_fire_init(); static void fx_fire_step(int vw, int vh); static void fx_fire_deinit(); static void fx_dmk_init(); static void fx_dmk_step(int vw, int vh); static void fx_dmk_deinit(); // Indexed by QTEA_OSD_FX_*; the static_asserts below hold the order. static const qtea_osd_fx fx_table[QTEA_OSD_NUM_FX] = { { fx_tea_init, fx_tea_step, fx_tea_deinit }, // QTEA_OSD_FX_TEA { fx_snow_init, fx_snow_step, fx_snow_deinit }, // QTEA_OSD_FX_SNOW { fx_mush_init, fx_mush_step, fx_mush_deinit }, // QTEA_OSD_FX_MUSH { fx_fire_init, fx_fire_step, fx_fire_deinit }, // QTEA_OSD_FX_FIRE { fx_dmk_init, fx_dmk_step, fx_dmk_deinit } // QTEA_OSD_FX_DMK }; static_assert(QTEA_OSD_FX_TEA == 0, "fx_table row order must match the enum"); static_assert(QTEA_OSD_FX_SNOW == 1, "fx_table row order must match the enum"); static_assert(QTEA_OSD_FX_MUSH == 2, "fx_table row order must match the enum"); static_assert(QTEA_OSD_FX_FIRE == 3, "fx_table row order must match the enum"); static_assert(QTEA_OSD_FX_DMK == 4, "fx_table row order must match the enum"); static_assert(sizeof(fx_table) / sizeof(fx_table[0]) == QTEA_OSD_NUM_FX, "fx_table must have one row per effect"); static unsigned fx_active[QTEA_OSD_NUM_FX]; void qtea_osd_fx_enable(int fx_id) { if (fx_id < 0 || fx_id >= QTEA_OSD_NUM_FX || fx_active[fx_id]) return; fx_active[fx_id] = 1; if (fx_table[fx_id].init) fx_table[fx_id].init(); } void qtea_osd_fx_disable(int fx_id) { if (fx_id < 0 || fx_id >= QTEA_OSD_NUM_FX || !fx_active[fx_id]) return; fx_active[fx_id] = 0; if (fx_table[fx_id].deinit) fx_table[fx_id].deinit(); } void qtea_osd_fx_clear() { for (int i = 0; i < QTEA_OSD_NUM_FX; ++i) qtea_osd_fx_disable(i); } static int fx_any_active() { for (int i = 0; i < QTEA_OSD_NUM_FX; ++i) if (fx_active[i]) return 1; return 0; } /* ------------------------------------------------------------------------ */ /* Text layer */ /* ------------------------------------------------------------------------ */ struct qtea_osd_text_slot { int frames; // 0 inactive, >0 countdown, -1 persistent int anchor; int x, y; uint32_t rgba; char text[QTEA_OSD_TEXT_MAX]; }; static qtea_osd_text_slot text_slots[QTEA_OSD_NUM_TEXT_SLOTS]; void qtea_osd_text(int slot, int frames, int anchor, int x, int y, uint32_t rgba, const char *text) { if (slot < 0 || slot >= QTEA_OSD_NUM_TEXT_SLOTS) return; qtea_osd_text_slot *s = &text_slots[slot]; s->frames = frames; s->anchor = anchor; s->x = x; s->y = y; s->rgba = rgba ? rgba : osd_text_rgba; if (text) snprintf(s->text, sizeof(s->text), "%s", text); else s->text[0] = '\0'; } void qtea_osd_text_clear(int slot) { if (slot < 0 || slot >= QTEA_OSD_NUM_TEXT_SLOTS) return; text_slots[slot].frames = 0; text_slots[slot].text[0] = '\0'; } // Longest line, in canvas pixels. static int text_pixel_width(const char *text) { int max_w = 0; int cur_w = 0; for (size_t c = 0; text[c] != '\0'; ++c) { if (text[c] == '\n') { if (cur_w > max_w) max_w = cur_w; cur_w = 0; continue; } cur_w += fwidth; } if (cur_w > max_w) max_w = cur_w; return max_w; } // Display height of a string, in canvas pixels. static int text_pixel_height(const char *text) { int lines = 1; for (size_t c = 0; text[c] != '\0'; ++c) if (text[c] == '\n') ++lines; return lines * ((int)fheight + QTEA_OSD_LINE_GAP); } static void resolve_anchor(qtea_osd_text_slot *s, int *out_x, int *out_y) { int tw = text_pixel_width(s->text); int th = text_pixel_height(s->text); int ax = 0; int ay = 0; // A 1-pixel inset from the edge. switch (s->anchor) { default: case QTEA_OSD_ANCHOR_TL: { ax = s->x + 1; ay = s->y + 1; break; } case QTEA_OSD_ANCHOR_TR: { ax = vis_w - s->x - tw - 2; ay = s->y + 1; break; } case QTEA_OSD_ANCHOR_BL: { ax = s->x + 1; ay = vis_h - s->y - th - 1; break; } case QTEA_OSD_ANCHOR_BR: { ax = vis_w - s->x - tw - 2; ay = vis_h - s->y - th - 1; break; } } *out_x = ax; *out_y = ay; } static int text_active() { for (int i = 0; i < QTEA_OSD_NUM_TEXT_SLOTS; ++i) { const qtea_osd_text_slot *s = &text_slots[i]; if (s->frames != 0 && s->text[0] != '\0') return 1; } return 0; } /* ------------------------------------------------------------------------ */ /* Canvas primitives */ /* ------------------------------------------------------------------------ */ // Opaque pixel, unclipped static inline void canvas_set(int x, int y, uint32_t rgba) { uint8_t *p = &canvas[(y * QTEA_OSD_W + x) * 4]; p[0] = (rgba >> 24) & 0xff; // R p[1] = (rgba >> 16) & 0xff; // G p[2] = (rgba >> 8) & 0xff; // B p[3] = rgba & 0xff; // A } // "Over" with straight alpha; src is 0xRRGGBBAA static inline void canvas_blend(int x, int y, uint32_t rgba) { uint8_t sa = rgba & 0xff; if (sa == 0) return; if (sa == 0xff) { canvas_set(x, y, rgba); return; } uint8_t *p = &canvas[(y * QTEA_OSD_W + x) * 4]; uint16_t sr = (rgba >> 24) & 0xff; uint16_t sg = (rgba >> 16) & 0xff; uint16_t sb = (rgba >> 8) & 0xff; uint16_t da = p[3]; uint16_t inv = 255 - sa; p[0] = (uint8_t)((sr * sa + p[0] * inv + 127) / 255); p[1] = (uint8_t)((sg * sa + p[1] * inv + 127) / 255); p[2] = (uint8_t)((sb * sa + p[2] * inv + 127) / 255); p[3] = (uint8_t)(sa + (da * inv + 127) / 255); } static void canvas_clear() { memset(canvas, 0, sizeof(canvas)); } // Alpha included static void canvas_fill_visible(uint32_t rgba) { uint8_t r = (rgba >> 24) & 0xff; uint8_t g = (rgba >> 16) & 0xff; uint8_t b = (rgba >> 8) & 0xff; uint8_t a = rgba & 0xff; for (int y = 0; y < vis_h; ++y) { uint8_t *row = &canvas[(y * QTEA_OSD_W) * 4]; for (int x = 0; x < vis_w; ++x) { row[x * 4 + 0] = r; row[x * 4 + 1] = g; row[x * 4 + 2] = b; row[x * 4 + 3] = a; } } } /* ------------------------------------------------------------------------ */ /* Bitmap font rasteriser */ /* ------------------------------------------------------------------------ */ // Clipped to the visible region, with a one-pixel black outline. static void qtea_osd_render_text(int xo, int yo, uint32_t rgba, const char *text) { int x = xo; int y = yo; for (size_t c = 0; text[c] != '\0'; ++c) { if (text[c] == '\n') { y += fheight + QTEA_OSD_LINE_GAP; x = xo; continue; } if (x + (int)fwidth <= 0 || x >= vis_w || y + (int)fheight <= 0 || y >= vis_h) { x += fwidth; continue; } const uint8_t *bitmap = &font[(uint8_t)text[c] << 3]; // Outline: the unset neighbours of every set pixel. for (unsigned gy = 0; gy < fheight; ++gy) { uint8_t row = bitmap[gy]; for (unsigned gx = 0; gx < fwidth; ++gx) { if (!(row & (1 << (7 - gx)))) continue; for (int dy = -1; dy <= 1; ++dy) { for (int dx = -1; dx <= 1; ++dx) { if (dx == 0 && dy == 0) continue; int px = x + (int)gx + dx; int py = y + (int)gy + dy; if (px < 0 || px >= vis_w || py < 0 || py >= vis_h) continue; // The glyph pass covers set pixels. int srcx = (int)gx + dx; int srcy = (int)gy + dy; if (srcx >= 0 && srcx < (int)fwidth && srcy >= 0 && srcy < (int)fheight && (bitmap[srcy] & (1 << (7 - srcx)))) continue; canvas_set(px, py, 0x000000ff); } } } } // The glyph. for (unsigned gy = 0; gy < fheight; ++gy) { uint8_t row = bitmap[gy]; for (unsigned gx = 0; gx < fwidth; ++gx) { if (!(row & (1 << (7 - gx)))) continue; int px = x + (int)gx; int py = y + (int)gy; if (px < 0 || px >= vis_w || py < 0 || py >= vis_h) continue; canvas_set(px, py, rgba); } } x += fwidth; } } /* ------------------------------------------------------------------------ */ /* Effect implementations */ /* ------------------------------------------------------------------------ */ // Tea: demoscene plasma. Four sinusoids per pixel (x, y, a rotated // diagonal, radial from the visible centre), each with its own phase, summed // into a palette of tea-amber tones. The whole pattern drifts slowly. static uint32_t plasma_palette[256]; // 0xRRGGBB static int8_t plasma_sin[256]; // [-127, +127] // Phases, advanced once per frame. static uint8_t plasma_pa = 0; // x static uint8_t plasma_pb = 0; // y static uint8_t plasma_pc = 0; // diagonal static uint8_t plasma_pd = 0; // radial static uint8_t plasma_pe = 0; // drift static void fx_tea_init() { for (int i = 0; i < 256; ++i) { double theta = (double)i * (2.0 * 3.14159265358979323846 / 256.0); plasma_sin[i] = (int8_t)(std::sin(theta) * 127.0); } const uint8_t stops[5][3] = { { 0x24, 0x0c, 0x05 }, // dark warm brown - troughs { 0x4a, 0x1a, 0x07 }, // deep umber { 0x80, 0x36, 0x0d }, // dark brown { 0xb4, 0x4e, 0x12 }, // brewed mahogany { 0xd4, 0x76, 0x20 } // saturated amber - highlight }; const int n_stops = 5; const int seg = 256 / (n_stops - 1); // 64 for (int i = 0; i < 256; ++i) { int s = i / seg; if (s >= n_stops - 1) s = n_stops - 2; int t = i - s * seg; // 0..63 const uint8_t *a = stops[s]; const uint8_t *b = stops[s + 1]; int r = a[0] + ((b[0] - a[0]) * t) / seg; int g = a[1] + ((b[1] - a[1]) * t) / seg; int bl = a[2] + ((b[2] - a[2]) * t) / seg; plasma_palette[i] = ((uint32_t)r << 24) | ((uint32_t)g << 16) | ((uint32_t)bl << 8); } } static void fx_tea_deinit() { } static void fx_tea_step(int vw, int vh) { if (vw < 1 || vh < 1) return; if (vw > QTEA_OSD_W) vw = QTEA_OSD_W; if (vh > QTEA_OSD_H) vh = QTEA_OSD_H; plasma_pa += 2; plasma_pb += 1; plasma_pc += 3; plasma_pd += 1; plasma_pe += 1; const uint8_t alpha = 0x50; // Radial scale: about five rings across the half-diagonal at any // resolution. int cx = vw >> 1; int cy = vh >> 1; int half_diag_sq = cx * cx + cy * cy; int rad_fp = (half_diag_sq > 0) ? ((5 * 256) << 16) / half_diag_sq // 16.16 : (1 << 16); // A circular wander, so the pattern drifts rather than breathes. int drift_x = plasma_sin[plasma_pe] >> 2; int drift_y = plasma_sin[(uint8_t)(plasma_pe + 64)] >> 2; for (int y = 0; y < vh; ++y) { int dy = y - cy; int dy2 = dy * dy; int sy = plasma_sin[(uint8_t)((y << 1) + plasma_pb + drift_y)]; for (int x = 0; x < vw; ++x) { int dx = x - cx; int sx = plasma_sin[(uint8_t)((x << 1) + plasma_pa + drift_x)]; // x + 2y rather than x + y, breaking the grid symmetry int sxy = plasma_sin[(uint8_t)(x + (y << 1) + plasma_pc)]; uint8_t rad = (uint8_t)((((dx * dx + dy2) * rad_fp) >> 16)); int sr = plasma_sin[(uint8_t)(rad + plasma_pd)]; // [-508, 508] to [0, 255] int idx = (sx + sy + sxy + sr + 508) >> 2; if (idx > 255) idx = 255; canvas_blend(x, y, plasma_palette[idx] | alpha); } } } // Snow, after ZSNES: white particles at varied speed, drift and alpha. constexpr size_t FX_SNOW_FLAKES = 256; struct snow_flake { float fx, fy; float speed; // y per frame float drift; // x per frame uint8_t alpha; // 0x80..0xff }; static snow_flake snow_flakes[FX_SNOW_FLAKES]; static uint32_t snow_rng = 0x12345678; static void fx_snow_init() { for (size_t i = 0; i < FX_SNOW_FLAKES; ++i) { snow_flakes[i].fx = xorshift32(&snow_rng) % (vis_w > 0 ? vis_w : 1); snow_flakes[i].fy = xorshift32(&snow_rng) % (vis_h > 0 ? vis_h : 1); snow_flakes[i].speed = 0.5f + ((xorshift32(&snow_rng) % 100) / 100.0f) * 1.25f; snow_flakes[i].drift = (((xorshift32(&snow_rng) % 100) / 100.0f) - 0.5f) * 0.8f; snow_flakes[i].alpha = 0x80 + (xorshift32(&snow_rng) % 0x80); } } static void fx_snow_deinit() { } static void fx_snow_step(int vw, int vh) { for (size_t i = 0; i < FX_SNOW_FLAKES; ++i) { snow_flake *f = &snow_flakes[i]; // Init runs before the visible region is known; flakes outside it // are reseeded rather than clamped to the rim. if (f->fx < 0.0f || f->fx >= (float)vw || f->fy < 0.0f || f->fy >= (float)vh) { f->fx = (float)(xorshift32(&snow_rng) % (vw > 0 ? vw : 1)); f->fy = (float)(xorshift32(&snow_rng) % (vh > 0 ? vh : 1)); } f->fy += f->speed; f->fx += f->drift; int x = f->fx; int y = f->fy; if (y >= vh) { f->fy = 0.0f; y = 0; f->fx = (float)(xorshift32(&snow_rng) % (vw > 0 ? vw : 1)); x = (int)f->fx; } if (x < 0) { f->fx = (float)(vw - 1); x = vw - 1; } if (x >= vw) { f->fx = 0.0f; x = 0; } if (x >= 0 && x < vw && y >= 0 && y < vh) { uint32_t col = 0xffffff00 | f->alpha; canvas_blend(x, y, col); } } } // Mushrooms: Amanita, each growing from nothing, holding, fading and // respawning elsewhere on a staggered lifecycle. A spotted half-ellipse cap // on a trapezoidal stem. constexpr int FX_MUSH_COUNT = 32; constexpr int FX_MUSH_GROW = 120; // frames constexpr int FX_MUSH_HOLD = 180; constexpr int FX_MUSH_FADE = 90; constexpr int FX_MUSH_LIFE = FX_MUSH_GROW + FX_MUSH_HOLD + FX_MUSH_FADE; constexpr int FX_MUSH_SPOT_MIN = 8; constexpr int FX_MUSH_SPOT_MAX = 18; // 0xRRGGBB; alpha comes from the lifecycle envelope constexpr uint32_t FX_MUSH_CAP_RGB = 0xd62828; constexpr uint32_t FX_MUSH_STEM_RGB = 0xf0e8dd; constexpr uint32_t FX_MUSH_SPOT_RGB = FX_MUSH_STEM_RGB; // Cap-local: nx in [-1, 1] across the cap, ny in [-1, 0] from apex to base. struct mush_spot { float nx; float ny; }; struct mushroom { int base_x; // centre int base_y; // bottom of the stem int cap_rx; // full-size radii int cap_ry; int stem_h; int stem_top_w; // half-widths int stem_bot_w; int age; // frames int nspots; mush_spot spots[FX_MUSH_SPOT_MAX]; }; static mushroom mushrooms[FX_MUSH_COUNT]; static uint32_t mush_rng = 0xfeedface; static float mush_randf() { return (xorshift32(&mush_rng) & 0xffff) / 65535.0f; } static void mush_spawn(mushroom *m, int vw, int vh, int initial_age) { // Everything derives from the cap width. int cap_rx_min = 12; int cap_rx_max = 20; if (vw < 160) { cap_rx_min = 6; cap_rx_max = 12; } int cap_rx = cap_rx_min + (int)(mush_randf() * (float)(cap_rx_max - cap_rx_min)); int cap_ry = (int)((float)cap_rx * (0.4f + mush_randf() * 0.2f)); if (cap_ry < 4) cap_ry = 4; int stem_h = (int)((float)cap_rx * (0.8f + mush_randf() * 0.6f)); if (stem_h < 6) stem_h = 6; // The bottom slightly wider, for a taper. int stem_top_w = (int)((float)cap_rx * (0.22f + mush_randf() * 0.16f)); if (stem_top_w < 2) stem_top_w = 2; int stem_bot_w = stem_top_w + 1 + (int)(mush_randf() * 2.0f); m->cap_rx = cap_rx; m->cap_ry = cap_ry; m->stem_h = stem_h; m->stem_top_w = stem_top_w; m->stem_bot_w = stem_bot_w; m->age = initial_age; // Spots on the upper half-disk, inset from the rim. int target = FX_MUSH_SPOT_MIN + (int)(mush_randf() * (float)(FX_MUSH_SPOT_MAX - FX_MUSH_SPOT_MIN + 1)); if (target > FX_MUSH_SPOT_MAX) target = FX_MUSH_SPOT_MAX; m->nspots = 0; int attempts = 0; while (m->nspots < target) { ++attempts; if (attempts > 64 && m->nspots >= FX_MUSH_SPOT_MIN) break; float nx = mush_randf() * 2.0f - 1.0f; // -1..1 float ny = -mush_randf(); // -1..0 (upper half) if (nx * nx + ny * ny > 0.78f) continue; m->spots[m->nspots].nx = nx; m->spots[m->nspots].ny = ny; ++m->nspots; } // Fits the visible area with a margin. int margin = 2; int min_x = cap_rx + margin; int max_x = vw - cap_rx - margin; if (max_x <= min_x) max_x = min_x + 1; int total_h = cap_ry + stem_h; int min_y = total_h + margin; int max_y = vh - margin; if (max_y <= min_y) max_y = min_y + 1; m->base_x = min_x + (int)(mush_randf() * (float)(max_x - min_x)); m->base_y = min_y + (int)(mush_randf() * (float)(max_y - min_y)); } static void fx_mush_init() { // Staggered ages. for (int i = 0; i < FX_MUSH_COUNT; ++i) mush_spawn(&mushrooms[i], vis_w, vis_h, (FX_MUSH_LIFE * i) / FX_MUSH_COUNT); } static void fx_mush_deinit() { } static void fx_hline(int x0, int x1, int y, int vw, int vh, uint32_t col) { if (y < 0 || y >= vh) return; if (x0 < 0) x0 = 0; if (x1 >= vw) x1 = vw - 1; for (int x = x0; x <= x1; ++x) canvas_blend(x, y, col); } static void fx_mush_step(int vw, int vh) { for (int i = 0; i < FX_MUSH_COUNT; ++i) { mushroom *m = &mushrooms[i]; ++m->age; if (m->age >= FX_MUSH_LIFE) { mush_spawn(m, vw, vh, 0); continue; } // growth scales the geometry during the grow phase; env scales // alpha over the whole life. float growth, env; if (m->age < FX_MUSH_GROW) { growth = (float)m->age / (float)FX_MUSH_GROW; env = growth; } else if (m->age < FX_MUSH_GROW + FX_MUSH_HOLD) { growth = 1.0f; env = 1.0f; } else { growth = 1.0f; env = (float)(FX_MUSH_LIFE - m->age) / (float)FX_MUSH_FADE; if (env < 0.0f) env = 0.0f; } uint8_t alpha = (uint8_t)(env * 0.6f * 255.0f); if (alpha == 0) continue; uint32_t cap_col = (FX_MUSH_CAP_RGB << 8) | alpha; uint32_t stem_col = (FX_MUSH_STEM_RGB << 8) | alpha; uint32_t spot_col = (FX_MUSH_SPOT_RGB << 8) | alpha; // The cap widens late, so it pops open as it emerges. float h_growth = (growth < 0.7f) ? (growth / 0.7f) : 1.0f; int stem_h = (int)((float)m->stem_h * growth); int cap_ry = (int)((float)m->cap_ry * growth); int cap_rx = (int)((float)m->cap_rx * h_growth); if (cap_rx < 1) cap_rx = 1; if (cap_ry < 1) cap_ry = 1; int cx = m->base_x; int stem_bot_y = m->base_y; int stem_top_y = stem_bot_y - stem_h; int cap_cy = stem_top_y; // Stem, from one row below the cap so the two never blend. int top_w = m->stem_top_w; int bot_w = m->stem_bot_w; if (stem_h > 0) { for (int y = stem_top_y + 1; y <= stem_bot_y; ++y) { float t = (stem_h > 0) ? (float)(y - stem_top_y) / (float)stem_h : 0.0f; int hw = top_w + (int)((float)(bot_w - top_w) * t + 0.5f); if (y == stem_bot_y && hw > 1) --hw; fx_hline(cx - hw, cx + hw, y, vw, vh, stem_col); } } // Cap: a half-ellipse, rows narrower than 2 skipped so the apex // isn't a nub. for (int dy = -cap_ry; dy <= 0; ++dy) { float ny = (float)dy / (float)cap_ry; float k = 1.0f - ny * ny; int hw = (int)((float)cap_rx * std::sqrt(k) + 0.5f); if (hw < 2) continue; int yy = cap_cy + dy; fx_hline(cx - hw, cx + hw, yy, vw, vh, cap_col); } // Spots, once the cap is more than a sliver. if (cap_rx >= 6 && cap_ry >= 4) { for (int s = 0; s < m->nspots; ++s) { const mush_spot *sp = &m->spots[s]; int sx = cx + (int)(sp->nx * (float)cap_rx + 0.5f); int sy = cap_cy + (int)(sp->ny * (float)cap_ry + 0.5f); if (sx < 0 || sx >= vw || sy < 0 || sy >= vh) continue; canvas_blend(sx, sy, spot_col); } } } } // Fire, Doom-style: a heat buffer seeded at the bottom row, each cell // taking its value from a jittered cell below it minus a random cooling. constexpr int FX_FIRE_PAL_MAX = 36; static uint32_t fx_fire_palette[FX_FIRE_PAL_MAX + 1]; static uint8_t fx_fire_buf[QTEA_OSD_W * QTEA_OSD_H]; static uint32_t fx_fire_rng = 0xc0ffee42; static void fx_fire_init() { memset(fx_fire_buf, 0, sizeof(fx_fire_buf)); // { index, R, G, B }, interpolated between. const unsigned stops[6][4] = { { 0, 0x07, 0x07, 0x07 }, { 4, 0x28, 0x07, 0x07 }, { 12, 0xa8, 0x1f, 0x07 }, { 24, 0xe0, 0x7b, 0x0b }, { 32, 0xf4, 0xbb, 0x4b }, { 36, 0xff, 0xef, 0xc7 } }; for (int s = 0; s < 6 - 1; ++s) { int i0 = stops[s][0], i1 = stops[s + 1][0]; for (int i = i0; i <= i1; ++i) { float t = (i1 == i0) ? 0.0f : (float)(i - i0) / (float)(i1 - i0); unsigned r = stops[s][1] + ((stops[s + 1][1] - stops[s][1]) * t); unsigned g = stops[s][2] + ((stops[s + 1][2] - stops[s][2]) * t); unsigned b = stops[s][3] + ((stops[s + 1][3] - stops[s][3]) * t); fx_fire_palette[i] = (r << 16) | (g << 8) | b; } } } static void fx_fire_deinit() { } static void fx_fire_step(int vw, int vh) { if (vw < 1 || vh < 1) return; if (vw > QTEA_OSD_W) vw = QTEA_OSD_W; if (vh > QTEA_OSD_H) vh = QTEA_OSD_H; // Held every frame, which is what keeps the fire alive. uint8_t *seed_row = &fx_fire_buf[(vh - 1) * QTEA_OSD_W]; for (int x = 0; x < vw; ++x) seed_row[x] = FX_FIRE_PAL_MAX; // Bottom up, so sources are read before they are overwritten. Multiple // sources hitting one destination is part of the plume. for (int y = vh - 1; y > 0; --y) { const uint8_t *src_row = &fx_fire_buf[y * QTEA_OSD_W]; uint8_t *dst_row = &fx_fire_buf[(y - 1) * QTEA_OSD_W]; for (int x = 0; x < vw; ++x) { uint8_t pixel = src_row[x]; if (pixel == 0) { dst_row[x] = 0; continue; } uint32_t r = xorshift32(&fx_fire_rng); int rand = r & 3; int cool = ((r >> 2) & 7) < 3 ? 1 : 0; int dx = x + 2 - rand; if (dx < 0) dx = 0; if (dx >= vw) dx = vw - 1; dst_row[dx] = pixel - cool; } } for (int y = 0; y < vh; ++y) { const uint8_t *row = &fx_fire_buf[y * QTEA_OSD_W]; for (int x = 0; x < vw; ++x) { uint8_t idx = row[x]; if (idx == 0) continue; uint32_t rgb = fx_fire_palette[idx]; int a = 0x40 + (idx * (0xff - 0x40)) / FX_FIRE_PAL_MAX; if (a > 0xff) a = 0xff; canvas_blend(x, y, (rgb << 8) | (uint32_t)a); } } } // Danmaku: a phyllotactic emitter, each bullet flying out radially at the // golden angle from the last. The irrational angle fills evenly, tracing a // sunflower seedhead. Bullets free their slot on leaving the visible area. constexpr int FX_DMK_BULLETS = 1024; constexpr float FX_DMK_GOLDEN_ANGLE = 2.39996322972865332f; constexpr float FX_DMK_TWO_PI = 6.28318530717958647692f; constexpr float FX_DMK_SPEED = 1.2f; // pixels per frame constexpr int FX_DMK_RADIUS = 1; // diamond half-width constexpr int FX_DMK_CULL_AGE = 2; // not drawn below this constexpr int FX_DMK_SPAWN_PER_FRAME = 8; static float fx_dmk_theta[FX_DMK_BULLETS]; static int fx_dmk_age[FX_DMK_BULLETS]; // -1 is free static float fx_dmk_next_theta = 0.0f; static void fx_dmk_init() { for (int i = 0; i < FX_DMK_BULLETS; ++i) fx_dmk_age[i] = -1; fx_dmk_next_theta = 0.0f; } static void fx_dmk_deinit() { } static void fx_dmk_step(int vw, int vh) { if (vw < 1 || vh < 1) return; float cx = vw * 0.666666f; float cy = vh * 0.333333f; int spawned = 0; for (int i = 0; i < FX_DMK_BULLETS && spawned < FX_DMK_SPAWN_PER_FRAME; ++i) { if (fx_dmk_age[i] < 0) { fx_dmk_theta[i] = fx_dmk_next_theta; fx_dmk_age[i] = 0; fx_dmk_next_theta += FX_DMK_GOLDEN_ANGLE; if (fx_dmk_next_theta >= FX_DMK_TWO_PI) fx_dmk_next_theta -= FX_DMK_TWO_PI; ++spawned; } } for (int i = 0; i < FX_DMK_BULLETS; ++i) { if (fx_dmk_age[i] < 0) continue; fx_dmk_age[i] += 1; float r = FX_DMK_SPEED * (float)fx_dmk_age[i]; float theta = fx_dmk_theta[i]; int x = (int)(cx + r * cosf(theta)); int y = (int)(cy + r * std::sin(theta)); if (x < 0 || x >= vw || y < 0 || y >= vh) { fx_dmk_age[i] = -1; continue; } // Too close to centre to draw without clumping if (fx_dmk_age[i] < FX_DMK_CULL_AGE) continue; // A diamond, each pixel clipped: only the centre was checked. for (int dy = -FX_DMK_RADIUS; dy <= FX_DMK_RADIUS; ++dy) { int span = FX_DMK_RADIUS - (dy < 0 ? -dy : dy); int py = y + dy; if (py < 0 || py >= vh) continue; for (int dx = -span; dx <= span; ++dx) { int px = x + dx; if (px < 0 || px >= vw) continue; canvas_blend(px, py, 0xe48898a0); } } } } /* ------------------------------------------------------------------------ */ /* Public lifecycle and per-frame */ /* ------------------------------------------------------------------------ */ void qtea_osd_set_visible(int w, int h) { if (w < 1) w = 1; if (h < 1) h = 1; if (w > QTEA_OSD_W) w = QTEA_OSD_W; if (h > QTEA_OSD_H) h = QTEA_OSD_H; vis_w = w; vis_h = h; } void qtea_osd_toggle(int active, int bgfx) { osdactive = active; osd_bgfx = bgfx; if (osdactive) { // A running effect that is the one requested keeps going. if (!(bgfx >= 2 && bgfx - 2 < QTEA_OSD_NUM_FX && fx_active[bgfx - 2])) qtea_osd_fx_clear(); // Effects override this. osd_text_rgba = QTEA_OSD_ORANGE; switch (bgfx) { case QTEA_OSD_BGFX_NONE: default: { // None qtea_osd_shade_set(0x00000000); break; } case QTEA_OSD_BGFX_SHADE: { // Shade qtea_osd_shade_set(0xd4550040); // JG break; } case QTEA_OSD_BGFX_TEA: { // Tea Swirl qtea_osd_fx_enable(QTEA_OSD_FX_TEA); qtea_osd_shade_set(0x6e260e80); // Oolong break; } case QTEA_OSD_BGFX_SNOW: { // Snow qtea_osd_fx_enable(QTEA_OSD_FX_SNOW); qtea_osd_shade_set(0x1010a080); // ZSNESish osd_text_rgba = 0xd0d0ffff; // Ice break; } case QTEA_OSD_BGFX_MUSH: { // Mushrooms qtea_osd_fx_enable(QTEA_OSD_FX_MUSH); qtea_osd_shade_set(0x000000a0); // Dark osd_text_rgba = 0xff2020ff; // Unapologetic red break; } case QTEA_OSD_BGFX_FIRE: { // Fire qtea_osd_fx_enable(QTEA_OSD_FX_FIRE); qtea_osd_shade_set(0x000000d0); // Very dark break; } case QTEA_OSD_BGFX_DMK: { // Danmaku qtea_osd_fx_enable(QTEA_OSD_FX_DMK); qtea_osd_shade_set(0xa0); // Dark osd_text_rgba = 0x666bffff; break; } } } else { qtea_osd_shade_set(0x00000000); qtea_osd_fx_clear(); } } void qtea_osd_init() { canvas_clear(); shade_rgba = 0; for (int i = 0; i < QTEA_OSD_NUM_FX; ++i) fx_active[i] = 0; for (int i = 0; i < QTEA_OSD_NUM_TEXT_SLOTS; ++i) { text_slots[i].frames = 0; text_slots[i].text[0] = '\0'; } } void qtea_osd_deinit() { qtea_osd_fx_clear(); } void qtea_osd_set_refresh(int hz) { if (hz < 1 || hz == refresh_hz) { return; } refresh_hz = hz; refresh_frags = 0; // means nothing against another rate } void qtea_osd_step() { // 60 ticks across the display's frames, as the core is stepped. int steps = QTEA_OSD_TICKS_PER_SEC / refresh_hz; refresh_frags += QTEA_OSD_TICKS_PER_SEC % refresh_hz; if (refresh_frags >= refresh_hz) { ++steps; refresh_frags -= refresh_hz; } if (steps <= 0) { return; } // Countdowns take every step, several per frame below 60Hz. for (int t = 0; t < steps; ++t) { for (int i = 0; i < QTEA_OSD_NUM_TEXT_SLOTS; ++i) { if (text_slots[i].frames > 0) --text_slots[i].frames; } } // An effect draws as it advances, so once per frame; below 60Hz it runs // slower. tick_pending = 1; } int qtea_osd_is_active() { if (shade_rgba != 0) return 1; if (fx_any_active()) return 1; if (text_active()) return 1; return 0; } int qtea_osd_bgfx_get() { return osd_bgfx; } const void *qtea_osd_composite(int *active, int *dirty) { int has_shade = shade_rgba != 0; int has_fx = fx_any_active(); int has_text = text_active(); if (active) *active = (has_shade || has_fx || has_text); if (!has_shade && !has_fx && !has_text) { if (dirty) *dirty = 0; tick_pending = 0; return canvas; } // Between ticks the canvas still holds the right image. if (!tick_pending) { if (dirty) *dirty = 0; return canvas; } tick_pending = 0; if (dirty) *dirty = 1; // Layer 0: Shade or clear if (has_shade) canvas_fill_visible(shade_rgba); else canvas_clear(); // Layer 1: Effects if (has_fx) { for (int i = 0; i < QTEA_OSD_NUM_FX; ++i) { if (fx_active[i] && fx_table[i].step) fx_table[i].step(vis_w, vis_h); } } // Layer 2: Text if (has_text) { for (int i = 0; i < QTEA_OSD_NUM_TEXT_SLOTS; ++i) { qtea_osd_text_slot *s = &text_slots[i]; if (s->frames == 0 || s->text[0] == '\0') continue; int tx, ty; resolve_anchor(s, &tx, &ty); qtea_osd_render_text(tx, ty, s->rgba, s->text); } } return canvas; } qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_osd.h000066400000000000000000000100501525155022500227100ustar00rootroot00000000000000#pragma once /* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 // The OSD rasterises into a fixed 640x480 RGBA8888 canvas; the renderer // composites a portion of it over the output at integer scale. It animates // on its own timebase, so durations and effect speed don't move with the // refresh rate; qtea_osd_text() durations are in these ticks. constexpr int QTEA_OSD_TICKS_PER_SEC = 60; constexpr int QTEA_OSD_W = 640; constexpr int QTEA_OSD_H = 480; // Text slots enum { QTEA_OSD_TEXT_FRONTEND = 0, // bottom left QTEA_OSD_TEXT_CORE = 1, // bottom right QTEA_OSD_TEXT_MENU = 2, // top left QTEA_OSD_TEXT_AUX = 3, // reserved QTEA_OSD_NUM_TEXT_SLOTS }; // Pixel effects enum { QTEA_OSD_FX_TEA = 0, QTEA_OSD_FX_SNOW = 1, QTEA_OSD_FX_MUSH = 2, QTEA_OSD_FX_FIRE = 3, QTEA_OSD_FX_DMK = 4, QTEA_OSD_NUM_FX }; // g_bgfx values, the bgfx argument of qtea_osd_toggle: 0 nothing, 1 shade // only, 2 and above an effect with its own shade colour. enum { QTEA_OSD_BGFX_NONE = 0, QTEA_OSD_BGFX_SHADE = 1, QTEA_OSD_BGFX_TEA = 2, QTEA_OSD_BGFX_SNOW = 3, QTEA_OSD_BGFX_MUSH = 4, QTEA_OSD_BGFX_FIRE = 5, QTEA_OSD_BGFX_DMK = 6, QTEA_OSD_NUM_BGFX }; // Text anchor enum { QTEA_OSD_ANCHOR_TL = 0, QTEA_OSD_ANCHOR_TR = 1, QTEA_OSD_ANCHOR_BL = 2, QTEA_OSD_ANCHOR_BR = 3 }; void qtea_osd_init(); void qtea_osd_deinit(); // On or off; bgfx is a QTEA_OSD_BGFX_* value, ignored when off. void qtea_osd_toggle(int active, int bgfx); void qtea_osd_set_visible(int vis_w, int vis_h); // Shade layer: RGBA, or 0 to disable void qtea_osd_shade_set(uint32_t rgba); // Effects layer void qtea_osd_fx_enable(int fx_id); void qtea_osd_fx_disable(int fx_id); void qtea_osd_fx_clear(); // Text layer: (x, y) in canvas pixels from the anchor corner. frames > 0 // counts down in OSD ticks, -1 persists, 0 (or a null text) clears. void qtea_osd_text(int slot, int frames, int anchor, int x, int y, uint32_t rgba, const char *text); void qtea_osd_text_clear(int slot); // 1 if any layer is active; the screenshot path restores after a clean grab. int qtea_osd_is_active(); // Last bgfx passed to qtea_osd_toggle. int qtea_osd_bgfx_get(); // Display refresh rate, whenever known or changed. void qtea_osd_set_refresh(int hz); // Once per rendered frame; the timebase is distributed across display // frames as a 60fps game is. void qtea_osd_step(); // Composite the active layers and return the canvas. *active says whether // to draw the quad, *dirty whether to re-upload the texture. const void *qtea_osd_composite(int *active, int *dirty); qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_parse.h000066400000000000000000000040671525155022500232500ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include #include #include namespace qtea { // The whole string must be a number; out is untouched on failure. For // hand-editable and third-party strings, where a bare std::stoi is unsafe. inline bool parse_int(const std::string &str, int &out) { try { size_t pos = 0; const int val = std::stoi(str, &pos); if (pos != str.size()) { return false; } out = val; return true; } catch (const std::logic_error &) { return false; } } } // namespace qtea qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_paths.cpp000066400000000000000000000215041525155022500236030ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 "qtea_paths.h" #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include #elif defined(__APPLE__) # include # include #elif defined(__FreeBSD__) || defined(__DragonFly__) # include # include #else # include #endif #include "logdriver.h" namespace fs = std::filesystem; namespace qtea::paths { namespace { std::string core_name; // The real file, not argv[0]. Empty if the platform can't say. std::string query_exe_path() { #if defined(_WIN32) std::vector buf(MAX_PATH); for (;;) { DWORD n = GetModuleFileNameA(nullptr, buf.data(), static_cast(buf.size())); if (n == 0) { return {}; } // Truncation fills the buffer exactly. if (n < buf.size() - 1) { return std::string(buf.data(), n); } buf.resize(buf.size() * 2); } #elif defined(__APPLE__) uint32_t sz = 0; _NSGetExecutablePath(nullptr, &sz); std::vector buf(sz + 1, '\0'); if (_NSGetExecutablePath(buf.data(), &sz) != 0) { return {}; } return std::string(buf.data()); #elif defined(__FreeBSD__) || defined(__DragonFly__) int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; std::vector buf(1024); size_t sz = buf.size(); if (sysctl(mib, 4, buf.data(), &sz, nullptr, 0) != 0) { return {}; } return std::string(buf.data()); #else // Linux, and NetBSD with procfs. for (const char *link : { "/proc/self/exe", "/proc/curproc/exe" }) { std::vector buf(1024); for (;;) { ssize_t n = readlink(link, buf.data(), buf.size()); if (n < 0) { break; } if (static_cast(n) < buf.size()) { return std::string(buf.data(), static_cast(n)); } buf.resize(buf.size() * 2); } } return {}; #endif } // Per lookup: the core name can change on a restart. std::vector roots() { std::vector out; const std::string &exe = exe_dir(); if (!exe.empty()) { // Build tree, or a relocatable layout. out.push_back(fs::path(exe)); #if defined(__APPLE__) // Bundle layout. out.push_back(fs::path(exe) / ".." / "Resources"); #endif // A relocated prefix. if (!core_name.empty()) { out.push_back(fs::path(exe) / ".." / "share" / core_name); } } // The configured prefix. if (!core_name.empty()) { out.push_back(fs::path(QTEA_DATAROOTDIR) / core_name); } // Last resort. std::error_code ec; fs::path cwd = fs::current_path(ec); if (!ec) { out.push_back(cwd); } return out; } #if defined(_WIN32) // Beside the executable: a Windows release is a zip run in place, so // everything travels with it. No core name, since the folder belongs to one // core; HOME and XDG ignored, since an MSYS2 shell sets both. An unwritable // folder gets no saves, logged, rather than saves somewhere else. std::string user_dir() { const std::string &exe = exe_dir(); if (!exe.empty()) { return exe; } std::error_code ec; fs::path cwd = fs::current_path(ec); return ec ? std::string{} : cwd.string(); } #else const char *env_nonempty(const char *name) { const char *v = std::getenv(name); return (v && *v) ? v : nullptr; } // /; empty until the core name is registered. std::string user_dir(const char *xdg_env, const char *home_subdir) { if (core_name.empty()) { return {}; } // Convention on Linux, escape hatch on macOS. if (const char *xdg = env_nonempty(xdg_env)) { return (fs::path(xdg) / core_name).string(); } if (const char *home = env_nonempty("HOME")) { return (fs::path(home) / home_subdir / core_name).string(); } // Neither set. std::error_code ec; fs::path cwd = fs::current_path(ec); if (ec) { return {}; } return (cwd / core_name).string(); } #endif } // namespace void set_core_name(const std::string &name) { core_name = name; } const std::string &exe_dir() { static const std::string dir = [] { const std::string exe = query_exe_path(); if (exe.empty()) { return std::string{}; } std::error_code ec; // A symlinked launcher must land on the real file. fs::path p = fs::weakly_canonical(fs::path(exe), ec); if (ec) { p = fs::path(exe); } return p.parent_path().string(); }(); return dir; } std::string find_data_file(const std::string &relative) { for (const auto &root : roots()) { fs::path p = root / relative; std::error_code ec; if (fs::exists(p, ec) && !ec) { return fs::weakly_canonical(p, ec).string(); } } return {}; } std::string find_data_dir(const std::string &relative) { const std::string found = find_data_file(relative); if (found.empty()) { return {}; } return fs::path(found).parent_path().string() + "/"; } std::string data_root() { for (const auto &root : roots()) { std::error_code ec; if (fs::is_directory(root / "shaders", ec) && !ec) { fs::path p = fs::weakly_canonical(root, ec); return ec ? root.string() : p.string(); } } // Nothing carries the frontend's data; a wrong path beats an empty one. const std::string &exe = exe_dir(); if (!exe.empty()) { return exe; } std::error_code ec; fs::path cwd = fs::current_path(ec); return ec ? std::string{} : cwd.string(); } std::string user_data_dir() { #if defined(_WIN32) return user_dir(); #elif defined(__APPLE__) return user_dir("XDG_DATA_HOME", "Library/Application Support"); #else return user_dir("XDG_DATA_HOME", ".local/share"); #endif } std::string user_config_dir() { #if defined(_WIN32) return user_dir(); #elif defined(__APPLE__) // Preferences is for plists. return user_dir("XDG_CONFIG_HOME", "Library/Application Support"); #else return user_dir("XDG_CONFIG_HOME", ".config"); #endif } bool make_dir(const std::string &path) { if (path.empty()) { return false; } std::error_code ec; // False for an existing directory; only the code matters. fs::create_directories(path, ec); if (ec) { LogDriver::log(LogLevel::Error, "Could not create directory " + path + ": " + ec.message()); return false; } return true; } std::string long_path(const std::string &path) { #ifdef _WIN32 if (path.rfind("\\\\?\\", 0) == 0) { return path; } std::error_code ec; fs::path p = fs::absolute(fs::path(path), ec); if (ec) { return path; } std::string s = p.lexically_normal().make_preferred().string(); // Win32 caps paths at MAX_PATH unless escaped. Only escape past it, so // ordinary paths reach cores unchanged. The escape suppresses // normalisation, hence the separate UNC form. if (s.size() < 240) { return path; } return s.rfind("\\\\", 0) == 0 ? "\\\\?\\UNC\\" + s.substr(2) : "\\\\?\\" + s; #else return path; #endif } } // namespace qtea::paths qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_paths.h000066400000000000000000000061241525155022500232510ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ #pragma once #include // Read-only data (icons, shaders, LICENSES, core assets) is beside the // binary in a build tree and under // installed, so several // roots are searched; the working directory is a last resort. The core name // names both that and the per-user directory, so JGManager::set_paths() // registers it first. namespace qtea::paths { // Idempotent; called again after a restart, which may change the name. void set_core_name(const std::string &name); // Directory of the real executable, symlinks resolved, no trailing // separator. Empty if the platform can't report it. const std::string &exe_dir(); // First existing root/`relative` (forward slashes), or empty. std::string find_data_file(const std::string &relative); // The directory such a path resolves within, trailing separator included. std::string find_data_dir(const std::string &relative); // For jg_pathinfo_t::core: the first root holding shaders/, else the // executable's directory, never empty. std::string data_root(); // Per-user writable directories, not created here. / under XDG // on Linux and the BSDs, ~/Library/Application Support for both on macOS, // XDG_*_HOME honoured on either. The executable's directory on Windows, // which is portable. std::string user_data_dir(); std::string user_config_dir(); // mkdir -p; logs and returns false rather than throwing. bool make_dir(const std::string &path); // \\?\-escaped copy of paths Win32 would reject as overlong. Identity // below the limit and on other platforms. std::string long_path(const std::string &path); } // namespace qtea::paths qtea-0.1.1-0ca6377fa9cf181cba7884c0512b9d73cd405a5b/src/qtea_settings.cpp000066400000000000000000000742071525155022500243340ustar00rootroot00000000000000/* Copyright (c) 2021-2026 Jolly Good Emulation Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "qtea_inputcodes.h" #include "qtea_settings.h" #include "qtea_window.h" namespace { // Keys QKeySequence::toString renders poorly. const std::unordered_map named_keys = { { Qt::Key_Space, "Space" }, { Qt::Key_Backspace, "Backspace" }, { Qt::Key_Tab, "Tab" }, { Qt::Key_Return, "Enter" }, { Qt::Key_Enter, "KP Enter" }, { Qt::Key_Pause, "Pause" }, { Qt::Key_ScrollLock, "Scroll Lock" }, { Qt::Key_Escape, "Escape" }, { Qt::Key_Home, "Home" }, { Qt::Key_Left, "Left" }, { Qt::Key_Up, "Up" }, { Qt::Key_Right, "Right" }, { Qt::Key_Down, "Down" }, { Qt::Key_PageUp, "Page Up" }, { Qt::Key_PageDown, "Page Down" }, { Qt::Key_End, "End" }, { Qt::Key_Print, "Print" }, { Qt::Key_Insert, "Insert" }, { Qt::Key_Menu, "Menu" }, { Qt::Key_Help, "Help" }, { Qt::Key_NumLock, "Num Lock" }, { Qt::Key_CapsLock, "Caps Lock" }, { Qt::Key_Shift, "Shift" }, { Qt::Key_Control, "Control" }, { Qt::Key_Meta, "Meta" }, { Qt::Key_Alt, "Alt" }, { Qt::Key_AltGr, "Alt Gr" }, { Qt::Key_Delete, "Delete" }, { Qt::Key_F1, "F1" }, { Qt::Key_F2, "F2" }, { Qt::Key_F3, "F3" }, { Qt::Key_F4, "F4" }, { Qt::Key_F5, "F5" }, { Qt::Key_F6, "F6" }, { Qt::Key_F7, "F7" }, { Qt::Key_F8, "F8" }, { Qt::Key_F9, "F9" }, { Qt::Key_F10, "F10" }, { Qt::Key_F11, "F11" }, { Qt::Key_F12, "F12" }, { Qt::Key_VolumeDown, "Volume Down" }, { Qt::Key_VolumeMute, "Volume Mute" }, { Qt::Key_VolumeUp, "Volume Up" }, { Qt::Key_MediaPlay, "Play" }, { Qt::Key_MediaStop, "Stop" }, { Qt::Key_MediaPrevious,"Prev" }, { Qt::Key_MediaNext, "Next" }, { Qt::Key_HomePage, "Home Page" }, { Qt::Key_LaunchMail, "Mail" }, { Qt::Key_Search, "Search" }, { Qt::Key_Back, "Back" }, { Qt::Key_Forward, "Forward" }, { Qt::Key_Stop, "Stop" }, { Qt::Key_Refresh, "Refresh" }, { Qt::Key_Sleep, "Sleep" }, { Qt::Key_Favorites, "Favorites" }, }; // InputRow column metrics, shared with the header row above the rows. The // rebind button's width is fixed rather than hint-driven: growing into // "Press a key..." would otherwise slide that row's bindings out from under // the headers. constexpr int ROW_MARGIN = 6; constexpr int COL_NAME_W = 140; constexpr int COL_REBIND_W = 130; constexpr int COL_BIND_W = 70; // jg_setting_t opts string to option labels. struct ParsedOpts { std::vector labels; bool is_range{false}; }; ParsedOpts parse_opts(const char *opts_cstr) { ParsedOpts out; if (!opts_cstr) return out; std::stringstream unparsed(opts_cstr); std::string temp; while (std::getline(unparsed, temp, ',')) { // "=