diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..af5db2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# Do not include any hidden metadata saved by apps and the OS. +desktop.ini +.DS_Store +.vscode/ + +# Do not include any built or cached files. +build/ +__pycache__/ +*.pyc +*.pyo + +# Do not include the dumps used to generate the cartdb files. +#dumps/ diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..280bd3f --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,105 @@ + +cmake_minimum_required(VERSION 3.25) + +set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_LIST_DIR}/cmake/toolchain.cmake") + +project( + cart_tool_private + LANGUAGES C CXX ASM + VERSION 0.3.0 + DESCRIPTION "Konami System 573 security cartridge tool" +) + +find_package(Python3 REQUIRED COMPONENTS Interpreter) + +## Main executable + +add_executable( + cart_tool + src/asset.cpp + src/cart.cpp + src/cartdb.cpp + src/gpu.cpp + src/io.cpp + src/main.cpp + src/pad.cpp + src/spu.cpp + src/uibase.cpp + src/uicommon.cpp + src/util.cpp + src/zs01.cpp + src/app/actions.cpp + src/app/app.cpp + src/app/misc.cpp + src/app/unlock.cpp + src/libc/crt0.c + src/libc/cxxsupport.cpp + src/libc/malloc.c + src/libc/memset.s + src/libc/misc.c + src/libc/misc.s + src/libc/string.c + src/ps1/pcdrv.s + src/ps1/system.c + src/ps1/system.s + src/ps1/unhandledexc.c + src/vendor/miniz.c + src/vendor/printf.c + src/vendor/qrcodegen.c +) +target_include_directories( + cart_tool PRIVATE + src + src/libc +) +target_compile_definitions( + cart_tool PRIVATE + VERSION="${PROJECT_VERSION}" + #ENABLE_ARGV=1 + ENABLE_PS1_CONTROLLER=1 + MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS=1 + MINIZ_NO_ARCHIVE_WRITING_APIS=1 + MINIZ_NO_STDIO=1 + MINIZ_NO_TIME=1 + PRINTF_DISABLE_SUPPORT_FLOAT=1 +) + +add_custom_command( + TARGET cart_tool POST_BUILD + COMMAND + "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/tools/convertExecutable.py" + $ cart_tool.psexe + BYPRODUCTS cart_tool.psexe + COMMENT "Converting executable" +) + +## Default resource archive + +add_custom_command( + COMMAND + "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/tools/buildResourceArchive.py" + "${PROJECT_SOURCE_DIR}/resources.json" resources.zip + OUTPUT resources.zip + DEPENDS resources.json + COMMENT "Building resource archive" +) +ps1_target_incbin( + cart_tool PRIVATE + .rodata _resources _resourcesSize + "${PROJECT_BINARY_DIR}/resources.zip" +) + +## CD-ROM image + +#configure_file(assets/cdreadme.txt cdreadme.txt NEWLINE_STYLE CRLF) +#add_custom_command( +# COMMAND +# "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/tools/buildCDImage.py" +# "${PROJECT_SOURCE_DIR}/cd.json" cart_tool.iso +# OUTPUT cart_tool.iso +# DEPENDS cd.json cart_tool +# COMMENT "Building CD-ROM image" +#) + +# Add a dummy target that depends on the CD image to make sure it gets built. +#add_custom_target(cd ALL DEPENDS cart_tool.iso) diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..56780c0 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,30 @@ +{ + "version": 6, + "cmakeMinimumRequired": { + "major": 3, + "minor": 25, + "patch": 0 + }, + "configurePresets": [ + { + "name": "debug", + "displayName": "Debug build", + "description": "Build the project with -Og and assertions enabled.", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "release", + "displayName": "Release build", + "description": "Build the project with -O2 and assertions disabled.", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release" + } + } + ] +} diff --git a/README.md b/README.md index 5bb99cc..c4f87fa 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,36 @@ -# cart-tool-private -System 573 security cartridge tool + +# Konami System 573 security cartridge tool + +## Building + +The following dependencies are required in order to build the project: + +- CMake 3.25 or later; +- Python 3.10 or later; +- [Ninja](https://ninja-build.org/); +- a recent version of the GCC toolchain that targets the `mipsel-none-elf` + architecture. + +The toolchain can be installed on Windows, Linux or macOS by following the +instructions [here](https://github.com/grumpycoders/pcsx-redux/blob/main/src/mips/psyqo/GETTING_STARTED.md#the-toolchain) +and should be added to `PATH`. The other dependencies can be installed through a +package manager. + +The Python script used to convert images at build time requires additional +dependencies which can be installed by running: + +``` +py -m pip install -r tools/requirements.txt (Windows) +sudo pip install -r tools/requirements.txt (Linux/macOS) +``` + +Once all prerequisites are installed, the tool can be built in debug mode (with +command-line argument parsing disabled and serial port logging enabled by +default) by running: + +``` +cmake --preset debug +cmake --build ./build +``` + +Replace `debug` with `release` to build in release mode. diff --git a/assets/app.strings.json b/assets/app.strings.json new file mode 100644 index 0000000..e221b08 --- /dev/null +++ b/assets/app.strings.json @@ -0,0 +1,149 @@ +{ + "App": { + "cartDetectWorker": { + "readDigitalIO": "Retrieving digital I/O board ID...", + "identifyCart": "Identifying security cartridge...", + "readCart": "Reading security cartridge...", + "identifyGame": "Attempting to identify game..." + }, + "cartUnlockWorker": { + "read": "Dumping cartridge...", + "identify": "Attempting to identify game..." + }, + "qrCodeWorker": { + "compress": "Compressing cartridge dump...", + "generate": "Generating QR code..." + } + }, + + "ButtonMappingScreen": { + "title": "{CART_ICON} Select button mapping", + "prompt": "Use {START_BUTTON} or the Test button to select a mapping preset suitable for your cabinet or JAMMA setup. Other buttons will be enabled once a mapping is selected.", + "itemPrompt": "{RIGHT_ARROW} Press and hold {START_BUTTON} or Test to confirm", + + "joystick": "JAMMA supergun or joystick/buttons", + "ddrCab": "Dance Dance Revolution (2-player) cabinet", + "ddrSoloCab": "Dance Dance Revolution Solo cabinet", + "dmCab": "DrumMania or PercussionFreaks cabinet", + "dmxCab": "Dance Maniax cabinet" + }, + + "CartActionsScreen": { + "title": "{CART_ICON} Cartridge options", + "itemPrompt": "{RIGHT_ARROW} Press {START_BUTTON} to confirm, hold {LEFT_BUTTON} + {RIGHT_BUTTON} to go back", + + "qrDump": { + "name": "Dump cartridge as QR code", + "prompt": "Generate a QR code encoding the contents of the cartridge's EEPROM in compressed format. The code can be scanned and decoded to a raw dump." + }, + "hexdump": { + "name": "View cartridge hexdump", + "prompt": "Display the raw contents of the cartridge's EEPROM." + }, + "resetSystemID": { + "name": "Reset system identifier (unpair cartridge)", + "prompt": "Delete any previously saved system identifier, allowing the cartridge to be used to reinstall the game on any system." + }, + "editSystemID": { + "name": "Edit system identifier (pair to another 573)", + "prompt": "Edit the saved system identifier to allow the cartridge to be used on a specific system without having to reinstall the game first." + }, + "reflash": { + "name": "Erase and reflash cartridge", + "prompt": "Wipe all data and flash the cartridge with another game's identifiers. All cartridges can be converted for use with any other game that uses the same cartridge type." + }, + "erase": { + "name": "Erase cartridge", + "prompt": "Wipe all data including game identifiers. Erased cartridges can be flashed for use with games unsupported by this tool using a master calendar." + } + }, + + "CartInfoScreen": { + "title": "{CART_ICON} Cartridge information", + "digitalIOInfo": "Digital I/O ID:\t%s\nDigital I/O SN:\t%s\n\n", + "cartInfo": "Cartridge type:\t%s\nUnlock status:\t%s\nDS2401 identifier:\t%s\nZS01 identifier:\t%s\n\n", + + "id": { + "error": "read failure", + "noSystemID": "no digital I/O board", + "noCartID": "cartridge has no DS2401", + "noZSID": "not a ZS01 cartridge" + }, + "unlockStatus": { + "locked": "{CLOSED_LOCK} locked, game key required", + "unlocked": "{OPEN_LOCK} unlocked" + }, + "description": { + "noCart": "No supported cartridge has been found.\n\nTurn off the system and insert a security cartridge in order to continue. DO NOT HOTPLUG CARTRIDGES; hotplugging may damage both the 573 and the cartridge.\n\nIf a cartridge is inserted but not detected, try cleaning its pins as well as the system's security cartridge connector.", + "initError": "Failed to initialize and read unprotected data from this cartridge.\n\nTurn off the system and make sure the cartridge is inserted correctly. If this issue persists, try using another cartridge of the same type.", + + "locked": { + "unidentified": "This cartridge contains data for an unsupported game.\n\nAs the cartridge is currently locked, you will have to manually select which game it belongs to in order to dump its contents or reflash it for use with a supported game, as each game has a different unlocking key.", + "identified": "This cartridge has been identified as:\n %s\n\nIf this is correct, you may proceed to unlock the cartridge using the appropriate key for this game in order to access and modify its contents.", + "unknown": "This cartridge cannot be identified without unlocking it first.\n\nYou will have to manually select which game it belongs to in order to dump its contents or reflash it for use with a supported game, as each game has a different unlocking key." + }, + "unlocked": { + "unidentified": "This cartridge contains data for an unsupported game.\n\nThe system identifier (if any) cannot be reset or edited, however you may still dump the cartridge's contents or reflash it for use with a supported game.", + "identified": "This cartridge has been identified as:\n %s\n\nYou may now proceed to reset the system identifier, edit it or erase and reflash the cartridge for use with another game.", + "blank": "This cartridge has been previously erased and is now blank.\n\nIt must be flashed and optionally initialized with a system identifier in order to be used with a supported game." + } + }, + "prompt": { + "locked": "Press {START_BUTTON} to proceed to unlock the cartridge.", + "unlocked": "Press {START_BUTTON} to continue.", + "error": "Press the Test button to view debug logs." + }, + + "x76f041": { + "name": "{CHIP_ICON} Xicor X76F041", + "warning": "X76F041 cartridges keep track of how many times a wrong key has been used. If too many unlock attempts fail, they will lock out any further access and thus become PERMANENTLY BRICKED, with no way to restore access.\n\nAre you sure the game/key is correct?" + }, + "x76f100": { + "name": "{CHIP_ICON} Xicor X76F100", + "warning": "X76F100 and ZS01 cartridges keep track of how many times a wrong key has been used. If too many unlock attempts fail, the cartridge will self-erase and will have to be reinitialized to factory data and paired to the system again if the game requires it.\n\nAre you sure the game/key is correct?" + }, + "zs01": { + "name": "{CHIP_ICON} Konami ZS01 (PIC16CE625)", + "desc": null, + "warning": "X76F100 and ZS01 cartridges keep track of how many times a wrong key has been used. If too many unlock attempts fail, the cartridge will self-erase and will have to be reinitialized to factory data and paired to the system again if the game requires it.\n\nAre you sure the game/key is correct?" + } + }, + + "QRCodeScreen": { + "title": "{CART_ICON} Cartridge dump", + "prompt": "Scan this code and paste the resulting string into the decodeDump.py script provided alongside this tool to obtain a dump of the cartridge. Press {START_BUTTON} to go back." + }, + + "UnlockConfirmScreen": { + "title": "Warning", + "no": "No, go back", + "yes": "Yes, continue" + }, + + "UnlockErrorScreen": { + "title": "Error", + "ok": "{START_BUTTON} Continue" + }, + + "UnlockKeyScreen": { + "title": "{CART_ICON} Select unlocking key", + "prompt": "If the cartridge has been converted before, select the game it was last converted to.", + "itemPrompt": "{RIGHT_ARROW} Press {START_BUTTON} to confirm, hold {LEFT_BUTTON} + {RIGHT_BUTTON} to go back", + + "autoUnlock": "Use identified game key", + "customKey": "Enter key manually...", + "nullKey": "Use null key (00-00-00-00-00-00-00-00)" + }, + + "WarningScreen": { + "title": "Warning", + "body": "This tool is experimental and provided with no warranty whatsoever. It is not guaranteed to work and improper usage may PERMANENTLY BRICK your System 573 security cartridges.\n\nUse this tool at your own risk. Do not proceed if you do not know what you are doing.", + + "cooldown": "Wait... (%ds)", + "ok": "{START_BUTTON} Continue" + }, + + "WorkerStatusScreen": { + "title": "Working..." + } +} diff --git a/assets/cdreadme.txt b/assets/cdreadme.txt new file mode 100644 index 0000000..9ea9372 --- /dev/null +++ b/assets/cdreadme.txt @@ -0,0 +1,16 @@ + +Konami System 573 security cartridge reset tool +=============================================== + +Version ${PROJECT_VERSION} + +Use this disc by simply putting it into your 573; make sure DIP switch 4 (the +rightmost one) is off. Remember to insert the cartridge you want to reset or +dump prior to turning on the system. + +More information and source code are available at: + ${PROJECT_HOMEPAGE_URL} + +WARNING: This tool is experimental and provided with no warranty whatsoever. It +is not guaranteed to work and improper usage can PERMANENTLY BRICK your System +573 security cartridges. Use this tool at your own risk. diff --git a/assets/licenses.txt b/assets/licenses.txt new file mode 100644 index 0000000..2132ad3 --- /dev/null +++ b/assets/licenses.txt @@ -0,0 +1,91 @@ + +# miniz +# https://github.com/richgel999/miniz + +Copyright 2013-2014 RAD Game Tools and Valve Software +Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + +All Rights Reserved. + +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. + +# printf +# https://github.com/mpaland/printf + +The MIT License (MIT) + +Copyright (c) 2014 Marco Paland + +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. + +# ps1-bare-metal +# https://github.com/spicyjpeg/ps1-bare-metal + +ps1-bare-metal - (C) 2023 spicyjpeg + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +# qrcodegen +# https://www.nayuki.io/page/qr-code-generator-library + +Copyright (c) 2022 Project Nayuki. (MIT License) + +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. diff --git a/assets/sounds/click.vag b/assets/sounds/click.vag new file mode 100644 index 0000000..151b098 Binary files /dev/null and b/assets/sounds/click.vag differ diff --git a/assets/sounds/enter.vag b/assets/sounds/enter.vag new file mode 100644 index 0000000..faf3627 Binary files /dev/null and b/assets/sounds/enter.vag differ diff --git a/assets/sounds/exit.vag b/assets/sounds/exit.vag new file mode 100644 index 0000000..2131b25 Binary files /dev/null and b/assets/sounds/exit.vag differ diff --git a/assets/sounds/move.vag b/assets/sounds/move.vag new file mode 100644 index 0000000..afe9e63 Binary files /dev/null and b/assets/sounds/move.vag differ diff --git a/assets/sounds/move_left.vag b/assets/sounds/move_left.vag new file mode 100644 index 0000000..ae8d084 Binary files /dev/null and b/assets/sounds/move_left.vag differ diff --git a/assets/sounds/move_right.vag b/assets/sounds/move_right.vag new file mode 100644 index 0000000..3416f50 Binary files /dev/null and b/assets/sounds/move_right.vag differ diff --git a/assets/textures/background.png b/assets/textures/background.png new file mode 100644 index 0000000..c14dc40 Binary files /dev/null and b/assets/textures/background.png differ diff --git a/assets/textures/font.metrics.json b/assets/textures/font.metrics.json new file mode 100644 index 0000000..5960d17 --- /dev/null +++ b/assets/textures/font.metrics.json @@ -0,0 +1,111 @@ +{ + " ": { "x": 0, "y": 0, "width": 4, "height": 9 }, + "!": { "x": 6, "y": 0, "width": 2, "height": 9 }, + "\"": { "x": 12, "y": 0, "width": 4, "height": 9 }, + "#": { "x": 18, "y": 0, "width": 6, "height": 9 }, + "$": { "x": 24, "y": 0, "width": 6, "height": 9 }, + "%": { "x": 30, "y": 0, "width": 6, "height": 9 }, + "&": { "x": 36, "y": 0, "width": 6, "height": 9 }, + "'": { "x": 42, "y": 0, "width": 2, "height": 9 }, + "(": { "x": 48, "y": 0, "width": 3, "height": 9 }, + ")": { "x": 54, "y": 0, "width": 3, "height": 9 }, + "*": { "x": 60, "y": 0, "width": 4, "height": 9 }, + "+": { "x": 66, "y": 0, "width": 6, "height": 9 }, + ",": { "x": 72, "y": 0, "width": 3, "height": 9 }, + "-": { "x": 78, "y": 0, "width": 6, "height": 9 }, + ".": { "x": 84, "y": 0, "width": 2, "height": 9 }, + "/": { "x": 90, "y": 0, "width": 6, "height": 9 }, + "0": { "x": 0, "y": 9, "width": 6, "height": 9 }, + "1": { "x": 6, "y": 9, "width": 6, "height": 9 }, + "2": { "x": 12, "y": 9, "width": 6, "height": 9 }, + "3": { "x": 18, "y": 9, "width": 6, "height": 9 }, + "4": { "x": 24, "y": 9, "width": 6, "height": 9 }, + "5": { "x": 30, "y": 9, "width": 6, "height": 9 }, + "6": { "x": 36, "y": 9, "width": 6, "height": 9 }, + "7": { "x": 42, "y": 9, "width": 6, "height": 9 }, + "8": { "x": 48, "y": 9, "width": 6, "height": 9 }, + "9": { "x": 54, "y": 9, "width": 6, "height": 9 }, + ":": { "x": 60, "y": 9, "width": 2, "height": 9 }, + ";": { "x": 66, "y": 9, "width": 3, "height": 9 }, + "<": { "x": 72, "y": 9, "width": 6, "height": 9 }, + "=": { "x": 78, "y": 9, "width": 6, "height": 9 }, + ">": { "x": 84, "y": 9, "width": 6, "height": 9 }, + "?": { "x": 90, "y": 9, "width": 6, "height": 9 }, + "@": { "x": 0, "y": 18, "width": 6, "height": 9 }, + "A": { "x": 6, "y": 18, "width": 6, "height": 9 }, + "B": { "x": 12, "y": 18, "width": 6, "height": 9 }, + "C": { "x": 18, "y": 18, "width": 6, "height": 9 }, + "D": { "x": 24, "y": 18, "width": 6, "height": 9 }, + "E": { "x": 30, "y": 18, "width": 6, "height": 9 }, + "F": { "x": 36, "y": 18, "width": 6, "height": 9 }, + "G": { "x": 42, "y": 18, "width": 6, "height": 9 }, + "H": { "x": 48, "y": 18, "width": 6, "height": 9 }, + "I": { "x": 54, "y": 18, "width": 4, "height": 9 }, + "J": { "x": 60, "y": 18, "width": 5, "height": 9 }, + "K": { "x": 66, "y": 18, "width": 6, "height": 9 }, + "L": { "x": 72, "y": 18, "width": 6, "height": 9 }, + "M": { "x": 78, "y": 18, "width": 6, "height": 9 }, + "N": { "x": 84, "y": 18, "width": 6, "height": 9 }, + "O": { "x": 90, "y": 18, "width": 6, "height": 9 }, + "P": { "x": 0, "y": 27, "width": 6, "height": 9 }, + "Q": { "x": 6, "y": 27, "width": 6, "height": 9 }, + "R": { "x": 12, "y": 27, "width": 6, "height": 9 }, + "S": { "x": 18, "y": 27, "width": 6, "height": 9 }, + "T": { "x": 24, "y": 27, "width": 6, "height": 9 }, + "U": { "x": 30, "y": 27, "width": 6, "height": 9 }, + "V": { "x": 36, "y": 27, "width": 6, "height": 9 }, + "W": { "x": 42, "y": 27, "width": 6, "height": 9 }, + "X": { "x": 48, "y": 27, "width": 6, "height": 9 }, + "Y": { "x": 54, "y": 27, "width": 6, "height": 9 }, + "Z": { "x": 60, "y": 27, "width": 6, "height": 9 }, + "[": { "x": 66, "y": 27, "width": 3, "height": 9 }, + "\\": { "x": 72, "y": 27, "width": 6, "height": 9 }, + "]": { "x": 78, "y": 27, "width": 3, "height": 9 }, + "^": { "x": 84, "y": 27, "width": 4, "height": 9 }, + "_": { "x": 90, "y": 27, "width": 6, "height": 9 }, + "`": { "x": 0, "y": 36, "width": 3, "height": 9 }, + "a": { "x": 6, "y": 36, "width": 6, "height": 9 }, + "b": { "x": 12, "y": 36, "width": 6, "height": 9 }, + "c": { "x": 18, "y": 36, "width": 6, "height": 9 }, + "d": { "x": 24, "y": 36, "width": 6, "height": 9 }, + "e": { "x": 30, "y": 36, "width": 6, "height": 9 }, + "f": { "x": 36, "y": 36, "width": 5, "height": 9 }, + "g": { "x": 42, "y": 36, "width": 6, "height": 9 }, + "h": { "x": 48, "y": 36, "width": 5, "height": 9 }, + "i": { "x": 54, "y": 36, "width": 2, "height": 9 }, + "j": { "x": 60, "y": 36, "width": 4, "height": 9 }, + "k": { "x": 66, "y": 36, "width": 5, "height": 9 }, + "l": { "x": 72, "y": 36, "width": 2, "height": 9 }, + "m": { "x": 78, "y": 36, "width": 6, "height": 9 }, + "n": { "x": 84, "y": 36, "width": 5, "height": 9 }, + "o": { "x": 90, "y": 36, "width": 6, "height": 9 }, + "p": { "x": 0, "y": 45, "width": 6, "height": 9 }, + "q": { "x": 6, "y": 45, "width": 6, "height": 9 }, + "r": { "x": 12, "y": 45, "width": 6, "height": 9 }, + "s": { "x": 18, "y": 45, "width": 6, "height": 9 }, + "t": { "x": 24, "y": 45, "width": 5, "height": 9 }, + "u": { "x": 30, "y": 45, "width": 5, "height": 9 }, + "v": { "x": 36, "y": 45, "width": 6, "height": 9 }, + "w": { "x": 42, "y": 45, "width": 6, "height": 9 }, + "x": { "x": 48, "y": 45, "width": 6, "height": 9 }, + "y": { "x": 54, "y": 45, "width": 6, "height": 9 }, + "z": { "x": 60, "y": 45, "width": 5, "height": 9 }, + "{": { "x": 66, "y": 45, "width": 4, "height": 9 }, + "|": { "x": 72, "y": 45, "width": 2, "height": 9 }, + "}": { "x": 78, "y": 45, "width": 4, "height": 9 }, + "~": { "x": 84, "y": 45, "width": 6, "height": 9 }, + + "\u007f": { "x": 90, "y": 45, "width": 6, "height": 9 }, + "\u0080": { "x": 0, "y": 54, "width": 6, "height": 9 }, + "\u0081": { "x": 6, "y": 54, "width": 6, "height": 9 }, + "\u0082": { "x": 12, "y": 54, "width": 4, "height": 9 }, + + "\u0083": { "x": 18, "y": 54, "width": 4, "height": 9 }, + "\u0084": { "x": 24, "y": 54, "width": 7, "height": 9, "icon": true }, + "\u0085": { "x": 31, "y": 54, "width": 7, "height": 9, "icon": true }, + "\u0086": { "x": 38, "y": 54, "width": 9, "height": 9, "icon": true }, + "\u0087": { "x": 47, "y": 54, "width": 8, "height": 10, "icon": true }, + "\u0088": { "x": 55, "y": 54, "width": 11, "height": 10, "icon": true }, + "\u0089": { "x": 66, "y": 54, "width": 12, "height": 10, "icon": true }, + "\u008a": { "x": 78, "y": 54, "width": 14, "height": 10, "icon": true } +} diff --git a/assets/textures/font.png b/assets/textures/font.png new file mode 100644 index 0000000..be70b46 Binary files /dev/null and b/assets/textures/font.png differ diff --git a/cmake/executable.ld b/cmake/executable.ld new file mode 100644 index 0000000..3e37c88 --- /dev/null +++ b/cmake/executable.ld @@ -0,0 +1,106 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +OUTPUT_FORMAT(elf32-littlemips) +ENTRY(_start) + +MEMORY { + KERNEL_RAM (rwx) : ORIGIN = 0x80000000, LENGTH = 0x010000 + APP_RAM (rwx) : ORIGIN = 0x80010000, LENGTH = 0x7f0000 +} + +SECTIONS { + /* Code sections */ + + .text : { + *(.text .text.* .gnu.linkonce.t.*) + *(.plt .MIPS.stubs) + } > APP_RAM + + .rodata : { + *(.rodata .rodata.* .gnu.linkonce.r.*) + } > APP_RAM + + /* Global constructor/destructor arrays */ + + . = ALIGN((. != 0) ? 4 : 1); + _preinitArrayStart = .; + + .preinit_array : { + KEEP(*(.preinit_array)) + } + + _preinitArrayEnd = .; + _initArrayStart = .; + + .init_array : { + KEEP(*(SORT(.init_array.*) SORT(.ctors.*))) + KEEP(*(.init_array .ctors)) + } > APP_RAM + + _initArrayEnd = .; + _finiArrayStart = .; + + .fini_array : { + KEEP(*(.fini_array .dtors)) + KEEP(*(SORT(.fini_array.*) SORT(.dtors.*))) + } > APP_RAM + + _finiArrayEnd = .; + + /* Data sections */ + + .data : { + *(.data .data.* .gnu.linkonce.d.*) + } > APP_RAM + + /* + * Set _gp (copied to $gp) to point to the beginning of .sdata plus 0x8000, + * so anything within .sdata and .sbss can be accessed using the $gp + * register as base plus a signed 16-bit immediate. + */ + _gp = ALIGN(16) + 0x7ff0; + + .sdata : { + *(.sdata .sdata.* .gnu.linkonce.s.*) + } > APP_RAM + + . = ALIGN((. != 0) ? 4 : 1); + _bssStart = .; + + .sbss (NOLOAD) : { + *(.sbss .sbss.* .gnu.linkonce.sb.*) + *(.scommon) + } > APP_RAM + + .bss (NOLOAD) : { + *(.bss .bss.* .gnu.linkonce.b.*) + *(COMMON) + } > APP_RAM + + . = ALIGN((. != 0) ? 4 : 1); + _bssEnd = .; + + /* Dummy sections */ + + .dummy (NOLOAD) : { + KEEP(*(.dummy)) + } > APP_RAM + + /DISCARD/ : { + *(.gnu.lto_*) + } +} diff --git a/cmake/setup.cmake b/cmake/setup.cmake new file mode 100644 index 0000000..0a3ec4c --- /dev/null +++ b/cmake/setup.cmake @@ -0,0 +1,136 @@ +# ps1-bare-metal - (C) 2023 spicyjpeg +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +# PERFORMANCE OF THIS SOFTWARE. + +cmake_minimum_required(VERSION 3.25) + +# Override the default file extensions for executables and libraries. This is +# not strictly required, but it makes CMake's behavior more consistent. +set(CMAKE_EXECUTABLE_SUFFIX .elf) +set(CMAKE_STATIC_LIBRARY_PREFIX lib) +set(CMAKE_STATIC_LIBRARY_SUFFIX .a) + +# Add libgcc.a (-lgcc) to the set of libraries linked to all executables by +# default. This library ships with GCC and must be linked to anything compiled +# with it. +link_libraries(-lgcc) + +# Create a dummy "flags" library that is not made up of any files, but adds the +# appropriate compiler and linker flags for PS1 executables to anything linked +# to it. The library is then added to the default set of libraries. +add_library (flags INTERFACE) +link_libraries(flags) + +target_compile_options( + flags INTERFACE + -g + -Wall + -Wa,--strip-local-absolute + -ffreestanding + -fno-builtin + -fno-pic + -nostdlib + -fdata-sections + -ffunction-sections + -fsigned-char + -fno-strict-overflow + -msoft-float + -march=r3000 + -mabi=32 + -mno-mt + -mno-llsc + -mno-abicalls + -mgpopt + -mno-extern-sdata + -G8 + $<$: + # These options will only be added when compiling C++ source files. + -fno-exceptions + -fno-rtti + -fno-unwind-tables + -fno-threadsafe-statics + -fno-use-cxa-atexit + > + $, + # These options will only be added if CMAKE_BUILD_TYPE is set to Debug. + -Og + -mdivide-breaks + , + # These options will be added if CMAKE_BUILD_TYPE is not set to Debug. + -O2 + #-flto + > +) +target_link_options( + flags INTERFACE + -static + -nostdlib + -Wl,-gc-sections + -G8 + -T${CMAKE_CURRENT_LIST_DIR}/executable.ld +) + +# Define a new ps1_target_incbin() command to embed the contents of a binary +# file into an executable. This is accomplished by generating an assembly +# listing that uses the .incbin directive to embed the file from a template. +function(ps1_target_incbin + target type section symbolName sizeSymbolName path +) + string(MAKE_C_IDENTIFIER "${symbolName}" _symbolName) + string(MAKE_C_IDENTIFIER "${sizeSymbolName}" _sizeSymbolName) + string(MAKE_C_IDENTIFIER "${section}" _section) + + cmake_path(ABSOLUTE_PATH path OUTPUT_VARIABLE _path) + + # Generate a unique name for the assembly file by hashing the target name + # and symbol name, and place it in the current build directory. + string(SHA1 _hash "${target} ${_symbolName}") + set(_assemblyFile "${CMAKE_CURRENT_BINARY_DIR}/incbin_${_hash}.s") + + file( + CONFIGURE + OUTPUT "${_assemblyFile}" + CONTENT [[ +.section ${_section}.${_symbolName}, "aw" +.balign 8 + +.global ${_symbolName} +.local ${_symbolName}_end +.type ${_symbolName}, @object +.size ${_symbolName}, (${_symbolName}_end - ${_symbolName}) + +${_symbolName}: + .incbin "${_path}" +${_symbolName}_end: + +.section ${_section}.${_sizeSymbolName}, "aw" +.balign 4 + +.global ${_sizeSymbolName} +.type ${_sizeSymbolName}, @object +.size ${_sizeSymbolName}, 4 + +${_sizeSymbolName}: + .int (${_symbolName}_end - ${_symbolName}) +]] + ESCAPE_QUOTES + NEWLINE_STYLE LF + ) + + # Add the assembly file to the target and add the embedded binary file as a + # dependency to make sure it is built first if it needs to be built. + target_sources("${target}" "${type}" "${_assemblyFile}") + set_source_files_properties( + "${_assemblyFile}" PROPERTIES OBJECT_DEPENDS "${_path}" + ) +endfunction() diff --git a/cmake/toolchain.cmake b/cmake/toolchain.cmake new file mode 100644 index 0000000..c9be047 --- /dev/null +++ b/cmake/toolchain.cmake @@ -0,0 +1,90 @@ +# ps1-bare-metal - (C) 2023 spicyjpeg +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +# PERFORMANCE OF THIS SOFTWARE. + +cmake_minimum_required(VERSION 3.25) + +# Create two user-editable variables to allow for a custom compiler toolchain to +# be used by passing -DTOOLCHAIN_PATH=... and -DTOOLCHAIN_TARGET=... to CMake. +set( + TOOLCHAIN_PATH "" CACHE PATH + "Directory containing GCC toolchain executables (if not listed in PATH)" +) +set( + TOOLCHAIN_TARGET mipsel-none-elf CACHE STRING + "GCC toolchain target triplet" +) + +# Prevent CMake from using any host compiler by manually overriding the platform +# and setting it to "generic" (i.e. no defaults). +set(CMAKE_SYSTEM_NAME Generic) +set(CMAKE_SYSTEM_PROCESSOR mipsel) + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) + +# Tell CMake not to run the linker when testing the toolchain and to pass our +# custom variables through to autogenerated "compiler test" projects. This will +# prevent the compiler detection process from erroring out. +set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) +set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES TOOLCHAIN_PATH TOOLCHAIN_TARGET) + +# Always generate compile_commands.json when building. This allows some IDEs and +# tools (such as clangd) to automatically configure include directories and +# other options. +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +## Toolchain path setup + +# Attempt to locate the GCC command (mipsel-none-elf-gcc) in the provided path +# (if any) as well as in the system's standard paths for programs such as the +# ones listed in the PATH environment variable. +find_program( + _gccPath ${TOOLCHAIN_TARGET}-gcc + HINTS + "${TOOLCHAIN_PATH}" + "${TOOLCHAIN_PATH}/bin" + "${TOOLCHAIN_PATH}/../bin" + NO_CACHE REQUIRED +) +cmake_path(GET _gccPath PARENT_PATH _toolchainPath) + +# If a valid path was not provided but GCC was found, overwrite the variable to +# avoid searching again the next time the project is configured. +if(NOT IS_DIRECTORY TOOLCHAIN_PATH) + set( + TOOLCHAIN_PATH "${_toolchainPath}" CACHE PATH + "Directory containing GCC toolchain executables (if not listed in PATH)" + FORCE + ) +endif() + +# Set the paths to all tools required by CMake. The appropriate extension for +# executables (.exe on Windows, none on Unix) is extracted from the path to GCC +# using a regular expression, as CMake does not otherwise expose it. +set(_prefix "${_toolchainPath}/${TOOLCHAIN_TARGET}-") +string(REGEX MATCH ".+-gcc(.*)$" _dummy "${_gccPath}") + +set(CMAKE_ASM_COMPILER "${_prefix}gcc${CMAKE_MATCH_1}") +set(CMAKE_C_COMPILER "${_prefix}gcc${CMAKE_MATCH_1}") +set(CMAKE_CXX_COMPILER "${_prefix}g++${CMAKE_MATCH_1}") +set(CMAKE_AR "${_prefix}ar${CMAKE_MATCH_1}") +set(CMAKE_LINKER "${_prefix}ld${CMAKE_MATCH_1}") +set(CMAKE_RANLIB "${_prefix}ranlib${CMAKE_MATCH_1}") +set(CMAKE_OBJCOPY "${_prefix}objcopy${CMAKE_MATCH_1}") +set(CMAKE_SIZE "${_prefix}size${CMAKE_MATCH_1}") +set(CMAKE_STRIP "${_prefix}strip${CMAKE_MATCH_1}") + +# Continue initialization by running setup.cmake after project() is invoked. +set(CMAKE_PROJECT_INCLUDE "${CMAKE_CURRENT_LIST_DIR}/setup.cmake") diff --git a/data/games.json b/data/games.json new file mode 100644 index 0000000..58a07c4 --- /dev/null +++ b/data/games.json @@ -0,0 +1,2081 @@ +[ + { + "mameID": "darkhleg", + "code": "GX706", + "region": "JAA", + "name": "Dark Horse Legend", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "strgchmp", + "code": "GQ710", + "region": "UAA", + "name": "Steering Champ", + "year": 1997, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "hndlchmp", + "code": "GQ710", + "region": "SAA", + "name": "Handle Champ", + "year": 1997, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "hndlchmpj", + "code": "GQ710", + "region": "JAB", + "name": "Handle Champ", + "year": 1997, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "fbaitbc", + "code": "GE765", + "region": "UAB", + "name": "Fisherman's Bait: A Bass Challenge", + "year": 1998, + "ioBoard": "GE765-PWB(B)", + "installerVersion": null + }, + { + "mameID": "bassangl", + "code": "GE765", + "region": "JAA", + "name": "Bass Angler", + "year": 1998, + "ioBoard": "GE765-PWB(B)", + "installerVersion": null + }, + { + "mameID": "powyakex", + "code": "GX802", + "region": "JAB", + "name": "Jikkyou Powerful Pro Yakyuu EX", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "jppyex98", + "code": "GC811", + "region": "JAA", + "name": "Jikkyou Powerful Pro Yakyuu EX '98", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "konam80s", + "code": "GC826", + "region": "EAA", + "name": "Konami 80's AC Special", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "konam80su", + "code": "GC826", + "region": "UAA", + "name": "Konami 80's AC Special", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "konam80sa", + "code": "GC826", + "region": "AAA", + "name": "Konami 80's AC Special", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "konam80sk", + "code": "GC826", + "region": "KAA", + "name": "Konami 80's AC Special", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "konam80sj", + "code": "GC826", + "region": "JAA", + "name": "Konami 80's Gallery", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "ddr", + "code": "GC845", + "region": "JBA", + "name": "Dance Dance Revolution: Internet Ranking Ver.", + "year": 1998, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddrja", + "code": "GC845", + "region": "JAA", + "name": "Dance Dance Revolution", + "year": 1998, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddrjb", + "code": "GC845", + "region": "JAB", + "name": "Dance Dance Revolution", + "year": 1998, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddru", + "code": "GN845", + "region": "UAA", + "name": "Dance Dance Revolution", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "dstageea", + "code": "GN845", + "region": "EAA", + "name": "Dancing Stage", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "dstage", + "code": "GC845", + "region": "EBA", + "name": "Dancing Stage: INTERNET R@NKING", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddra", + "code": "GN845", + "region": "AAA", + "name": "Dance Dance Revolution", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "fbait2bc", + "code": "GE865", + "region": "UAB", + "name": "Fisherman's Bait 2: A Bass Challenge", + "year": 1998, + "ioBoard": "GE765-PWB(B)", + "installerVersion": null + }, + { + "mameID": "bassang2", + "code": "GE865", + "region": "JAA", + "name": "Bass Angler 2", + "year": 1998, + "ioBoard": "GE765-PWB(B)", + "installerVersion": null + }, + { + "mameID": "dmx", + "code": "GQ874", + "region": "JAA", + "name": "Dance Maniax", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.6" + }, + { + "mameID": "dmxa", + "code": "GQ874", + "region": "AAA", + "name": "Dance Maniax", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.6" + }, + { + "mameID": "dncfrks", + "code": "GK874", + "region": "KAA", + "name": "Dance Freaks", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.6" + }, + { + "mameID": "hyperbbc", + "code": "GQ876", + "region": "EAA", + "name": "Hyper Bishi Bashi Champ [3-player]", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "hyperbbca", + "code": "GQ876", + "region": "AAA", + "name": "Hyper Bishi Bashi Champ [3-player]", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "hyperbbck", + "code": "GE876", + "region": "KAA", + "name": "Hyper Bishi Bashi Champ [3-player]", + "year": 1998, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "gchgchmp", + "code": "GE877", + "region": "JAB", + "name": "Gachaga Champ", + "year": 1999, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "drmn", + "code": "GQ881", + "region": "JAD", + "name": "DrumMania", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "drmnja", + "code": "GQ881", + "region": "JAD", + "name": "DrumMania Update CD", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "drmnu", + "code": "GQ881", + "region": "UAB", + "name": "DrumMania", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "pcnfrks", + "code": "GQ881", + "region": "EAB", + "name": "PercussionFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "pcnfrksa", + "code": "GQ881", + "region": "AAB", + "name": "PercussionFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "pcnfrksk", + "code": "GQ881", + "region": "KAB", + "name": "PercussionFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrk2m", + "code": "GQ883", + "region": "JAD", + "name": "GuitarFreaks 2ndMIX Ver 1.01", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrk2mja", + "code": "GQ883", + "region": "JAA", + "name": "GuitarFreaks 2ndMIX", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrk2mu", + "code": "GQ883", + "region": "UAA", + "name": "GuitarFreaks 2ndMIX", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrk2me", + "code": "GQ883", + "region": "EAA", + "name": "GuitarFreaks 2ndMIX", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrk2ma", + "code": "GQ883", + "region": "AAA", + "name": "GuitarFreaks 2ndMIX", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrk2mk", + "code": "GQ883", + "region": "KAA", + "name": "GuitarFreaks 2ndMIX", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "dsftkd", + "code": "GC884", + "region": "JAA", + "name": "Dancing Stage featuring TRUE KiSS DESTiNATiON", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddr2ml", + "code": "GE885", + "region": "JAC", + "name": "Dance Dance Revolution 2ndMIX: Dance Dance Revolution LINK VERSION", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddr2mlja", + "code": "GE885", + "region": "JAA", + "name": "Dance Dance Revolution 2ndMIX: Dance Dance Revolution LINK VERSION", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddr2mljb", + "code": "GE885", + "region": "JAB", + "name": "Dance Dance Revolution 2ndMIX: Dance Dance Revolution LINK VERSION", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrks", + "code": "GQ886", + "region": "JAD", + "name": "GuitarFreaks Ver 1.01", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrksu", + "code": "GQ886", + "region": "UAD", + "name": "GuitarFreaks Ver 1.01", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrkse", + "code": "GQ886", + "region": "EAD", + "name": "GuitarFreaks Ver 1.01", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrksa", + "code": "GQ886", + "region": "AAD", + "name": "GuitarFreaks Ver 1.01", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrksja", + "code": "GQ886", + "region": "JAA", + "name": "GuitarFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrksua", + "code": "GQ886", + "region": "UAA", + "name": "GuitarFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrksea", + "code": "GQ886", + "region": "EAA", + "name": "GuitarFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrksaa", + "code": "GQ886", + "region": "AAA", + "name": "GuitarFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrksjb", + "code": "GQ886", + "region": "JAC", + "name": "GuitarFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrksub", + "code": "GQ886", + "region": "UAC", + "name": "GuitarFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrkseb", + "code": "GQ886", + "region": "EAC", + "name": "GuitarFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrksab", + "code": "GQ886", + "region": "AAC", + "name": "GuitarFreaks", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddr3m", + "code": "GN887", + "region": "JAA", + "name": "Dance Dance Revolution 3rdMIX", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.0" + }, + { + "mameID": "ddr3mja", + "code": "GE887", + "region": "JAA", + "name": "Dance Dance Revolution 3rdMIX", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.0" + }, + { + "mameID": "ddr3ma", + "code": "GN887", + "region": "AAA", + "name": "Dance Dance Revolution 3rdMIX", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.1" + }, + { + "mameID": "ddr3maa", + "code": "GE887", + "region": "AAA", + "name": "Dance Dance Revolution 3rdMIX", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.1" + }, + { + "mameID": "ddr3mk", + "code": "GN887", + "region": "KBA", + "name": "Dance Dance Revolution 3rdMIX: Ver.Korea2", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.3" + }, + { + "mameID": "ddr3mka", + "code": "GN887", + "region": "KAA", + "name": "Dance Dance Revolution 3rdMIX: Ver.Korea", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.0" + }, + { + "mameID": "ddr3mkb", + "code": "GE887", + "region": "KBA", + "name": "Dance Dance Revolution 3rdMIX: Ver.Korea2", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.3" + }, + { + "mameID": "ddr3mkc", + "code": "GE887", + "region": "KAA", + "name": "Dance Dance Revolution 3rdMIX: Ver.Korea", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.3" + }, + { + "mameID": "fbaitmc", + "code": "GX889", + "region": "EA", + "name": "Fisherman's Bait: Marlin Challenge", + "year": 1999, + "ioBoard": "GE765-PWB(B)", + "installerVersion": null + }, + { + "mameID": "fbaitmcu", + "code": "GX889", + "region": "UA", + "name": "Fisherman's Bait: Marlin Challenge", + "year": 1999, + "ioBoard": "GE765-PWB(B)", + "installerVersion": null + }, + { + "mameID": "fbaitmca", + "code": "GX889", + "region": "AA", + "name": "Fisherman's Bait: Marlin Challenge", + "year": 1999, + "ioBoard": "GE765-PWB(B)", + "installerVersion": null + }, + { + "mameID": "fbaitmcj", + "code": "GX889", + "region": "JA", + "name": "Fisherman's Bait: Marlin Challenge", + "year": 1999, + "ioBoard": "GE765-PWB(B)", + "installerVersion": null + }, + { + "mameID": "ddr2m", + "code": "GN895", + "region": "JAA", + "name": "Dance Dance Revolution 2ndMIX", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddrbocd", + "code": "GE892", + "region": "JAA", + "name": "Dance Dance Revolution Best of Cool Dancers", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddrsbm", + "code": "GQ894", + "region": "JAA", + "name": "Dance Dance Revolution Solo Bass Mix", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": null + }, + { + "mameID": "ddr2mc", + "code": "GE896", + "region": "JAA", + "name": "Dance Dance Revolution 2ndMIX with beatmania IIDX CLUB VERSiON", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddrs2000", + "code": "GC905", + "region": "JAA", + "name": "Dance Dance Revolution Solo 2000", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.2" + }, + { + "mameID": "ddrs2000a", + "code": "GC905", + "region": "AAA", + "name": "Dance Dance Revolution Solo 2000", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.2" + }, + { + "mameID": "gunmania", + "code": "GL906", + "region": "JAA", + "name": "GunMania", + "year": 2000, + "ioBoard": "PWB0000073070", + "installerVersion": null + }, + { + "mameID": "hypbbc2p", + "code": "GX908", + "region": "JAA", + "name": "Hyper Bishi Bashi Champ [2-player]", + "year": 1999, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "hypbbc2pk", + "code": "GX908", + "region": "KAA", + "name": "Hyper Bishi Bashi Champ [2-player]", + "year": 1999, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "dsfdct", + "code": "GC910", + "region": "JCA", + "name": "Dancing Stage featuring Dreams Come True", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": null + }, + { + "mameID": "dsfdctja", + "code": "GC910", + "region": "JAA", + "name": "Dancing Stage featuring Dreams Come True", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": null + }, + { + "mameID": "drmn2m", + "code": "GE912", + "region": "JAB", + "name": "DrumMania 2ndMIX", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.5" + }, + { + "mameID": "drmn2mja", + "code": "GE912", + "region": "JAB", + "name": "DrumMania 2ndMIX Session Power Up Kit", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.5" + }, + { + "mameID": "pcnfrk2m", + "code": "GE912", + "region": "AAA", + "name": "PercussionFreaks 2ndMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.5" + }, + { + "mameID": "pcnfrk2maa", + "code": "GE912", + "region": "AAB", + "name": "PercussionFreaks 2ndMIX Session Power Up Kit", + "year": 1999, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.5" + }, + { + "mameID": "pcnfrk2mk", + "code": "GE912", + "region": "KAA", + "name": "PercussionFreaks 2ndMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.5" + }, + { + "mameID": "fghtmn", + "code": "GQ918", + "region": "EAA", + "name": "Fighting Mania", + "year": 2000, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "fghtmnu", + "code": "GQ918", + "region": "UAA", + "name": "Fighting Mania", + "year": 2000, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "fghtmna", + "code": "GQ918", + "region": "AAA", + "name": "Fighting Mania", + "year": 2000, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "fghtmnk", + "code": "GQ918", + "region": "KAA", + "name": "Fighting Mania", + "year": 2000, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "pnchmn", + "code": "GQ918", + "region": "JAB", + "name": "Punch Mania: Hokuto no Ken", + "year": 2000, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "pnchmnja", + "code": "GQ918", + "region": "JAB", + "name": "Punch Mania: Hokuto no Ken [alt CD]", + "year": 2000, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "ddrkara", + "code": "GQ921", + "region": "JBB", + "name": "Dance Dance Revolution Karaoke MIX", + "year": 1999, + "ioBoard": "GX921-PWB(B)", + "installerVersion": null + }, + { + "mameID": "gtrfrk2ml1", + "code": "GE929", + "region": "JAA", + "name": "GuitarFreaks 2ndMIX Link Kit 1", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "gtrfrk2ml2", + "code": "GC929", + "region": "JBB", + "name": "GuitarFreaks 2ndMIX Link Kit 2", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "stepchmp", + "code": "GQ930", + "region": "JA", + "name": "Step Champ", + "year": 1999, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "dsem", + "code": "GK936", + "region": "EAA", + "name": "Dancing Stage EuroMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.7" + }, + { + "mameID": "dsemea", + "code": "GE936", + "region": "EAA", + "name": "Dancing Stage EuroMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.7" + }, + { + "mameID": "ddrkara2", + "code": "GQ947", + "region": "JAA", + "name": "Dance Dance Revolution Karaoke MIX 2", + "year": 2000, + "ioBoard": "GX921-PWB(B)", + "installerVersion": null + }, + { + "mameID": "gtrfrk3m", + "code": "GE949", + "region": "JAC", + "name": "GuitarFreaks 3rdMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.4" + }, + { + "mameID": "gtrfrk3mja", + "code": "GE949", + "region": "JAB", + "name": "GuitarFreaks 3rdMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.4" + }, + { + "mameID": "gtrfrk3mjb", + "code": "GE949", + "region": "JAZ02", + "name": "GuitarFreaks 3rdMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.4" + }, + { + "mameID": "ddr2mc2", + "code": "GE984", + "region": "JAA", + "name": "Dance Dance Revolution 2ndMIX AND beatmania IIDX substream CLUB VERSiON 2", + "year": 1999, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "animechmp", + "code": "GCA07", + "region": "JAA", + "name": "Anime Champ", + "year": 2000, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "pnchmn2", + "code": "GQA09", + "region": "JAA", + "name": "Punch Mania 2: Hokuto no Ken", + "year": 2000, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "pnchmn2ja", + "code": "GQA09", + "region": "JRA", + "name": "Punch Mania 2: Hokuto no Ken e-Amusement", + "year": 2000, + "ioBoard": "GX700-PWB(F)", + "installerVersion": null + }, + { + "mameID": "salarymc", + "code": "GCA18", + "region": "JAA", + "name": "Salary Man Champ [2-player]", + "year": 2000, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "ddr3mp", + "code": "GCA22", + "region": "JAA", + "name": "Dance Dance Revolution 3rdMIX PLUS", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.6" + }, + { + "mameID": "drmn3m", + "code": "GCA23", + "region": "JAA", + "name": "DrumMania 3rdMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "pcnfrk3m", + "code": "GCA23", + "region": "AAA", + "name": "PercussionFreaks 3rdMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "pcnfrk3mk", + "code": "GCA23", + "region": "KAA", + "name": "PercussionFreaks 3rdMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "gtrfrk4m", + "code": "GEA24", + "region": "JAA", + "name": "GuitarFreaks 4thMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "drmn4m", + "code": "GEA25", + "region": "JAA", + "name": "DrumMania 4thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "drmn4mja", + "code": "GEA25", + "region": "JYA", + "name": "DrumMania 4thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "drmn4mjb", + "code": "GEA25", + "region": "JZA", + "name": "DrumMania 4thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "pcnfrk4m", + "code": "GEA25", + "region": "AAA", + "name": "PercussionFreaks 4thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "pcnfrk4maa", + "code": "GEA25", + "region": "AYA", + "name": "PercussionFreaks 4thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "pcnfrk4mab", + "code": "GEA25", + "region": "AZA", + "name": "PercussionFreaks 4thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "pcnfrk4mk", + "code": "GCA25", + "region": "KAA", + "name": "PercussionFreaks 4thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "pcnfrk4mka", + "code": "GKA25", + "region": "KAA", + "name": "PercussionFreaks 4thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5m", + "code": "GEA26", + "region": "JAA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5mja", + "code": "GEA26", + "region": "JYA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5mjb", + "code": "GEA26", + "region": "JZA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5mjc", + "code": "GCA26", + "region": "JAA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5mjd", + "code": "GCA26", + "region": "JYA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5mje", + "code": "GCA26", + "region": "JZA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5ma", + "code": "GEA26", + "region": "AAA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5maa", + "code": "GEA26", + "region": "AYA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5mab", + "code": "GEA26", + "region": "AZA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5mac", + "code": "GCA26", + "region": "AAA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5mad", + "code": "GCA26", + "region": "AYA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk5mae", + "code": "GCA26", + "region": "AZA", + "name": "GuitarFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "ddr5m", + "code": "GCA27", + "region": "JAA", + "name": "Dance Dance Revolution 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "ddr4m", + "code": "GCA33", + "region": "JAA", + "name": "Dance Dance Revolution 4thMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "ddr4mja", + "code": "GUA33", + "region": "JAA", + "name": "Dance Dance Revolution 4thMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "ddr4ma", + "code": "GCA33", + "region": "AAA", + "name": "Dance Dance Revolution 4thMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "ddr4maa", + "code": "GUA33", + "region": "AAA", + "name": "Dance Dance Revolution 4thMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "ddrs4m", + "code": "GCA33", + "region": "JBA", + "name": "Dance Dance Revolution Solo 4thMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "ddrs4mja", + "code": "GUA33", + "region": "JBA", + "name": "Dance Dance Revolution Solo 4thMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "ddrs4ma", + "code": "GCA33", + "region": "ABA", + "name": "Dance Dance Revolution Solo 4thMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "ddrs4maa", + "code": "GUA33", + "region": "ABA", + "name": "Dance Dance Revolution Solo 4thMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "ddr4mp", + "code": "GCA34", + "region": "JAA", + "name": "Dance Dance Revolution 4thMIX PLUS", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "ddrs4mp", + "code": "GCA34", + "region": "JBA", + "name": "Dance Dance Revolution Solo 4thMIX PLUS", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "kicknkick", + "code": "GNA36", + "region": "EAA", + "name": "Kick & Kick", + "year": 2001, + "ioBoard": "GX700-PWB(K)", + "installerVersion": null + }, + { + "mameID": "dsfdr", + "code": "GCA37", + "region": "JAA", + "name": "Dancing Stage Featuring Disney's Rave", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "dmx2mapp", + "code": "GCA38", + "region": "JAA", + "name": "Dance Maniax 2ndMIX append JPARADISE", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "dmx2mappja", + "code": "GCA38", + "region": "JBA", + "name": "Dance Maniax 2ndMIX append JPARADISE for Dance Maniax", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "dmx2mappjb", + "code": "GCA38", + "region": "JRA", + "name": "Dance Maniax 2ndMIX append JPARADISE e-Amusement", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "dmx2m", + "code": "GCA39", + "region": "JAA", + "name": "Dance Maniax 2ndMIX", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "dmx2mja", + "code": "GCA39", + "region": "JRA", + "name": "Dance Maniax 2ndMIX e-Amusement", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "mamboagg", + "code": "GQA40", + "region": "JAB", + "name": "Mambo A Go-Go", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "mamboaggja", + "code": "GQA40", + "region": "JRB", + "name": "Mambo A Go-Go e-Amusement", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "ddrusa", + "code": "GKA44", + "region": "UAA", + "name": "Dance Dance Revolution USA", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "ddrusaa", + "code": "GEA44", + "region": "UAA", + "name": "Dance Dance Revolution USA", + "year": 2000, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.8" + }, + { + "mameID": "drmn5m", + "code": "GCB05", + "region": "JAA", + "name": "DrumMania 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "drmn5mja", + "code": "GCB05", + "region": "JYA", + "name": "DrumMania 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "drmn5mjb", + "code": "GCB05", + "region": "JZA", + "name": "DrumMania 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "pcnfrk5m", + "code": "GCB05", + "region": "AAA", + "name": "PercussionFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "pcnfrk5maa", + "code": "GCB05", + "region": "AYA", + "name": "PercussionFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "pcnfrk5mab", + "code": "GCB05", + "region": "AZA", + "name": "PercussionFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "pcnfrk5mk", + "code": "GCB05", + "region": "KAA", + "name": "PercussionFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "pcnfrk5mka", + "code": "GKB05", + "region": "KAA", + "name": "PercussionFreaks 5thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk6m", + "code": "GCB06", + "region": "JAA", + "name": "GuitarFreaks 6thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk6mja", + "code": "GCB06", + "region": "JYA", + "name": "GuitarFreaks 6thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gtrfrk6mjb", + "code": "GCB06", + "region": "JZA", + "name": "GuitarFreaks 6thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "drmn6m", + "code": "GCB16", + "region": "JAA", + "name": "DrumMania 6thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn6mja", + "code": "GCB16", + "region": "JYA", + "name": "DrumMania 6thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn6mjb", + "code": "GCB16", + "region": "JZA", + "name": "DrumMania 6thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk6m", + "code": "GCB16", + "region": "AAA", + "name": "PercussionFreaks 6thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk6maa", + "code": "GCB16", + "region": "AYA", + "name": "PercussionFreaks 6thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk6mab", + "code": "GCB16", + "region": "AZA", + "name": "PercussionFreaks 6thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk7m", + "code": "GCB17", + "region": "JAA", + "name": "GuitarFreaks 7thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk7mja", + "code": "GCB17", + "region": "JYA", + "name": "GuitarFreaks 7thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk7mjb", + "code": "GCB17", + "region": "JZA", + "name": "GuitarFreaks 7thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "ddrmax", + "code": "GCB19", + "region": "JAA", + "name": "DDRMAX: Dance Dance Revolution 6thMIX", + "year": 2001, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "ddrmax2", + "code": "GCB20", + "region": "JAA", + "name": "DDRMAX2: Dance Dance Revolution 7thMIX", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "mrtlbeat", + "code": "GEB47", + "region": "JAB", + "name": "Martial Beat", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "mrtlbeatja", + "code": "GEB47", + "region": "JBA", + "name": "Martial Beat", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "mrtlbeatjb", + "code": "GNB47", + "region": "JAB", + "name": "Martial Beat", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "mrtlbeatjc", + "code": "GNB47", + "region": "JBA", + "name": "Martial Beat", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.9" + }, + { + "mameID": "gbbchmp", + "code": "GBA48", + "region": "JAB", + "name": "Great Bishi Bashi Champ", + "year": 2002, + "ioBoard": null, + "installerVersion": null + }, + { + "mameID": "drmn7m", + "code": "GCC07", + "region": "JBA", + "name": "DrumMania 7thMIX power-up ver.", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn7mja", + "code": "GCC07", + "region": "JAA", + "name": "DrumMania 7thMIX", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn7mjb", + "code": "GCC07", + "region": "JYA", + "name": "DrumMania 7thMIX", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn7mjc", + "code": "GCC07", + "region": "JZA", + "name": "DrumMania 7thMIX", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk7m", + "code": "GCC07", + "region": "AAA", + "name": "PercussionFreaks 7thMIX", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk7maa", + "code": "GCC07", + "region": "AYA", + "name": "PercussionFreaks 7thMIX", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk7mab", + "code": "GCC07", + "region": "AZA", + "name": "PercussionFreaks 7thMIX", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk8m", + "code": "GCC08", + "region": "JBA", + "name": "GuitarFreaks 8thMIX power-up ver.", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk8mja", + "code": "GCC08", + "region": "JAA", + "name": "GuitarFreaks 8thMIX", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk8mjb", + "code": "GCC08", + "region": "JYA", + "name": "GuitarFreaks 8thMIX", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk8mjc", + "code": "GCC08", + "region": "JZA", + "name": "GuitarFreaks 8thMIX", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "dsem2", + "code": "GKC23", + "region": "EAA", + "name": "Dancing Stage EuroMIX 2", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "dsem2ea", + "code": "GCC23", + "region": "EAA", + "name": "Dancing Stage EuroMIX 2", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "ddrextrm", + "code": "GCC36", + "region": "JAA", + "name": "Dance Dance Revolution EXTREME", + "year": 2002, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn8m", + "code": "GCC38", + "region": "JAA", + "name": "DrumMania 8thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn8mja", + "code": "GCC38", + "region": "JBA", + "name": "DrumMania 8thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk8m", + "code": "GCC38", + "region": "AAA", + "name": "PercussionFreaks 8thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk9m", + "code": "GCC39", + "region": "JAA", + "name": "GuitarFreaks 9thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk9mja", + "code": "GCC39", + "region": "JBA", + "name": "GuitarFreaks 9thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn9m", + "code": "GCD09", + "region": "JAB", + "name": "DrumMania 9thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn9mja", + "code": "GCD09", + "region": "JAA", + "name": "DrumMania 9thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn9mjb", + "code": "GCD09", + "region": "JAA", + "name": "DrumMania 9thMIX e-Amusement", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn9mjc", + "code": "GCD09", + "region": "JBB", + "name": "DrumMania 9thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn9mjd", + "code": "GCD09", + "region": "JBA", + "name": "DrumMania 9thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn9mje", + "code": "GCD09", + "region": "JBA", + "name": "DrumMania 9thMIX e-Amusement", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk9m", + "code": "GCD09", + "region": "AAA", + "name": "PercussionFreaks 9thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk9maa", + "code": "GCD09", + "region": "AAA", + "name": "PercussionFreaks 9thMIX e-Amusement", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk9mab", + "code": "GCD09", + "region": "ABA", + "name": "PercussionFreaks 9thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk9mac", + "code": "GCD09", + "region": "ABA", + "name": "PercussionFreaks 9thMIX e-Amusement", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk10m", + "code": "GCD10", + "region": "JAB", + "name": "GuitarFreaks 10thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk10mja", + "code": "GCD10", + "region": "JAA", + "name": "GuitarFreaks 10thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk10mjb", + "code": "GCD10", + "region": "JAA", + "name": "GuitarFreaks 10thMIX e-Amusement", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk10mjc", + "code": "GCD10", + "region": "JBB", + "name": "GuitarFreaks 10thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk10mjd", + "code": "GCD10", + "region": "JBA", + "name": "GuitarFreaks 10thMIX", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk10mje", + "code": "GCD10", + "region": "JBA", + "name": "GuitarFreaks 10thMIX e-Amusement", + "year": 2003, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk11m", + "code": "GCD39", + "region": "JAA", + "name": "GuitarFreaks 11thMIX", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk11mja", + "code": "GCD39", + "region": "JAA", + "name": "GuitarFreaks 11thMIX e-Amusement", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk11mjb", + "code": "GCD39", + "region": "JBA", + "name": "GuitarFreaks 11thMIX", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk11mjc", + "code": "GCD39", + "region": "JBA", + "name": "GuitarFreaks 11thMIX e-Amusement", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk11ma", + "code": "GCD39", + "region": "AAA", + "name": "GuitarFreaks 11thMIX", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk11maa", + "code": "GCD39", + "region": "AAA", + "name": "GuitarFreaks 11thMIX e-Amusement", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk11mab", + "code": "GCD39", + "region": "ABA", + "name": "GuitarFreaks 11thMIX", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "gtrfrk11mac", + "code": "GCD39", + "region": "ABA", + "name": "GuitarFreaks 11thMIX e-Amusement", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn10m", + "code": "GCD40", + "region": "JAA", + "name": "DrumMania 10thMIX", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn10mja", + "code": "GCD40", + "region": "JAA", + "name": "DrumMania 10thMIX e-Amusement", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn10mjb", + "code": "GCD40", + "region": "JBA", + "name": "DrumMania 10thMIX", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "drmn10mjc", + "code": "GCD40", + "region": "JBA", + "name": "DrumMania 10thMIX e-Amusement", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk10m", + "code": "GCD40", + "region": "AAA", + "name": "PercussionFreaks 10thMIX", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk10maa", + "code": "GCD40", + "region": "AAA", + "name": "PercussionFreaks 10thMIX e-Amusement", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk10mab", + "code": "GCD40", + "region": "ABA", + "name": "PercussionFreaks 10thMIX", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + }, + { + "mameID": "pcnfrk10mac", + "code": "GCD40", + "region": "ABA", + "name": "PercussionFreaks 10thMIX e-Amusement", + "year": 2004, + "ioBoard": "GX894-PWB(B)", + "installerVersion": "1.95" + } +] diff --git a/resources.json b/resources.json new file mode 100644 index 0000000..e38ccec --- /dev/null +++ b/resources.json @@ -0,0 +1,77 @@ +[ + { + "type": "tim", + "name": "assets/textures/background.tim", + "source": "assets/textures/background.png", + "quantize": 16, + "imagePos": { "x": 960, "y": 0 }, + "clutPos": { "x": 1008, "y": 0 } + }, + { + "type": "tim", + "name": "assets/textures/font.tim", + "source": "assets/textures/font.png", + "quantize": 16, + "imagePos": { "x": 984, "y": 0 }, + "clutPos": { "x": 1008, "y": 1 } + }, + { + "type": "metrics", + "name": "assets/textures/font.metrics", + "source": "assets/textures/font.metrics.json" + }, + { + "type": "binary", + "name": "assets/sounds/move.vag", + "source": "assets/sounds/move.vag", + "compress": null + }, + { + "type": "binary", + "name": "assets/sounds/enter.vag", + "source": "assets/sounds/enter.vag", + "compress": null + }, + { + "type": "binary", + "name": "assets/sounds/exit.vag", + "source": "assets/sounds/exit.vag", + "compress": null + }, + { + "type": "binary", + "name": "assets/sounds/click.vag", + "source": "assets/sounds/click.vag", + "compress": null + }, + { + "type": "strings", + "name": "assets/app.strings", + "source": "assets/app.strings.json" + }, + { + "type": "text", + "name": "assets/licenses.txt", + "source": "assets/licenses.txt" + }, + + { + "type": "binary", + "name": "data/fpga.bit", + "source": "data/fpga.bit" + }, + { + "type": "binary", + "name": "data/x76f041.cartdb", + "source": "data/x76f041.cartdb" + }, + { + "type": "empty", + "name": "data/x76f100.cartdb" + }, + { + "type": "binary", + "name": "data/zs01.cartdb", + "source": "data/zs01.cartdb" + } +] diff --git a/src/app/actions.cpp b/src/app/actions.cpp new file mode 100644 index 0000000..77e604f --- /dev/null +++ b/src/app/actions.cpp @@ -0,0 +1,110 @@ + +#include "app/actions.hpp" +#include "app/app.hpp" +#include "defs.hpp" +#include "uibase.hpp" +#include "util.hpp" + +/* Unlocked cartridge screens */ + +struct Action { +public: + util::Hash name, prompt; + void (App::*target)(void); +}; + +// TODO: implement these +static const Action _IDENTIFIED_ACTIONS[]{ + { + .name = "CartActionsScreen.qrDump.name"_h, + .prompt = "CartActionsScreen.qrDump.prompt"_h, + .target = nullptr + }, { + .name = "CartActionsScreen.hexdump.name"_h, + .prompt = "CartActionsScreen.hexdump.prompt"_h, + .target = nullptr + }, { + .name = "CartActionsScreen.resetSystemID.name"_h, + .prompt = "CartActionsScreen.resetSystemID.prompt"_h, + .target = nullptr + }, { + .name = "CartActionsScreen.editSystemID.name"_h, + .prompt = "CartActionsScreen.editSystemID.prompt"_h, + .target = nullptr + }, { + .name = "CartActionsScreen.reflash.name"_h, + .prompt = "CartActionsScreen.reflash.prompt"_h, + .target = nullptr + }, { + .name = "CartActionsScreen.erase.name"_h, + .prompt = "CartActionsScreen.erase.prompt"_h, + .target = nullptr + } +}; + +static const Action _UNIDENTIFIED_ACTIONS[]{ + { + .name = "CartActionsScreen.qrDump.name"_h, + .prompt = "CartActionsScreen.qrDump.prompt"_h, + .target = nullptr + }, { + .name = "CartActionsScreen.hexdump.name"_h, + .prompt = "CartActionsScreen.hexdump.prompt"_h, + .target = nullptr + }, { + .name = "CartActionsScreen.reflash.name"_h, + .prompt = "CartActionsScreen.reflash.prompt"_h, + .target = nullptr + }, { + .name = "CartActionsScreen.erase.name"_h, + .prompt = "CartActionsScreen.erase.prompt"_h, + .target = nullptr + } +}; + +const char *CartActionsScreen::_getItemName(ui::Context &ctx, int index) const { + return STRH(_IDENTIFIED_ACTIONS[index].name); +} + +void CartActionsScreen::show(ui::Context &ctx, bool goBack) { + _title = STR("CartActionsScreen.title"); + _prompt = STRH(_IDENTIFIED_ACTIONS[0].prompt); + _itemPrompt = STR("CartActionsScreen.itemPrompt"); + + _listLength = 6; + + ListScreen::show(ctx, goBack); +} + +void CartActionsScreen::update(ui::Context &ctx) { + _prompt = STRH(_IDENTIFIED_ACTIONS[_activeItem].prompt); + + ListScreen::update(ctx); + + // TODO: implement this + if (ctx.buttons.pressed(ui::BTN_START)) { + //APP->_setupWorker(&App::_qrCodeWorker); + //ctx.show(APP->_workerStatusScreen, false, true); + } + if (ctx.buttons.held(ui::BTN_LEFT) && ctx.buttons.held(ui::BTN_RIGHT)) { + ctx.show(APP->_cartInfoScreen, true, true); + } +} + +static constexpr int QR_CODE_SCALE = 2; + +void QRCodeScreen::show(ui::Context &ctx, bool goBack) { + _title = STR("QRCodeScreen.title"); + _prompt = STR("QRCodeScreen.prompt"); + + _imageScale = QR_CODE_SCALE; + _imagePadding = QR_CODE_SCALE * 6; + _backdropColor = 0xffffff; + + ImageScreen::show(ctx, goBack); +} + +void QRCodeScreen::update(ui::Context &ctx) { + if (ctx.buttons.pressed(ui::BTN_START)) + ctx.show(APP->_cartInfoScreen, true, true); +} diff --git a/src/app/actions.hpp b/src/app/actions.hpp new file mode 100644 index 0000000..71f31cb --- /dev/null +++ b/src/app/actions.hpp @@ -0,0 +1,32 @@ + +#pragma once + +#include +#include "asset.hpp" +#include "uibase.hpp" +#include "uicommon.hpp" +#include "util.hpp" + +/* Unlocked cartridge screens */ + +class CartActionsScreen : public ui::ListScreen { +protected: + const char *_getItemName(ui::Context &ctx, int index) const; + +public: + void show(ui::Context &ctx, bool goBack = false); + void update(ui::Context &ctx); +}; + +class QRCodeScreen : public ui::ImageScreen { +public: + inline bool generateCode(const char *textInput) { + return asset::generateQRCode(_image, 960, 128, textInput); + } + inline bool generateCode(const uint8_t *binaryInput, size_t length) { + return asset::generateQRCode(_image, 960, 128, binaryInput, length); + } + + void show(ui::Context &ctx, bool goBack = false); + void update(ui::Context &ctx); +}; diff --git a/src/app/app.cpp b/src/app/app.cpp new file mode 100644 index 0000000..c344fba --- /dev/null +++ b/src/app/app.cpp @@ -0,0 +1,182 @@ + +#include +#include +#include "app/app.hpp" +#include "ps1/system.h" +#include "asset.hpp" +#include "cart.hpp" +#include "cartdb.hpp" +#include "io.hpp" +#include "uibase.hpp" +#include "util.hpp" + +/* App class */ + +App::App(void) +: _cart(nullptr), _identified(nullptr), _identifyResult(cartdb::UNIDENTIFIED) { + _workerStack = new uint8_t[WORKER_STACK_SIZE]; +} + +App::~App(void) { + //_dbFile.unload(); + delete[] _workerStack; + + if (_cart) + delete _cart; +} + +void App::_setupWorker(void (App::* func)(void)) { + LOG("starting thread, func=0x%08x", func); + + _workerStatus.reset(); + initThread( + // This is not how you implement delegates in C++. + &_workerThread, util::forcedCast(func), this, + &_workerStack[(WORKER_STACK_SIZE - 1) & ~7] + ); +} + +void App::_setupInterrupts(void) { + setInterruptHandler( + util::forcedCast(&App::_interruptHandler), this + ); + + setInterruptMask((1 << IRQ_VBLANK) | (1 << IRQ_GPU)); +} + +void App::_dummyWorker(void) { + for (;;) + __asm__ volatile(""); +} + +static const char *const _CARTDB_PATHS[cart::NUM_CHIP_TYPES]{ + nullptr, + "data/x76f041.cartdb", + "data/x76f100.cartdb", + "data/zs01.cartdb" +}; + +void App::_cartDetectWorker(void) { + _workerStatus.update(0, 4, WSTR("App.cartDetectWorker.identifyCart")); + + _db.data.unload(); + _cart = cart::createCart(); + + if (_cart->chipType) { + LOG("cart object @ 0x%08x", _cart); + _workerStatus.update(1, 4, WSTR("App.cartDetectWorker.readCart")); + + _cart->readCartID(); + _cart->readPublicData(); + + if (!_loader->loadAsset(_db.data, _CARTDB_PATHS[_cart->chipType])) { + LOG("failed to load cartdb, type=%d", _cart->chipType); + goto _cartInitDone; + } + if (!_db.init()) { + _db.data.unload(); + goto _cartInitDone; + } + + _workerStatus.update(2, 4, WSTR("App.cartDetectWorker.identifyGame")); + + if (_cart->flags & cart::PUBLIC_DATA_OK) + _identifyResult = _db.identifyCart(*_cart); + else + LOG("no public data available"); + } + +_cartInitDone: + _workerStatus.update(3, 4, WSTR("App.cartDetectWorker.readDigitalIO")); + + if (io::isDigitalIOPresent()) { + asset::Asset file; + bool ready; + + if (!_loader->loadAsset(file, "data/fpga.bit")) { + LOG("failed to load data/fpga.bit"); + goto _initDone; + } + + ready = io::loadBitstream( + reinterpret_cast(file.ptr), file.length + ); + file.unload(); + + if (!ready) { + LOG("bitstream upload failed"); + goto _initDone; + } + + delayMicroseconds(5000); // Probably not necessary + io::initKonamiBitstream(); + _cart->readSystemID(); + } + +_initDone: + _workerStatus.finish(_cartInfoScreen); + _dummyWorker(); +} + +void App::_cartUnlockWorker(void) { + _workerStatus.update(0, 2, WSTR("App.cartUnlockWorker.read")); + + //_cart->readPrivateData(); // TODO: implement this + + _workerStatus.update(1, 2, WSTR("App.cartUnlockWorker.identify")); + + if (_cart->flags & cart::PRIVATE_DATA_OK) + _identifyResult = _db.identifyCart(*_cart); + + _workerStatus.finish(_cartInfoScreen, true); + _dummyWorker(); +} + +void App::_qrCodeWorker(void) { + char qrString[cart::MAX_QR_STRING_LENGTH]; + + _workerStatus.update(0, 2, WSTR("App.qrCodeWorker.compress")); + _cart->toQRString(qrString); + + _workerStatus.update(1, 2, WSTR("App.qrCodeWorker.generate")); + _qrCodeScreen.generateCode(qrString); + + _workerStatus.finish(_qrCodeScreen); + _dummyWorker(); +} + +void App::_interruptHandler(void) { + if (acknowledgeInterrupt(IRQ_VBLANK)) { + _ctx->tick(); + io::clearWatchdog(); + switchThread(nullptr); + } + + if (acknowledgeInterrupt(IRQ_GPU)) + _ctx->gpuCtx.drawNextLayer(); +} + +void App::run( + ui::Context &ctx, asset::AssetLoader &loader, asset::StringTable &strings +) { + LOG("starting app @ 0x%08x", this); + + _ctx = &ctx; + _loader = &loader; + _strings = &strings; + + ctx.screenData = this; + ctx.show(_warningScreen); + ctx.sounds[ui::SOUND_STARTUP].play(); + + _setupWorker(&App::_dummyWorker); + _setupInterrupts(); + + for (;;) { + ctx.update(); + ctx.draw(); + + switchThreadImmediate(&_workerThread); + ctx.gpuCtx.flip(); + } +} diff --git a/src/app/app.hpp b/src/app/app.hpp new file mode 100644 index 0000000..86388d0 --- /dev/null +++ b/src/app/app.hpp @@ -0,0 +1,123 @@ + +#pragma once + +#include +#include "app/actions.hpp" +#include "app/misc.hpp" +#include "app/unlock.hpp" +#include "ps1/system.h" +#include "asset.hpp" +#include "cart.hpp" +#include "cartdb.hpp" +#include "uibase.hpp" + +/* Worker status class */ + +// This class is used by the worker thread to report its current status back to +// the main thread and the WorkerStatusScreen. +class WorkerStatus { +public: + volatile int progress, progressTotal; + volatile bool nextGoBack; + + const char *volatile message; + ui::Screen *volatile nextScreen; + + inline void update(int part, int total) { + auto mask = setInterruptMask(0); + progress = part; + progressTotal = total; + + if (mask) + setInterruptMask(mask); + } + inline void update(int part, int total, const char *text) { + auto mask = setInterruptMask(0); + progress = part; + progressTotal = total; + message = text; + + if (mask) + setInterruptMask(mask); + } + inline void finish(ui::Screen &next, bool goBack = false) { + auto mask = setInterruptMask(0); + nextScreen = &next; + nextGoBack = goBack; + + if (mask) + setInterruptMask(mask); + } + inline void reset(void) { + progress = 0; + progressTotal = 1; + nextScreen = nullptr; + } +}; + +/* App class */ + +static constexpr size_t WORKER_STACK_SIZE = 0x10000; + +class App { + friend class WorkerStatusScreen; + friend class WarningScreen; + friend class ButtonMappingScreen; + friend class CartInfoScreen; + friend class UnlockKeyScreen; + friend class UnlockConfirmScreen; + friend class UnlockErrorScreen; + friend class CartActionsScreen; + friend class QRCodeScreen; + +private: + WorkerStatusScreen _workerStatusScreen; + WarningScreen _warningScreen; + ButtonMappingScreen _buttonMappingScreen; + CartInfoScreen _cartInfoScreen; + UnlockKeyScreen _unlockKeyScreen; + UnlockConfirmScreen _unlockConfirmScreen; + UnlockErrorScreen _unlockErrorScreen; + CartActionsScreen _cartActionsScreen; + QRCodeScreen _qrCodeScreen; + + ui::Context *_ctx; + asset::AssetLoader *_loader; + asset::StringTable *_strings; + + cartdb::CartDB _db; + Thread _workerThread; + WorkerStatus _workerStatus; + + uint8_t *_workerStack; + cart::Cart *_cart; + + cartdb::Entry *_identified; + cartdb::IdentifyResult _identifyResult; + + void _setupWorker(void (App::* func)(void)); + void _setupInterrupts(void); + + void _dummyWorker(void); + void _cartDetectWorker(void); + void _cartUnlockWorker(void); + void _qrCodeWorker(void); + + void _interruptHandler(void); + +public: + App(void); + ~App(void); + void run( + ui::Context &ctx, asset::AssetLoader &loader, + asset::StringTable &strings + ); +}; + +#define APP (reinterpret_cast(ctx.screenData)) +#define STR(id) (APP->_strings->get(id ## _h)) +#define STRH(id) (APP->_strings->get(id)) + +#define WAPP (reinterpret_cast(_ctx->screenData)) +#define WSTR(id) (WAPP->_strings->get(id ## _h)) +#define WSTRH(id) (WAPP->_strings->get(id)) diff --git a/src/app/misc.cpp b/src/app/misc.cpp new file mode 100644 index 0000000..6054766 --- /dev/null +++ b/src/app/misc.cpp @@ -0,0 +1,105 @@ + +#include +#include "app/app.hpp" +#include "app/misc.hpp" +#include "defs.hpp" +#include "uibase.hpp" +#include "util.hpp" + +/* Initial setup screens */ + +void WorkerStatusScreen::show(ui::Context &ctx, bool goBack) { + _title = STR("WorkerStatusScreen.title"); + + ProgressScreen::show(ctx, goBack); +} + +void WorkerStatusScreen::update(ui::Context &ctx) { + auto &status = APP->_workerStatus; + auto nextScreen = status.nextScreen; + + if (nextScreen) { + LOG("worker finished, next=0x%08x", nextScreen); + + ctx.show(*nextScreen, status.nextGoBack); + return; + } + + _setProgress(ctx, status.progress, status.progressTotal); + _body = status.message; +} + +static constexpr int WARNING_COOLDOWN = 15; + +void WarningScreen::show(ui::Context &ctx, bool goBack) { + _title = STR("WarningScreen.title"); + _body = STR("WarningScreen.body"); + _buttons[0] = _buttonText; + + _locked = true; + _numButtons = 1; + +#ifdef NDEBUG + _cooldownTimer = ctx.time + WARNING_COOLDOWN * 60; +#else + _cooldownTimer = 0; +#endif + + MessageScreen::show(ctx, goBack); + + ctx.buttons.buttonMap = ui::MAP_SINGLE_BUTTON; +} + +void WarningScreen::update(ui::Context &ctx) { + MessageScreen::update(ctx); + + int time = _cooldownTimer - ctx.time; + _locked = (time > 0); + + if (_locked) { + time = (time / ctx.gpuCtx.refreshRate) + 1; + + sprintf(_buttonText, STR("WarningScreen.cooldown"), time); + return; + } + + _buttons[0] = STR("WarningScreen.ok"); + + if (ctx.buttons.pressed(ui::BTN_RIGHT) || ctx.buttons.pressed(ui::BTN_START)) + ctx.show(APP->_buttonMappingScreen, false, true); +} + +static const util::Hash _MAPPING_NAMES[]{ + "ButtonMappingScreen.joystick"_h, + "ButtonMappingScreen.ddrCab"_h, + "ButtonMappingScreen.ddrSoloCab"_h, + "ButtonMappingScreen.dmCab"_h, + "ButtonMappingScreen.dmxCab"_h +}; + +const char *ButtonMappingScreen::_getItemName(ui::Context &ctx, int index) const { + return STRH(_MAPPING_NAMES[index]); +} + +void ButtonMappingScreen::show(ui::Context &ctx, bool goBack) { + _title = STR("ButtonMappingScreen.title"); + _prompt = STR("ButtonMappingScreen.prompt"); + _itemPrompt = STR("ButtonMappingScreen.itemPrompt"); + + _listLength = ui::NUM_BUTTON_MAPS - 1; + + ListScreen::show(ctx, goBack); + + ctx.buttons.buttonMap = ui::MAP_SINGLE_BUTTON; +} + +void ButtonMappingScreen::update(ui::Context &ctx) { + ListScreen::update(ctx); + + if (ctx.buttons.pressed(ui::BTN_START)) { + ctx.buttons.buttonMap = ui::ButtonMap(_activeItem); + + APP->_setupWorker(&App::_cartDetectWorker); + ctx.show(APP->_workerStatusScreen, false, true); + } +} diff --git a/src/app/misc.hpp b/src/app/misc.hpp new file mode 100644 index 0000000..31f8619 --- /dev/null +++ b/src/app/misc.hpp @@ -0,0 +1,32 @@ + +#pragma once + +#include "uibase.hpp" +#include "uicommon.hpp" + +/* Initial setup screens */ + +class WorkerStatusScreen : public ui::ProgressScreen { +public: + void show(ui::Context &ctx, bool goBack = false); + void update(ui::Context &ctx); +}; + +class WarningScreen : public ui::MessageScreen { +private: + int _cooldownTimer; + char _buttonText[16]; + +public: + void show(ui::Context &ctx, bool goBack = false); + void update(ui::Context &ctx); +}; + +class ButtonMappingScreen : public ui::ListScreen { +protected: + const char *_getItemName(ui::Context &ctx, int index) const; + +public: + void show(ui::Context &ctx, bool goBack = false); + void update(ui::Context &ctx); +}; diff --git a/src/app/unlock.cpp b/src/app/unlock.cpp new file mode 100644 index 0000000..04889cb --- /dev/null +++ b/src/app/unlock.cpp @@ -0,0 +1,276 @@ + +#include +#include +#include "app/app.hpp" +#include "app/unlock.hpp" +#include "cart.hpp" +#include "cartdb.hpp" +#include "defs.hpp" +#include "uibase.hpp" +#include "util.hpp" + +/* Pre-unlock cartridge screens */ + +struct CartType { +public: + util::Hash name, warning, error; +}; + +static const CartType _CART_TYPES[cart::NUM_CHIP_TYPES]{ + { + .name = "CartInfoScreen.noCart.name"_h, + .warning = "CartInfoScreen.noCart.warning"_h, + .error = 0 + }, { + .name = "CartInfoScreen.x76f041.name"_h, + .warning = "CartInfoScreen.x76f041.warning"_h, + .error = 0 + }, { + .name = "CartInfoScreen.x76f100.name"_h, + .warning = "CartInfoScreen.x76f100.warning"_h, + .error = 0 + }, { + .name = "CartInfoScreen.zs01.name"_h, + .warning = "CartInfoScreen.zs01.warning"_h, + .error = 0 + } +}; + +static const util::Hash _LOCKED_PROMPTS[]{ + "CartInfoScreen.description.locked.unidentified"_h, + "CartInfoScreen.description.locked.identified"_h, + "CartInfoScreen.description.locked.unknown"_h +}; +static const util::Hash _UNLOCKED_PROMPTS[]{ + "CartInfoScreen.description.unlocked.unidentified"_h, + "CartInfoScreen.description.unlocked.identified"_h, + "CartInfoScreen.description.unlocked.blank"_h +}; + +void CartInfoScreen::show(ui::Context &ctx, bool goBack) { + _title = STR("CartInfoScreen.title"); + _body = _bodyText; + + TextScreen::show(ctx, goBack); + + auto &_cart = *(APP->_cart); + auto flags = _cart.flags; + + char id1[32], id2[32]; + char *ptr = _bodyText, *end = &_bodyText[sizeof(_bodyText)]; + + // Digital I/O board info + if (flags & cart::SYSTEM_ID_OK) { + util::hexToString(id1, _cart.systemID, sizeof(_cart.systemID), '-'); + util::serialNumberToString(id2, &_cart.systemID[1]); + } else if (flags & cart::HAS_DIGITAL_IO) { + strcpy(id1, STR("CartInfoScreen.id.error")); + strcpy(id2, id1); + } else { + strcpy(id1, STR("CartInfoScreen.id.noSystemID")); + strcpy(id2, id1); + } + + ptr += snprintf(ptr, end - ptr, STR("CartInfoScreen.digitalIOInfo"), id1, id2); + + // Cartridge info + if (!_cart.chipType) { + memccpy(ptr, STR("CartInfoScreen.description.noCart"), 0, end - ptr); + + _prompt = STR("CartInfoScreen.prompt.error"); + return; + } else if (!(_cart.flags & cart::PUBLIC_DATA_OK)) { + memccpy(ptr, STR("CartInfoScreen.description.initError"), 0, end - ptr); + + _prompt = STR("CartInfoScreen.prompt.error"); + return; + } + + if (flags & cart::CART_ID_OK) + util::hexToString(id1, _cart.cartID, sizeof(_cart.cartID), '-'); + else if (flags & cart::HAS_DS2401) + strcpy(id1, STR("CartInfoScreen.id.error")); + else + strcpy(id1, STR("CartInfoScreen.id.noCartID")); + + if (flags & cart::ZS_ID_OK) + util::hexToString(id2, _cart.zsID, sizeof(_cart.zsID), '-'); + else if (_cart.chipType == cart::TYPE_ZS01) + strcpy(id2, STR("CartInfoScreen.id.error")); + else + strcpy(id2, STR("CartInfoScreen.id.noZSID")); + + auto unlockStatus = (flags & cart::PRIVATE_DATA_OK) ? + STR("CartInfoScreen.unlockStatus.unlocked") : + STR("CartInfoScreen.unlockStatus.locked"); + + ptr += snprintf( + ptr, end - ptr, STR("CartInfoScreen.cartInfo"), + STRH(_CART_TYPES[_cart.chipType].name), unlockStatus, id1, id2 + ); + + // At this point the cartridge can be in one of 6 states: + // - locked, identified + // => unlock required, auto unlock available + // - locked, unidentified + // => unlock required + // - locked, blank or no public data + // => unlock required + // - unlocked, identified + // => all actions available + // - unlocked, no private data, unidentified + // => only dumping/flashing available + // - unlocked, no private data, blank + // => only dumping/flashing available + auto result = APP->_identifyResult; + char name[96]; + + if (result == cartdb::IDENTIFIED) + APP->_identified->getDisplayName(name, sizeof(name)); + + if (flags & cart::PRIVATE_DATA_OK) { + ptr += snprintf(ptr, end - ptr, STRH(_UNLOCKED_PROMPTS[result]), name); + + _prompt = STR("CartInfoScreen.prompt.unlocked"); + } else { + ptr += snprintf(ptr, end - ptr, STRH(_LOCKED_PROMPTS[result]), name); + + _prompt = STR("CartInfoScreen.prompt.locked"); + } +} + +void CartInfoScreen::update(ui::Context &ctx) { + auto &_cart = *(APP->_cart); + + if (!_cart.chipType) + return; + + if (ctx.buttons.pressed(ui::BTN_START)) { + /*if (_cart.flags & cart::PRIVATE_DATA_OK) + ctx.show(APP->_cartActionsScreen, false, true); + else + ctx.show(APP->_unlockKeyScreen, false, true);*/ + } +} + +enum SpecialUnlockKeyEntry { + ENTRY_AUTO_UNLOCK = -3, + ENTRY_CUSTOM_KEY = -2, + ENTRY_NULL_KEY = -1 +}; + +int UnlockKeyScreen::_getSpecialEntryOffset(ui::Context &ctx) const { + return (APP->_identifyResult == cartdb::IDENTIFIED) + ? ENTRY_AUTO_UNLOCK : ENTRY_CUSTOM_KEY; +} + +const char *UnlockKeyScreen::_getItemName(ui::Context &ctx, int index) const { + static char name[96]; // TODO: get rid of this ugly crap + + index += _getSpecialEntryOffset(ctx); + + switch (index) { + case ENTRY_AUTO_UNLOCK: + return _autoUnlockItem; + + case ENTRY_CUSTOM_KEY: + return _customKeyItem; + + case ENTRY_NULL_KEY: + return _nullKeyItem; + + default: + APP->_db.getEntry(index).getDisplayName(name, sizeof(name)); + return name; + } +} + +void UnlockKeyScreen::show(ui::Context &ctx, bool goBack) { + _title = STR("UnlockKeyScreen.title"); + _prompt = STR("UnlockKeyScreen.prompt"); + _itemPrompt = STR("UnlockKeyScreen.itemPrompt"); + _autoUnlockItem = STR("UnlockKeyScreen.autoUnlock"); + _customKeyItem = STR("UnlockKeyScreen.customKey"); + _nullKeyItem = STR("UnlockKeyScreen.nullKey"); + + _listLength = APP->_db.numEntries - _getSpecialEntryOffset(ctx); + + ListScreen::show(ctx, goBack); +} + +void UnlockKeyScreen::update(ui::Context &ctx) { + ListScreen::update(ctx); + + if (ctx.buttons.pressed(ui::BTN_START)) { + int index = _activeItem + _getSpecialEntryOffset(ctx); + + switch (index) { + case ENTRY_AUTO_UNLOCK: + memcpy( + APP->_cart->dataKey, APP->_identified->dataKey, + sizeof(APP->_cart->dataKey) + ); + ctx.show(APP->_unlockConfirmScreen, false, true); + break; + + case ENTRY_CUSTOM_KEY: + //ctx.show(APP->_unlockKeyEntryScreen, false, true); + break; + + case ENTRY_NULL_KEY: + memset(APP->_cart->dataKey, 0, sizeof(APP->_cart->dataKey)); + ctx.show(APP->_unlockConfirmScreen, false, true); + break; + + default: + memcpy( + APP->_cart->dataKey, APP->_db.getEntry(index).dataKey, + sizeof(APP->_cart->dataKey) + ); + ctx.show(APP->_unlockConfirmScreen, false, true); + } + } else if (ctx.buttons.held(ui::BTN_LEFT) && ctx.buttons.held(ui::BTN_RIGHT)) { + ctx.show(APP->_cartInfoScreen, true, true); + } +} + +void UnlockConfirmScreen::show(ui::Context &ctx, bool goBack) { + _title = STR("UnlockConfirmScreen.title"); + _body = STRH(_CART_TYPES[APP->_cart->chipType].warning); + _buttons[0] = STR("UnlockConfirmScreen.no"); + _buttons[1] = STR("UnlockConfirmScreen.yes"); + + _numButtons = 2; + + MessageScreen::show(ctx, goBack); +} + +void UnlockConfirmScreen::update(ui::Context &ctx) { + MessageScreen::update(ctx); + + if (ctx.buttons.pressed(ui::BTN_START)) { + if (_activeButton) { + APP->_setupWorker(&App::_cartUnlockWorker); + ctx.show(APP->_workerStatusScreen, false, true); + } else { + ctx.show(APP->_unlockKeyScreen, true, true); + } + } +} + +void UnlockErrorScreen::show(ui::Context &ctx, bool goBack) { + _title = STR("UnlockErrorScreen.title"); + _body = STRH(_CART_TYPES[APP->_cart->chipType].error); + _buttons[0] = STR("UnlockErrorScreen.ok"); + + _numButtons = 1; + + MessageScreen::show(ctx, goBack); +} + +void UnlockErrorScreen::update(ui::Context &ctx) { + MessageScreen::update(ctx); + + if (ctx.buttons.pressed(ui::BTN_START)) + ctx.show(APP->_cartInfoScreen, true, true); +} diff --git a/src/app/unlock.hpp b/src/app/unlock.hpp new file mode 100644 index 0000000..7e253e1 --- /dev/null +++ b/src/app/unlock.hpp @@ -0,0 +1,42 @@ + +#pragma once + +#include "uibase.hpp" +#include "uicommon.hpp" + +/* Pre-unlock cartridge screens */ + +class CartInfoScreen : public ui::TextScreen { +private: + char _bodyText[1024]; + +public: + void show(ui::Context &ctx, bool goBack = false); + void update(ui::Context &ctx); +}; + +class UnlockKeyScreen : public ui::ListScreen { +private: + const char *_autoUnlockItem, *_customKeyItem, *_nullKeyItem; + + int _getSpecialEntryOffset(ui::Context &ctx) const; + +protected: + const char *_getItemName(ui::Context &ctx, int index) const; + +public: + void show(ui::Context &ctx, bool goBack = false); + void update(ui::Context &ctx); +}; + +class UnlockConfirmScreen : public ui::MessageScreen { +public: + void show(ui::Context &ctx, bool goBack = false); + void update(ui::Context &ctx); +}; + +class UnlockErrorScreen : public ui::MessageScreen { +public: + void show(ui::Context &ctx, bool goBack = false); + void update(ui::Context &ctx); +}; diff --git a/src/asset.cpp b/src/asset.cpp new file mode 100644 index 0000000..17e50b8 --- /dev/null +++ b/src/asset.cpp @@ -0,0 +1,261 @@ + +#include +#include +#include +#include +#include "ps1/gpucmd.h" +#include "ps1/pcdrv.h" +#include "vendor/miniz.h" +#include "vendor/qrcodegen.h" +#include "asset.hpp" + +namespace asset { + +/* Asset loader */ + +bool AssetLoader::openMemory(const void *zipData, size_t length) { + //close(); + mz_zip_zero_struct(&_zip); + + // Sorting the central directory in a zip with a small number of files is + // just a waste of time. + if (!mz_zip_reader_init_mem( + &_zip, zipData, length, + MZ_ZIP_FLAG_CASE_SENSITIVE | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY + )) { + LOG("zip init error, code=%d", mz_zip_get_last_error(&_zip)); + return false; + } + + LOG("ptr=0x%08x, length=0x%x", zipData, length); + ready = true; + return true; +} + +bool AssetLoader::openHost(const char *path) { + if (pcdrvInit() < 0) + return false; + + _hostFile = pcdrvOpen(path, PCDRV_MODE_READ); + if (_hostFile < 0) + return false; + + int length = pcdrvSeek(_hostFile, 0, PCDRV_SEEK_END); + if (length < 0) + return false; + + _zip.m_pIO_opaque = reinterpret_cast(_hostFile); + _zip.m_pNeeds_keepalive = nullptr; + _zip.m_pRead = []( + void *opaque, uint64_t offset, void *data, size_t length + ) -> size_t { + int hostFile = reinterpret_cast(opaque); + + if ( + pcdrvSeek(hostFile, static_cast(offset), PCDRV_SEEK_SET) + != int(offset) + ) + return 0; + + int actualLength = pcdrvRead(hostFile, data, length); + if (actualLength < 0) + return 0; + + return actualLength; + }; + + if (!mz_zip_reader_init( + &_zip, length, + MZ_ZIP_FLAG_CASE_SENSITIVE | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY + )) { + LOG("zip init error, code=%d", mz_zip_get_last_error(&_zip)); + return false; + } + + LOG("length=0x%x", length); + ready = true; + return true; +} + +void AssetLoader::close(void) { + if (!ready) + return; + if (_hostFile >= 0) + pcdrvClose(_hostFile); + + mz_zip_reader_end(&_zip); + ready = false; +} + +size_t AssetLoader::loadAsset(Asset &output, const char *path) { + output.ptr = mz_zip_reader_extract_file_to_heap(&_zip, path, &output.length, 0); + + if (!output.ptr) + return 0; + + return output.length; +} + +size_t AssetLoader::loadTIM(gpu::Image &output, const char *path) { + size_t size; + void *data = mz_zip_reader_extract_file_to_heap(&_zip, path, &size, 0); + + if (!data) + return 0; + + auto header = reinterpret_cast(data); + auto ptr = reinterpret_cast(&header[1]); + + if (!output.initFromTIMHeader(header)) { + mz_free(data); + return 0; + } + if (header->flags & (1 << 3)) { + auto clut = reinterpret_cast(ptr); + + gpu::upload(clut->vram, &clut[1], true); + ptr += clut->length; + } + + auto image = reinterpret_cast(ptr); + + gpu::upload(image->vram, &image[1], true); + mz_free(data); + return size; +} + +size_t AssetLoader::loadVAG(spu::Sound &output, const char *path) { + // Sounds should be decompressed and uploaded to the SPU one chunk at a + // time, but whatever. + size_t size; + void *data = mz_zip_reader_extract_file_to_heap(&_zip, path, &size, 0); + + if (!data) + return 0; + + auto header = reinterpret_cast(data); + + if (!output.initFromVAGHeader(header, spuOffset)) { + mz_free(data); + return 0; + } + + spuOffset += spu::upload( + spuOffset, reinterpret_cast(&header[1]), + size - sizeof(spu::VAGHeader), true + ); + mz_free(data); + return size; +} + +size_t AssetLoader::loadFontMetrics(gpu::Font &output, const char *path) { + if (!mz_zip_reader_extract_file_to_mem( + &_zip, path, output.metrics, sizeof(output.metrics), 0 + )) + return 0; + + return sizeof(output.metrics); +} + +/* String table manager */ + +const char *StringTable::get(util::Hash id) { + if (!data.ptr) + return "missingno"; + + auto blob = reinterpret_cast(data.ptr); + auto table = reinterpret_cast(data.ptr); + + auto entry = &table[id % TABLE_BUCKET_COUNT]; + + if (entry->hash == id) + return &blob[entry->offset]; + + while (entry->chained) { + entry = &table[entry->chained]; + + if (entry->hash == id) + return &blob[entry->offset]; + } + + return "missingno"; +} + +size_t StringTable::format(char *buffer, size_t length, util::Hash id, ...) { + va_list ap; + + va_start(ap, id); + size_t outLength = vsnprintf(buffer, length, get(id), ap); + va_end(ap); + + return outLength; +} + +/* QR code encoder */ + +static void _loadQRCode( + gpu::Image &output, int x, int y, const uint32_t *qrCode +) { + int size = qrcodegen_getSize(qrCode); + gpu::RectWH rect; + + // Generate a 16-color (only 2 colors used) palette and place it below the + // QR code in VRAM. + const uint32_t palette[8]{ 0x8000ffff }; + + rect.x = x; + rect.y = y + size; + rect.w = 16; + rect.h = 1; + gpu::upload(rect, palette, true); + + rect.y = y; + rect.w = qrcodegen_getStride(qrCode) * 2; + rect.h = size; + gpu::upload(rect, &qrCode[1], true); + + output.initFromVRAMRect(rect, GP0_COLOR_4BPP); + output.width = size; + output.palette = gp0_clut(x / 64, (y + size) / 256); + + LOG("loaded at (%d,%d), size=%d", x, y, size); +} + +bool generateQRCode( + gpu::Image &output, int x, int y, const char *str, qrcodegen_Ecc ecc +) { + uint32_t qrCode[qrcodegen_BUFFER_LEN_MAX]; + uint32_t tempBuffer[qrcodegen_BUFFER_LEN_MAX]; + + auto segment = qrcodegen_makeAlphanumeric( + str, reinterpret_cast(tempBuffer) + ); + if (!qrcodegen_encodeSegments(&segment, 1, ecc, tempBuffer, qrCode)) { + LOG("QR encoding failed"); + return false; + } + + _loadQRCode(output, x, y, qrCode); + return true; +} + +bool generateQRCode( + gpu::Image &output, int x, int y, const uint8_t *data, size_t length, + qrcodegen_Ecc ecc +) { + uint32_t qrCode[qrcodegen_BUFFER_LEN_MAX]; + uint32_t tempBuffer[qrcodegen_BUFFER_LEN_MAX]; + + auto segment = qrcodegen_makeBytes( + data, length, reinterpret_cast(tempBuffer) + ); + if (!qrcodegen_encodeSegments(&segment, 1, ecc, tempBuffer, qrCode)) { + LOG("QR encoding failed"); + return false; + } + + _loadQRCode(output, x, y, qrCode); + return true; +} + +} diff --git a/src/asset.hpp b/src/asset.hpp new file mode 100644 index 0000000..d209282 --- /dev/null +++ b/src/asset.hpp @@ -0,0 +1,92 @@ + +#pragma once + +#include +#include +#include "vendor/miniz.h" +#include "vendor/qrcodegen.h" +#include "gpu.hpp" +#include "spu.hpp" +#include "util.hpp" + +namespace asset { + +/* Asset loader (wrapper around a zip file) */ + +class Asset { +public: + void *ptr; + size_t length; + + inline Asset(void) + : ptr(nullptr), length(0) {} + inline ~Asset(void) { + unload(); + } + + inline void unload(void) { + if (ptr) { + mz_free(ptr); + ptr = nullptr; + } + } +}; + +class AssetLoader { +private: + mz_zip_archive _zip; + int _hostFile; + +public: + bool ready; + uint32_t spuOffset; + + inline AssetLoader(uint32_t spuOffset = 0x1000) + : _hostFile(-1), ready(false), spuOffset(spuOffset) {} + inline ~AssetLoader(void) { + close(); + } + + bool openMemory(const void *zipData, size_t length); + bool openHost(const char *path); + void close(void); + size_t loadAsset(Asset &output, const char *path); + size_t loadTIM(gpu::Image &output, const char *path); + size_t loadVAG(spu::Sound &output, const char *path); + size_t loadFontMetrics(gpu::Font &output, const char *path); +}; + +/* String table manager */ + +static constexpr int TABLE_BUCKET_COUNT = 256; + +struct [[gnu::packed]] StringTableEntry { +public: + uint32_t hash; + uint16_t offset, chained; +}; + +class StringTable { +public: + Asset data; + + inline const char *operator[](util::Hash id) { + return get(id); + } + + const char *get(util::Hash id); + size_t format(char *buffer, size_t length, util::Hash id, ...); +}; + +/* QR code encoder */ + +bool generateQRCode( + gpu::Image &output, int x, int y, const char *str, + qrcodegen_Ecc ecc = qrcodegen_Ecc_MEDIUM +); +bool generateQRCode( + gpu::Image &output, int x, int y, const uint8_t *data, size_t length, + qrcodegen_Ecc ecc = qrcodegen_Ecc_MEDIUM +); + +} diff --git a/src/cart.cpp b/src/cart.cpp new file mode 100644 index 0000000..32d4833 --- /dev/null +++ b/src/cart.cpp @@ -0,0 +1,497 @@ + +#include +#include +#include +#include "ps1/system.h" +#include "vendor/miniz.h" +#include "cart.hpp" +#include "io.hpp" +#include "util.hpp" +#include "zs01.hpp" + +namespace cart { + +/* Common functions */ + +enum ChipID : uint32_t { + _ID_X76F041 = 0x55aa5519, + _ID_X76F100 = 0x55aa0019, + _ID_ZS01 = 0x5a530001 +}; + +static const size_t _DATA_LENGTHS[NUM_CHIP_TYPES]{ 0, 512, 112, 112 }; + +static constexpr int _X76_MAX_ACK_POLLS = 5; +static constexpr int _X76_WRITE_DELAY = 10000; +static constexpr int _ZS01_PACKET_DELAY = 30000; + +static bool _validateID(const uint8_t *id) { + if (!id[0] || (id[0] == 0xff)) { + LOG("invalid device type 0x%02x", id[0]); + return false; + } + + uint8_t crc = util::dsCRC8(id, 7); + if (crc != id[7]) { + LOG("CRC mismatch, exp=0x%02x, got=0x%02x", crc, id[7]); + return false; + } + + return true; +} + +size_t getDataLength(ChipType type) { + return _DATA_LENGTHS[type]; +} + +Cart *createCart(void) { + if (!io::getCartInsertionStatus()) { + LOG("DSR not asserted"); + return new Cart(); + } + + uint32_t id1 = io::i2cResetX76(); + LOG("id1=0x%08x", id1); + + switch (id1) { + case _ID_X76F041: + return new X76F041Cart(); + + //case _ID_X76F100: + //return new X76F100Cart(); + + default: + uint32_t id2 = io::i2cResetZS01(); + LOG("id2=0x%08x", id2); + + if (id2 == _ID_ZS01) + return new ZS01Cart(); + + return new Cart(); + } +} + +/* Base cart class */ + +Cart::Cart(void) { + memset(&version, 0, 44); + + version = DUMP_VERSION; + chipType = TYPE_NONE; + flags = 0; +} + +size_t Cart::toQRString(char *output) { + uint8_t compressed[MAX_QR_STRING_LENGTH]; + size_t uncompLength = getDumpLength(); + size_t compLength = MAX_QR_STRING_LENGTH; + + int error = mz_compress2( + compressed, + reinterpret_cast(&compLength), + &version, + uncompLength, + MZ_BEST_COMPRESSION + ); + + if (error != MZ_OK) { + LOG("compression error, code=%d", error); + return 0; + } + LOG( + "dump compressed, size=%d, ratio=%d%%", compLength, + compLength * 100 / uncompLength + ); + + compLength = util::encodeBase45(&output[5], compressed, compLength); + memcpy(&output[0], "573::", 5); + memcpy(&output[compLength + 5], "::", 3); + + return compLength + 7; +} + +Error Cart::readSystemID(void) { + uint8_t id[8]; + auto mask = setInterruptMask(0); + + if (!io::dsDIOReset()) { + if (mask) + setInterruptMask(mask); + + LOG("no 1-wire device found"); + return DS2401_NO_RESP; + } + + flags |= HAS_DIGITAL_IO; + + io::dsDIOWriteByte(0x33); + for (int i = 0; i < 8; i++) + id[i] = io::dsDIOReadByte(); + + if (mask) + setInterruptMask(mask); + if (!_validateID(id)) + return DS2401_ID_ERROR; + + memcpy(systemID, id, sizeof(id)); + + flags |= SYSTEM_ID_OK; + return NO_ERROR; +} + +Error X76Cart::readCartID(void) { + uint8_t id[8]; + auto mask = setInterruptMask(0); + + if (!io::dsCartReset()) { + if (mask) + setInterruptMask(mask); + + LOG("no 1-wire device found"); + return DS2401_NO_RESP; + } + + flags |= HAS_DS2401; + + io::dsCartWriteByte(0x33); + for (int i = 0; i < 8; i++) + id[i] = io::dsCartReadByte(); + + if (mask) + setInterruptMask(mask); + if (!_validateID(id)) + return DS2401_ID_ERROR; + + memcpy(cartID, id, sizeof(id)); + + flags |= CART_ID_OK; + return NO_ERROR; +} + +Error X76Cart::_x76Command( + uint8_t command, uint8_t param, uint8_t pollByte +) const { + io::i2cStartWithCS(); + + io::i2cWriteByte(command); + if (!io::i2cGetACK()) { + io::i2cStopWithCS(); + LOG("NACK while sending command"); + return X76_NACK; + } + + io::i2cWriteByte(param); + if (!io::i2cGetACK()) { + io::i2cStopWithCS(); + LOG("NACK while sending parameter"); + return X76_NACK; + } + + if (!io::i2cWriteBytes(dataKey, sizeof(dataKey))) { + io::i2cStopWithCS(); + LOG("NACK while sending data key"); + return X76_NACK; + } + + for (int i = _X76_MAX_ACK_POLLS; i; i--) { + delayMicroseconds(_X76_WRITE_DELAY); + io::i2cStart(); + io::i2cWriteByte(pollByte); + if (io::i2cGetACK()) + return NO_ERROR; + } + + io::i2cStopWithCS(); + LOG("ACK polling timeout (wrong key?)"); + return X76_POLL_FAIL; +} + +/* X76F041 driver */ + +enum X76F041Command : uint8_t { + _X76F041_READ = 0x60, + _X76F041_WRITE = 0x40, + _X76F041_CONFIG = 0x80, + _X76F041_ACK_POLL = 0xc0 +}; + +enum X76F041ConfigOp : uint8_t { + _X76F041_CFG_SET_DATA_KEY = 0x20, + _X76F041_CFG_READ_CONFIG = 0x60, + _X76F041_CFG_WRITE_CONFIG = 0x50, + _X76F041_CFG_ERASE = 0x70 +}; + +X76F041Cart::X76F041Cart(void) { + Cart(); + + chipType = TYPE_X76F041; +} + +Error X76F041Cart::readPrivateData(void) { + // Reads can be done with any block size, but a single read operation can't + // cross 128-byte block boundaries. + for (int i = 0; i < 512; i += 128) { + Error error = _x76Command( + _X76F041_READ | (i >> 8), i & 0xff, _X76F041_ACK_POLL + ); + if (error) + return error; + + io::i2cReadByte(); // Ignore "secure read setup" byte + io::i2cStart(); + + io::i2cWriteByte(i & 0xff); + if (io::i2cGetACK()) { + LOG("NACK after resending address"); + return X76_NACK; + } + + io::i2cReadBytes(&data[i], 128); + io::i2cStopWithCS(); + } + + return NO_ERROR; +} + +Error X76F041Cart::writeData(void) { + // Writes can only be done in 8-byte blocks. + for (int i = 0; i < 512; i += 8) { + Error error = _x76Command( + _X76F041_WRITE | (i >> 8), i & 0xff, _X76F041_ACK_POLL + ); + if (error) + return error; + + if (!io::i2cWriteBytes(&data[i], 8)) { + LOG("NACK while sending data bytes"); + return X76_NACK; + } + + io::i2cStopWithCS(_X76_WRITE_DELAY); + } + + return NO_ERROR; +} + +Error X76F041Cart::erase(void) { + Error error = _x76Command( + _X76F041_CONFIG, _X76F041_CFG_ERASE, _X76F041_ACK_POLL + ); + if (error) + return error; + + io::i2cStopWithCS(_X76_WRITE_DELAY); + return NO_ERROR; +} + +Error X76F041Cart::setDataKey(const uint8_t *newKey) { + Error error = _x76Command( + _X76F041_CONFIG, _X76F041_CFG_SET_DATA_KEY, _X76F041_ACK_POLL + ); + if (error) + return error; + + // The X76F041 requires the key to be sent twice as a way of ensuring it + // gets received correctly. + for (int i = 2; i; i--) { + if (!io::i2cWriteBytes(newKey, sizeof(dataKey))) { + io::i2cStopWithCS(); + LOG("NACK while setting new data key"); + return X76_NACK; + } + } + + io::i2cStopWithCS(_X76_WRITE_DELAY); + + // Update the data key stored in the class. + memcpy(dataKey, newKey, sizeof(dataKey)); + return NO_ERROR; +} + +/* X76F100 driver */ + +enum X76F100Command : uint8_t { + _X76F100_READ = 0x81, + _X76F100_WRITE = 0x80, + _X76F100_SET_READ_KEY = 0xfe, + _X76F100_SET_WRITE_KEY = 0xfc, + _X76F100_ACK_POLL = 0x55 +}; + +X76F100Cart::X76F100Cart(void) { + Cart(); + + chipType = TYPE_X76F100; +} + +// TODO: actually implement this (even though no X76F100 carts were ever made) + +/* ZS01 driver */ + +ZS01Cart::ZS01Cart(void) { + Cart(); + + chipType = TYPE_ZS01; + flags = HAS_DS2401; +} + +Error ZS01Cart::_transact(zs01::Packet &request, zs01::Packet &response) { + io::i2cStart(); + if (!io::i2cWriteBytes( + &request.command, sizeof(zs01::Packet), _ZS01_PACKET_DELAY + )) { + io::i2cStop(); + LOG("NACK while sending request packet"); + return ZS01_NACK; + } + + io::i2cReadBytes(&response.command, sizeof(zs01::Packet)); + io::i2cStop(); + + if (!response.decodeResponse()) + return ZS01_CRC_MISMATCH; + + _state = response.address; + if (response.command != zs01::RESP_NO_ERROR) { + LOG("ZS01 error, code=0x%02x", response.command); + return ZS01_ERROR; + } + + return NO_ERROR; +} + +Error ZS01Cart::readCartID(void) { + zs01::Packet request, response; + Error error; + + request.address = zs01::ADDR_ZS01_ID; + request.encodeReadRequest(); + + error = _transact(request, response); + if (error) + return error; + if (!_validateID(response.data)) + return DS2401_ID_ERROR; + + response.copyDataTo(zsID); + + flags |= ZS_ID_OK; + + request.address = zs01::ADDR_DS2401_ID; + request.encodeReadRequest(); + + error = _transact(request, response); + if (error) + return error; + if (!_validateID(response.data)) + return DS2401_ID_ERROR; + + response.copyDataTo(cartID); + + flags |= CART_ID_OK; + return NO_ERROR; +} + +Error ZS01Cart::readPublicData(void) { + zs01::Packet request, response; + + for (int i = zs01::ADDR_PUBLIC; i < zs01::ADDR_PUBLIC_END; i++) { + request.address = i; + request.encodeReadRequest(); + + Error error = _transact(request, response); + if (error) + return error; + + response.copyDataTo(&data[i * sizeof(response.data)]); + } + + flags |= PUBLIC_DATA_OK; + return NO_ERROR; +} + +Error ZS01Cart::readPrivateData(void) { + zs01::Packet request, response; + zs01::Key key; + key.unpackFrom(dataKey); + + for (int i = zs01::ADDR_PRIVATE; i < zs01::ADDR_PRIVATE_END; i++) { + request.address = i; + request.encodeReadRequest(key, _state); + + Error error = _transact(request, response); + if (error) + return error; + + response.copyDataTo(&data[i * sizeof(response.data)]); + } + + flags |= PRIVATE_DATA_OK; + + request.address = zs01::ADDR_CONFIG; + request.encodeReadRequest(key, _state); + + Error error = _transact(request, response); + if (error) + return error; + + response.copyDataTo(config); + + flags |= CONFIG_OK; + return NO_ERROR; +} + +Error ZS01Cart::writeData(void) { + zs01::Packet request, response; + zs01::Key key; + key.unpackFrom(dataKey); + + for (int i = zs01::ADDR_PUBLIC; i < zs01::ADDR_PRIVATE_END; i++) { + request.address = i; + request.copyDataFrom(&data[i * sizeof(request.data)]); + request.encodeWriteRequest(key, _state); + + Error error = _transact(request, response); + if (error) + return error; + } + + request.address = zs01::ADDR_CONFIG; + request.copyDataFrom(config); + request.encodeWriteRequest(key, _state); + + return _transact(request, response); +} + +Error ZS01Cart::erase(void) { + zs01::Packet request, response; + zs01::Key key; + key.unpackFrom(dataKey); + + memset(request.data, 0, sizeof(request.data)); + request.address = zs01::ADDR_ERASE; + request.encodeWriteRequest(key, _state); + + return _transact(request, response); +} + +Error ZS01Cart::setDataKey(const uint8_t *newKey) { + zs01::Packet request, response; + zs01::Key key; + key.unpackFrom(dataKey); + + request.address = zs01::ADDR_DATA_KEY; + request.copyDataFrom(newKey); + request.encodeWriteRequest(key, _state); + + Error error = _transact(request, response); + if (error) + return error; + + // Update the data key stored in the class. + memcpy(dataKey, newKey, sizeof(dataKey)); + return NO_ERROR; +} + +} diff --git a/src/cart.hpp b/src/cart.hpp new file mode 100644 index 0000000..d163e95 --- /dev/null +++ b/src/cart.hpp @@ -0,0 +1,123 @@ + +#pragma once + +#include +#include +#include "zs01.hpp" + +namespace cart { + +enum Error { + NO_ERROR = 0, + UNSUPPORTED_OP = 1, + DS2401_NO_RESP = 2, + DS2401_ID_ERROR = 3, + X76_NACK = 4, + X76_POLL_FAIL = 5, + X76_VERIFY_FAIL = 6, + ZS01_NACK = 7, + ZS01_ERROR = 8, + ZS01_CRC_MISMATCH = 9 +}; + +enum ChipType : uint8_t { + TYPE_NONE = 0, + TYPE_X76F041 = 1, + TYPE_X76F100 = 2, + TYPE_ZS01 = 3 +}; + +enum CartFlag : uint8_t { + HAS_DIGITAL_IO = 1 << 0, + HAS_DS2401 = 1 << 1, + CONFIG_OK = 1 << 2, + SYSTEM_ID_OK = 1 << 3, + CART_ID_OK = 1 << 4, + ZS_ID_OK = 1 << 5, + PUBLIC_DATA_OK = 1 << 6, + PRIVATE_DATA_OK = 1 << 7 +}; + +static constexpr int DUMP_VERSION = 1; +static constexpr int NUM_CHIP_TYPES = 4; +static constexpr int MAX_QR_STRING_LENGTH = 0x600; + +class Cart; + +size_t getDataLength(ChipType type); +Cart *createCart(void); + +class [[gnu::packed]] Cart { +public: + uint8_t version; + ChipType chipType; + + uint8_t flags, _state; + uint8_t dataKey[8], config[8]; + uint8_t systemID[8], cartID[8], zsID[8]; + + inline size_t getDumpLength(void) { + return getDataLength(chipType) + 44; + } + + Cart(void); + size_t toQRString(char *output); + virtual Error readSystemID(void); + virtual Error readCartID(void) { return UNSUPPORTED_OP; } + virtual Error readPublicData(void) { return UNSUPPORTED_OP; } + virtual Error readPrivateData(void) { return UNSUPPORTED_OP; } + virtual Error writeData(void) { return UNSUPPORTED_OP; } + virtual Error erase(void) { return UNSUPPORTED_OP; } + virtual Error setDataKey(const uint8_t *newKey) { return UNSUPPORTED_OP; } +}; + +class [[gnu::packed]] X76Cart : public Cart { +protected: + Error _readDS2401(void); + Error _x76Command(uint8_t command, uint8_t param, uint8_t pollByte) const; + +public: + uint8_t data[512]; + + Error readCartID(void); +}; + +class [[gnu::packed]] X76F041Cart : public X76Cart { +public: + uint8_t data[512]; + + X76F041Cart(void); + Error readPrivateData(void); + Error writeData(void); + Error erase(void); + Error setDataKey(const uint8_t *newKey); +}; + +class [[gnu::packed]] X76F100Cart : public X76Cart { +public: + uint8_t data[112]; + + X76F100Cart(void); + //Error readPrivateData(void); + //Error writeData(void); + //Error erase(void); + //Error setDataKey(const uint8_t *newKey); +}; + +class [[gnu::packed]] ZS01Cart : public Cart { +private: + Error _transact(zs01::Packet &request, zs01::Packet &response); + +public: + uint8_t data[112]; + + ZS01Cart(void); + Error readCartID(void); + Error readPublicData(void); + Error readPrivateData(void); + Error writeData(void); + Error erase(void); + Error setDataKey(const uint8_t *newKey); +}; + +} diff --git a/src/cartdb.cpp b/src/cartdb.cpp new file mode 100644 index 0000000..2e9ede6 --- /dev/null +++ b/src/cartdb.cpp @@ -0,0 +1,37 @@ + + +#include +#include +#include "asset.hpp" +#include "cart.hpp" +#include "cartdb.hpp" +#include "util.hpp" + +namespace cartdb { + +bool CartDB::init(void) { + if (!data.ptr) + return false; + + auto &firstEntry = *reinterpret_cast(data.ptr); + + if (firstEntry.version != ENTRY_VERSION) { + LOG("unsupported DB version %d", firstEntry.version); + return false; + } + + _chipType = firstEntry.chipType; + _entryLength = sizeof(Entry) + cart::getDataLength(_chipType); + numEntries = data.length / _entryLength; + + return true; +} + +IdentifyResult CartDB::identifyCart(cart::Cart &cart) const { + // TODO: implement this + + LOG("no matching game found"); + return UNIDENTIFIED; +} + +} diff --git a/src/cartdb.hpp b/src/cartdb.hpp new file mode 100644 index 0000000..3538dab --- /dev/null +++ b/src/cartdb.hpp @@ -0,0 +1,79 @@ + +#pragma once + +#include +#include +#include +#include "asset.hpp" +#include "cart.hpp" + +namespace cartdb { + +enum IdentifyResult { + UNIDENTIFIED = 0, + IDENTIFIED = 1, + BLANK = 2 +}; + +enum EntryFlag : uint8_t { + HAS_SYSTEM_ID = 1 << 0, + HAS_CART_ID = 1 << 1, + HAS_ZS_ID = 1 << 2, + HAS_CHECKSUM = 1 << 3 +}; + +static constexpr int ENTRY_VERSION = 1; + +class [[gnu::packed]] Entry { +public: + uint8_t version; + cart::ChipType chipType; + + uint8_t flags, _reserved; + uint8_t systemIDOffset, cartIDOffset, zsIDOffset, checksumOffset; + char code[8], region[8], name[64]; + uint8_t dataKey[8], config[8]; + + inline int getDisplayName(char *output, size_t length) const { + return snprintf(output, length, "%s %s\t%s", code, region, name); + } +}; + +class [[gnu::packed]] X76F041Entry : public Entry { +public: + uint8_t data[512]; +}; + +class [[gnu::packed]] X76F100Entry : public Entry { +public: + uint8_t data[112]; +}; + +class [[gnu::packed]] ZS01Entry : public Entry { +public: + uint8_t data[112]; +}; + +class CartDB { +private: + cart::ChipType _chipType; + size_t _entryLength; + +public: + asset::Asset data; + size_t numEntries; + + inline CartDB(void) + : _entryLength(0), numEntries(0) {} + inline const Entry &getEntry(int index) const { + auto _data = reinterpret_cast(data.ptr); + //assert(data); + + return *reinterpret_cast(&_data[index * _entryLength]); + } + + bool init(void); + IdentifyResult identifyCart(cart::Cart &cart) const; +}; + +} diff --git a/src/defs.hpp b/src/defs.hpp new file mode 100644 index 0000000..a654ad5 --- /dev/null +++ b/src/defs.hpp @@ -0,0 +1,24 @@ + +#pragma once + +#ifndef VERSION +#define VERSION "" +#endif + +#ifdef NDEBUG +#define VERSION_STRING VERSION +#else +#define VERSION_STRING VERSION "-debug" +#endif + +#define CH_UP_ARROW "\x80" +#define CH_DOWN_ARROW "\x81" +#define CH_LEFT_ARROW "\x82" +#define CH_RIGHT_ARROW "\x83" +#define CH_LEFT_BUTTON "\x84" +#define CH_RIGHT_BUTTON "\x85" +#define CH_START_BUTTON "\x86" +#define CH_CLOSED_LOCK "\x87" +#define CH_OPEN_LOCK "\x88" +#define CH_CHIP_ICON "\x89" +#define CH_CART_ICON "\x8a" diff --git a/src/gpu.cpp b/src/gpu.cpp new file mode 100644 index 0000000..e204af6 --- /dev/null +++ b/src/gpu.cpp @@ -0,0 +1,474 @@ + +#include +#include +#include "ps1/gpucmd.h" +#include "ps1/registers.h" +#include "ps1/system.h" +#include "gpu.hpp" + +namespace gpu { + +/* Basic API */ + +static constexpr int _DMA_CHUNK_SIZE = 8; +static constexpr int _DMA_TIMEOUT = 10000; + +size_t upload(const RectWH &rect, const void *data, bool wait) { + size_t length = (rect.w * rect.h) / 2; + + assert(!(length % _DMA_CHUNK_SIZE)); + length = (length + _DMA_CHUNK_SIZE - 1) / _DMA_CHUNK_SIZE; + + if (!waitForDMATransfer(DMA_GPU, _DMA_TIMEOUT)) + return 0; + + GPU_GP1 = gp1_dmaRequestMode(GP1_DREQ_NONE); + + while (!(GPU_GP1 & GP1_STAT_CMD_READY)) + __asm__ volatile(""); + + GPU_GP0 = gp0_flushCache(); + GPU_GP0 = gp0_vramWrite(); + GPU_GP0 = gp0_xy(rect.x, rect.y); + GPU_GP0 = gp0_xy(rect.w, rect.h); + + GPU_GP1 = gp1_dmaRequestMode(GP1_DREQ_GP0_WRITE); + + while (!(GPU_GP1 & GP1_STAT_WRITE_READY)) + __asm__ volatile(""); + + DMA_MADR(DMA_GPU) = reinterpret_cast(data); + DMA_BCR (DMA_GPU) = _DMA_CHUNK_SIZE | (length << 16); + DMA_CHCR(DMA_GPU) = DMA_CHCR_WRITE | DMA_CHCR_MODE_SLICE | DMA_CHCR_ENABLE; + + if (wait) + waitForDMATransfer(DMA_GPU, _DMA_TIMEOUT); + + return length * _DMA_CHUNK_SIZE * 4; +} + +/* Rendering context */ + +void Context::_flushLayer(void) { + if (_currentListPtr == _lastListPtr) + return; + + auto layer = _drawBuffer().layers.pushItem(); + assert(layer); + + *(_currentListPtr++) = gp0_endTag(1); + *(_currentListPtr++) = gp0_irq(); + + *layer = _lastListPtr; + _lastListPtr = _currentListPtr; +} + +void Context::_applyResolution(VideoMode mode, int shiftX, int shiftY) const { + GP1HorizontalRes hres; + GP1VerticalRes vres = (height > 256) ? GP1_VRES_512 : GP1_VRES_256; + + int span; + + if (width < 320) { + hres = GP1_HRES_256; + span = width * 10; + } else if (width < 368) { + hres = GP1_HRES_320; + span = width * 8; + } else if (width < 512) { + hres = GP1_HRES_368; + span = width * 7; + } else if (width < 640) { + hres = GP1_HRES_512; + span = width * 5; + } else { + hres = GP1_HRES_640; + span = width * 4; + } + + int x = shiftX + 0x760, offsetX = span / 2; + int y = shiftY + (mode ? 0xa3 : 0x88), offsetY = height / (vres ? 4 : 2); + + GPU_GP1 = gp1_fbMode(hres, vres, mode, height > 256, GP1_COLOR_16BPP); + GPU_GP1 = gp1_fbRangeH(x - offsetX, x + offsetX); + GPU_GP1 = gp1_fbRangeV(y - offsetY, y + offsetY); +} + +void Context::flip(void) { + auto &oldBuffer = _drawBuffer(), &newBuffer = _dispBuffer(); + + // Ensure the GPU has finished drawing the previous frame. + while (newBuffer.layers.length) + __asm__ volatile(""); + + auto mask = setInterruptMask(0); + + _flushLayer(); + _currentListPtr = newBuffer.displayList; + _lastListPtr = newBuffer.displayList; + _currentBuffer ^= 1; + + GPU_GP1 = gp1_fbOffset(oldBuffer.clip.x1, oldBuffer.clip.y1); + + // Kick off drawing. + drawNextLayer(); + if (mask) + setInterruptMask(mask); +} + +void Context::drawNextLayer(void) { + //auto mask = setInterruptMask(0); + auto layer = _dispBuffer().layers.popItem(); + + //if (mask) + //setInterruptMask(mask); + if (!layer) + return; + + while (DMA_CHCR(DMA_GPU) & DMA_CHCR_ENABLE) + __asm__ volatile(""); + while (!(GPU_GP1 & GP1_STAT_CMD_READY)) + __asm__ volatile(""); + + GPU_GP1 = gp1_acknowledge(); + GPU_GP1 = gp1_dmaRequestMode(GP1_DREQ_GP0_WRITE); + + DMA_MADR(DMA_GPU) = reinterpret_cast(*layer); + DMA_CHCR(DMA_GPU) = DMA_CHCR_WRITE | DMA_CHCR_MODE_LIST | DMA_CHCR_ENABLE; +} + +void Context::setResolution( + VideoMode mode, int _width, int _height, bool sideBySide +) { + auto mask = setInterruptMask(0); + + width = _width; + height = _height; + refreshRate = mode ? 50 : 60; + + for (int fb = 1; fb >= 0; fb--) { + auto &clip = _buffers[fb].clip; + + clip.x1 = sideBySide ? (_width * fb) : 0; + clip.y1 = sideBySide ? 0 : (_height * fb); + clip.x2 = clip.x1 + _width - 1; + clip.y2 = clip.y1 + _height - 1; + } + + _currentListPtr = _buffers[0].displayList; + _lastListPtr = _buffers[0].displayList; + _currentBuffer = 0; + + _applyResolution(mode); + if (mask) + setInterruptMask(mask); +} + +uint32_t *Context::newPacket(size_t length) { + auto ptr = _currentListPtr; + _currentListPtr = &ptr[length + 1]; + + //assert(_currentListPtr <= &_drawBuffer().displayList[DISPLAY_LIST_SIZE]); + + *(ptr++) = gp0_tag(length, _currentListPtr); + return ptr; +} + +void Context::newLayer(int x, int y, int drawWidth, int drawHeight) { + auto mask = setInterruptMask(0); + + _flushLayer(); + if (mask) + setInterruptMask(mask); + + auto &clip = _dispBuffer().clip; + + x += clip.x1; + y += clip.y1; + + auto cmd = newPacket(3); + + cmd[0] = gp0_fbOrigin(x, y); + cmd[1] = gp0_fbOffset1( + util::max(int(clip.x1), x), + util::max(int(clip.y1), y) + ); + cmd[2] = gp0_fbOffset2( + util::min(int(clip.x2), x + drawWidth - 1), + util::min(int(clip.y2), y + drawHeight - 1) + ); +} + +void Context::setTexturePage(uint16_t page, bool dither) { + uint32_t cmd = gp0_texpage(page, dither, false); + + if (cmd != _lastTexpage) { + *newPacket(1) = cmd; + _lastTexpage = cmd; + } +} + +void Context::setBlendMode(BlendMode blendMode, bool dither) { + uint16_t page = _lastTexpage & ~gp0_texpage( + gp0_page(0, 0, GP0_BLEND_BITMASK, GP0_COLOR_4BPP), true, true + ); + page |= gp0_page(0, 0, blendMode, GP0_COLOR_4BPP); + + setTexturePage(page, dither); +} + +void Context::drawRect( + int x, int y, int width, int height, Color color, bool blend +) { + auto cmd = newPacket(3); + + cmd[0] = color | gp0_rectangle(false, false, blend); + cmd[1] = gp0_xy(x, y); + cmd[2] = gp0_xy(width, height); +} + +void Context::drawGradientRectH( + int x, int y, int width, int height, Color left, Color right, bool blend +) { + auto cmd = newPacket(8); + + cmd[0] = left | gp0_shadedQuad(true, false, blend); + cmd[1] = gp0_xy(x, y); + cmd[2] = right; + cmd[3] = gp0_xy(x + width, y); + cmd[4] = left; + cmd[5] = gp0_xy(x, y + height); + cmd[6] = right; + cmd[7] = gp0_xy(x + width, y + height); +} + +void Context::drawGradientRectV( + int x, int y, int width, int height, Color top, Color bottom, bool blend +) { + auto cmd = newPacket(8); + + cmd[0] = top | gp0_shadedQuad(true, false, blend); + cmd[1] = gp0_xy(x, y); + cmd[2] = top; + cmd[3] = gp0_xy(x + width, y); + cmd[4] = bottom; + cmd[5] = gp0_xy(x, y + height); + cmd[6] = bottom; + cmd[7] = gp0_xy(x + width, y + height); +} + +void Context::drawGradientRectD( + int x, int y, int width, int height, Color top, Color middle, Color bottom, + bool blend +) { + auto cmd = newPacket(8); + + cmd[0] = top | gp0_shadedQuad(true, false, blend); + cmd[1] = gp0_xy(x, y); + cmd[2] = middle; + cmd[3] = gp0_xy(x + width, y); + cmd[4] = middle; + cmd[5] = gp0_xy(x, y + height); + cmd[6] = bottom; + cmd[7] = gp0_xy(x + width, y + height); +} + +void Context::drawBackdrop(Color color, BlendMode blendMode) { + setBlendMode(blendMode, true); + drawRect(0, 0, width, height, color, true); +} + +/* Image and font classes */ + +void Image::initFromVRAMRect( + const RectWH &rect, ColorDepth colorDepth, BlendMode blendMode +) { + int shift = 2 - int(colorDepth); + + u = (rect.x & 0x3f) << shift; + v = rect.y & 0xff; + width = rect.w << shift; + height = rect.h; + texpage = gp0_page(rect.x / 64, rect.y / 256, blendMode, colorDepth); +} + +bool Image::initFromTIMHeader(const TIMHeader *header, BlendMode blendMode) { + if (header->magic != 0x10) + return false; + + auto ptr = reinterpret_cast(&header[1]); + + if (header->flags & (1 << 3)) { + auto clut = reinterpret_cast(ptr); + + palette = gp0_clut(clut->vram.x / 16, clut->vram.y); + ptr += clut->length; + } + + auto image = reinterpret_cast(ptr); + + initFromVRAMRect(image->vram, ColorDepth(header->flags & 3), blendMode); + return true; +} + +void Image::drawScaled( + Context &ctx, int x, int y, int w, int h, bool blend +) const { + int x2 = x + w, u2 = u + width; + int y2 = y + h, v2 = v + height; + + auto cmd = ctx.newPacket(9); + + cmd[0] = gp0_quad(true, blend); + cmd[1] = gp0_xy(x, y); + cmd[2] = gp0_uv(u, v, palette); + cmd[3] = gp0_xy(x2, y); + cmd[4] = gp0_uv(u2, v, texpage); + cmd[5] = gp0_xy(x, y2); + cmd[6] = gp0_uv(u, v2, 0); + cmd[7] = gp0_xy(x2, y2); + cmd[8] = gp0_uv(u2, v2, 0); +} + +void Image::draw(Context &ctx, int x, int y, bool blend) const { + ctx.setTexturePage(texpage); + auto cmd = ctx.newPacket(4); + + cmd[0] = gp0_rectangle(true, true, blend); + cmd[1] = gp0_xy(x, y); + cmd[2] = gp0_uv(u, v, palette); + cmd[3] = gp0_xy(width, height); +} + +void Font::draw( + Context &ctx, const char *str, const Rect &rect, Color color, bool wordWrap +) const { + // This is required for non-ASCII characters to work properly. + auto _str = reinterpret_cast(str); + + if (!str) + return; + + ctx.setTexturePage(image.texpage); + + int x = rect.x1; + int y = rect.y1; + + for (uint8_t ch = *_str; ch; ch = *(++_str)) { + bool wrap = wordWrap; + + assert(ch < (FONT_CHAR_OFFSET + FONT_CHAR_COUNT)); + switch (ch) { + case '\t': + x += FONT_TAB_WIDTH - 1; + x -= x % FONT_TAB_WIDTH; + break; + + case '\n': + x = rect.x1; + y += FONT_LINE_HEIGHT; + break; + + case '\r': + x = rect.x1; + break; + + case ' ': + x += FONT_SPACE_WIDTH; + break; + + default: + uint32_t size = metrics[ch - FONT_CHAR_OFFSET]; + + int u = size & 0xff; size >>= 8; + int v = size & 0xff; size >>= 8; + int w = size & 0x7f; size >>= 7; + int h = size & 0x7f; size >>= 7; + + auto cmd = ctx.newPacket(4); + + cmd[0] = color | gp0_rectangle(true, size, true); + cmd[1] = gp0_xy(x, y); + cmd[2] = gp0_uv(u + image.u, v + image.v, image.palette); + cmd[3] = gp0_xy(w, h); + + x += w; + wrap = false; + } + + // Handle word wrapping by calculating the length of the next word and + // checking if it can still fit in the current line. + int boundaryX = rect.x2; + if (wrap) + boundaryX -= getStringWidth( + reinterpret_cast(&_str[1]), true + ); + + if (x > boundaryX) { + x = rect.x1; + y += FONT_LINE_HEIGHT; + } + if (y > rect.y2) + break; + } +} + +void Font::draw( + Context &ctx, const char *str, const RectWH &rect, Color color, + bool wordWrap +) const { + Rect _rect{ + .x1 = rect.x, + .y1 = rect.y, + .x2 = int16_t(rect.x + rect.w), + .y2 = int16_t(rect.y + rect.h) + }; + + draw(ctx, str, _rect, color, wordWrap); +} + +int Font::getStringWidth(const char *str, bool breakOnSpace) const { + auto _str = reinterpret_cast(str); + if (!str) + return 0; + + int width = 0, maxWidth = 0; + + for (uint8_t ch = *_str; ch; ch = *(++_str)) { + assert(ch < (FONT_CHAR_OFFSET + FONT_CHAR_COUNT)); + switch (ch) { + case '\t': + if (breakOnSpace) + goto _break; + + width += FONT_TAB_WIDTH - 1; + width -= width % FONT_TAB_WIDTH; + break; + + case '\n': + case '\r': + if (breakOnSpace) + goto _break; + if (width > maxWidth) + maxWidth = width; + + width = 0; + break; + + case ' ': + if (breakOnSpace) + goto _break; + + width += FONT_SPACE_WIDTH; + break; + + default: + width += (metrics[ch - FONT_CHAR_OFFSET] >> 16) & 0x7f; + } + } + +_break: + return (width > maxWidth) ? width : maxWidth; +} + +} diff --git a/src/gpu.hpp b/src/gpu.hpp new file mode 100644 index 0000000..e7fcc68 --- /dev/null +++ b/src/gpu.hpp @@ -0,0 +1,199 @@ + +#pragma once + +#include +#include +#include "ps1/gpucmd.h" +#include "ps1/registers.h" +#include "util.hpp" + +namespace gpu { + +/* Types */ + +using Color = uint32_t; +using BlendMode = GP0BlendMode; +using ColorDepth = GP0ColorDepth; +using VideoMode = GP1VideoMode; + +struct Rect { +public: + int16_t x1, y1, x2, y2; +}; + +struct RectWH { +public: + int16_t x, y, w, h; +}; + +struct RectRB { +public: + int16_t x, y, r, b; +}; + +/* Basic API */ + +static inline void init(void) { + GPU_GP1 = gp1_resetGPU(); + GPU_GP1 = gp1_resetFIFO(); + + TIMER_CTRL(0) = TIMER_CTRL_EXT_CLOCK; + TIMER_CTRL(1) = TIMER_CTRL_EXT_CLOCK; +} + +static inline void enableDisplay(bool enable) { + GPU_GP1 = gp1_dispBlank(!enable); +} + +size_t upload(const RectWH &rect, const void *data, bool wait); + +/* Rendering context */ + +static constexpr size_t DISPLAY_LIST_SIZE = 0x4000; +static constexpr size_t LAYER_STACK_SIZE = 16; + +struct Buffer { +public: + Rect clip; + uint32_t displayList[DISPLAY_LIST_SIZE]; + + volatile util::RingBuffer layers; +}; + +class Context { +private: + Buffer _buffers[2]; + uint32_t *_currentListPtr, *_lastListPtr; + int _currentBuffer; + + uint32_t _lastTexpage; + + inline Buffer &_drawBuffer(void) { + return _buffers[_currentBuffer]; + } + inline Buffer &_dispBuffer(void) { + return _buffers[_currentBuffer ^ 1]; + } + + void _flushLayer(void); + void _applyResolution(VideoMode mode, int shiftX = 0, int shiftY = 0) const; + +public: + int width, height, refreshRate; + + inline Context( + VideoMode mode, int width, int height, bool sideBySide = false + ) : _lastTexpage(0) { + setResolution(mode, width, height, sideBySide); + } + inline void newLayer(int x, int y) { + newLayer(x, y, width, height); + } + + inline void drawRect(RectWH &rect, Color color, bool blend = false) { + drawRect(rect.x, rect.y, rect.w, rect.h, color, blend); + } + inline void drawGradientRectH( + RectWH &rect, Color left, Color right, bool blend = false + ) { + drawGradientRectH(rect.x, rect.y, rect.w, rect.h, left, right, blend); + } + inline void drawGradientRectV( + RectWH &rect, Color top, Color bottom, bool blend = false + ) { + drawGradientRectV(rect.x, rect.y, rect.w, rect.h, top, bottom, blend); + } + inline void drawGradientRectD( + RectWH &rect, Color top, Color middle, Color bottom, bool blend = false + ) { + drawGradientRectD( + rect.x, rect.y, rect.w, rect.h, top, middle, bottom, blend + ); + } + + void setResolution( + VideoMode mode, int width, int height, bool sideBySide = false + ); + void drawNextLayer(void); + void flip(void); + + uint32_t *newPacket(size_t length); + void newLayer(int x, int y, int drawWidth, int drawHeight); + void setTexturePage(uint16_t page, bool dither = false); + void setBlendMode(BlendMode blendMode, bool dither = false); + + void drawRect( + int x, int y, int width, int height, Color color, bool blend = false + ); + void drawGradientRectH( + int x, int y, int width, int height, Color left, Color right, + bool blend = false + ); + void drawGradientRectV( + int x, int y, int width, int height, Color top, Color bottom, + bool blend = false + ); + void drawGradientRectD( + int x, int y, int width, int height, Color top, Color middle, + Color bottom, bool blend = false + ); + void drawBackdrop(Color color, BlendMode blendMode); +}; + +/* Image and font classes */ + +struct [[gnu::packed]] TIMHeader { +public: + uint32_t magic, flags; +}; + +struct [[gnu::packed]] TIMSectionHeader { +public: + uint32_t length; + RectWH vram; +}; + +class Image { +public: + uint16_t u, v, width, height; + uint16_t texpage, palette; + + inline Image(void) + : width(0), height(0) {} + + void initFromVRAMRect( + const RectWH &rect, ColorDepth colorDepth, + BlendMode blendMode = GP0_BLEND_SEMITRANS + ); + bool initFromTIMHeader( + const TIMHeader *header, BlendMode blendMode = GP0_BLEND_SEMITRANS + ); + void drawScaled( + Context &ctx, int x, int y, int w, int h, bool blend = false + ) const; + void draw(Context &ctx, int x, int y, bool blend = false) const; +}; + +static constexpr int FONT_CHAR_OFFSET = ' '; +static constexpr int FONT_CHAR_COUNT = 120; +static constexpr int FONT_SPACE_WIDTH = 4; +static constexpr int FONT_TAB_WIDTH = 32; +static constexpr int FONT_LINE_HEIGHT = 10; + +class Font { +public: + Image image; + uint32_t metrics[FONT_CHAR_COUNT]; + + void draw( + Context &ctx, const char *str, const Rect &rect, Color color = 0x808080, + bool wordWrap = false + ) const; + void draw( + Context &ctx, const char *str, const RectWH &rect, + Color color = 0x808080, bool wordWrap = false + ) const; + int getStringWidth(const char *str, bool breakOnSpace = false) const; +}; + +} diff --git a/src/io.cpp b/src/io.cpp new file mode 100644 index 0000000..f8fd678 --- /dev/null +++ b/src/io.cpp @@ -0,0 +1,405 @@ + +#include +#include +#include "ps1/registers.h" +#include "ps1/system.h" +#include "io.hpp" +#include "util.hpp" + +namespace io { + +uint16_t _bankSwitchReg, _cartOutputReg, _miscOutputReg; + +void init(void) { + _bankSwitchReg = 0; + _cartOutputReg = 0; + _miscOutputReg = 0x0107; + + BIU_DEV0_ADDR = 0x1f000000; + BIU_DEV0_CTRL = 0 + | (7 << 0) // Write delay + | (4 << 4) // Read delay + | BIU_CTRL_RECOVERY + | BIU_CTRL_HOLD + | BIU_CTRL_FLOAT + | BIU_CTRL_PRESTROBE + | BIU_CTRL_WIDTH_16 + | BIU_CTRL_AUTO_INCR + | (23 << 16) // Number of address lines + | ( 4 << 24) // DMA read/write delay + | BIU_CTRL_DMA_DELAY; + + SYS573_WATCHDOG = 0; + SYS573_BANK_CTRL = 0; + SYS573_CART_OUT = 0; + SYS573_MISC_OUT = 0x0107; + + // Some of the digital I/O board's light outputs are controlled by the FPGA + // and cannot be turned off until the FPGA is initialized. + if (isDigitalIOPresent()) { + //SYS573D_CPLD_LIGHTS_B0 = 0xf000; + SYS573D_CPLD_LIGHTS_C0 = 0xf000; + SYS573D_CPLD_LIGHTS_C1 = 0xf000; + } else { + SYS573A_LIGHTS_A = 0x00ff; + SYS573A_LIGHTS_B = 0x00ff; + SYS573A_LIGHTS_C = 0x00ff; + SYS573A_LIGHTS_D = 0x00ff; + } +} + +uint32_t getJAMMAInputs(void) { + uint32_t inputs; + + inputs = SYS573_JAMMA_MAIN; + inputs |= (SYS573_JAMMA_EXT1 & 0x0f00) << 8; + inputs |= (SYS573_JAMMA_EXT2 & 0x0f00) << 12; + inputs |= (SYS573_MISC_IN & 0x1f00) << 16; + + return inputs ^ 0x1fffffff; +} + +/* Digital I/O board driver */ + +static void _writeBitstreamLSB(const uint8_t *data, size_t length) { + for (; length; length--) { + uint16_t bits = *(data++); + + for (int i = 8; i; i--, bits >>= 1) + SYS573D_CPLD_BITSTREAM = (bits & 1) << 15; + } +} + +static void _writeBitstreamMSB(const uint8_t *data, size_t length) { + for (; length; length--) { + uint16_t bits = *(data++) << 8; + + for (int i = 8; i; i--, bits <<= 1) + SYS573D_CPLD_BITSTREAM = bits & (1 << 15); + } +} + +bool loadBitstream(const uint8_t *data, size_t length) { + if (data[0] != 0xff) + return false; + + // Konami's bitstreams are always stored LSB first, however Xilinx tools + // seem to export bitstreams MSB first by default. The only way out of this + // mess is to autodetect the bit order by checking for preamble and frame + // start sequences, as specified in the XCS40XL datasheet. + uint8_t id1 = data[1], id2 = data[4]; + void (*writeFunc)(const uint8_t *, size_t); + + if (((id1 & 0x0f) == 0x04) && ((id2 & 0xf0) == 0xf0)) + writeFunc = &_writeBitstreamLSB; + else if (((id1 & 0xf0) == 0x20) && ((id2 & 0x0f) == 0x0f)) + writeFunc = &_writeBitstreamMSB; + else + return false; + + for (int i = 3; i; i--) { + SYS573D_CPLD_UNK_RESET = 0; + + SYS573D_CPLD_CTRL = SYS573D_CPLD_CTRL_UNK4; + SYS573D_CPLD_CTRL = SYS573D_CPLD_CTRL_UNK4 | SYS573D_CPLD_CTRL_UNK3; + SYS573D_CPLD_CTRL = SYS573D_CPLD_CTRL_UNK4 | SYS573D_CPLD_CTRL_UNK3 | + SYS573D_CPLD_CTRL_UNK2 | SYS573D_CPLD_CTRL_UNK1; + delayMicroseconds(5000); + + if (!(SYS573D_CPLD_STAT & SYS573D_CPLD_STAT_INIT)) + continue; + + writeFunc(data, length); + + for (int j = 15; j; j--) { + if ( + (SYS573D_CPLD_STAT & (SYS573D_CPLD_STAT_INIT | SYS573D_CPLD_STAT_DONE)) + == (SYS573D_CPLD_STAT_INIT | SYS573D_CPLD_STAT_DONE) + ) + return true; + + delayMicroseconds(1000); + } + } + + return false; +} + +void initKonamiBitstream(void) { + SYS573D_FPGA_INIT = 0xf000; + SYS573D_FPGA_INIT = 0x0000; + delayMicroseconds(1000); + + SYS573D_FPGA_INIT = 0xf000; + delayMicroseconds(1000); + + // Turn off all lights including the ones that were left on by init(). + SYS573D_FPGA_LIGHTS_A0 = 0xf000; + SYS573D_FPGA_LIGHTS_A1 = 0xf000; + SYS573D_CPLD_LIGHTS_B0 = 0xf000; + SYS573D_FPGA_LIGHTS_B1 = 0xf000; + SYS573D_CPLD_LIGHTS_C0 = 0xf000; + SYS573D_CPLD_LIGHTS_C1 = 0xf000; + SYS573D_FPGA_LIGHTS_D0 = 0xf000; +} + +/* I2C driver */ + +// SDA is open-drain so it is toggled by changing pin direction. +#define _SDA(value) setCartSDADir(!(value)) +#define SDA(value) _SDA(value), delayMicroseconds(20) +#define _SCL(value) setCartOutput(OUT_SCL, value) +#define SCL(value) _SCL(value), delayMicroseconds(20) +#define _CS(value) setCartOutput(OUT_CS, value) +#define CS(value) _CS(value), delayMicroseconds(20) +#define _RESET(value) setCartOutput(OUT_RESET, value) +#define RESET(value) _RESET(value), delayMicroseconds(20) + +void i2cStart(void) { + _SDA(true); + SCL(true); + + SDA(false); // START: SDA falling, SCL high + SCL(false); +} + +void i2cStartWithCS(int csDelay) { + _SDA(true); + _SCL(true); + CS(true); + + CS(false); + delayMicroseconds(csDelay); + SDA(false); // START: SDA falling, SCL high + SCL(false); +} + +void i2cStop(void) { + _SDA(false); + SCL(true); + + SDA(true); // STOP: SDA rising, SCL high +} + +void i2cStopWithCS(int csDelay) { + _SDA(false); + SCL(true); + + SDA(true); // STOP: SDA rising, SCL high + delayMicroseconds(csDelay); + CS(true); +} + +uint8_t i2cReadByte(void) { + uint8_t value = 0; + + for (int bit = 7; bit >= 0; bit--) { // MSB first + SCL(true); + if (getCartSDA()) + value |= (1 << bit); + SCL(false); + } + + delayMicroseconds(20); + return value; +} + +void i2cWriteByte(uint8_t value) { + for (int bit = 7; bit >= 0; bit--) { // MSB first + _SDA(value & (1 << bit)); + SCL(true); + SCL(false); + } + + SDA(true); +} + +void i2cSendACK(bool ack) { + _SDA(!ack); + SCL(true); + SCL(false); + SDA(true); +} + +bool i2cGetACK(void) { + delayMicroseconds(20); // Required for ZS01 + SCL(true); + bool ack = !getCartSDA(); + SCL(false); + + delayMicroseconds(20); + return ack; +} + +void i2cReadBytes(uint8_t *data, size_t length) { + for (; length; length--) { + *(data++) = i2cReadByte(); + + if (length > 1) + i2cSendACK(true); + } +} + +bool i2cWriteBytes(const uint8_t *data, size_t length, int lastACKDelay) { + for (; length; length--) { + i2cWriteByte(*(data++)); + + if (length == 1) + delayMicroseconds(lastACKDelay); + if (!i2cGetACK()) + return false; + } + + return true; +} + +uint32_t i2cResetX76(void) { + uint32_t value = 0; + + _SDA(true); + _SCL(false); + _CS(false); + _RESET(false); + + RESET(true); + SCL(true); + SCL(false); + RESET(false); + + for (int bit = 0; bit < 32; bit++) { // LSB first + SCL(true); + if (getCartSDA()) + value |= (1 << bit); + SCL(false); + } + + SCL(true); + CS(true); + return value; +} + +// For whatever reason the ZS01 does not implement the exact same response to +// reset protocol as the X76 chips. The reset pin is also active-low rather +// than active-high, and CS is ignored. +uint32_t i2cResetZS01(void) { + uint32_t value = 0; + + _SDA(true); + _SCL(false); + _CS(false); + _RESET(true); + + RESET(false); + RESET(true); + delayMicroseconds(100); + + SCL(true); + SCL(false); + + for (int bit = 31; bit >= 0; bit--) { // MSB first + if (getCartSDA()) + value |= (1 << bit); + SCL(true); + SCL(false); + } + + SCL(true); + return value; +} + +/* 1-wire driver */ + +#define _CART1WIRE(value) setCartOutput(OUT_1WIRE, !(value)) +#define _DIO1WIRE(value) setDIO1Wire(value) + +bool dsCartReset(void) { + _CART1WIRE(false); + delayMicroseconds(480); + _CART1WIRE(true); + + delayMicroseconds(60); + bool present = !getCartInput(IN_1WIRE); + delayMicroseconds(60); + + delayMicroseconds(1000); + return present; +} + +bool dsDIOReset(void) { + _DIO1WIRE(false); + delayMicroseconds(480); + _DIO1WIRE(true); + + delayMicroseconds(60); + bool present = !getDIO1Wire(); + delayMicroseconds(60); + + delayMicroseconds(1000); + return present; +} + +uint8_t dsCartReadByte(void) { + uint8_t value = 0; + + for (int bit = 0; bit < 8; bit++) { // LSB first + _CART1WIRE(false); + delayMicroseconds(2); + _CART1WIRE(true); + delayMicroseconds(10); + if (getCartInput(IN_1WIRE)) + value |= (1 << bit); + delayMicroseconds(50); + } + + return value; +} + +uint8_t dsDIOReadByte(void) { + uint8_t value = 0; + + for (int bit = 0; bit < 8; bit++) { // LSB first + _DIO1WIRE(false); + delayMicroseconds(2); + _DIO1WIRE(true); + delayMicroseconds(10); + if (getDIO1Wire()) + value |= (1 << bit); + delayMicroseconds(50); + } + + return value; +} + +void dsCartWriteByte(uint8_t value) { + for (int bit = 0; bit < 8; bit++) { // LSB first + if (value & (1 << bit)) { + _CART1WIRE(false); + delayMicroseconds(2); + _CART1WIRE(true); + delayMicroseconds(60); + } else { + _CART1WIRE(false); + delayMicroseconds(60); + _CART1WIRE(true); + delayMicroseconds(2); + } + } +} + +void dsDIOWriteByte(uint8_t value) { + for (int bit = 0; bit < 8; bit++) { // LSB first + if (value & (1 << bit)) { + _DIO1WIRE(false); + delayMicroseconds(2); + _DIO1WIRE(true); + delayMicroseconds(60); + } else { + _DIO1WIRE(false); + delayMicroseconds(60); + _DIO1WIRE(true); + delayMicroseconds(2); + } + } +} + +} diff --git a/src/io.hpp b/src/io.hpp new file mode 100644 index 0000000..b693587 --- /dev/null +++ b/src/io.hpp @@ -0,0 +1,180 @@ + +#pragma once + +#include +#include "ps1/registers.h" + +namespace io { + +/* Register and bit definitions */ + +enum JAMMAInput : uint32_t { + // SYS573_JAMMA_MAIN + JAMMA_P2_LEFT = 1 << 0, + JAMMA_P2_RIGHT = 1 << 1, + JAMMA_P2_UP = 1 << 2, + JAMMA_P2_DOWN = 1 << 3, + JAMMA_P2_BUTTON1 = 1 << 4, + JAMMA_P2_BUTTON2 = 1 << 5, + JAMMA_P2_BUTTON3 = 1 << 6, + JAMMA_P2_START = 1 << 7, + JAMMA_P1_LEFT = 1 << 8, + JAMMA_P1_RIGHT = 1 << 9, + JAMMA_P1_UP = 1 << 10, + JAMMA_P1_DOWN = 1 << 11, + JAMMA_P1_BUTTON1 = 1 << 12, + JAMMA_P1_BUTTON2 = 1 << 13, + JAMMA_P1_BUTTON3 = 1 << 14, + JAMMA_P1_START = 1 << 15, + + // SYS573_JAMMA_EXT1 + JAMMA_P1_BUTTON4 = 1 << 16, + JAMMA_P1_BUTTON5 = 1 << 17, + JAMMA_TEST = 1 << 18, + JAMMA_P1_BUTTON6 = 1 << 19, + + // SYS573_JAMMA_EXT2 + JAMMA_P2_BUTTON4 = 1 << 20, + JAMMA_P2_BUTTON5 = 1 << 21, + JAMMA_UNKNOWN = 1 << 22, + JAMMA_P2_BUTTON6 = 1 << 23, + + // SYS573_MISC_IN + JAMMA_COIN1 = 1 << 24, + JAMMA_COIN2 = 1 << 25, + JAMMA_PCMCIA_CD1 = 1 << 26, + JAMMA_PCMCIA_CD2 = 1 << 27, + JAMMA_SERVICE = 1 << 28 +}; + +enum CartInputPin { + IN_1WIRE = 6 +}; + +enum CartOutputPin { + OUT_SDA = 0, + OUT_SCL = 1, + OUT_CS = 2, + OUT_RESET = 3, + OUT_1WIRE = 4 +}; + +enum MiscOutputPin { + MISC_ADC_MOSI = 0, + MISC_ADC_CS = 1, + MISC_ADC_SCK = 2, + MISC_COIN_COUNT1 = 3, + MISC_COIN_COUNT2 = 4, + MISC_AMP_ENABLE = 5, + MISC_CDDA_ENABLE = 6, + MISC_SPU_ENABLE = 7, + MISC_JVS_STAT = 8 +}; + +/* Inputs */ + +static inline void clearWatchdog(void) { + SYS573_WATCHDOG = 0; +} + +static inline uint32_t getDIPSwitches(void) { + return SYS573_DIP_CART & 0xf; +} + +static inline bool getCartInsertionStatus(void) { + return (SIO_STAT(1) >> 7) & 1; +} + +static inline bool getCartSerialStatus(void) { + SIO_CTRL(1) |= 1 << 5; + return (SIO_STAT(1) >> 8) & 1; +} + +/* Bitbanged I/O */ + +extern uint16_t _bankSwitchReg, _cartOutputReg, _miscOutputReg; + +static inline bool getCartInput(CartInputPin pin) { + return (SYS573_DIP_CART >> (8 + pin)) & 1; +} + +static inline bool getCartSDA(void) { + return (SYS573_MISC_IN >> 2) & 1; +} + +static inline void setCartOutput(CartOutputPin pin, bool value) { + if (value) + _cartOutputReg |= 1 << pin; + else + _cartOutputReg &= ~(1 << pin); + + SYS573_CART_OUT = _cartOutputReg; +} + +static inline void setCartSDADir(bool dir) { + if (dir) + _bankSwitchReg |= 1 << 6; + else + _bankSwitchReg &= ~(1 << 6); + + SYS573_BANK_CTRL = _bankSwitchReg; +} + +static inline void setMiscOutput(MiscOutputPin pin, bool value) { + if (value) + _miscOutputReg |= 1 << pin; + else + _miscOutputReg &= ~(1 << pin); + + SYS573_MISC_OUT = _miscOutputReg; +} + +/* Digital I/O board driver */ + +// TODO: these do not seem to actually be LDC and HDC... +static inline bool isDigitalIOPresent(void) { + return ( + (SYS573D_CPLD_STAT & (SYS573D_CPLD_STAT_LDC | SYS573D_CPLD_STAT_HDC)) + == SYS573D_CPLD_STAT_HDC + ); +} + +static inline bool getDIO1Wire(void) { + return (SYS573D_FPGA_DS2401 >> 12) & 1; +} + +static inline void setDIO1Wire(bool value) { + SYS573D_FPGA_DS2401 = (value ^ 1) << 12; +} + +/* Other APIs */ + +void init(void); +uint32_t getJAMMAInputs(void); + +bool loadBitstream(const uint8_t *data, size_t length); +void initKonamiBitstream(void); + +void i2cStart(void); +void i2cStartWithCS(int csDelay = 0); +void i2cStop(void); +void i2cStopWithCS(int csDelay = 0); + +uint8_t i2cReadByte(void); +void i2cWriteByte(uint8_t value); +void i2cSendACK(bool ack); +bool i2cGetACK(void); +void i2cReadBytes(uint8_t *data, size_t length); +bool i2cWriteBytes(const uint8_t *data, size_t length, int lastACKDelay = 0); + +uint32_t i2cResetX76(void); +uint32_t i2cResetZS01(void); + +bool dsCartReset(void); +bool dsDIOReset(void); +uint8_t dsCartReadByte(void); +uint8_t dsDIOReadByte(void); +void dsCartWriteByte(uint8_t value); +void dsDIOWriteByte(uint8_t value); + +} diff --git a/src/libc/assert.h b/src/libc/assert.h new file mode 100644 index 0000000..2f5b5d5 --- /dev/null +++ b/src/libc/assert.h @@ -0,0 +1,36 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#pragma once + +// NDEBUG is automatically defined by CMake when the executable is built in +// release mode. +#ifdef NDEBUG +#define assert(expr) +#else +#define assert(expr) \ + ((expr) ? ((void) 0) : _assertAbort(__FILE__, __LINE__, #expr)) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +void _assertAbort(const char *file, int line, const char *expr); + +#ifdef __cplusplus +} +#endif diff --git a/src/libc/crt0.c b/src/libc/crt0.c new file mode 100644 index 0000000..0fde2fd --- /dev/null +++ b/src/libc/crt0.c @@ -0,0 +1,77 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include + +#define _align(x, n) (((x) + ((n) - 1)) & ~((n) - 1)) + +typedef void (*Function)(void); + +/* Linker symbols */ + +// These are defined by the linker script. Note that these are not variables, +// they are virtual symbols whose location matches their value. The simplest way +// to turn them into pointers is to declare them as arrays. +extern char _sdataStart[], _bssStart[], _bssEnd[]; + +extern const Function _preinitArrayStart[], _preinitArrayEnd[]; +extern const Function _initArrayStart[], _initArrayEnd[]; +extern const Function _finiArrayStart[], _finiArrayEnd[]; + +/* Heap API (used by malloc) */ + +static uintptr_t _heapEnd = (uintptr_t) _bssEnd; +static uintptr_t _heapLimit = 0x80200000; // TODO: add a way to change this + +void *sbrk(ptrdiff_t incr) { + uintptr_t currentEnd = _heapEnd; + uintptr_t newEnd = _align(currentEnd + incr, 8); + + if (newEnd >= _heapLimit) + return 0; + + _heapEnd = newEnd; + return (void *) currentEnd; +} + +/* Program entry point */ + +int main(int argc, const char **argv); + +int _start(int argc, const char **argv) { + // Set $gp to point to the middle of the .sdata/.sbss sections, ensuring + // variables placed in those sections can be quickly accessed. See the + // linker script for more details. + __asm__ volatile("la $gp, _gp;"); + + // Set all uninitialized variables to zero by clearing the BSS section. + __builtin_memset(_bssStart, 0, _bssEnd - _bssStart); + + // Invoke all global constructors if any, then main() and finally all global + // destructors. + for (const Function *ctor = _preinitArrayStart; ctor < _preinitArrayEnd; ctor++) + (*ctor)(); + for (const Function *ctor = _initArrayStart; ctor < _initArrayEnd; ctor++) + (*ctor)(); + + int returnValue = main(argc, argv); + + for (const Function *dtor = _initArrayStart; dtor < _initArrayEnd; dtor++) + (*dtor)(); + + return returnValue; +} diff --git a/src/libc/ctype.h b/src/libc/ctype.h new file mode 100644 index 0000000..f2233fb --- /dev/null +++ b/src/libc/ctype.h @@ -0,0 +1,35 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +int isprint(int ch); +int isgraph(int ch); +int isspace(int ch); +int isblank(int ch); +int isalpha(int ch); +int isdigit(int ch); + +int tolower(int ch); +int toupper(int ch); + +#ifdef __cplusplus +} +#endif diff --git a/src/libc/cxxsupport.cpp b/src/libc/cxxsupport.cpp new file mode 100644 index 0000000..b2ba547 --- /dev/null +++ b/src/libc/cxxsupport.cpp @@ -0,0 +1,50 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include + +extern "C" void *__builtin_new(size_t size) { + return malloc(size); +} + +extern "C" void __builtin_delete(void *ptr) { + free(ptr); +} + +void *operator new(size_t size) noexcept { + return malloc(size); +} + +void *operator new[](size_t size) noexcept { + return malloc(size); +} + +void operator delete(void *ptr) noexcept { + free(ptr); +} + +void operator delete[](void *ptr) noexcept { + free(ptr); +} + +void operator delete(void *ptr, size_t size) noexcept { + free(ptr); +} + +void operator delete[](void *ptr, size_t size) noexcept { + free(ptr); +} diff --git a/src/libc/malloc.c b/src/libc/malloc.c new file mode 100644 index 0000000..f19b543 --- /dev/null +++ b/src/libc/malloc.c @@ -0,0 +1,238 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + * + * This code is based on psyqo's malloc implementation, available here: + * https://github.com/grumpycoders/pcsx-redux/blob/main/src/mips/psyqo/src/alloc.c + */ + +#include +#include +#include + +#define _align(x, n) (((x) + ((n) - 1)) & ~((n) - 1)) +#define _updateHeapUsage(incr) + +/* Internal state */ + +typedef struct _Block { + struct _Block *prev, *next; + + void *ptr; + size_t size; +} Block; + +static void *_mallocStart; +static Block *_mallocHead, *_mallocTail; + +/* Allocator implementation */ + +static Block *_findBlock(Block *head, size_t size) { + Block *prev = head; + + for (; prev; prev = prev->next) { + if (prev->next) { + uintptr_t nextBot = (uintptr_t) prev->next; + nextBot -= (uintptr_t) prev->ptr + prev->size; + + if (nextBot >= size) + return prev; + } + } + + return prev; +} + +void *malloc(size_t size) { + if (!size) + return 0; + + size_t _size = _align(size + sizeof(Block), 8); + + // Nothing's initialized yet? Let's just initialize the bottom of our heap, + // flag it as allocated. + if (!_mallocHead) { + if (!_mallocStart) + _mallocStart = sbrk(0); + + Block *new = (Block *) sbrk(_size); + if (!new) + return 0; + + void *ptr = (void *) &new[1]; + new->ptr = ptr; + new->size = _size - sizeof(Block); + new->prev = 0; + new->next = 0; + + _mallocHead = new; + _mallocTail = new; + + _updateHeapUsage(size); + return ptr; + } + + // We *may* have the bottom of our heap that has shifted, because of a free. + // So let's check first if we have free space there, because I'm nervous + // about having an incomplete data structure. + if (((uintptr_t) _mallocStart + _size) < ((uintptr_t) _mallocHead)) { + Block *new = (Block *) _mallocStart; + + void *ptr = (void *) &new[1]; + new->ptr = ptr; + new->size = _size - sizeof(Block); + new->prev = 0; + new->next = _mallocHead; + + _mallocHead->prev = new; + _mallocHead = new; + + _updateHeapUsage(size); + return ptr; + } + + // No luck at the beginning of the heap, let's walk the heap to find a fit. + Block *prev = _findBlock(_mallocHead, _size); + if (prev) { + Block *new = (Block *) ((uintptr_t) prev->ptr + prev->size); + + void *ptr = (void *)((uintptr_t) new + sizeof(Block)); + new->ptr = ptr; + new->size = _size - sizeof(Block); + new->prev = prev; + new->next = prev->next; + + (new->next)->prev = new; + prev->next = new; + + _updateHeapUsage(size); + return ptr; + } + + // Time to extend the size of the heap. + Block *new = (Block *) sbrk(_size); + if (!new) + return 0; + + void *ptr = (void *) &new[1]; + new->ptr = ptr; + new->size = _size - sizeof(Block); + new->prev = _mallocTail; + new->next = 0; + + _mallocTail->next = new; + _mallocTail = new; + + _updateHeapUsage(size); + return ptr; +} + +void *calloc(size_t num, size_t size) { + return malloc(num * size); +} + +void *realloc(void *ptr, size_t size) { + if (!size) { + free(ptr); + return 0; + } + if (!ptr) + return malloc(size); + + size_t _size = _align(size + sizeof(Block), 8); + Block *prev = (Block *) ((uintptr_t) ptr - sizeof(Block)); + + // New memory block shorter? + if (prev->size >= _size) { + _updateHeapUsage(size - prev->size); + prev->size = _size; + + if (!prev->next) + sbrk((ptr - sbrk(0)) + _size); + + return ptr; + } + + // New memory block larger; is it the last one? + if (!prev->next) { + void *new = sbrk(_size - prev->size); + if (!new) + return 0; + + _updateHeapUsage(size - prev->size); + prev->size = _size; + return ptr; + } + + // Do we have free memory after it? + if (((prev->next)->ptr - ptr) > _size) { + _updateHeapUsage(size - prev->size); + prev->size = _size; + return ptr; + } + + // No luck. + void *new = malloc(_size); + if (!new) + return 0; + + __builtin_memcpy(new, ptr, prev->size); + free(ptr); + return new; +} + +void free(void *ptr) { + if (!ptr || !_mallocHead) + return; + + // First block; bumping head ahead. + if (ptr == _mallocHead->ptr) { + size_t size = _mallocHead->size; + size += (uintptr_t) _mallocHead->ptr - (uintptr_t) _mallocHead; + _mallocHead = _mallocHead->next; + + if (_mallocHead) { + _mallocHead->prev = 0; + } else { + _mallocTail = 0; + sbrk(-size); + } + + _updateHeapUsage(-(_mallocHead->size)); + return; + } + + // Finding the proper block + Block *cur = _mallocHead; + + for (cur = _mallocHead; ptr != cur->ptr; cur = cur->next) { + if (!cur->next) + return; + } + + if (cur->next) { + // In the middle, just unlink it + (cur->next)->prev = cur->prev; + } else { + // At the end, shrink heap + void *top = sbrk(0); + size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; + _mallocTail = cur->prev; + + sbrk(-size); + } + + _updateHeapUsage(-(cur->size)); + (cur->prev)->next = cur->next; +} diff --git a/src/libc/memset.s b/src/libc/memset.s new file mode 100644 index 0000000..9d1a0fb --- /dev/null +++ b/src/libc/memset.s @@ -0,0 +1,134 @@ +# ps1-bare-metal - (C) 2023 spicyjpeg +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +# PERFORMANCE OF THIS SOFTWARE. + +.set noreorder + +# This is an optimized implementation of memset() that makes use of Duff's +# device and unaligned store instructions to fill large areas of memory much +# faster than a simple byte-by-byte loop would. + +.section .text.memset, "ax", @progbits +.global memset +.type memset, @function + +memset: + # If more than 16 bytes have to be written then take the "large" path, + # otherwise use the code below. + addiu $t0, $a2, -16 + bgtz $t0, .LlargeFill + move $v0, $a0 # returnValue = dest + + # Jump to one of the sb opcodes below. This is basically a cut-down Duff's + # device implementation with no looping. + la $t0, .LsmallDuff + 0x40 # addr = &smallDuff[(16 - count) * 4] + sll $t1, $a2, 2 + subu $t0, $t1 + addu $a0, $a2 # dest -= 16 - count + jr $t0 + addiu $a0, -16 + +.LsmallDuff: + sb $a1, 0x0($a0) + sb $a1, 0x1($a0) + sb $a1, 0x2($a0) + sb $a1, 0x3($a0) + sb $a1, 0x4($a0) + sb $a1, 0x5($a0) + sb $a1, 0x6($a0) + sb $a1, 0x7($a0) + sb $a1, 0x8($a0) + sb $a1, 0x9($a0) + sb $a1, 0xa($a0) + sb $a1, 0xb($a0) + sb $a1, 0xc($a0) + sb $a1, 0xd($a0) + sb $a1, 0xe($a0) + sb $a1, 0xf($a0) + jr $ra + nop + +.LlargeFill: + # Initialize fast filling by repeating the fill byte 4 times, so it can be + # written 32 bits at a time. + andi $a1, 0xff # ch &= 0xff + sll $t0, $a1, 8 # ch |= (ch << 8) | (ch << 16) | (ch << 24) + or $a1, $t0 + sll $t0, $a1, 16 + or $a1, $t0 + + # Fill the first 1-4 bytes (here the swr instruction does all the magic) + # and update dest and count accordingly. + swr $a1, 0($a0) + andi $t0, $a0, 3 # align = 4 - (dest % 4) + addiu $t0, -4 + addu $a2, $t0 # count -= align + subu $a0, $t0 # dest += align + + la $t1, .LlargeDuff + andi $t2, $a2, 3 # remainder = count % 4 + subu $a2, $t2 # count -= remainder + +.LlargeFillLoop: + # If 128 bytes or more still have to be written, skip calculating the jump + # offset and execute the whole block of sw opcodes. + addiu $a2, -0x80 # count -= 0x80 + bgez $a2, .LlargeDuff + #nop + + # Jump to one of the sw opcodes below. This is the "full" Duff's device. + subu $t0, $t1, $a2 # addr = &largeDuff[0x80 - (count + 0x80)] + jr $t0 + addu $a0, $a2 # dest -= 0x80 - (count + 0x80) + +.LlargeDuff: + sw $a1, 0x00($a0) + sw $a1, 0x04($a0) + sw $a1, 0x08($a0) + sw $a1, 0x0c($a0) + sw $a1, 0x10($a0) + sw $a1, 0x14($a0) + sw $a1, 0x18($a0) + sw $a1, 0x1c($a0) + sw $a1, 0x20($a0) + sw $a1, 0x24($a0) + sw $a1, 0x28($a0) + sw $a1, 0x2c($a0) + sw $a1, 0x30($a0) + sw $a1, 0x34($a0) + sw $a1, 0x38($a0) + sw $a1, 0x3c($a0) + sw $a1, 0x40($a0) + sw $a1, 0x44($a0) + sw $a1, 0x48($a0) + sw $a1, 0x4c($a0) + sw $a1, 0x50($a0) + sw $a1, 0x54($a0) + sw $a1, 0x58($a0) + sw $a1, 0x5c($a0) + sw $a1, 0x60($a0) + sw $a1, 0x64($a0) + sw $a1, 0x68($a0) + sw $a1, 0x6c($a0) + sw $a1, 0x70($a0) + sw $a1, 0x74($a0) + sw $a1, 0x78($a0) + sw $a1, 0x7c($a0) + + bgtz $a2, .LlargeFillLoop + addiu $a0, 0x80 # dest += 0x80 + + # Fill the remaining 1-4 bytes, using (again) an unaligned store. + addu $a0, $t2 # lastByte = dest + remainder - 1 + jr $ra + swl $a1, -1($a0) diff --git a/src/libc/misc.c b/src/libc/misc.c new file mode 100644 index 0000000..c9632f1 --- /dev/null +++ b/src/libc/misc.c @@ -0,0 +1,87 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include "ps1/registers.h" + +/* Serial port stdin/stdout */ + +void initSerialIO(int baud) { + SIO_CTRL(1) = SIO_CTRL_RESET; + + SIO_MODE(1) = SIO_MODE_BAUD_DIV16 | SIO_MODE_DATA_8 | SIO_MODE_STOP_1; + SIO_BAUD(1) = (F_CPU / 16) / baud; + SIO_CTRL(1) = SIO_CTRL_TX_ENABLE | SIO_CTRL_RX_ENABLE | SIO_CTRL_RTS; +} + +void _putchar(char ch) { + // The serial interface will buffer but not send any data if the CTS input + // is not asserted, so we are going to abort if CTS is not set to avoid + // waiting forever. + while ( + (SIO_STAT(1) & (SIO_STAT_TX_NOT_FULL | SIO_STAT_CTS)) == SIO_STAT_CTS + ) + __asm__ volatile(""); + + if (SIO_STAT(1) & SIO_STAT_CTS) + SIO_DATA(1) = ch; +} + +int _getchar(void) { + while (!(SIO_STAT(1) & SIO_STAT_RX_NOT_EMPTY)) + __asm__ volatile(""); + + return SIO_DATA(1); +} + +int _puts(const char *str) { + int length = 1; + + for (; *str; str++, length++) + _putchar(*str); + + _putchar('\n'); + return length; +} + +/* Abort functions */ + +void _assertAbort(const char *file, int line, const char *expr) { +#ifndef NDEBUG + printf("%s:%d: assert(%s)\n", file, line, expr); +#endif + + for (;;) + __asm__ volatile(""); +} + +void abort(void) { +#ifndef NDEBUG + puts("abort()"); +#endif + + for (;;) + __asm__ volatile(""); +} + +void __cxa_pure_virtual(void) { +#ifndef NDEBUG + puts("__cxa_pure_virtual()"); +#endif + + for (;;) + __asm__ volatile(""); +} diff --git a/src/libc/misc.s b/src/libc/misc.s new file mode 100644 index 0000000..3c2a367 --- /dev/null +++ b/src/libc/misc.s @@ -0,0 +1,113 @@ +# ps1-bare-metal - (C) 2023 spicyjpeg +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +# PERFORMANCE OF THIS SOFTWARE. + +.set noreorder + +## setjmp() and longjmp() + +# This is not a "proper" implementation of setjmp/longjmp as it does not save +# COP0 and GTE registers, but it is good enough for most use cases. + +.section .text.setjmp, "ax", @progbits +.global setjmp +.type setjmp, @function + +setjmp: + sw $ra, 0x00($a0) + sw $s0, 0x04($a0) + sw $s1, 0x08($a0) + sw $s2, 0x0c($a0) + sw $s3, 0x10($a0) + sw $s4, 0x14($a0) + sw $s5, 0x18($a0) + sw $s6, 0x1c($a0) + sw $s7, 0x20($a0) + sw $gp, 0x24($a0) + sw $sp, 0x28($a0) + sw $fp, 0x2c($a0) + + jr $ra # return 0 + li $v0, 0 + +.section .text.longjmp, "ax", @progbits +.global longjmp +.type longjmp, @function + +longjmp: + lw $ra, 0x00($a0) + lw $s0, 0x04($a0) + lw $s1, 0x08($a0) + lw $s2, 0x0c($a0) + lw $s3, 0x10($a0) + lw $s4, 0x14($a0) + lw $s5, 0x18($a0) + lw $s6, 0x1c($a0) + lw $s7, 0x20($a0) + lw $gp, 0x24($a0) + lw $sp, 0x28($a0) + lw $fp, 0x2c($a0) + + jr $ra # return status (from setjmp) + move $v0, $a1 + +## Leading zero count intrinsics + +# libgcc provides two functions used internally by GCC to count the number of +# leading zeroes in a value, __clzsi2() (32-bit) and __clzdi2() (64-bit). We're +# going to override them with smaller implementations that make use of the GTE's +# LZCS/LZCR registers. + +.set LZCS, $30 +.set LZCR, $31 + +.section .text.__clzsi2, "ax", @progbits +.global __clzsi2 +.type __clzsi2, @function + +__clzsi2: + mtc2 $a0, LZCS + bltz $a0, .Lreturn # if (value & (1 << 31)) return 0 + li $v0, 0 + mfc2 $v0, LZCR # else return GTE_CLZ(value) + +.Lreturn: + jr $ra + nop + +.section .text.__clzdi2, "ax", @progbits +.global __clzdi2 +.type __clzdi2, @function + +__clzdi2: + mtc2 $a1, LZCS + bltz $a1, .Lreturn2 # if (msb & (1 << 31)) return 0 + li $v0, 0 + bnez $a1, .LreturnMSB # else if (msb) return GTE_CLZ(msb) + nop + +.LnoMSB: + mtc2 $a0, LZCS + bltz $a0, .Lreturn2 # else if (lsb & (1 << 31)) return 32 + li $v0, 32 + mfc2 $v0, LZCR # else return 32 + GTE_CLZ(lsb) + + jr $ra + addiu $v0, 32 + +.LreturnMSB: + mfc2 $v0, LZCR + +.Lreturn2: + jr $ra + nop diff --git a/src/libc/setjmp.h b/src/libc/setjmp.h new file mode 100644 index 0000000..2171075 --- /dev/null +++ b/src/libc/setjmp.h @@ -0,0 +1,38 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#pragma once + +#include + +typedef struct _JumpBuffer { + uint32_t ra; + uint32_t s0, s1, s2, s3, s4, s5, s6, s7; + uint32_t gp, sp, fp; +} JumpBuffer; + +typedef JumpBuffer *jmp_buf; + +#ifdef __cplusplus +extern "C" { +#endif + +int setjmp(jmp_buf env); +void longjmp(jmp_buf env, int status); + +#ifdef __cplusplus +} +#endif diff --git a/src/libc/stdio.h b/src/libc/stdio.h new file mode 100644 index 0000000..7c2cb60 --- /dev/null +++ b/src/libc/stdio.h @@ -0,0 +1,45 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#pragma once + +// Include printf() from the third-party library. +#include "vendor/printf.h" + +#define putchar _putchar +#define getchar _getchar +#define puts _puts + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Initializes the serial port (SIO1) with the given baud rate, no + * parity, 8 data bits and 1 stop bit. Must be called prior to using putchar(), + * getchar(), puts() or printf(). + * + * @param baud + */ +void initSerialIO(int baud); + +void _putchar(char ch); +int _getchar(void); +int _puts(const char *str); + +#ifdef __cplusplus +} +#endif diff --git a/src/libc/stdlib.h b/src/libc/stdlib.h new file mode 100644 index 0000000..d1c3a61 --- /dev/null +++ b/src/libc/stdlib.h @@ -0,0 +1,47 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +static inline int abs(int value) { + return (value < 0) ? (-value) : value; +} +static inline long labs(long value) { + return (value < 0) ? (-value) : value; +} + +void abort(void); + +long strtol(const char *str, char **str_end, int base); +long long strtoll(const char *str, char **str_end, int base); + +void *sbrk(ptrdiff_t incr); + +void *malloc(size_t size); +void *calloc(size_t num, size_t size); +void *realloc(void *ptr, size_t size); +void free(void *ptr); + +#ifdef __cplusplus +} +#endif diff --git a/src/libc/string.c b/src/libc/string.c new file mode 100644 index 0000000..b2a2c74 --- /dev/null +++ b/src/libc/string.c @@ -0,0 +1,428 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include +#include +#include + +/* Character manipulation */ + +int isprint(int ch) { + return (ch >= ' ') && (ch <= '~'); +} + +int isgraph(int ch) { + return (ch > ' ') && (ch <= '~'); +} + +int isspace(int ch) { + return (ch == ' ') || ((ch >= '\t') && (ch <= '\r')); +} + +int isblank(int ch) { + return (ch == ' ') || (ch == '\t'); +} + +int isalpha(int ch) { + return ((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z')); +} + +int isdigit(int ch) { + return (ch >= '0') && (ch <= '9'); +} + +int tolower(int ch) { + if ((ch >= 'A') && (ch <= 'Z')) + ch += 'a' - 'A'; + + return ch; +} + +int toupper(int ch) { + if ((ch >= 'a') && (ch <= 'z')) + ch += 'A' - 'a'; + + return ch; +} + +/* Memory buffer manipulation */ + +#if 0 +void *memset(void *dest, int ch, size_t count) { + uint8_t *_dest = (uint8_t *) dest; + + for (; count; count--) + *(_dest++) = (uint8_t) ch; + + return dest; +} +#endif + +void *memcpy(void *restrict dest, const void *restrict src, size_t count) { + uint8_t *_dest = (uint8_t *) dest; + const uint8_t *_src = (const uint8_t *) src; + + for (; count; count--) + *(_dest++) = *(_src++); + + return dest; +} + +void *memccpy(void *restrict dest, const void *restrict src, int ch, size_t count) { + uint8_t *_dest = (uint8_t *) dest; + const uint8_t *_src = (const uint8_t *) src; + + for (; count; count--) { + uint8_t a = *(_src++); + + *(_dest++) = a; + if (a == ch) + return (void *) _dest; + } + + return 0; +} + +void *memmove(void *dest, const void *src, size_t count) { + uint8_t *_dest = (uint8_t *) dest; + const uint8_t *_src = (const uint8_t *) src; + + if (_dest == _src) + return dest; + if ((_dest >= &_src[count]) || (&_dest[count] <= _src)) + return memcpy(dest, src, count); + + if (_dest < _src) { // Copy forwards + for (; count; count--) + *(_dest++) = *(_src++); + } else { // Copy backwards + _src += count; + _dest += count; + + for (; count; count--) + *(--_dest) = *(--_src); + } + + return dest; +} + +int memcmp(const void *lhs, const void *rhs, size_t count) { + const uint8_t *_lhs = (const uint8_t *) lhs; + const uint8_t *_rhs = (const uint8_t *) rhs; + + for (; count; count--) { + uint8_t a = *(_lhs++), b = *(_rhs++); + + if (a != b) + return a - b; + } + + return 0; +} + +void *memchr(const void *ptr, int ch, size_t count) { + const uint8_t *_ptr = (const uint8_t *) ptr; + + for (; count; count--, _ptr++) { + if (*_ptr == ch) + return (void *) _ptr; + } + + return 0; +} + +/* String manipulation */ + +char *strcpy(char *restrict dest, const char *restrict src) { + char *_dest = dest; + + while (*src) + *(_dest++) = *(src++); + + *_dest = 0; + return dest; +} + +char *strncpy(char *restrict dest, const char *restrict src, size_t count) { + char *_dest = dest; + + for (; count && *src; count--) + *(_dest++) = *(src++); + for (; count; count--) + *(_dest++) = 0; + + return dest; +} + +int strcmp(const char *lhs, const char *rhs) { + for (;;) { + char a = *(lhs++), b = *(rhs++); + + if (a != b) + return a - b; + if (!a && !b) + return 0; + } +} + +int strncmp(const char *lhs, const char *rhs, size_t count) { + for (; count && *lhs && *rhs; count--) { + char a = *(lhs++), b = *(rhs++); + + if (a != b) + return a - b; + } + + return 0; +} + +char *strchr(const char *str, int ch) { + for (; *str; str++) { + if (*str == ch) + return (char *) str; + } + + return 0; +} + +char *strrchr(const char *str, int ch) { + size_t length = strlen(str); + + for (str += length; length; length--) { + str--; + if (*str == ch) + return (char *) str; + } + + return 0; +} + +char *strpbrk(const char *str, const char *breakset) { + for (; *str; str++) { + char a = *str; + + for (const char *ch = breakset; *ch; ch++) { + if (a == *ch) + return (char *) str; + } + } + + return 0; +} + +char *strstr(const char *str, const char *substr) { + size_t length = strlen(substr); + + if (!length) + return (char *) str; + + for (; *str; str++) { + if (!memcmp(str, substr, length)) + return (char *) str; + } + + return 0; +} + +size_t strlen(const char *str) { + size_t length = 0; + + for (; *str; str++) + length++; + + return length; +} + +// Non-standard, used internally +size_t strnlen(const char *str, size_t count) { + size_t length = 0; + + for (; *str && (length < count); str++) + length++; + + return length; +} + +char *strcat(char *restrict dest, const char *restrict src) { + char *_dest = &dest[strlen(dest)]; + + while (*src) + *(_dest++) = *(src++); + + *_dest = 0; + return dest; +} + +char *strncat(char *restrict dest, const char *restrict src, size_t count) { + char *_dest = &dest[strlen(dest)]; + + for (; count && *src; count--) + *(_dest++) = *(src++); + + *_dest = 0; + return dest; +} + +char *strdup(const char *str) { + size_t length = strlen(str) + 1; + char *copy = malloc(length); + + if (!copy) + return 0; + + memcpy(copy, str, length); + return copy; +} + +char *strndup(const char *str, size_t count) { + size_t length = strnlen(str, count) + 1; + char *copy = malloc(length); + + if (!copy) + return 0; + + memcpy(copy, str, length); + return copy; +} + +/* String tokenizer */ + +static char *_strtokPtr = 0, *_strtokEndPtr = 0; + +char *strtok(char *restrict str, const char *restrict delim) { + if (str) { + _strtokPtr = str; + _strtokEndPtr = &str[strlen(str)]; + } + + if (_strtokPtr >= _strtokEndPtr) + return 0; + if (!(*_strtokPtr)) + return 0; + + char *split = strstr(_strtokPtr, delim); + char *token = _strtokPtr; + + if (split) { + *(split++) = 0; + _strtokPtr = split; + } else { + _strtokPtr += strlen(token); + } + + return token; +} + +/* Number parsers */ + +long long strtoll(const char *restrict str, char **restrict str_end, int base) { + if (!str) + return 0; + + while (isspace(*str)) + str++; + + int negative = (*str == '-'); + if (negative) + str++; + + while (isspace(*str)) + str++; + + // Parse any base prefix if present. If a base was specified make sure it + // matches, otherwise use it to determine which base the value is in. + long long value = 0; + + if (*str == '0') { + int _base; + + switch (str[1]) { + case 0: + goto _exit; + + case 'X': + case 'x': + _base = 16; + str += 2; + break; + + case 'O': + case 'o': + _base = 8; + str += 2; + break; + + case 'B': + case 'b': + _base = 2; + str += 2; + break; + + default: + // Numbers starting with a zero are *not* interpreted as octal + // unless base = 8. + _base = 0; + str++; + } + + if (!base) + base = _base; + else if (base != _base) + return 0; + } + + if (!base) + base = 10; + else if ((base < 2) || (base > 36)) + return 0; + + // Parse the actual value. + for (; *str; str++) { + char ch = *str; + int digit; + + switch (ch) { + case '0' ... '9': + digit = ch - '0'; + break; + + case 'A' ... 'Z': + digit = (ch - 'A') + 10; + break; + + case 'a' ... 'z': + digit = (ch - 'a') + 10; + break; + + default: + goto _exit; + } + + value = (value * base) + digit; + } + +_exit: + if (str_end) + *str_end = (char *) str; + + return negative ? (-value) : value; +} + +long strtol(const char *restrict str, char **restrict str_end, int base) { + return (long) strtoll(str, str_end, base); +} diff --git a/src/libc/string.h b/src/libc/string.h new file mode 100644 index 0000000..d0cda0c --- /dev/null +++ b/src/libc/string.h @@ -0,0 +1,51 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void *memset(void *dest, int ch, size_t count); +void *memcpy(void *dest, const void *src, size_t count); +void *memccpy(void *dest, const void *src, int ch, size_t count); +void *memmove(void *dest, const void *src, size_t count); +int memcmp(const void *lhs, const void *rhs, size_t count); +void *memchr(const void *ptr, int ch, size_t count); + +char *strcpy(char *dest, const char *src); +char *strncpy(char *dest, const char *src, size_t count); +int strcmp(const char *lhs, const char *rhs); +int strncmp(const char *lhs, const char *rhs, size_t count); +char *strchr(const char *str, int ch); +char *strrchr(const char *str, int ch); +char *strpbrk(const char *str, const char *breakset); +char *strstr(const char *str, const char *substr); + +size_t strlen(const char *str); +char *strcat(char *dest, const char *src); +char *strncat(char *dest, const char *src, size_t count); +char *strdup(const char *str); +char *strndup(const char *str, size_t count); + +char *strtok(char *str, const char *delim); + +#ifdef __cplusplus +} +#endif diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..5eff63b --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,129 @@ + +#include +#include +#include "app/app.hpp" +#include "ps1/gpucmd.h" +#include "ps1/system.h" +#include "asset.hpp" +#include "defs.hpp" +#include "gpu.hpp" +#include "io.hpp" +#include "spu.hpp" +#include "uibase.hpp" +#include "util.hpp" + +extern "C" const uint8_t _resources[]; +extern "C" const size_t _resourcesSize; + +int main(int argc, const char **argv) { + installExceptionHandler(); + gpu::init(); + spu::init(); + io::init(); + + int width = 320, height = 240; + + const void *ptr = nullptr; + size_t length = 0; + +#ifdef NDEBUG + for (; argc > 0; argc--) { + auto arg = *(argv++); + + if (!arg) + continue; + + switch (util::hash(arg, '=')) { + //case "boot.rom"_h: + //break; + + //case "boot.from"_h: + //break; + + case "console"_h: + initSerialIO(strtol(&arg[7], nullptr, 0)); + util::logger.enableSyslog = true; + break; + + case "screen.width"_h: + width = int(strtol(&arg[13], nullptr, 0)); + break; + + case "screen.height"_h: + height = int(strtol(&arg[14], nullptr, 0)); + break; + + // Allow the default assets to be overridden by passing a pointer to + // an in-memory ZIP file as a command-line argument. + case "resources.ptr"_h: + ptr = reinterpret_cast( + strtol(&arg[14], nullptr, 16) + ); + break; + + case "resources.length"_h: + length = size_t(strtol(&arg[17], nullptr, 16)); + break; + } + } +#else + // Enable serial port logging by default and skip argv parsing (some + // emulators like to leave $a0/$a1 uninitialized) in debug builds. + initSerialIO(115200); + util::logger.enableSyslog = true; +#endif + + LOG("build " VERSION_STRING " (" __DATE__ " " __TIME__ ")"); + LOG("(C) 2022-2023 spicyjpeg"); + + asset::AssetLoader loader; + + if (ptr && length) + loader.openMemory(ptr, length); + if (!loader.ready) { + LOG("loading default resource archive"); + loader.openMemory(_resources, _resourcesSize); + } + + io::clearWatchdog(); + + gpu::Context gpuCtx(GP1_MODE_NTSC, width, height, height > 256); + ui::Context uiCtx(gpuCtx); + + ui::TiledBackground background; + ui::LogOverlay overlay(util::logger); + + asset::StringTable strings; + + if ( + !loader.loadTIM(background.tile, "assets/textures/background.tim") || + !loader.loadTIM(uiCtx.font.image, "assets/textures/font.tim") || + !loader.loadFontMetrics(uiCtx.font, "assets/textures/font.metrics") || + !loader.loadAsset(strings.data, "assets/app.strings") + ) { + LOG("required assets not found, exiting"); + return 1; + } + + io::clearWatchdog(); + + loader.loadVAG(uiCtx.sounds[ui::SOUND_STARTUP], "assets/sounds/startup.vag"); + loader.loadVAG(uiCtx.sounds[ui::SOUND_MOVE], "assets/sounds/move.vag"); + loader.loadVAG(uiCtx.sounds[ui::SOUND_ENTER], "assets/sounds/enter.vag"); + loader.loadVAG(uiCtx.sounds[ui::SOUND_EXIT], "assets/sounds/exit.vag"); + loader.loadVAG(uiCtx.sounds[ui::SOUND_CLICK], "assets/sounds/click.vag"); + + background.text = "v" VERSION_STRING; + uiCtx.setBackgroundLayer(background); + uiCtx.setOverlayLayer(overlay); + + App app; + + gpu::enableDisplay(true); + spu::setVolume(0x3fff); + io::setMiscOutput(io::MISC_SPU_ENABLE, true); + io::clearWatchdog(); + + app.run(uiCtx, loader, strings); + return 0; +} diff --git a/src/pad.cpp b/src/pad.cpp new file mode 100644 index 0000000..8ba79a3 --- /dev/null +++ b/src/pad.cpp @@ -0,0 +1,136 @@ + +#include +#include +#include "ps1/registers.h" +#include "ps1/system.h" +#include "pad.hpp" +#include "util.hpp" + +namespace pad { + +static constexpr int _BAUD_RATE = 250000; +static constexpr int _CS_DELAY = 60; +static constexpr int _ACK_TIMEOUT = 120; + +/* Basic API */ + +void init(void) { + SIO_CTRL(0) = SIO_CTRL_RESET; + + SIO_MODE(0) = SIO_MODE_BAUD_DIV1 | SIO_MODE_DATA_8; + SIO_BAUD(0) = F_CPU / _BAUD_RATE; + SIO_CTRL(0) = 0; +} + +uint8_t exchangeByte(uint8_t value) { + while (!(SIO_STAT(0) & SIO_STAT_TX_NOT_FULL)) + __asm__ volatile(""); + + SIO_CTRL(0) |= SIO_CTRL_ACKNOWLEDGE; + SIO_DATA(0) = value; + + while (!(SIO_STAT(0) & SIO_STAT_RX_NOT_EMPTY)) + __asm__ volatile(""); + + return SIO_DATA(0); +} + +/* Controller port class */ + +Port ports[2]{ + (SIO_CTRL_TX_ENABLE | SIO_CTRL_RX_ENABLE | SIO_CTRL_DSR_IRQ_ENABLE + | SIO_CTRL_CS_PORT_1), + (SIO_CTRL_TX_ENABLE | SIO_CTRL_RX_ENABLE | SIO_CTRL_DSR_IRQ_ENABLE + | SIO_CTRL_CS_PORT_2) +}; + +bool Port::start(uint8_t address) const { + SIO_CTRL(0) = sioFlags | SIO_CTRL_DTR | SIO_CTRL_ACKNOWLEDGE; + delayMicroseconds(_CS_DELAY); + + IRQ_STAT = ~(1 << IRQ_SIO0); + SIO_DATA(0) = address; + + // The controller only pulses /ACK for a brief period of time and the DSR + // status bit in the SIO_STAT register is not latched, so the only way to + // detect the pulse reliably is to have it trigger a dummy (latched) IRQ and + // check for it. + if (!waitForInterrupt(IRQ_SIO0, _ACK_TIMEOUT)) + return false; + while (SIO_STAT(0) & SIO_STAT_RX_NOT_EMPTY) + SIO_DATA(0); + + return true; +} + +void Port::stop(void) const { + delayMicroseconds(_CS_DELAY); + SIO_CTRL(0) = sioFlags; +} + +size_t Port::exchangeBytes( + const uint8_t *input, uint8_t *output, size_t length +) const { + size_t remaining = length; + + for (; remaining; remaining--) { + *(output++) = exchangeByte(*(input++)); + + // Controllers do not trigger /ACK on the last byte. + if (remaining > 1) { + if (!waitForInterrupt(IRQ_SIO0, _ACK_TIMEOUT)) + break; + } + } + + return length - remaining; +} + +size_t Port::exchangePacket( + uint8_t address, const uint8_t *request, uint8_t *response, + size_t reqLength, size_t maxRespLength +) const { + if (!start(address)) + return 0; + + size_t respLength = 0; + + while (respLength < maxRespLength) { + if (reqLength) { + *(response++) = exchangeByte(*(request++)); + reqLength--; + } else { + *(response++) = exchangeByte(0); + } + + respLength++; + if (!waitForInterrupt(IRQ_SIO0, _ACK_TIMEOUT)) + break; + } + + stop(); + return respLength; +} + +bool Port::pollPad(void) { + const uint8_t request[4]{ CMD_POLL, 0, 0, 0 }; + uint8_t response[8]; + + if (exchangePacket( + ADDR_CONTROLLER, request, response, sizeof(request), sizeof(response) + ) >= 4) { + if (response[1] == PREFIX_PAD) { + padType = PadType(response[0] >> 4); + buttons = ~(response[2] | (response[3] << 8)); + + return true; + } + } + + padType = PAD_NONE; + buttons = 0; + + return false; +} + +} diff --git a/src/pad.hpp b/src/pad.hpp new file mode 100644 index 0000000..b3433cd --- /dev/null +++ b/src/pad.hpp @@ -0,0 +1,136 @@ + +#pragma once + +#include +#include + +namespace pad { + +/* Definitions */ + +enum Address : uint8_t { + ADDR_CONTROLLER = 0x01, + ADDR_PS2_IR = 0x21, + ADDR_PS2_MULTITAP = 0x61, + ADDR_CARD = 0x81 +}; + +enum ResponsePrefix : uint8_t { + PREFIX_PAD = 0x5a, + PREFIX_CARD = 0x5d +}; + +enum Command : uint8_t { + // Basic controller commands + CMD_POLL = 'B', + CMD_CONFIG = 'C', + + // Configuration mode commands + CMD_INIT_PRESSURE = '@', // DualShock 2 only + CMD_RESP_INFO = 'A', // DualShock 2 only + CMD_SET_ANALOG = 'D', + CMD_GET_ANALOG = 'E', + CMD_MOTOR_INFO = 'F', + CMD_MOTOR_LIST = 'G', + CMD_MOTOR_STATE = 'H', + CMD_GET_MODES = 'L', + CMD_REQ_CONFIG = 'M', + CMD_RESP_CONFIG = 'O', // DualShock 2 only + + // Memory card commands + CMD_READ_SECTOR = 'R', + CMD_IDENTIFY_CARD = 'S', // OEM cards only + CMD_WRITE_SECTOR = 'W' +}; + +enum PadType : uint8_t { + PAD_NONE = 0, + PAD_MOUSE = 1, + PAD_NEGCON = 2, + PAD_IRQ10_GUN = 3, + PAD_DIGITAL = 4, + PAD_ANALOG_STICK = 5, + PAD_GUNCON = 6, + PAD_ANALOG = 7, + PAD_MULTITAP = 8, + PAD_JOGCON = 14, + PAD_CONFIG_MODE = 15 +}; + +enum PadButton : uint16_t { + // Standard controllers + BTN_SELECT = 1 << 0, + BTN_L3 = 1 << 1, + BTN_R3 = 1 << 2, + BTN_START = 1 << 3, + BTN_UP = 1 << 4, + BTN_RIGHT = 1 << 5, + BTN_DOWN = 1 << 6, + BTN_LEFT = 1 << 7, + BTN_L2 = 1 << 8, + BTN_R2 = 1 << 9, + BTN_L1 = 1 << 10, + BTN_R1 = 1 << 11, + BTN_TRIANGLE = 1 << 12, + BTN_CIRCLE = 1 << 13, + BTN_CROSS = 1 << 14, + BTN_SQUARE = 1 << 15, + + // Mouse + BTN_MOUSE_RIGHT = 1 << 10, + BTN_MOUSE_LEFT = 1 << 11, + + // neGcon + BTN_NEGCON_START = 1 << 3, + BTN_NEGCON_UP = 1 << 4, + BTN_NEGCON_RIGHT = 1 << 5, + BTN_NEGCON_DOWN = 1 << 6, + BTN_NEGCON_LEFT = 1 << 7, + BTN_NEGCON_R = 1 << 11, + BTN_NEGCON_B = 1 << 12, + BTN_NEGCON_A = 1 << 13, + + // Guncon + BTN_GUNCON_A = 1 << 3, + BTN_GUNCON_TRIGGER = 1 << 13, + BTN_GUNCON_B = 1 << 14, + + // IRQ10 lightgun + BTN_IRQ10_GUN_START = 1 << 3, + BTN_IRQ10_GUN_BACK = 1 << 14, + BTN_IRQ10_GUN_TRIGGER = 1 << 15 +}; + +/* API */ + +void init(void); +uint8_t exchangeByte(uint8_t value); + +/* Controller port class */ + +class Port { +public: + uint16_t sioFlags; + + PadType padType; + uint16_t buttons; + + inline Port(uint16_t sioFlags) + : sioFlags(sioFlags), padType(PAD_NONE), buttons(0) {} + + bool start(uint8_t address) const; + void stop(void) const; + size_t exchangeBytes( + const uint8_t *input, uint8_t *output, size_t length + ) const; + size_t exchangePacket( + uint8_t address, const uint8_t *request, uint8_t *response, + size_t reqLength, size_t maxRespLength + ) const; + + bool pollPad(void); +}; + +extern Port ports[2]; + +} diff --git a/src/ps1/gpucmd.h b/src/ps1/gpucmd.h new file mode 100644 index 0000000..ce11e5d --- /dev/null +++ b/src/ps1/gpucmd.h @@ -0,0 +1,337 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#pragma once + +#include +#include +#include + +#define DEF16 static inline uint16_t __attribute__((always_inline)) +#define DEF32 static inline uint32_t __attribute__((always_inline)) + +/* DMA tags */ + +DEF32 gp0_tag(size_t length, void *next) { + return 0 + | (((uint32_t) next & 0xffffff) << 0) + | (((uint32_t) length & 0x0000ff) << 24); +} + +DEF32 gp0_endTag(size_t length) { + return gp0_tag(length, (void *) 0xffffff); +} + +/* Drawing attributes */ + +typedef enum { + GP0_BLEND_BITMASK = 3, + GP0_BLEND_SEMITRANS = 0, + GP0_BLEND_ADD = 1, + GP0_BLEND_SUBTRACT = 2, + GP0_BLEND_DIV4_ADD = 3 +} GP0BlendMode; + +typedef enum { + GP0_COLOR_BITMASK = 3, + GP0_COLOR_4BPP = 0, + GP0_COLOR_8BPP = 1, + GP0_COLOR_16BPP = 2 +} GP0ColorDepth; + +DEF16 gp0_page( + unsigned int x, unsigned int y, GP0BlendMode blendMode, + GP0ColorDepth colorDepth +) { + return 0 + | ((x & 15) << 0) + | ((y & 1) << 4) + | ((blendMode & 3) << 5) + | ((colorDepth & 3) << 7) + | ((y & 2) << 10); +} +DEF16 gp0_clut(unsigned int x, unsigned int y) { + return 0 + | ((x & 0x03f) << 0) + | ((y & 0x3ff) << 6); +} + +DEF32 gp0_xy(int x, int y) { + return 0 + | ((x & 0xffff) << 0) + | ((y & 0xffff) << 16); +} +DEF32 gp0_uv(unsigned int u, unsigned int v, uint16_t attr) { + return 0 + | ((u & 0x00ff) << 0) + | ((v & 0x00ff) << 8) + | ((attr & 0xffff) << 16); +} +DEF32 gp0_rgb(uint8_t r, uint8_t g, uint8_t b) { + return 0 + | ((r & 0xff) << 0) + | ((g & 0xff) << 8) + | ((b & 0xff) << 16); +} + +/* GP0 (drawing) commands */ + +typedef enum { + GP0_CMD_MISC = 0 << 29, + GP0_CMD_POLYGON = 1 << 29, + GP0_CMD_LINE = 2 << 29, + GP0_CMD_RECTANGLE = 3 << 29, + GP0_CMD_VRAM_BLIT = 4 << 29, + GP0_CMD_VRAM_WRITE = 5 << 29, + GP0_CMD_VRAM_READ = 6 << 29, + GP0_CMD_ATTRIBUTE = 7 << 29 +} GP0Command; + +typedef enum { + GP0_CMD_NOP = GP0_CMD_MISC | ( 0 << 24), + GP0_CMD_FLUSH_CACHE = GP0_CMD_MISC | ( 1 << 24), + GP0_CMD_VRAM_FILL = GP0_CMD_MISC | ( 2 << 24), + GP0_CMD_NOP2 = GP0_CMD_MISC | ( 3 << 24), + GP0_CMD_IRQ = GP0_CMD_MISC | (31 << 24) +} GP0MiscCommand; + +typedef enum { + GP0_CMD_TEXPAGE = GP0_CMD_ATTRIBUTE | (1 << 24), + GP0_CMD_TEXWINDOW = GP0_CMD_ATTRIBUTE | (2 << 24), + GP0_CMD_FB_OFFSET1 = GP0_CMD_ATTRIBUTE | (3 << 24), + GP0_CMD_FB_OFFSET2 = GP0_CMD_ATTRIBUTE | (4 << 24), + GP0_CMD_FB_ORIGIN = GP0_CMD_ATTRIBUTE | (5 << 24), + GP0_CMD_FB_MASK = GP0_CMD_ATTRIBUTE | (6 << 24) +} GP0AttributeCommand; + +DEF32 _gp0_polygon( + bool quad, bool unshaded, bool gouraud, bool textured, bool blend +) { + return GP0_CMD_POLYGON + | ((unshaded & 1) << 24) + | ((blend & 1) << 25) + | ((textured & 1) << 26) + | ((quad & 1) << 27) + | ((gouraud & 1) << 28); +} +DEF32 gp0_triangle(bool textured, bool blend) { + return _gp0_polygon(false, true, false, textured, blend); +} +DEF32 gp0_shadedTriangle(bool gouraud, bool textured, bool blend) { + return _gp0_polygon(false, false, gouraud, textured, blend); +} +DEF32 gp0_quad(bool textured, bool blend) { + return _gp0_polygon(true, true, false, textured, blend); +} +DEF32 gp0_shadedQuad(bool gouraud, bool textured, bool blend) { + return _gp0_polygon(true, false, gouraud, textured, blend); +} + +DEF32 gp0_line(bool gouraud, bool blend) { + return GP0_CMD_LINE + | ((blend & 1) << 25) + | ((gouraud & 1) << 28); +} +DEF32 gp0_polyLine(bool gouraud, bool blend) { + return GP0_CMD_LINE + | ((blend & 1) << 25) + | (1 << 27) + | ((gouraud & 1) << 28); +} + +DEF32 _gp0_rectangle(uint8_t size, bool textured, bool unshaded, bool blend) { + return GP0_CMD_RECTANGLE + | ((unshaded & 1) << 24) + | ((blend & 1) << 25) + | ((textured & 1) << 26) + | ((size & 3) << 27); +} +DEF32 gp0_rectangle(bool textured, bool unshaded, bool blend) { + return _gp0_rectangle(0, textured, unshaded, blend); +} +DEF32 gp0_rectangle1x1(bool textured, bool unshaded, bool blend) { + return _gp0_rectangle(1, textured, unshaded, blend); +} +DEF32 gp0_rectangle8x8(bool textured, bool unshaded, bool blend) { + return _gp0_rectangle(2, textured, unshaded, blend); +} +DEF32 gp0_rectangle16x16(bool textured, bool unshaded, bool blend) { + return _gp0_rectangle(3, textured, unshaded, blend); +} + +DEF32 gp0_vramBlit(void) { + return GP0_CMD_VRAM_BLIT; +} +DEF32 gp0_vramWrite(void) { + return GP0_CMD_VRAM_WRITE; +} +DEF32 gp0_vramRead(void) { + return GP0_CMD_VRAM_READ; +} + +DEF32 gp0_flushCache(void) { + return GP0_CMD_FLUSH_CACHE; +} +DEF32 gp0_vramFill(void) { + return GP0_CMD_VRAM_FILL; +} +DEF32 gp0_irq(void) { + return GP0_CMD_IRQ; +} + +DEF32 gp0_texpage(uint16_t page, bool dither, bool unlockFB) { + return GP0_CMD_TEXPAGE + | ((page & 0x9ff) << 0) + | ((dither & 1) << 9) + | ((unlockFB & 1) << 10); +} +DEF32 gp0_texwindow( + uint8_t baseX, uint8_t baseY, uint8_t maskX, uint8_t maskY +) { + return GP0_CMD_TEXWINDOW + | ((maskX & 0x1f) << 0) + | ((maskY & 0x1f) << 5) + | ((baseX & 0x1f) << 10) + | ((baseY & 0x1f) << 15); +} +DEF32 gp0_fbOffset1(unsigned int x, unsigned int y) { + return GP0_CMD_FB_OFFSET1 + | ((x & 0x3ff) << 0) + | ((y & 0x3ff) << 10); +} +DEF32 gp0_fbOffset2(unsigned int x, unsigned int y) { + return GP0_CMD_FB_OFFSET2 + | ((x & 0x3ff) << 0) + | ((y & 0x3ff) << 10); +} +DEF32 gp0_fbOrigin(int x, int y) { + return GP0_CMD_FB_ORIGIN + | ((x & 0x7ff) << 0) + | ((y & 0x7ff) << 11); +} +DEF32 gp0_fbMask(bool setMask, bool useMask) { + return GP0_CMD_FB_MASK + | (setMask << 0) + | (useMask << 1); +} + +/* GP1 (display control) commands */ + +typedef enum { + GP1_HRES_BITMASK = (3 << 0) | (1 << 6), + GP1_HRES_256 = 0 << 0, // Dotclock divided by 10 + GP1_HRES_320 = 1 << 0, // Dotclock divided by 8 + GP1_HRES_368 = 1 << 6, // Dotclock divided by 7 + GP1_HRES_512 = 2 << 0, // Dotclock divided by 5 + GP1_HRES_640 = 3 << 0 // Dotclock divided by 4 +} GP1HorizontalRes; + +typedef enum { + GP1_VRES_BITMASK = 1 << 2, + GP1_VRES_256 = 0 << 2, + GP1_VRES_512 = 1 << 2 +} GP1VerticalRes; + +typedef enum { + GP1_MODE_BITMASK = 1, + GP1_MODE_NTSC = 0, + GP1_MODE_PAL = 1 +} GP1VideoMode; + +typedef enum { + GP1_COLOR_BITMASK = 1, + GP1_COLOR_16BPP = 0, + GP1_COLOR_24BPP = 1 +} GP1ColorDepth; + +typedef enum { + GP1_DREQ_BITMASK = 3, + GP1_DREQ_NONE = 0, + GP1_DREQ_FIFO = 1, + GP1_DREQ_GP0_WRITE = 2, + GP1_DREQ_GP0_READ = 3 +} GP1DMARequestMode; + +typedef enum { + GP1_VRAM_BITMASK = 1, + GP1_VRAM_1MB = 0, + GP1_VRAM_2MB = 1 +} GP1VRAMSize; + +typedef enum { + GP1_CMD_RESET_GPU = 0 << 24, + GP1_CMD_RESET_FIFO = 1 << 24, + GP1_CMD_ACKNOWLEDGE = 2 << 24, + GP1_CMD_DISP_BLANK = 3 << 24, + GP1_CMD_DREQ_MODE = 4 << 24, + GP1_CMD_FB_OFFSET = 5 << 24, + GP1_CMD_FB_RANGE_H = 6 << 24, + GP1_CMD_FB_RANGE_V = 7 << 24, + GP1_CMD_FB_MODE = 8 << 24, + GP1_CMD_VRAM_SIZE = 9 << 24, + GP1_CMD_GET_INFO = 16 << 24 +} GP1Command; + +DEF32 gp1_resetGPU(void) { + return GP1_CMD_RESET_GPU; +} +DEF32 gp1_resetFIFO(void) { + return GP1_CMD_RESET_FIFO; +} +DEF32 gp1_acknowledge(void) { + return GP1_CMD_ACKNOWLEDGE; +} +DEF32 gp1_dispBlank(bool blank) { + return GP1_CMD_DISP_BLANK + | (blank & 1); +} +DEF32 gp1_dmaRequestMode(GP1DMARequestMode mode) { + return GP1_CMD_DREQ_MODE + | (mode & 3); +} +DEF32 gp1_fbOffset(unsigned int x, unsigned int y) { + return GP1_CMD_FB_OFFSET + | ((x & 0x3ff) << 0) + | ((y & 0x3ff) << 10); +} +DEF32 gp1_fbRangeH(unsigned int low, unsigned int high) { + return GP1_CMD_FB_RANGE_H + | ((low & 0xfff) << 0) + | ((high & 0xfff) << 12); +} +DEF32 gp1_fbRangeV(unsigned int low, unsigned int high) { + return GP1_CMD_FB_RANGE_V + | ((low & 0x3ff) << 0) + | ((high & 0x3ff) << 10); +} +DEF32 gp1_fbMode( + GP1HorizontalRes horizontalRes, GP1VerticalRes verticalRes, + GP1VideoMode videoMode, bool interlace, GP1ColorDepth colorDepth +) { + return GP1_CMD_FB_MODE + | ((horizontalRes & 0x47) << 0) + | ((verticalRes & 1) << 2) + | ((videoMode & 1) << 3) + | ((colorDepth & 1) << 4) + | ((interlace & 1) << 5); +} +DEF32 gp1_vramSize(GP1VRAMSize size) { + return GP1_CMD_VRAM_SIZE + | (size & 1); +} + +#undef DEF16 +#undef DEF32 diff --git a/src/ps1/pcdrv.h b/src/ps1/pcdrv.h new file mode 100644 index 0000000..fc9510f --- /dev/null +++ b/src/ps1/pcdrv.h @@ -0,0 +1,47 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#pragma once + +#include + +typedef enum { + PCDRV_MODE_READ = 0, + PCDRV_MODE_WRITE = 1, + PCDRV_MODE_READ_WRITE = 2 +} PCDRVOpenMode; + +typedef enum { + PCDRV_SEEK_SET = 0, + PCDRV_SEEK_CUR = 1, + PCDRV_SEEK_END = 2 +} PCDRVSeekMode; + +#ifdef __cplusplus +extern "C" { +#endif + +int pcdrvInit(void); +int pcdrvCreate(const char *path); +int pcdrvOpen(const char *path, PCDRVOpenMode mode); +int pcdrvClose(int fd); +int pcdrvRead(int fd, void *data, size_t length); +int pcdrvWrite(int fd, const void *data, size_t length); +int pcdrvSeek(int fd, int offset, PCDRVSeekMode mode); + +#ifdef __cplusplus +} +#endif diff --git a/src/ps1/pcdrv.s b/src/ps1/pcdrv.s new file mode 100644 index 0000000..8da85a3 --- /dev/null +++ b/src/ps1/pcdrv.s @@ -0,0 +1,117 @@ +# ps1-bare-metal - (C) 2023 spicyjpeg +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +# PERFORMANCE OF THIS SOFTWARE. + +.set noreorder + +.section .text.pcdrvInit, "ax", @progbits +.global pcdrvInit +.type pcdrvInit, @function + +pcdrvInit: + break 0, 0x101 # () -> error + + jr $ra + nop + +.section .text.pcdrvCreate, "ax", @progbits +.global pcdrvCreate +.type pcdrvCreate, @function + +pcdrvCreate: + li $a2, 0 + move $a1, $a0 + break 0, 0x102 # (path, path, 0) -> error, fd + + bgez $v0, .LcreateOK # if (error < 0) fd = error + nop + move $v1, $v0 +.LcreateOK: + jr $ra # return fd + move $v0, $v1 + +.section .text.pcdrvOpen, "ax", @progbits +.global pcdrvOpen +.type pcdrvOpen, @function + +pcdrvOpen: + move $a2, $a1 + move $a1, $a0 + break 0, 0x103 # (path, path, mode) -> error, fd + + bgez $v0, .LopenOK # if (error < 0) fd = error + nop + move $v1, $v0 +.LopenOK: + jr $ra # return fd + move $v0, $v1 + +.section .text.pcdrvClose, "ax", @progbits +.global pcdrvClose +.type pcdrvClose, @function + +pcdrvClose: + move $a1, $a0 + break 0, 0x104 # (fd, fd) -> error + + jr $ra + nop + +.section .text.pcdrvRead, "ax", @progbits +.global pcdrvRead +.type pcdrvRead, @function + +pcdrvRead: + move $a3, $a1 + move $a1, $a0 + break 0, 0x105 # (fd, fd, length, data) -> error, length + + bgez $v0, .LreadOK # if (error < 0) length = error + nop + move $v1, $v0 +.LreadOK: + jr $ra # return length + move $v0, $v1 + +.section .text.pcdrvWrite, "ax", @progbits +.global pcdrvWrite +.type pcdrvWrite, @function + +pcdrvWrite: + move $a3, $a1 + move $a1, $a0 + break 0, 0x106 # (fd, fd, length, data) -> error, length + + bgez $v0, .LwriteOK # if (error < 0) length = error + nop + move $v1, $v0 +.LwriteOK: + jr $ra # return length + move $v0, $v1 + +.section .text.pcdrvSeek, "ax", @progbits +.global pcdrvSeek +.type pcdrvSeek, @function + +pcdrvSeek: + move $a3, $a2 + move $a2, $a1 + move $a1, $a0 + break 0, 0x107 # (fd, fd, offset, mode) -> error, offset + + bgez $v0, .LseekOK # if (error < 0) offset = error + nop + move $v1, $v0 +.LseekOK: + jr $ra # return offset + move $v0, $v1 diff --git a/src/ps1/registers.h b/src/ps1/registers.h new file mode 100644 index 0000000..531a727 --- /dev/null +++ b/src/ps1/registers.h @@ -0,0 +1,507 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#pragma once + +#include + +#define _ADDR8(addr) ((volatile uint8_t *) (addr)) +#define _ADDR16(addr) ((volatile uint16_t *) (addr)) +#define _ADDR32(addr) ((volatile uint32_t *) (addr)) +#define _MMIO8(addr) (*_ADDR8(addr)) +#define _MMIO16(addr) (*_ADDR16(addr)) +#define _MMIO32(addr) (*_ADDR32(addr)) + +/* Constants */ + +#define F_CPU 33868800 +#define F_GPU_NTSC 53693175 +#define F_GPU_PAL 53203425 + +typedef enum { + DEV0_BASE = 0xbf000000, + EXP1_BASE = 0xbf000000, + IO_BASE = 0xbf800000, + EXP2_BASE = 0xbf802000, + EXP3_BASE = 0xbfa00000 +} BaseAddress; + +/* Bus interface */ + +typedef enum { + BIU_CTRL_WRITE_DELAY_BITMASK = 15 << 0, + BIU_CTRL_READ_DELAY_BITMASK = 15 << 4, + BIU_CTRL_RECOVERY = 1 << 8, + BIU_CTRL_HOLD = 1 << 9, + BIU_CTRL_FLOAT = 1 << 10, + BIU_CTRL_PRESTROBE = 1 << 11, + BIU_CTRL_WIDTH_8 = 0 << 12, + BIU_CTRL_WIDTH_16 = 1 << 12, + BIU_CTRL_AUTO_INCR = 1 << 13, + BIU_CTRL_SIZE_BITMASK = 31 << 16, + BIU_CTRL_DMA_DELAY_BITMASK = 15 << 24, + BIU_CTRL_ADDR_ERROR = 1 << 28, + BIU_CTRL_DMA_DELAY = 1 << 29, + BIU_CTRL_DMA32 = 1 << 30, + BIU_CTRL_WAIT = 1 << 31 +} BIUControlFlag; + +#define BIU_DEV0_ADDR _MMIO32(IO_BASE | 0x1000) // PIO/573 +#define BIU_EXP2_ADDR _MMIO32(IO_BASE | 0x1004) // PIO/debug +#define BIU_DEV0_CTRL _MMIO32(IO_BASE | 0x1008) // PIO/573 +#define BIU_EXP3_CTRL _MMIO32(IO_BASE | 0x100c) // PIO/debug +#define BIU_DEV2_CTRL _MMIO32(IO_BASE | 0x1010) // BIOS ROM +#define BIU_DEV4_CTRL _MMIO32(IO_BASE | 0x1014) // SPU +#define BIU_DEV5_CTRL _MMIO32(IO_BASE | 0x1018) // CD-ROM +#define BIU_EXP2_CTRL _MMIO32(IO_BASE | 0x101c) // PIO/debug +#define BIU_COM_DELAY _MMIO32(IO_BASE | 0x1020) + +/* Serial interfaces */ + +typedef enum { + SIO_STAT_TX_NOT_FULL = 1 << 0, + SIO_STAT_RX_NOT_EMPTY = 1 << 1, + SIO_STAT_TX_EMPTY = 1 << 2, + SIO_STAT_RX_PARITY_ERR = 1 << 3, + SIO_STAT_RX_OVERRUN = 1 << 4, // SIO1 only + SIO_STAT_RX_STOP_ERR = 1 << 5, // SIO1 only + SIO_STAT_RX_INVERT = 1 << 6, // SIO1 only + SIO_STAT_DSR = 1 << 7, // DSR is /ACK on SIO0 + SIO_STAT_CTS = 1 << 8, // SIO1 only + SIO_STAT_IRQ = 1 << 9 +} SIOStatusFlag; + +typedef enum { + SIO_MODE_BAUD_MASK = 3 << 0, + SIO_MODE_BAUD_DIV1 = 1 << 0, + SIO_MODE_BAUD_DIV16 = 2 << 0, + SIO_MODE_BAUD_DIV64 = 3 << 0, + SIO_MODE_DATA_BITMASK = 3 << 2, + SIO_MODE_DATA_5 = 0 << 2, + SIO_MODE_DATA_6 = 1 << 2, + SIO_MODE_DATA_7 = 2 << 2, + SIO_MODE_DATA_8 = 3 << 2, + SIO_MODE_PARITY_BITMASK = 3 << 4, + SIO_MODE_PARITY_NONE = 0 << 4, + SIO_MODE_PARITY_EVEN = 1 << 4, + SIO_MODE_PARITY_ODD = 3 << 4, + SIO_MODE_STOP_BITMASK = 3 << 6, // SIO1 only + SIO_MODE_STOP_1 = 1 << 6, // SIO1 only + SIO_MODE_STOP_1_5 = 2 << 6, // SIO1 only + SIO_MODE_STOP_2 = 3 << 6, // SIO1 only + SIO_MODE_SCK_INVERT = 1 << 8 // SIO0 only +} SIOModeFlag; + +typedef enum { + SIO_CTRL_TX_ENABLE = 1 << 0, + SIO_CTRL_DTR = 1 << 1, // DTR is /CS on SIO0 + SIO_CTRL_RX_ENABLE = 1 << 2, + SIO_CTRL_TX_INVERT = 1 << 3, // SIO1 only + SIO_CTRL_ACKNOWLEDGE = 1 << 4, + SIO_CTRL_RTS = 1 << 5, // SIO1 only + SIO_CTRL_RESET = 1 << 6, + SIO_CTRL_TX_IRQ_ENABLE = 1 << 10, + SIO_CTRL_RX_IRQ_ENABLE = 1 << 11, + SIO_CTRL_DSR_IRQ_ENABLE = 1 << 12, // DSR is /ACK on SIO0 + SIO_CTRL_CS_PORT_1 = 0 << 13, // SIO0 only + SIO_CTRL_CS_PORT_2 = 1 << 13 // SIO0 only +} SIOControlFlag; + +// SIO_DATA is a 32-bit register, but some emulators do not implement it +// correctly and break if it's read more than 8 bits at a time. +#define SIO_DATA(N) _MMIO8 ((IO_BASE | 0x1040) + (16 * (N))) +#define SIO_STAT(N) _MMIO16((IO_BASE | 0x1044) + (16 * (N))) +#define SIO_MODE(N) _MMIO16((IO_BASE | 0x1048) + (16 * (N))) +#define SIO_CTRL(N) _MMIO16((IO_BASE | 0x104a) + (16 * (N))) +#define SIO_BAUD(N) _MMIO16((IO_BASE | 0x104e) + (16 * (N))) + +/* DRAM controller */ + +typedef enum { + DRAM_CTRL_UNKNOWN = 1 << 3, + DRAM_CTRL_FETCH_DELAY = 1 << 7, + DRAM_CTRL_SIZE_MUL1 = 0 << 9, + DRAM_CTRL_SIZE_MUL4 = 1 << 9, + DRAM_CTRL_COUNT_1 = 0 << 10, // 1 DRAM bank (single RAS) + DRAM_CTRL_COUNT_2 = 1 << 10, // 2 DRAM banks (dual RAS) + DRAM_CTRL_SIZE_1MB = 0 << 11, // 1MB chips (4MB with MUL4) + DRAM_CTRL_SIZE_2MB = 1 << 11 // 2MB chips (8MB with MUL4) +} DRAMControlFlag; + +#define DRAM_CTRL _MMIO32(IO_BASE | 0x1060) + +/* IRQ controller */ + +typedef enum { + IRQ_VBLANK = 0, + IRQ_GPU = 1, + IRQ_CDROM = 2, + IRQ_DMA = 3, + IRQ_TIMER0 = 4, + IRQ_TIMER1 = 5, + IRQ_TIMER2 = 6, + IRQ_SIO0 = 7, + IRQ_SIO1 = 8, + IRQ_SPU = 9, + IRQ_GUN = 10, + IRQ_PIO = 10 +} IRQChannel; + +#define IRQ_STAT _MMIO16(IO_BASE | 0x1070) +#define IRQ_MASK _MMIO16(IO_BASE | 0x1074) + +/* DMA */ + +typedef enum { + DMA_MDEC_IN = 0, + DMA_MDEC_OUT = 1, + DMA_GPU = 2, + DMA_CDROM = 3, + DMA_SPU = 4, + DMA_PIO = 5, + DMA_OTC = 6 +} DMAChannel; + +typedef enum { + DMA_CHCR_READ = 0 << 0, + DMA_CHCR_WRITE = 1 << 0, + DMA_CHCR_CHOPPING = 1 << 8, + DMA_CHCR_MODE_BITMASK = 3 << 9, + DMA_CHCR_MODE_BURST = 0 << 9, + DMA_CHCR_MODE_SLICE = 1 << 9, + DMA_CHCR_MODE_LIST = 2 << 9, + DMA_CHCR_DMA_TIME_BITMASK = 7 << 16, + DMA_CHCR_CPU_TIME_BITMASK = 7 << 20, + DMA_CHCR_ENABLE = 1 << 24, + DMA_CHCR_TRIGGER = 1 << 28, + DMA_CHCR_PAUSE = 1 << 29 // Burst mode only +} DMACHCRFlag; + +typedef enum { + DMA_DICR_CH_MODE_MASK = 0x7f << 0, + DMA_DICR_BUS_ERROR = 1 << 15, + DMA_DICR_CH_ENABLE_MASK = 0x7f << 16, + DMA_DICR_IRQ_ENABLE = 1 << 23, + DMA_DICR_CH_STAT_MASK = 0x7f << 24, + DMA_DICR_IRQ = 1 << 31 +} DMADICRFlag; + +#define DMA_DICR_CH_MODE(dma) (1 << ((dma) + 0)) +#define DMA_DICR_CH_ENABLE(dma) (1 << ((dma) + 16)) +#define DMA_DICR_CH_STAT(dma) (1 << ((dma) + 24)) + +#define DMA_MADR(N) _MMIO32((IO_BASE | 0x1080) + (16 * (N))) +#define DMA_BCR(N) _MMIO32((IO_BASE | 0x1084) + (16 * (N))) +#define DMA_CHCR(N) _MMIO32((IO_BASE | 0x1088) + (16 * (N))) + +#define DMA_DPCR _MMIO32(IO_BASE | 0x10f0) +#define DMA_DICR _MMIO32(IO_BASE | 0x10f4) + +/* Timers */ + +typedef enum { + TIMER_CTRL_ENABLE_SYNC = 1 << 0, + TIMER_CTRL_SYNC_BITMASK = 3 << 1, + TIMER_CTRL_SYNC_PAUSE = 0 << 1, + TIMER_CTRL_SYNC_RESET1 = 1 << 1, + TIMER_CTRL_SYNC_RESET2 = 2 << 1, + TIMER_CTRL_SYNC_PAUSE_ONCE = 3 << 1, + TIMER_CTRL_RELOAD = 1 << 3, + TIMER_CTRL_IRQ_ON_RELOAD = 1 << 4, + TIMER_CTRL_IRQ_ON_OVERFLOW = 1 << 5, + TIMER_CTRL_IRQ_REPEAT = 1 << 6, + TIMER_CTRL_IRQ_LATCH = 1 << 7, + TIMER_CTRL_EXT_CLOCK = 1 << 8, + TIMER_CTRL_PRESCALE = 1 << 9, + TIMER_CTRL_IRQ = 1 << 10, + TIMER_CTRL_RELOADED = 1 << 11, + TIMER_CTRL_OVERFLOWED = 1 << 12 +} TimerControlFlag; + +#define TIMER_VALUE(N) _MMIO32((IO_BASE | 0x1100) + (16 * (N))) +#define TIMER_CTRL(N) _MMIO32((IO_BASE | 0x1104) + (16 * (N))) +#define TIMER_RELOAD(N) _MMIO32((IO_BASE | 0x1108) + (16 * (N))) + +/* CD-ROM drive */ + +typedef enum { + CDROM_STAT_BANK_BITMASK = 3 << 0, + CDROM_STAT_BANK_0 = 0 << 0, + CDROM_STAT_BANK_1 = 1 << 0, + CDROM_STAT_BANK_2 = 2 << 0, + CDROM_STAT_BANK_3 = 3 << 0, + CDROM_STAT_ADPCM_BUSY = 1 << 2, + CDROM_STAT_PARAM_EMPTY = 1 << 3, + CDROM_STAT_PARAM_FULL = 1 << 4, + CDROM_STAT_RESP_EMPTY = 1 << 5, + CDROM_STAT_DATA_EMPTY = 1 << 6, + CDROM_STAT_BUSY = 1 << 7 +} CDROMStatusFlag; + +typedef enum { + CDROM_REQ_START_IRQ_ENABLE = 1 << 5, + CDROM_REQ_BUFFER_WRITE = 1 << 6, + CDROM_REQ_BUFFER_READ = 1 << 7 +} CDROMRequestFlag; + +typedef enum { + CDROM_IRQ_NONE = 0, + CDROM_IRQ_DATA = 1, + CDROM_IRQ_COMPLETE = 2, + CDROM_IRQ_ACKNOWLEDGE = 3, + CDROM_IRQ_DATA_END = 4, + CDROM_IRQ_ERROR = 5 +} CDROMIRQType; + +typedef enum { + CDROM_CMDSTAT_ERROR = 1 << 0, + CDROM_CMDSTAT_SPINDLE_ON = 1 << 1, + CDROM_CMDSTAT_SEEK_ERROR = 1 << 2, + CDROM_CMDSTAT_ID_ERROR = 1 << 3, + CDROM_CMDSTAT_LID_OPEN = 1 << 4, + CDROM_CMDSTAT_READING = 1 << 5, + CDROM_CMDSTAT_SEEKING = 1 << 6, + CDROM_CMDSTAT_PLAYING = 1 << 7 +} CDROMCommandStatusFlag; + +typedef enum { + CDROM_MODE_CDDA = 1 << 0, + CDROM_MODE_AUTO_PAUSE = 1 << 1, + CDROM_MODE_CDDA_REPORT = 1 << 2, + CDROM_MODE_XA_FILTER = 1 << 3, + CDROM_MODE_IGNORE_LOC = 1 << 4, + CDROM_MODE_SIZE_2048 = 0 << 5, + CDROM_MODE_SIZE_2340 = 1 << 5, + CDROM_MODE_XA_ADPCM = 1 << 6, + CDROM_MODE_SPEED_1X = 0 << 7, + CDROM_MODE_SPEED_2X = 1 << 7 +} CDROMModeFlag; + +#define CDROM_STAT _MMIO8(IO_BASE | 0x1800) +#define CDROM_CMD _MMIO8(IO_BASE | 0x1801) +#define CDROM_DATA _MMIO8(IO_BASE | 0x1802) +#define CDROM_IRQ _MMIO8(IO_BASE | 0x1803) + +#define CDROM_REG(N) _MMIO8((IO_BASE | 0x1800) + (N)) + +/* GPU */ + +typedef enum { + GP1_STAT_MODE_PAL = 1 << 20, + GP1_STAT_DISP_BLANK = 1 << 23, + GP1_STAT_IRQ = 1 << 24, + GP1_STAT_DREQ = 1 << 25, + GP1_STAT_CMD_READY = 1 << 26, + GP1_STAT_READ_READY = 1 << 27, + GP1_STAT_WRITE_READY = 1 << 28, + GP1_STAT_FIELD_ODD = 1 << 31 +} GP1StatusFlag; + +#define GPU_GP0 _MMIO32(IO_BASE | 0x1810) +#define GPU_GP1 _MMIO32(IO_BASE | 0x1814) + +/* MDEC */ + +typedef enum { + MDEC_STAT_BLOCK_BITMASK = 7 << 16, + MDEC_STAT_BLOCK_Y0 = 0 << 16, + MDEC_STAT_BLOCK_Y1 = 1 << 16, + MDEC_STAT_BLOCK_Y2 = 2 << 16, + MDEC_STAT_BLOCK_Y3 = 3 << 16, + MDEC_STAT_BLOCK_CR = 4 << 16, + MDEC_STAT_BLOCK_CB = 5 << 16, + MDEC_STAT_DREQ_OUT = 1 << 27, + MDEC_STAT_DREQ_IN = 1 << 28, + MDEC_STAT_BUSY = 1 << 29, + MDEC_STAT_DATA_FULL = 1 << 30, + MDEC_STAT_DATA_EMPTY = 1 << 31 +} MDECStatusFlag; + +typedef enum { + MDEC_CTRL_DMA_OUT = 1 << 29, + MDEC_CTRL_DMA_IN = 1 << 30, + MDEC_CTRL_RESET = 1 << 31 +} MDECControlFlag; + +#define MDEC0 _MMIO32(IO_BASE | 0x1820) +#define MDEC1 _MMIO32(IO_BASE | 0x1824) + +/* SPU */ + +typedef enum { + SPU_STAT_CDDA = 1 << 0, + SPU_STAT_EXT = 1 << 1, + SPU_STAT_CDDA_REVERB = 1 << 2, + SPU_STAT_EXT_REVERB = 1 << 3, + SPU_STAT_XFER_BITMASK = 3 << 4, + SPU_STAT_XFER_NONE = 0 << 4, + SPU_STAT_XFER_WRITE = 1 << 4, + SPU_STAT_XFER_DMA_WRITE = 2 << 4, + SPU_STAT_XFER_DMA_READ = 3 << 4, + SPU_STAT_IRQ = 1 << 6, + SPU_STAT_DREQ = 1 << 7, + SPU_STAT_WRITE_REQ = 1 << 8, + SPU_STAT_READ_REQ = 1 << 9, + SPU_STAT_BUSY = 1 << 10, + SPU_STAT_CAPTURE_BUF = 1 << 11 +} SPUStatusFlag; + +typedef enum { + SPU_CTRL_CDDA = 1 << 0, + SPU_CTRL_EXT = 1 << 1, + SPU_CTRL_CDDA_REVERB = 1 << 2, + SPU_CTRL_EXT_REVERB = 1 << 3, + SPU_CTRL_XFER_BITMASK = 3 << 4, + SPU_CTRL_XFER_NONE = 0 << 4, + SPU_CTRL_XFER_WRITE = 1 << 4, + SPU_CTRL_XFER_DMA_WRITE = 2 << 4, + SPU_CTRL_XFER_DMA_READ = 3 << 4, + SPU_CTRL_IRQ_ENABLE = 1 << 6, + SPU_CTRL_REVERB = 1 << 7, + SPU_CTRL_UNMUTE = 1 << 14, + SPU_CTRL_ENABLE = 1 << 15 +} SPUControlFlag; + +#define SPU_CH_VOL_L(N) _MMIO16((IO_BASE | 0x1c00) + (16 * (N))) +#define SPU_CH_VOL_R(N) _MMIO16((IO_BASE | 0x1c02) + (16 * (N))) +#define SPU_CH_FREQ(N) _MMIO16((IO_BASE | 0x1c04) + (16 * (N))) +#define SPU_CH_ADDR(N) _MMIO16((IO_BASE | 0x1c06) + (16 * (N))) +#define SPU_CH_ADSR1(N) _MMIO16((IO_BASE | 0x1c08) + (16 * (N))) +#define SPU_CH_ADSR2(N) _MMIO16((IO_BASE | 0x1c0a) + (16 * (N))) +#define SPU_CH_LOOP(N) _MMIO16((IO_BASE | 0x1c0e) + (16 * (N))) + +#define SPU_MASTER_VOL_L _MMIO16(IO_BASE | 0x1d80) +#define SPU_MASTER_VOL_R _MMIO16(IO_BASE | 0x1d82) +#define SPU_REVERB_VOL_L _MMIO16(IO_BASE | 0x1d84) +#define SPU_REVERB_VOL_R _MMIO16(IO_BASE | 0x1d86) +#define SPU_FLAG_ON1 _MMIO16(IO_BASE | 0x1d88) +#define SPU_FLAG_ON2 _MMIO16(IO_BASE | 0x1d8a) +#define SPU_FLAG_OFF1 _MMIO16(IO_BASE | 0x1d8c) +#define SPU_FLAG_OFF2 _MMIO16(IO_BASE | 0x1d8e) +#define SPU_FLAG_FM1 _MMIO16(IO_BASE | 0x1d90) +#define SPU_FLAG_FM2 _MMIO16(IO_BASE | 0x1d92) +#define SPU_FLAG_NOISE1 _MMIO16(IO_BASE | 0x1d94) +#define SPU_FLAG_NOISE2 _MMIO16(IO_BASE | 0x1d96) +#define SPU_FLAG_REVERB1 _MMIO16(IO_BASE | 0x1d98) +#define SPU_FLAG_REVERB2 _MMIO16(IO_BASE | 0x1d9a) +#define SPU_FLAG_STATUS1 _MMIO16(IO_BASE | 0x1d9c) +#define SPU_FLAG_STATUS2 _MMIO16(IO_BASE | 0x1d9e) + +#define SPU_REVERB_ADDR _MMIO16(IO_BASE | 0x1da2) +#define SPU_IRQ_ADDR _MMIO16(IO_BASE | 0x1da4) +#define SPU_ADDR _MMIO16(IO_BASE | 0x1da6) +#define SPU_DATA _MMIO16(IO_BASE | 0x1da8) +#define SPU_CTRL _MMIO16(IO_BASE | 0x1daa) +#define SPU_DMA_CTRL _MMIO16(IO_BASE | 0x1dac) +#define SPU_STAT _MMIO16(IO_BASE | 0x1dae) + +#define SPU_CDDA_VOL_L _MMIO16(IO_BASE | 0x1db0) +#define SPU_CDDA_VOL_R _MMIO16(IO_BASE | 0x1db2) +#define SPU_EXT_VOL_L _MMIO16(IO_BASE | 0x1db4) +#define SPU_EXT_VOL_R _MMIO16(IO_BASE | 0x1db6) +#define SPU_VOL_STAT_L _MMIO16(IO_BASE | 0x1db8) +#define SPU_VOL_STAT_R _MMIO16(IO_BASE | 0x1dba) + +#define SPU_REVERB_BASE _ADDR16(IO_BASE | 0x1dc0) + +/* System 573 base hardware */ + +typedef enum { + SYS573_MISC_OUT_ADC_MOSI = 1 << 0, + SYS573_MISC_OUT_ADC_CS = 1 << 1, + SYS573_MISC_OUT_ADC_SCK = 1 << 2, + SYS573_MISC_OUT_COIN_COUNT1 = 1 << 3, + SYS573_MISC_OUT_COIN_COUNT2 = 1 << 4, + SYS573_MISC_OUT_AMP_ENABLE = 1 << 5, + SYS573_MISC_OUT_CDDA_ENABLE = 1 << 6, + SYS573_MISC_OUT_SPU_ENABLE = 1 << 7, + SYS573_MISC_OUT_JVS_STAT = 1 << 8 +} Sys573MiscOutputFlag; + +typedef enum { + SYS573_MISC_IN_ADC_MISO = 1 << 0, + SYS573_MISC_IN_ADC_SARS = 1 << 1, + SYS573_MISC_IN_CART_SDA = 1 << 2, + SYS573_MISC_IN_JVS_SENSE = 1 << 3, + SYS573_MISC_IN_JVS_AVAIL = 1 << 4, + SYS573_MISC_IN_JVS_UNK = 1 << 5, + SYS573_MISC_IN_CART_ISIG = 1 << 6, + SYS573_MISC_IN_CART_DSIG = 1 << 7, + SYS573_MISC_IN_COIN1 = 1 << 8, + SYS573_MISC_IN_COIN2 = 1 << 9, + SYS573_MISC_IN_PCMCIA_CD1 = 1 << 10, + SYS573_MISC_IN_PCMCIA_CD2 = 1 << 11, + SYS573_MISC_IN_SERVICE = 1 << 12 +} Sys573MiscInputFlag; + +#define SYS573_MISC_OUT _MMIO16(DEV0_BASE | 0x400000) +#define SYS573_DIP_CART _MMIO16(DEV0_BASE | 0x400004) +#define SYS573_MISC_IN _MMIO16(DEV0_BASE | 0x400006) +#define SYS573_JAMMA_MAIN _MMIO16(DEV0_BASE | 0x400008) +#define SYS573_JVS_RX_DATA _MMIO16(DEV0_BASE | 0x40000a) +#define SYS573_JAMMA_EXT1 _MMIO16(DEV0_BASE | 0x40000c) +#define SYS573_JAMMA_EXT2 _MMIO16(DEV0_BASE | 0x40000e) +#define SYS573_BANK_CTRL _MMIO16(DEV0_BASE | 0x500000) +#define SYS573_JVS_RESET _MMIO16(DEV0_BASE | 0x520000) +#define SYS573_IDE_RESET _MMIO16(DEV0_BASE | 0x560000) +#define SYS573_WATCHDOG _MMIO16(DEV0_BASE | 0x5c0000) +#define SYS573_EXT_OUT _MMIO16(DEV0_BASE | 0x600000) +#define SYS573_JVS_TX_DATA _MMIO16(DEV0_BASE | 0x680000) +#define SYS573_CART_OUT _MMIO16(DEV0_BASE | 0x6a0000) + +#define SYS573_FLASH_BASE _ADDR16(DEV0_BASE | 0x000000) +#define SYS573_IDE_CS0_BASE _ADDR16(DEV0_BASE | 0x480000) +#define SYS573_IDE_CS1_BASE _ADDR16(DEV0_BASE | 0x4c0000) +#define SYS573_RTC_BASE _ADDR16(DEV0_BASE | 0x620000) +#define SYS573_IO_BASE _ADDR16(DEV0_BASE | 0x640000) + +/* System 573 analog I/O board */ + +#define SYS573A_LIGHTS_A _MMIO16(DEV0_BASE | 0x640080) +#define SYS573A_LIGHTS_B _MMIO16(DEV0_BASE | 0x640088) +#define SYS573A_LIGHTS_C _MMIO16(DEV0_BASE | 0x640090) +#define SYS573A_LIGHTS_D _MMIO16(DEV0_BASE | 0x640098) + +/* System 573 digital I/O board */ + +typedef enum { + SYS573D_CPLD_STAT_INIT = 1 << 12, + SYS573D_CPLD_STAT_DONE = 1 << 13, + SYS573D_CPLD_STAT_LDC = 1 << 14, + SYS573D_CPLD_STAT_HDC = 1 << 15 +} Sys573DCPLDStatusFlag; + +typedef enum { + SYS573D_CPLD_CTRL_UNK1 = 1 << 12, + SYS573D_CPLD_CTRL_UNK2 = 1 << 13, + SYS573D_CPLD_CTRL_UNK3 = 1 << 14, + SYS573D_CPLD_CTRL_UNK4 = 1 << 15 +} Sys573DCPLDControlFlag; + +#define SYS573D_FPGA_LIGHTS_A1 _MMIO16(DEV0_BASE | 0x6400e0) +#define SYS573D_FPGA_LIGHTS_A0 _MMIO16(DEV0_BASE | 0x6400e2) +#define SYS573D_FPGA_LIGHTS_B1 _MMIO16(DEV0_BASE | 0x6400e4) +#define SYS573D_FPGA_LIGHTS_D0 _MMIO16(DEV0_BASE | 0x6400e6) +#define SYS573D_FPGA_INIT _MMIO16(DEV0_BASE | 0x6400e8) +#define SYS573D_FPGA_DS2401 _MMIO16(DEV0_BASE | 0x6400ee) + +#define SYS573D_CPLD_UNK_RESET _MMIO16(DEV0_BASE | 0x6400f4) +#define SYS573D_CPLD_STAT _MMIO16(DEV0_BASE | 0x6400f6) +#define SYS573D_CPLD_CTRL _MMIO16(DEV0_BASE | 0x6400f6) +#define SYS573D_CPLD_BITSTREAM _MMIO16(DEV0_BASE | 0x6400f8) +#define SYS573D_CPLD_LIGHTS_C0 _MMIO16(DEV0_BASE | 0x6400fa) +#define SYS573D_CPLD_LIGHTS_C1 _MMIO16(DEV0_BASE | 0x6400fc) +#define SYS573D_CPLD_LIGHTS_B0 _MMIO16(DEV0_BASE | 0x6400fe) diff --git a/src/ps1/system.c b/src/ps1/system.c new file mode 100644 index 0000000..3c13748 --- /dev/null +++ b/src/ps1/system.c @@ -0,0 +1,156 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include +#include "ps1/registers.h" +#include "ps1/system.h" + +#define BIOS_API_TABLE ((VoidFunction *) 0x80000200) +#define BIOS_BP_VECTOR ((uint32_t *) 0x80000040) +#define BIOS_EXC_VECTOR ((uint32_t *) 0x80000080) + +/* Internal state */ + +static VoidFunction _flushCache = 0; +static Thread _mainThread; + +ArgFunction interruptHandler = 0; +void *interruptHandlerArg = 0; + +Thread *currentThread = &_mainThread; +Thread *nextThread = &_mainThread; + +/* Exception handler setup */ + +void _exceptionVector(void); + +void installExceptionHandler(void) { + // Clear all pending IRQ flags and prevent the interrupt controller from + // generating further IRQs. + IRQ_MASK = 0; + IRQ_STAT = 0; + DMA_DPCR = 0; + DMA_DICR = DMA_DICR_CH_STAT_MASK; + + // Ensure interrupts and the GTE are enabled at the COP0 side. + uint32_t sr = SR_IEc | SR_Im2 | SR_CU0 | SR_CU2; + __asm__ volatile("mtc0 %0, $12;" :: "r"(sr)); + + // Grab a direct pointer to the BIOS function to flush the instruction + // cache. This is the only function that must always run from the BIOS ROM + // as it temporarily disables main RAM. + _flushCache = BIOS_API_TABLE[0x44]; + + // Overwrite the default breakpoint and exception handlers placed into RAM + // by the BIOS with a function that will jump to our custom handler. + __builtin_memcpy(BIOS_BP_VECTOR, &_exceptionVector, 16); + __builtin_memcpy(BIOS_EXC_VECTOR, &_exceptionVector, 16); + _flushCache(); + + DMA_DPCR = 0x0bbbbbbb; + DMA_DICR = DMA_DICR_IRQ_ENABLE; +} + +void setInterruptHandler(ArgFunction func, void *arg) { + setInterruptMask(0); + + interruptHandler = func; + interruptHandlerArg = arg; + atomic_signal_fence(memory_order_release); +} + +void flushCache(void) { + //if (!_flushCache) + //_flushCache = BIOS_API_TABLE[0x44]; + + uint32_t mask = setInterruptMask(0); + + _flushCache(); + if (mask) + setInterruptMask(mask); +} + +/* IRQ acknowledgement and blocking delay */ + +void delayMicroseconds(int us) { + // 1 us = 33.8688 cycles = 17 loop iterations (2 cycles per iteration) + us *= (F_CPU + 1000000) / 2000000; + + __asm__ volatile( + ".set noreorder;" + "bgtz %0, .;" + "addiu %0, -1;" + ".set reorder;" + : "=r"(us) : "r"(us) + ); +} + +bool acknowledgeInterrupt(IRQChannel irq) { + if (IRQ_STAT & (1 << irq)) { + IRQ_STAT = ~(1 << irq); + return true; + } + + return false; +} + +bool waitForInterrupt(IRQChannel irq, int timeout) { + for (; timeout > 0; timeout--) { + if (acknowledgeInterrupt(irq)) + return true; + + delayMicroseconds(1); + } + + return false; +} + +bool waitForDMATransfer(DMAChannel dma, int timeout) { + for (; timeout > 0; timeout--) { + if (!(DMA_CHCR(dma) & DMA_CHCR_ENABLE)) + return true; + + delayMicroseconds(1); + } + + return false; +} + +/* Thread switching */ + +void switchThread(Thread *thread) { + if (!thread) + thread = &_mainThread; + + nextThread = thread; + atomic_signal_fence(memory_order_release); +} + +void switchThreadImmediate(Thread *thread) { + if (!thread) + thread = &_mainThread; + + nextThread = thread; + atomic_signal_fence(memory_order_release); + + // Execute a syscall to force the switch to happen. Note that the syscall + // handler will take a different path if $a0 is zero (see system.s), but + // that will never happen here since the check above is ensuring $a0 (i.e. + // the first argument) will always be a valid pointer. + __asm__ volatile("syscall 0;" :: "r"(thread) : "a0", "memory"); +} diff --git a/src/ps1/system.h b/src/ps1/system.h new file mode 100644 index 0000000..1e9f3ac --- /dev/null +++ b/src/ps1/system.h @@ -0,0 +1,218 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#pragma once + +#include +#include +#include "ps1/registers.h" + +typedef enum { + CAUSE_INT = 0, // Interrupt + CAUSE_AdEL = 4, // Load address error + CAUSE_AdES = 5, // Store address error + CAUSE_IBE = 6, // Instruction bus error + CAUSE_DBE = 7, // Data bus error + CAUSE_SYS = 8, // Syscall + CAUSE_BP = 9, // Breakpoint or break instruction + CAUSE_RI = 10, // Reserved instruction + CAUSE_CpU = 11, // Coprocessor unusable + CAUSE_Ov = 12 // Arithmetic overflow +} ExceptionCause; + +typedef enum { + SR_IEc = 1 << 0, // Current interrupt enable + SR_KUc = 1 << 1, // Current privilege level + SR_IEp = 1 << 2, // Previous interrupt enable + SR_KUp = 1 << 3, // Previous privilege level + SR_IEo = 1 << 4, // Old interrupt enable + SR_KUo = 1 << 5, // Old privilege level + SR_Im0 = 1 << 8, // IRQ mask 0 (software interrupt) + SR_Im1 = 1 << 9, // IRQ mask 1 (software interrupt) + SR_Im2 = 1 << 10, // IRQ mask 2 (hardware interrupt) + SR_CU0 = 1 << 28, // Coprocessor 0 privilege level + SR_CU2 = 1 << 30 // Coprocessor 2 enable +} SRFlag; + +typedef struct { + uint32_t pc, at, v0, v1, a0, a1, a2, a3; + uint32_t t0, t1, t2, t3, t4, t5, t6, t7; + uint32_t s0, s1, s2, s3, s4, s5, s6, s7; + uint32_t t8, t9, gp, sp, fp, ra, hi, lo; +} Thread; + +typedef void (*VoidFunction)(void); +typedef void (*ArgFunction)(void *arg); + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Read-only pointer to the currently running thread. + */ +extern Thread *currentThread; + +/** + * @brief Read-only pointer to the thread scheduled to be executed after the + * currently running one. Use switchThread() or switchThreadImmediate() to set + * this pointer. + */ +extern Thread *nextThread; + +/** + * @brief Disables interrupts temporarily, then sets the IRQ_MASK register to + * the specified value (which should be a bitfield of (1 << IRQ_*) flags) and + * returns its previous value. Must *not* be used in IRQ handlers. + */ +static inline uint32_t setInterruptMask(uint32_t mask) { + register uint32_t v0 __asm__("v0"); + register uint32_t a0 __asm__("a0") = 0; + register uint32_t a1 __asm__("a1") = mask; + + __asm__ volatile("syscall 0;" : "=r"(v0) : "r"(a0), "r"(a1) : "memory"); + return v0; +} + +/** + * @brief Initializes a thread structure with the provided entry point + * (function) and stacktop. The function *must not* return. The stack should be + * aligned to 8 bytes as required by the MIPS ABI. + * + * @param thread + * @param func + * @param stack Pointer to last 8 bytes in the stack + * @param arg Optional argument to entry point + */ +static inline void initThread( + Thread *thread, ArgFunction func, void *arg, void *stack +) { + register uint32_t gp __asm__("gp"); + + thread->pc = (uint32_t) func; + thread->a0 = (uint32_t) arg; + thread->gp = (uint32_t) gp; + thread->sp = (uint32_t) stack; + thread->fp = (uint32_t) stack; + thread->ra = 0; +} + +/** + * @brief Sets up the exception handler, removes the BIOS from memory and + * flushes the instruction cache. Must be called only once, before *any* other + * function in this header is used. + */ +void installExceptionHandler(void); + +/** + * @brief Disables interrupts and sets the function that will be called whenever + * a future interrupt or syscall occurs. Must be called after + * installExceptionHandler() and before interrupts are enabled. As the callback + * will run from within the exception handler, it is subject to several + * limitations: + * + * - it cannot call functions that rely on syscalls such as enableInterrupts(), + * switchThreadImmediate() or setInterruptHandler(); + * - it cannot wait for other interrupts to occur; + * - it must return quickly, as IRQs fired while the exception handler is + * running may otherwise be missed. + * + * Interrupts must be re-enabled manually after setting a new handler. + * + * @param func + * @param arg Optional argument to be passed to handler + */ +void setInterruptHandler(ArgFunction func, void *arg); + +/** + * @brief Clears the instruction cache. Must *not* be used in IRQ handlers. + */ +void flushCache(void); + +/** + * @brief Blocks for (roughly) the specified number of microseconds. This + * function does not rely on a hardware timer, so interrupts may throw off + * timings if not explicitly disabled prior to calling delayMicroseconds(). + * + * @param time + */ +void delayMicroseconds(int time); + +/** + * @brief Checks if the specified interrupt was fired but not yet acknowledged; + * if so, acknowledges it and returns true. This function can be used in a + * callback set using setInterruptHandler() to check for individual IRQs that + * need to be processed, but will also work with interrupts that are not + * explicitly enabled in the IRQ_MASK register. + * + * Note that most interrupts must additionally be acknowledged at the device + * side (through DMA/SIO/SPU/CD-ROM registers or by issuing the GP1 IRQ + * acknowledge command) once this function returns true. Lightgun, vblank and + * timer interrupts do not require device-side acknowledgement. + * + * @param irq + * @return True if the IRQ was pending and got acknowledged, false otherwise + */ +bool acknowledgeInterrupt(IRQChannel irq); + +/** + * @brief Waits for the specified interrupt to be fired for up to the specified + * number of microseconds. This function will work with interrupts that are not + * explicitly enabled in the IRQ_MASK register, but will *not* work with + * interrupts that have been enabled if any callback set using + * setInterruptHandler() acknowledges them. + * + * @param irq + * @param timeout + * @return False in case of a timeout, true otherwise + */ +bool waitForInterrupt(IRQChannel irq, int timeout); + +/** + * @brief Waits for the specified DMA channel to finish any ongoing transfer for + * up to the specified number of microseconds. + * + * @param dma + * @param timeout + * @return False in case of a timeout, true otherwise + */ +bool waitForDMATransfer(DMAChannel dma, int timeout); + +/** + * @brief Pauses the thread calling this function and starts/resumes executing + * the specified one. The switch will not happen immediately, but will only be + * processed once an interrupt occurs or a syscall is issued. If called from an + * IRQ handler, it will happen once all IRQ handlers have been executed. + * + * @param thread Pointer to new thread or NULL for main thread + */ +void switchThread(Thread *thread); + +/** + * @brief Pauses the thread calling this function immediately and starts/resumes + * executing the specified one. Once the other thread switches back, execution + * will resume from after the call to switchThreadImmediate(). This function + * must *not* be used in IRQ handlers; use switchThread() (which will behave + * identically as thread switches are processed right after IRQ handling) + * instead. + * + * @param thread Pointer to new thread or NULL for main thread + */ +void switchThreadImmediate(Thread *thread); + +#ifdef __cplusplus +} +#endif diff --git a/src/ps1/system.s b/src/ps1/system.s new file mode 100644 index 0000000..dedba12 --- /dev/null +++ b/src/ps1/system.s @@ -0,0 +1,201 @@ +# ps1-bare-metal - (C) 2023 spicyjpeg +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +# PERFORMANCE OF THIS SOFTWARE. + +.set noreorder +.set noat + +.set BADV, $8 +.set SR, $12 +.set CAUSE, $13 +.set EPC, $14 + +.set IO_BASE, 0xbf80 +.set IRQ_STAT, 0x1070 +.set IRQ_MASK, 0x1074 + +.section .text._exceptionVector, "ax", @progbits +.global _exceptionVector +.type _exceptionVector, @function + +_exceptionVector: + # This tiny stub is going to be relocated to the address the CPU jumps to + # when an exception occurs (0x80000080) at runtime, overriding the default + # one installed by the BIOS. + lui $k0, %hi(currentThread) + j _exceptionHandler + lw $k0, %lo(currentThread)($k0) + + nop + +.section .text._exceptionHandler, "ax", @progbits +.global _exceptionHandler +.type _exceptionHandler, @function + +_exceptionHandler: + # We're going to need at least 3 registers to store a pointer to the current + # thread, the return pointer (EPC) and the state of the CAUSE register + # respectively. $k0 and $k1 are always available to the exception handler, + # so only $at needs to be saved. + nop + sw $at, 0x04($k0) + mfc0 $at, CAUSE + + # Check CAUSE bits 2-6 to determine what triggered the exception. If it was + # caused by a syscall, increment EPC so it won't be executed again; + # furthermore, if the first argument passed to the syscall was zero, take an + # alternate, shorter code path (as it is the syscall to set IRQ_MASK). + li $k1, 8 << 2 # if (((CAUSE >> 2) & 0x1f) != 8) goto notFastSyscall + andi $at, 0x1f << 2 + bne $at, $k1, .LnotFastSyscall + mfc0 $k1, EPC + + bnez $a0, .LnotFastSyscall # if (arg0) goto notFastSyscall + addiu $k1, 4 # EPC++ + +.LfastSyscall: + # Save the current value of IRQ_MASK then set it "atomically" (as interrupts + # are disabled while the exception handler runs), then restore $at and + # return immediately without the overhead of saving and restoring the whole + # thread. + lui $at, IO_BASE + lhu $v0, IRQ_MASK($at) # returnValue = IRQ_MASK + lw $at, 0x04($k0) + sh $a1, IRQ_MASK($at) # IRQ_MASK = arg1 + + jr $k1 + rfe + +.LnotFastSyscall: + # If the fast path couldn't be taken, save the full state of the thread. The + # state of $hi/$lo is saved after all other registers in order to let the + # multiplier finish any ongoing calculation. + sw $v0, 0x08($k0) + sw $v1, 0x0c($k0) + sw $a0, 0x10($k0) + sw $a1, 0x14($k0) + sw $a2, 0x18($k0) + sw $a3, 0x1c($k0) + sw $t0, 0x20($k0) + sw $t1, 0x24($k0) + sw $t2, 0x28($k0) + sw $t3, 0x2c($k0) + sw $t4, 0x30($k0) + sw $t5, 0x34($k0) + sw $t6, 0x38($k0) + sw $t7, 0x3c($k0) + sw $s0, 0x40($k0) + sw $s1, 0x44($k0) + sw $s2, 0x48($k0) + sw $s3, 0x4c($k0) + sw $s4, 0x50($k0) + sw $s5, 0x54($k0) + sw $s6, 0x58($k0) + sw $s7, 0x5c($k0) + sw $t8, 0x60($k0) + sw $t9, 0x64($k0) + sw $gp, 0x68($k0) + sw $sp, 0x6c($k0) + sw $fp, 0x70($k0) + sw $ra, 0x74($k0) + + mfhi $v0 + mflo $v1 + sw $v0, 0x78($k0) + sw $v1, 0x7c($k0) + + # Check again if the CAUSE code is either 0 (IRQ) or 8 (syscall). If not + # call _unhandledException(), which will then display information about the + # exception and lock up. + lui $v0, %hi(interruptHandler) + andi $v1, $at, 0x17 << 2 # if (!(((CAUSE >> 2) & 0x1f) % 8)) goto irqOrSyscall + beqz $v1, .LirqOrSyscall + lw $v0, %lo(interruptHandler)($v0) + +.LotherException: + mfc0 $a1, BADV # _unhandledException((CAUSE >> 2) & 0x1f, BADV) + srl $a0, $at, 2 + jal _unhandledException + addiu $sp, -8 + + b .Lreturn + addiu $sp, 8 + +.LirqOrSyscall: + # Otherwise, check if the interrupted instruction was a GTE opcode and + # increment EPC to avoid executing it again (as with syscalls). This is a + # workaround for a hardware bug. + lw $v1, 0($k1) + li $at, 0x25 # if ((*EPC >> 25) == 0x25) EPC++ + srl $v1, 25 + bne $v1, $at, .LskipIncrement + lui $a0, %hi(interruptHandlerArg) + + addiu $k1, 4 + +.LskipIncrement: + lw $a0, %lo(interruptHandlerArg)($a0) + sw $k1, 0x00($k0) + + # Dispatch any pending interrupts. + jalr $v0 # interruptHandler(interruptHandlerArg) + addiu $sp, -8 + + addiu $sp, 8 + +.Lreturn: + # Grab a pointer to the next thread to be executed, restore its state and + # return. + lui $k0, %hi(nextThread) + lw $k0, %lo(nextThread)($k0) + lui $at, %hi(currentThread) + sw $k0, %lo(currentThread)($at) + + lw $v0, 0x78($k0) + lw $v1, 0x7c($k0) + mthi $v0 + mtlo $v1 + + lw $k1, 0x00($k0) + lw $at, 0x04($k0) + lw $v0, 0x08($k0) + lw $v1, 0x0c($k0) + lw $a0, 0x10($k0) + lw $a1, 0x14($k0) + lw $a2, 0x18($k0) + lw $a3, 0x1c($k0) + lw $t0, 0x20($k0) + lw $t1, 0x24($k0) + lw $t2, 0x28($k0) + lw $t3, 0x2c($k0) + lw $t4, 0x30($k0) + lw $t5, 0x34($k0) + lw $t6, 0x38($k0) + lw $t7, 0x3c($k0) + lw $s0, 0x40($k0) + lw $s1, 0x44($k0) + lw $s2, 0x48($k0) + lw $s3, 0x4c($k0) + lw $s4, 0x50($k0) + lw $s5, 0x54($k0) + lw $s6, 0x58($k0) + lw $s7, 0x5c($k0) + lw $t8, 0x60($k0) + lw $t9, 0x64($k0) + lw $gp, 0x68($k0) + lw $sp, 0x6c($k0) + lw $fp, 0x70($k0) + lw $ra, 0x74($k0) + + jr $k1 + rfe diff --git a/src/ps1/unhandledexc.c b/src/ps1/unhandledexc.c new file mode 100644 index 0000000..794d75b --- /dev/null +++ b/src/ps1/unhandledexc.c @@ -0,0 +1,78 @@ +/* + * ps1-bare-metal - (C) 2023 spicyjpeg + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + * + * If any exception other than an IRQ or syscall (such as a bus or alignment + * error) occurs, the exception handler defined in system.s will call + * _unhandledException() to safely halt the program. This is a very simple + * implementation of it that prints the state of all registers then locks up. + */ + +#include +#include +#include "ps1/system.h" + +#ifndef NDEBUG +static const char *const _causeNames[] = { + "load address error", + "store address error", + "instruction bus error", + "data bus error", + "syscall", + "break instruction", + "reserved instruction", + "coprocessor unusable", + "arithmetic overflow" +}; + +static const char _registerNames[] = + "pc" "at" "v0" "v1" "a0" "a1" "a2" "a3" + "t0" "t1" "t2" "t3" "t4" "t5" "t6" "t7" + "s0" "s1" "s2" "s3" "s4" "s5" "s6" "s7" + "t8" "t9" "gp" "sp" "fp" "ra" "hi" "lo"; +#endif + +void _unhandledException(ExceptionCause cause, uint32_t badv) { +#ifndef NDEBUG + if ((cause == CAUSE_AdEL) || (cause == CAUSE_AdES)) + printf("Exception: %s (%08x)\nRegister dump:\n", _causeNames[cause - 4], badv); + else + printf("Exception: %s\nRegister dump:\n", _causeNames[cause - 4]); + + const char *name = _registerNames; + uint32_t *reg = (uint32_t *) &(currentThread->pc); + + for (int i = 31; i >= 0; i--) { + char a = *(name++), b = *(name++); + + printf(" %c%c=%08x", a, b, *(reg++)); + if (!(i % 4)) + putchar('\n'); + } + + printf("Stack dump:\n"); + + uint32_t *addr = ((uint32_t *) currentThread->sp) - 7; + uint32_t *end = ((uint32_t *) currentThread->sp) + 7; + + for (; addr <= end; addr++) { + char arrow = (((uint32_t) addr) == currentThread->sp) ? '>' : ' '; + + printf("%c %08x: %08x\n", arrow, addr, *addr); + } +#endif + + for (;;) + __asm__ volatile(""); +} diff --git a/src/spu.cpp b/src/spu.cpp new file mode 100644 index 0000000..edea8bf --- /dev/null +++ b/src/spu.cpp @@ -0,0 +1,175 @@ + +#include +#include +#include "ps1/registers.h" +#include "spu.hpp" +#include "util.hpp" + +namespace spu { + +/* Basic API */ + +static constexpr int _DMA_CHUNK_SIZE = 8; +static constexpr int _DMA_TIMEOUT = 10000; +static constexpr int _STATUS_TIMEOUT = 1000; + +static constexpr uint32_t _DUMMY_BLOCK_ADDR = 0x1000; + +static bool _waitForStatus(uint16_t mask, uint16_t value) { + for (int timeout = _STATUS_TIMEOUT; timeout > 0; timeout--) { + if ((SPU_STAT & mask) == value) + return true; + + delayMicroseconds(1); + } + + return false; +} + +void init(void) { + BIU_DEV4_CTRL = 0 + | ( 1 << 0) // Write delay + | (14 << 4) // Read delay + | BIU_CTRL_RECOVERY + | BIU_CTRL_WIDTH_16 + | BIU_CTRL_AUTO_INCR + | (9 << 16) // Number of address lines + | (0 << 24) // DMA read/write delay + | BIU_CTRL_DMA_DELAY; + + SPU_CTRL = 0; + _waitForStatus(0x3f, 0); + + SPU_MASTER_VOL_L = 0; + SPU_MASTER_VOL_R = 0; + SPU_REVERB_VOL_L = 0; + SPU_REVERB_VOL_R = 0; + SPU_REVERB_ADDR = 0xfffe; + + SPU_CTRL = SPU_CTRL_ENABLE; + _waitForStatus(0x3f, 0); + + // Place a dummy (silent) looping block at the beginning of SPU RAM. + SPU_DMA_CTRL = 4; + SPU_ADDR = _DUMMY_BLOCK_ADDR / 8; + + SPU_DATA = 0x0500; + for (int i = 7; i > 0; i--) + SPU_DATA = 0; + + SPU_CTRL = SPU_CTRL_XFER_WRITE | SPU_CTRL_ENABLE; + _waitForStatus(SPU_CTRL_XFER_BITMASK | SPU_STAT_BUSY, SPU_CTRL_XFER_WRITE); + delayMicroseconds(100); + + SPU_CTRL = SPU_CTRL_UNMUTE | SPU_CTRL_ENABLE; + resetAllChannels(); +} + +int getFreeChannel(void) { + uint32_t flags = SPU_FLAG_STATUS1 | (SPU_FLAG_STATUS2 << 16); + + for (int ch = 0; flags; ch++, flags >>= 1) { + if (flags & 1) + return ch; + } + + return -1; +} + +void stopChannel(int ch) { + SPU_CH_VOL_L(ch) = 0; + SPU_CH_VOL_R(ch) = 0; + SPU_CH_FREQ(ch) = 0; + SPU_CH_ADDR(ch) = 0; + + if (ch < 16) { + SPU_FLAG_OFF1 = 1 << ch; + SPU_FLAG_ON1 = 1 << ch; + } else { + SPU_FLAG_OFF2 = 1 << (ch - 16); + SPU_FLAG_ON2 = 1 << (ch - 16); + } +} + +void resetAllChannels(void) { + for (int ch = 23; ch >= 0; ch--) { + SPU_CH_VOL_L(ch) = 0; + SPU_CH_VOL_R(ch) = 0; + SPU_CH_FREQ(ch) = 0x1000; + SPU_CH_ADDR(ch) = _DUMMY_BLOCK_ADDR / 8; + } + + SPU_FLAG_FM1 = 0; + SPU_FLAG_FM2 = 0; + SPU_FLAG_NOISE1 = 0; + SPU_FLAG_NOISE2 = 0; + SPU_FLAG_REVERB1 = 0; + SPU_FLAG_REVERB2 = 0; + SPU_FLAG_ON1 = 0xffff; + SPU_FLAG_ON2 = 0x00ff; +} + +size_t upload(uint32_t ramOffset, const void *data, size_t length, bool wait) { + length /= 4; + + assert(!(length % _DMA_CHUNK_SIZE)); + length = (length + _DMA_CHUNK_SIZE - 1) / _DMA_CHUNK_SIZE; + + if (!waitForDMATransfer(DMA_SPU, _DMA_TIMEOUT)) + return 0; + + uint16_t ctrlReg = SPU_CTRL & ~SPU_CTRL_XFER_BITMASK; + + SPU_CTRL = ctrlReg; + _waitForStatus(SPU_CTRL_XFER_BITMASK, 0); + + SPU_DMA_CTRL = 4; + SPU_ADDR = ramOffset / 8; + SPU_CTRL = ctrlReg | SPU_CTRL_XFER_DMA_WRITE; + _waitForStatus(SPU_CTRL_XFER_BITMASK, SPU_CTRL_XFER_DMA_WRITE); + + DMA_MADR(DMA_SPU) = reinterpret_cast(data); + DMA_BCR (DMA_SPU) = _DMA_CHUNK_SIZE | (length << 16); + DMA_CHCR(DMA_SPU) = DMA_CHCR_WRITE | DMA_CHCR_MODE_SLICE | DMA_CHCR_ENABLE; + + if (wait) + waitForDMATransfer(DMA_SPU, _DMA_TIMEOUT); + + return length * _DMA_CHUNK_SIZE * 4; +} + +/* Sound class */ + +bool Sound::initFromVAGHeader(const VAGHeader *header, uint32_t ramOffset) { + if ((header->magic != 0x70474156) || header->interleave) + return false; + + offset = ramOffset / 8; + sampleRate = (util::swapEndian(header->sampleRate) << 12) / 44100; + length = util::swapEndian(header->length); + + return true; +} + +int Sound::play(int ch, int16_t volume) const { + if ((ch < 0) || (ch > 23)) + return -1; + if (!offset) + return -1; + + SPU_CH_VOL_L(ch) = volume; + SPU_CH_VOL_R(ch) = volume; + SPU_CH_FREQ (ch) = sampleRate; + SPU_CH_ADDR (ch) = offset; + SPU_CH_ADSR1(ch) = 0x00ff; + SPU_CH_ADSR2(ch) = 0x0000; + + if (ch < 16) + SPU_FLAG_ON1 = 1 << ch; + else + SPU_FLAG_ON2 = 1 << (ch - 16); + + return ch; +} + +} diff --git a/src/spu.hpp b/src/spu.hpp new file mode 100644 index 0000000..1a07ca9 --- /dev/null +++ b/src/spu.hpp @@ -0,0 +1,49 @@ + +#pragma once + +#include +#include +#include "ps1/registers.h" + +namespace spu { + +/* Basic API */ + +static inline void setVolume(int16_t master, int16_t reverb = 0) { + SPU_MASTER_VOL_L = master; + SPU_MASTER_VOL_R = master; + SPU_REVERB_VOL_L = reverb; + SPU_REVERB_VOL_R = reverb; +} + +void init(void); +int getFreeChannel(void); +void stopChannel(int ch); +void resetAllChannels(void); +size_t upload(uint32_t ramOffset, const void *data, size_t length, bool wait); + +/* Sound class */ + +struct [[gnu::packed]] VAGHeader { +public: + uint32_t magic, version, interleave, length, sampleRate; + uint16_t _reserved[5], channels; + char name[16]; +}; + +class Sound { +public: + uint16_t offset, sampleRate; + size_t length; + + inline Sound(void) + : offset(0), length(0) {} + inline int play(int16_t volume = 0x3fff) const { + return play(getFreeChannel(), volume); + } + + bool initFromVAGHeader(const VAGHeader *header, uint32_t ramOffset); + int play(int ch, int16_t volume = 0x3fff) const; +}; + +} diff --git a/src/uibase.cpp b/src/uibase.cpp new file mode 100644 index 0000000..fa5c9c4 --- /dev/null +++ b/src/uibase.cpp @@ -0,0 +1,345 @@ + +#include +#include "ps1/gpucmd.h" +#include "gpu.hpp" +#include "io.hpp" +#include "pad.hpp" +#include "uibase.hpp" + +namespace ui { + +/* Button state manager */ + +static const uint32_t _BUTTON_MAPPINGS[NUM_BUTTON_MAPS][NUM_BUTTONS]{ + { // MAP_JOYSTICK + io::JAMMA_P1_LEFT | io::JAMMA_P1_UP | io::JAMMA_P2_LEFT | io::JAMMA_P2_UP, + io::JAMMA_P1_RIGHT | io::JAMMA_P1_DOWN | io::JAMMA_P2_RIGHT | io::JAMMA_P2_DOWN, + io::JAMMA_P1_START | io::JAMMA_P2_START, + io::JAMMA_TEST | io::JAMMA_SERVICE + }, + { // MAP_DDR_CAB + io::JAMMA_P1_BUTTON2 | io::JAMMA_P2_BUTTON2, + io::JAMMA_P1_BUTTON3 | io::JAMMA_P2_BUTTON3, + io::JAMMA_P1_START | io::JAMMA_P2_START, + io::JAMMA_TEST | io::JAMMA_SERVICE + }, + { // MAP_DDR_SOLO_CAB + io::JAMMA_P1_BUTTON5, + io::JAMMA_P2_BUTTON5, + io::JAMMA_P1_START, + io::JAMMA_TEST | io::JAMMA_SERVICE + }, + { // MAP_DM_CAB + io::JAMMA_P2_LEFT, + io::JAMMA_P2_RIGHT, + io::JAMMA_P1_START, + io::JAMMA_TEST | io::JAMMA_SERVICE + }, + { // MAP_DMX_CAB (more or less redundant with MAP_JOYSTICK) + io::JAMMA_P1_UP | io::JAMMA_P2_UP, + io::JAMMA_P1_DOWN | io::JAMMA_P2_DOWN, + io::JAMMA_P1_START | io::JAMMA_P2_START, + io::JAMMA_TEST | io::JAMMA_SERVICE + }, + { // MAP_SINGLE_BUTTON + 0, + 0, + io::JAMMA_P1_START | io::JAMMA_P2_START | io::JAMMA_TEST | io::JAMMA_SERVICE, + 0 + } +}; + +ButtonState::ButtonState(void) +: _held(0), _repeatTimer(0) {} + +void ButtonState::update(void) { + _prevHeld = _held; + _held = 0; + + uint32_t inputs = io::getJAMMAInputs(); + auto map = _BUTTON_MAPPINGS[buttonMap]; + + for (int i = 0; i < NUM_BUTTONS; i++) { + if (inputs & map[i]) + _held |= 1 << i; + } + +#ifdef ENABLE_PS1_CONTROLLER + if (pad::ports[0].pollPad() || pad::ports[1].pollPad()) { + _held = 0; // Ignore JAMMA inputs + + for (int i = 1; i >= 0; i--) { + auto &port = pad::ports[i]; + + if ( + (port.padType != pad::PAD_DIGITAL) && + (port.padType != pad::PAD_ANALOG) && + (port.padType != pad::PAD_ANALOG_STICK) + ) + continue; + + if (port.buttons & (pad::BTN_LEFT | pad::BTN_UP)) + _held |= 1 << BTN_LEFT; + if (port.buttons & (pad::BTN_RIGHT | pad::BTN_DOWN)) + _held |= 1 << BTN_RIGHT; + if (port.buttons & (pad::BTN_CIRCLE | pad::BTN_CROSS)) + _held |= 1 << BTN_START; + if (port.buttons & pad::BTN_SELECT) + _held |= 1 << BTN_DEBUG; + } + } +#endif + + uint32_t changed = _prevHeld ^ _held; + + if (buttonMap == MAP_SINGLE_BUTTON) { + _pressed = 0; + _released = 0; + _repeating = 0; + + // In single-button mode, interpret a short button press as the right + // button and a long press as start. + if (_held) { + if (_repeatTimer == REPEAT_DELAY) + _pressed |= 1 << BTN_START; + + _repeatTimer++; + } else if (_prevHeld) { + if (_repeatTimer >= REPEAT_DELAY) + _released |= 1 << BTN_START; + else + _pressed |= 1 << BTN_RIGHT; + + _repeatTimer = 0; + } + } else { + if (changed) + _repeatTimer = 0; + else if (_held) + _repeatTimer++; + + _pressed = (changed & _held) & ~_pressed; + _released = (changed & _prevHeld) & ~_released; + _repeating = (_repeatTimer >= REPEAT_DELAY) ? _held : 0; + } +} + +/* UI context */ + +Context::Context(gpu::Context &gpuCtx, void *screenData) +: _background(nullptr), _overlay(nullptr), _currentScreen(0), gpuCtx(gpuCtx), +time(0), screenData(screenData) { + _screens[0] = nullptr; + _screens[1] = nullptr; +} + +void Context::show(Screen &screen, bool goBack, bool playSound) { + auto oldScreen = _screens[_currentScreen]; + if (oldScreen) + oldScreen->hide(*this, goBack); + + _currentScreen ^= 1; + _screens[_currentScreen] = &screen; + screen.show(*this, goBack); + + if (playSound) + sounds[goBack ? SOUND_EXIT : SOUND_ENTER].play(); +} + +void Context::draw(void) { + auto oldScreen = _screens[_currentScreen ^ 1]; + auto newScreen = _screens[_currentScreen]; + + if (_background) + _background->draw(*this); + if (oldScreen) + oldScreen->draw(*this, false); + if (newScreen) + newScreen->draw(*this, true); + if (_overlay) + _overlay->draw(*this); +} + +void Context::update(void) { + buttons.update(); + + if (_overlay) + _overlay->update(*this); + if (_screens[_currentScreen]) + _screens[_currentScreen]->update(*this); +} + +/* Layer classes */ + +void Layer::_newLayer(Context &ctx, int x, int y, int width, int height) const { + ctx.gpuCtx.newLayer(x, y, width, height); +} + +void Layer::_setTexturePage(Context &ctx, uint16_t texpage, bool dither) const { + ctx.gpuCtx.setTexturePage(texpage, dither); +} + +void Layer::_setBlendMode( + Context &ctx, gpu::BlendMode blendMode, bool dither +) const { + ctx.gpuCtx.setBlendMode(blendMode, dither); +} + +void TiledBackground::draw(Context &ctx) const { + _newLayer(ctx, 0, 0, ctx.gpuCtx.width, ctx.gpuCtx.height); + _setTexturePage(ctx, tile.texpage); + + int offsetX = uint32_t(ctx.time / 2) % tile.width; + int offsetY = uint32_t(ctx.time / 3) % tile.height; + + for (int x = -offsetX; x < ctx.gpuCtx.width; x += tile.width) { + for (int y = -offsetY; y < ctx.gpuCtx.height; y += tile.height) + tile.draw(ctx.gpuCtx, x, y); + } + + gpu::RectWH rect; + + int width = ctx.font.getStringWidth(text); + rect.x = ctx.gpuCtx.width - (8 + width); + rect.y = ctx.gpuCtx.height - (8 + gpu::FONT_LINE_HEIGHT); + rect.w = width; + rect.h = gpu::FONT_LINE_HEIGHT; + ctx.font.draw(ctx.gpuCtx, text, rect, COLOR_TEXT2); +} + +LogOverlay::LogOverlay(util::Logger &logger) +: _logger(logger) { + _slideAnim.setValue(0); +} + +void LogOverlay::draw(Context &ctx) const { + int offset = _slideAnim.getValue(ctx.time); + if (!offset) + return; + + _newLayer( + ctx, 0, offset - ctx.gpuCtx.height, ctx.gpuCtx.width, + ctx.gpuCtx.height + ); + ctx.gpuCtx.drawBackdrop(COLOR_BACKDROP, GP0_BLEND_SUBTRACT); + + int screenHeight = ctx.gpuCtx.height - SCREEN_MARGIN_Y * 2; + int linesShown = screenHeight / gpu::FONT_LINE_HEIGHT; + + gpu::Rect rect; + + rect.x1 = SCREEN_MARGIN_X; + rect.y1 = SCREEN_MARGIN_Y; + rect.x2 = ctx.gpuCtx.width - SCREEN_MARGIN_X; + rect.y2 = SCREEN_MARGIN_Y + gpu::FONT_LINE_HEIGHT; + + for (int i = linesShown - 1; i >= 0; i--) { + ctx.font.draw(ctx.gpuCtx, _logger.getLine(i), rect, COLOR_TEXT1); + + rect.y1 = rect.y2; + rect.y2 += gpu::FONT_LINE_HEIGHT; + } +} + +void LogOverlay::update(Context &ctx) { + if (ctx.buttons.pressed(BTN_DEBUG)) { + bool shown = !_slideAnim.getTargetValue(); + + _slideAnim.setValue(ctx.time, shown ? ctx.gpuCtx.height : 0, SPEED_SLOW); + ctx.sounds[shown ? SOUND_ENTER : SOUND_EXIT].play(); + } +} + +/* Base screen classes */ + +void AnimatedScreen::_newLayer( + Context &ctx, int x, int y, int width, int height +) const { + Screen::_newLayer(ctx, x + _slideAnim.getValue(ctx.time), y, width, height); +} + +void AnimatedScreen::show(Context &ctx, bool goBack) { + int width = ctx.gpuCtx.width; + _slideAnim.setValue(ctx.time, goBack ? (-width) : width, 0, SPEED_SLOW); +} + +void AnimatedScreen::hide(Context &ctx, bool goBack) { + int width = ctx.gpuCtx.width; + _slideAnim.setValue(ctx.time, 0, goBack ? width : (-width), SPEED_SLOW); +} + +void BackdropScreen::show(Context &ctx, bool goBack) { + _backdropAnim.setValue(ctx.time, 0, 0x50, SPEED_FAST); +} + +void BackdropScreen::hide(Context &ctx, bool goBack) { + _backdropAnim.setValue(ctx.time, 0x50, 0, SPEED_FAST); +} + +void BackdropScreen::draw(Context &ctx, bool active) const { + int brightness = _backdropAnim.getValue(ctx.time); + if (!brightness) + return; + + _newLayer(ctx, 0, 0, ctx.gpuCtx.width, ctx.gpuCtx.height); + ctx.gpuCtx.drawBackdrop( + gp0_rgb(brightness, brightness, brightness), GP0_BLEND_ADD + ); +} + +ModalScreen::ModalScreen(int width, int height) +: _width(width), _height(height), _title(nullptr), _body(nullptr) {} + +void ModalScreen::show(Context &ctx, bool goBack) { + BackdropScreen::show(ctx, goBack); + + _titleBarAnim.setValue(ctx.time, 0, _width, SPEED_SLOW); +} + +void ModalScreen::draw(Context &ctx, bool active) const { + BackdropScreen::draw(ctx, active); + + if (active) { + int windowHeight = TITLE_BAR_HEIGHT + _height; + + _newLayer( + ctx, (ctx.gpuCtx.width - _width) / 2, + (ctx.gpuCtx.height - windowHeight) / 2, _width + SHADOW_OFFSET, + windowHeight + SHADOW_OFFSET + ); + _setBlendMode(ctx, GP0_BLEND_SEMITRANS, true); + + // Window + ctx.gpuCtx.drawGradientRectD( + 0, 0, _width, windowHeight, COLOR_WINDOW1, COLOR_WINDOW2, + COLOR_WINDOW3 + ); + ctx.gpuCtx.drawGradientRectH( + 0, 0, _titleBarAnim.getValue(ctx.time), TITLE_BAR_HEIGHT, + COLOR_ACCENT1, COLOR_ACCENT2 + ); + ctx.gpuCtx.drawRect( + _width, SHADOW_OFFSET, SHADOW_OFFSET, windowHeight, COLOR_SHADOW, + true + ); + ctx.gpuCtx.drawRect( + SHADOW_OFFSET, windowHeight, _width - SHADOW_OFFSET, SHADOW_OFFSET, + COLOR_SHADOW, true + ); + + // Text + gpu::Rect rect; + + rect.x1 = TITLE_BAR_PADDING; + rect.y1 = TITLE_BAR_PADDING; + rect.x2 = _width - TITLE_BAR_PADDING; + rect.y2 = TITLE_BAR_HEIGHT - TITLE_BAR_PADDING; + ctx.font.draw(ctx.gpuCtx, _title, rect, COLOR_TITLE); + + rect.y1 = TITLE_BAR_HEIGHT + MODAL_PADDING; + rect.y2 = _height - MODAL_PADDING; + ctx.font.draw(ctx.gpuCtx, _body, rect, COLOR_TEXT1, true); + } +} + +} diff --git a/src/uibase.hpp b/src/uibase.hpp new file mode 100644 index 0000000..c77c9ad --- /dev/null +++ b/src/uibase.hpp @@ -0,0 +1,247 @@ + +#pragma once + +#include +#include "gpu.hpp" +#include "spu.hpp" +#include "util.hpp" + +namespace ui { + +/* Public constants */ + +enum Color : gpu::Color { + COLOR_DEFAULT = 0x808080, + COLOR_SHADOW = 0x000000, + COLOR_BACKDROP = 0xb0b0b0, + COLOR_ACCENT1 = 0x50d0f0, + COLOR_ACCENT2 = 0x3088a0, + COLOR_WINDOW1 = 0x505050, + COLOR_WINDOW2 = 0x242424, + COLOR_WINDOW3 = 0x080808, + COLOR_HIGHLIGHT1 = 0x40b0c8, + COLOR_HIGHLIGHT2 = 0x3088a0, + COLOR_PROGRESS1 = 0x10c048, + COLOR_PROGRESS2 = 0x007820, + COLOR_BOX1 = 0x000000, + COLOR_BOX2 = 0x282828, + COLOR_TEXT1 = 0x707070, + COLOR_TEXT2 = 0x383838, + COLOR_TITLE = 0x808080, + COLOR_SUBTITLE = 0x4078a0 +}; + +static constexpr int NUM_UI_SOUNDS = 5; + +enum Sound { + SOUND_STARTUP = 0, + SOUND_MOVE = 1, + SOUND_ENTER = 2, + SOUND_EXIT = 3, + SOUND_CLICK = 4 +}; + +enum AnimationSpeed { + SPEED_FASTEST = 10, + SPEED_FAST = 15, + SPEED_SLOW = 20 +}; + +static constexpr int SCREEN_MARGIN_X = 16; +static constexpr int SCREEN_MARGIN_Y = 20; +static constexpr int SCREEN_BLOCK_MARGIN = 6; +static constexpr int SCREEN_PROMPT_HEIGHT = 30; + +static constexpr int LIST_BOX_PADDING = 4; +static constexpr int LIST_ITEM_PADDING = 2; + +static constexpr int MODAL_WIDTH = 256; +static constexpr int MODAL_HEIGHT_FULL = 120; +static constexpr int MODAL_HEIGHT_REDUCED = 50; +static constexpr int MODAL_PADDING = 5; + +static constexpr int TITLE_BAR_HEIGHT = 18; +static constexpr int TITLE_BAR_PADDING = 5; + +static constexpr int BUTTON_HEIGHT = 18; +static constexpr int BUTTON_SPACING = 3; +static constexpr int BUTTON_PADDING = 5; + +static constexpr int PROGRESS_BAR_HEIGHT = 8; + +static constexpr int SHADOW_OFFSET = 4; + +/* Button state manager */ + +static constexpr int NUM_BUTTONS = 4; +static constexpr int NUM_BUTTON_MAPS = 6; +static constexpr int REPEAT_DELAY = 30; + +enum Button { + BTN_LEFT = 0, + BTN_RIGHT = 1, + BTN_START = 2, + BTN_DEBUG = 3 +}; + +enum ButtonMap { + MAP_JOYSTICK = 0, + MAP_DDR_CAB = 1, + MAP_DDR_SOLO_CAB = 2, + MAP_DM_CAB = 3, + MAP_DMX_CAB = 4, + MAP_SINGLE_BUTTON = 5 // Used when selecting button mapping +}; + +class ButtonState { +private: + uint32_t _mappings[NUM_BUTTONS]; + uint8_t _held, _prevHeld; + uint8_t _pressed, _released, _repeating; + + int _repeatTimer; + +public: + ButtonMap buttonMap; + + inline bool pressed(Button button) const { + return _pressed & (1 << button); + } + inline bool pressedRepeating(Button button) const { + return (_pressed | _repeating) & (1 << button); + } + inline bool released(Button button) const { + return _released & (1 << button); + } + inline bool repeating(Button button) const { + return _repeating & (1 << button); + } + inline bool held(Button button) const { + return _held & (1 << button); + } + + ButtonState(void); + void update(void); +}; + +/* UI context */ + +class Layer; +class Screen; + +class Context { +private: + Screen *_screens[2]; + Layer *_background, *_overlay; + int _currentScreen; + +public: + gpu::Context &gpuCtx; + + gpu::Font font; + spu::Sound sounds[NUM_UI_SOUNDS]; + + ButtonState buttons; + + int time; + void *screenData; // Opaque, can be accessed by screens + + inline void tick(void) { + time++; + } + inline void setBackgroundLayer(Layer &layer) { + _background = &layer; + } + inline void setOverlayLayer(Layer &layer) { + _overlay = &layer; + } + + Context(gpu::Context &gpuCtx, void *screenData = nullptr); + void show(Screen &screen, bool goBack = false, bool playSound = false); + void draw(void); + void update(void); +}; + +/* Layer classes */ + +class Layer { +protected: + void _newLayer(Context &ctx, int x, int y, int width, int height) const; + void _setTexturePage(Context &ctx, uint16_t texpage, bool dither = false) const; + void _setBlendMode(Context &ctx, gpu::BlendMode blendMode, bool dither = false) const; + +public: + virtual void draw(Context &ctx) const {} + virtual void update(Context &ctx) {} +}; + +class TiledBackground : public Layer { +public: + gpu::Image tile; + const char *text; + + void draw(Context &ctx) const; +}; + +class LogOverlay : public Layer { +private: + util::Logger &_logger; + util::Tween _slideAnim; + +public: + LogOverlay(util::Logger &logger); + void draw(Context &ctx) const; + void update(Context &ctx); +}; + +/* Base screen classes */ + +// This is probably the most stripped-down way to implement something that +// vaguely resembles MVC. The class is the model, draw() is the view, update() +// is the controller. +class Screen : public Layer { +public: + virtual void show(Context &ctx, bool goBack = false) {} + virtual void hide(Context &ctx, bool goBack = false) {} + virtual void draw(Context &ctx, bool active = true) const {} + virtual void update(Context &ctx) {} +}; + +class AnimatedScreen : public Screen { +private: + util::Tween _slideAnim; + +protected: + void _newLayer(Context &ctx, int x, int y, int width, int height) const; + +public: + virtual void show(Context &ctx, bool goBack = false); + virtual void hide(Context &ctx, bool goBack = false); +}; + +class BackdropScreen : public Screen { +private: + util::Tween _backdropAnim; + +public: + virtual void show(Context &ctx, bool goBack = false); + virtual void hide(Context &ctx, bool goBack = false); + virtual void draw(Context &ctx, bool active = true) const; +}; + +class ModalScreen : public BackdropScreen { +private: + util::Tween _titleBarAnim; + +protected: + int _width, _height; + + const char *_title, *_body; + +public: + ModalScreen(int width, int height); + virtual void show(Context &ctx, bool goBack = false); + virtual void draw(Context &ctx, bool active = true) const; +}; + +} diff --git a/src/uicommon.cpp b/src/uicommon.cpp new file mode 100644 index 0000000..c71e39a --- /dev/null +++ b/src/uicommon.cpp @@ -0,0 +1,386 @@ + +#include "ps1/gpucmd.h" +#include "defs.hpp" +#include "gpu.hpp" +#include "uibase.hpp" +#include "uicommon.hpp" + +namespace ui { + +/* Common higher-level screens */ + +void PlaceholderScreen::draw(Context &ctx, bool active) const { + _newLayer(ctx, 0, 0, ctx.gpuCtx.width, ctx.gpuCtx.height); + ctx.gpuCtx.drawRect( + 0, 0, ctx.gpuCtx.width, ctx.gpuCtx.height, COLOR_WINDOW2 + ); +} + +MessageScreen::MessageScreen(void) +: ModalScreen(MODAL_WIDTH, MODAL_HEIGHT_FULL), _numButtons(0), _locked(false) {} + +void MessageScreen::show(Context &ctx, bool goBack) { + ModalScreen::show(ctx, goBack); + + _activeButton = 0; + _buttonAnim.setValue(_getButtonWidth()); +} + +void MessageScreen::draw(Context &ctx, bool active) const { + ModalScreen::draw(ctx, active); + + if (!active || !_numButtons) + return; + + int buttonX = _width / 8; + int buttonY = TITLE_BAR_HEIGHT + _height - (BUTTON_HEIGHT + MODAL_PADDING); + gpu::RectWH rect; + + rect.y = buttonY + BUTTON_PADDING; + rect.w = _getButtonWidth(); + rect.h = BUTTON_HEIGHT - BUTTON_PADDING * 2; + + for (int i = 0; i < _numButtons; i++) { + rect.x = buttonX + + (rect.w - ctx.font.getStringWidth(_buttons[i])) / 2; + + if (_locked) { + ctx.gpuCtx.drawRect( + buttonX, buttonY, rect.w, BUTTON_HEIGHT, COLOR_SHADOW, true + ); + + ctx.font.draw(ctx.gpuCtx, _buttons[i], rect, COLOR_TEXT2); + } else { + if (i == _activeButton) { + ctx.gpuCtx.drawRect( + buttonX, buttonY, rect.w, BUTTON_HEIGHT, COLOR_HIGHLIGHT2 + ); + ctx.gpuCtx.drawRect( + buttonX, buttonY, _buttonAnim.getValue(ctx.time), BUTTON_HEIGHT, + COLOR_HIGHLIGHT1 + ); + } else { + ctx.gpuCtx.drawRect( + buttonX, buttonY, rect.w, BUTTON_HEIGHT, COLOR_WINDOW3 + ); + } + + ctx.font.draw(ctx.gpuCtx, _buttons[i], rect, COLOR_TITLE); + } + + buttonX += rect.w + BUTTON_SPACING; + } +} + +void MessageScreen::update(Context &ctx) { + if (_locked) + return; + + if (ctx.buttons.pressed(ui::BTN_LEFT)) { + if (_activeButton > 0) { + _activeButton--; + + _buttonAnim.setValue(ctx.time, 0, _getButtonWidth(), SPEED_FASTEST); + ctx.sounds[SOUND_MOVE].play(); + } else { + ctx.sounds[SOUND_CLICK].play(); + } + } + if (ctx.buttons.pressed(ui::BTN_RIGHT)) { + if (_activeButton < (_numButtons - 1)) { + _activeButton++; + _buttonAnim.setValue(ctx.time, 0, _getButtonWidth(), SPEED_FASTEST); + ctx.sounds[SOUND_MOVE].play(); + } else { + ctx.sounds[SOUND_CLICK].play(); + } + } +} + +ProgressScreen::ProgressScreen(void) +: ModalScreen(MODAL_WIDTH, MODAL_HEIGHT_REDUCED) {} + +void ProgressScreen::show(Context &ctx, bool goBack) { + ModalScreen::show(ctx, goBack); + + _progressBarAnim.setValue(0); +} + +void ProgressScreen::draw(Context &ctx, bool active) const { + ModalScreen::draw(ctx, active); + + if (!active) + return; + + int fullBarWidth = _width - MODAL_PADDING * 2; + + int barX = (_width - fullBarWidth) / 2; + int barY = TITLE_BAR_HEIGHT + _height - + (PROGRESS_BAR_HEIGHT + MODAL_PADDING); + + _setBlendMode(ctx, GP0_BLEND_SEMITRANS, true); + + ctx.gpuCtx.drawRect( + barX, barY, fullBarWidth, PROGRESS_BAR_HEIGHT, COLOR_WINDOW3 + ); + ctx.gpuCtx.drawGradientRectH( + barX, barY, _progressBarAnim.getValue(ctx.time), PROGRESS_BAR_HEIGHT, + COLOR_PROGRESS2, COLOR_PROGRESS1 + ); +} + +TextScreen::TextScreen(void) +: _title(nullptr), _body(nullptr), _prompt(nullptr) {} + +void TextScreen::draw(Context &ctx, bool active) const { + int screenWidth = ctx.gpuCtx.width - SCREEN_MARGIN_X * 2; + int screenHeight = ctx.gpuCtx.height - SCREEN_MARGIN_Y * 2; + + _newLayer( + ctx, SCREEN_MARGIN_X, SCREEN_MARGIN_Y, screenWidth, screenHeight + ); + + gpu::Rect rect; + + rect.x1 = 0; + rect.y1 = 0; + rect.x2 = screenWidth; + rect.y2 = gpu::FONT_LINE_HEIGHT; + ctx.font.draw(ctx.gpuCtx, _title, rect, COLOR_TITLE); + + rect.y1 = gpu::FONT_LINE_HEIGHT + SCREEN_BLOCK_MARGIN; + rect.y2 = screenHeight - SCREEN_PROMPT_HEIGHT; + ctx.font.draw(ctx.gpuCtx, _body, rect, COLOR_TEXT1, true); + + rect.y1 = screenHeight - SCREEN_PROMPT_HEIGHT; + rect.y2 = screenHeight; + ctx.font.draw(ctx.gpuCtx, _prompt, rect, COLOR_TEXT1, true); +} + +ImageScreen::ImageScreen(void) +: _imageScale(1), _imagePadding(0), _title(nullptr), _prompt(nullptr) {} + +void ImageScreen::draw(Context &ctx, bool active) const { + _newLayer(ctx, 0, 0, ctx.gpuCtx.width, ctx.gpuCtx.height); + + if (_image.width && _image.height) { + int x = ctx.gpuCtx.width / 2; + int y = ctx.gpuCtx.height / 2; + int width = _image.width * _imageScale / 2; + int height = _image.height * _imageScale / 2; + + if (_prompt) + y -= (SCREEN_PROMPT_HEIGHT - gpu::FONT_LINE_HEIGHT) / 2; + + // Backdrop + if (_imagePadding) { + width += _imagePadding; + height += _imagePadding; + + ctx.gpuCtx.drawRect( + x - width, y - height, width * 2, height * 2, _backdropColor + ); + } + + // Image + width += 1; + height += 1; + + _image.drawScaled( + ctx.gpuCtx, x - width, y - height, width * 2, height * 2 + ); + } + + // Text + gpu::Rect rect; + + rect.x1 = SCREEN_MARGIN_X; + rect.y1 = SCREEN_MARGIN_Y; + rect.x2 = ctx.gpuCtx.width - SCREEN_MARGIN_X; + rect.y2 = SCREEN_MARGIN_Y + gpu::FONT_LINE_HEIGHT; + ctx.font.draw(ctx.gpuCtx, _title, rect, COLOR_TITLE); + + rect.y1 = ctx.gpuCtx.height - (SCREEN_MARGIN_Y + SCREEN_PROMPT_HEIGHT); + rect.y2 = ctx.gpuCtx.height - SCREEN_MARGIN_Y; + ctx.font.draw(ctx.gpuCtx, _prompt, rect, COLOR_TEXT1, true); +} + +ListScreen::ListScreen(void) +: _listLength(0), _prompt(nullptr) {} + +void ListScreen::_drawItems(Context &ctx) const { + int itemY = _scrollAnim.getValue(ctx.time); + int itemWidth = _getItemWidth(ctx); + int listHeight = _getListHeight(ctx); + + gpu::Rect rect; + + rect.x1 = LIST_BOX_PADDING + LIST_ITEM_PADDING; + rect.x2 = itemWidth - LIST_ITEM_PADDING; + rect.y2 = listHeight; + + for (int i = 0; (i < _listLength) && (itemY < listHeight); i++) { + int itemHeight = gpu::FONT_LINE_HEIGHT + LIST_ITEM_PADDING * 2; + if (i == _activeItem) + itemHeight += gpu::FONT_LINE_HEIGHT; + + if ((itemY + itemHeight) >= 0) { + if (i == _activeItem) { + ctx.gpuCtx.drawRect( + LIST_BOX_PADDING, itemY, itemWidth, itemHeight, + COLOR_HIGHLIGHT2 + ); + ctx.gpuCtx.drawRect( + LIST_BOX_PADDING, itemY, _itemAnim.getValue(ctx.time), + itemHeight, COLOR_HIGHLIGHT1 + ); + + rect.y1 = itemY + LIST_ITEM_PADDING + gpu::FONT_LINE_HEIGHT; + ctx.font.draw(ctx.gpuCtx, _itemPrompt, rect, COLOR_SUBTITLE); + } + + rect.y1 = itemY + LIST_ITEM_PADDING; + ctx.font.draw(ctx.gpuCtx, _getItemName(ctx, i), rect, COLOR_TITLE); + } + + itemY += itemHeight; + } +} + +void ListScreen::show(Context &ctx, bool goBack) { + AnimatedScreen::show(ctx, goBack); + + _activeItem = 0; + _scrollAnim.setValue(LIST_BOX_PADDING); + _itemAnim.setValue(_getItemWidth(ctx)); +} + +void ListScreen::draw(Context &ctx, bool active) const { + int screenWidth = ctx.gpuCtx.width - SCREEN_MARGIN_X * 2; + int screenHeight = ctx.gpuCtx.height - SCREEN_MARGIN_Y * 2; + int listHeight = _getListHeight(ctx); + + _newLayer( + ctx, SCREEN_MARGIN_X, SCREEN_MARGIN_Y, screenWidth, screenHeight + ); + + // Text + gpu::Rect rect; + + rect.x1 = 0; + rect.y1 = 0; + rect.x2 = screenWidth; + rect.y2 = gpu::FONT_LINE_HEIGHT; + ctx.font.draw(ctx.gpuCtx, _title, rect, COLOR_TITLE); + + rect.y1 = screenHeight - SCREEN_PROMPT_HEIGHT; + rect.y2 = screenHeight; + ctx.font.draw(ctx.gpuCtx, _prompt, rect, COLOR_TEXT1, true); + + _newLayer( + ctx, SCREEN_MARGIN_X, + SCREEN_MARGIN_Y + gpu::FONT_LINE_HEIGHT + SCREEN_BLOCK_MARGIN, + screenWidth, listHeight + ); + _setBlendMode(ctx, GP0_BLEND_SEMITRANS, true); + + // List box + ctx.gpuCtx.drawRect(0, 0, screenWidth / 2, listHeight, COLOR_BOX1); + ctx.gpuCtx.drawGradientRectH( + screenWidth / 2, 0, screenWidth / 2, listHeight, COLOR_BOX1, COLOR_BOX2 + ); + + if (_listLength) { + _drawItems(ctx); + + // Up/down arrow icons + gpu::RectWH iconRect; + + iconRect.x = screenWidth - (gpu::FONT_LINE_HEIGHT + LIST_BOX_PADDING); + iconRect.w = gpu::FONT_LINE_HEIGHT; + iconRect.h = gpu::FONT_LINE_HEIGHT; + + if (_activeItem) { + iconRect.y = LIST_BOX_PADDING; + ctx.font.draw(ctx.gpuCtx, CH_UP_ARROW, iconRect, COLOR_TEXT1); + } + if (_activeItem < (_listLength - 1)) { + iconRect.y = listHeight - (gpu::FONT_LINE_HEIGHT + LIST_BOX_PADDING); + ctx.font.draw(ctx.gpuCtx, CH_DOWN_ARROW, iconRect, COLOR_TEXT1); + } + } +} + +void ListScreen::update(Context &ctx) { + if ( + ctx.buttons.pressed(ui::BTN_LEFT) || + (ctx.buttons.repeating(ui::BTN_LEFT) && (_activeItem > 0)) + ) { + _activeItem--; + if (_activeItem < 0) { + _activeItem += _listLength; + ctx.sounds[SOUND_CLICK].play(); + } else { + ctx.sounds[SOUND_MOVE].play(); + } + + _itemAnim.setValue(ctx.time, 0, _getItemWidth(ctx), SPEED_FAST); + + } + if ( + ctx.buttons.pressed(ui::BTN_RIGHT) || + (ctx.buttons.repeating(ui::BTN_RIGHT) && (_activeItem < (_listLength - 1))) + ) { + _activeItem++; + if (_activeItem >= _listLength) { + _activeItem -= _listLength; + ctx.sounds[SOUND_CLICK].play(); + } else { + ctx.sounds[SOUND_MOVE].play(); + } + + _itemAnim.setValue(ctx.time, 0, _getItemWidth(ctx), SPEED_FAST); + } + + // Scroll the list if the selected item is not fully visible. + int itemHeight = gpu::FONT_LINE_HEIGHT + LIST_ITEM_PADDING * 2; + int activeItemHeight = itemHeight + gpu::FONT_LINE_HEIGHT; + + int topOffset = _activeItem * itemHeight; + int bottomOffset = topOffset + activeItemHeight - _getListHeight(ctx); + int currentOffset = -_scrollAnim.getTargetValue(); + + if (topOffset < currentOffset) + _scrollAnim.setValue(ctx.time, LIST_BOX_PADDING - topOffset, SPEED_FAST); + else if (bottomOffset > currentOffset) + _scrollAnim.setValue(ctx.time, -(LIST_BOX_PADDING + bottomOffset), SPEED_FAST); +} + +HexEntryScreen::HexEntryScreen(void) +: _title(nullptr), _prompt(nullptr) {} + +void HexEntryScreen::draw(Context &ctx, bool active) const { + int screenWidth = ctx.gpuCtx.width - SCREEN_MARGIN_X * 2; + int screenHeight = ctx.gpuCtx.height - SCREEN_MARGIN_Y * 2; + + _newLayer( + ctx, SCREEN_MARGIN_X, SCREEN_MARGIN_Y, screenWidth, screenHeight + ); + + /*gpu::RectWH rect; + + rect.x = 0; + rect.y = 0; + rect.w = screenWidth; + rect.h = gpu::FONT_LINE_HEIGHT; + ctx.font.draw(ctx.gpuCtx, _title, rect, COLOR_TITLE); + + rect.y = screenHeight - SCREEN_PROMPT_HEIGHT; + rect.h = SCREEN_PROMPT_HEIGHT; + ctx.font.draw(ctx.gpuCtx, _prompt, rect, COLOR_TEXT1, true);*/ +} + +void HexEntryScreen::update(Context &ctx) { +} + +} diff --git a/src/uicommon.hpp b/src/uicommon.hpp new file mode 100644 index 0000000..6197485 --- /dev/null +++ b/src/uicommon.hpp @@ -0,0 +1,120 @@ + +#pragma once + +#include "uibase.hpp" + +namespace ui { + +/* Common higher-level screens */ + +class PlaceholderScreen : public AnimatedScreen { +public: + void draw(Context &ctx, bool active) const; +}; + +class MessageScreen : public ModalScreen { +private: + util::Tween _buttonAnim; + + inline int _getButtonWidth(void) const { + return ((_width / 4) * 3) / _numButtons - BUTTON_SPACING; + } + +protected: + int _numButtons, _activeButton; + bool _locked; + + const char *_buttons[3]; + +public: + MessageScreen(void); + virtual void show(Context &ctx, bool goBack = false); + virtual void draw(Context &ctx, bool active = true) const; + virtual void update(Context &ctx); +}; + +class ProgressScreen : public ModalScreen { +private: + util::Tween _progressBarAnim; + +protected: + inline void _setProgress(Context &ctx, int part, int total) { + int totalWidth = _width - MODAL_PADDING * 2; + int partWidth = (totalWidth * part) / total; + + if (_progressBarAnim.getTargetValue() != partWidth) + _progressBarAnim.setValue(ctx.time, partWidth, SPEED_FASTEST); + } + +public: + ProgressScreen(void); + virtual void show(Context &ctx, bool goBack = false); + virtual void draw(Context &ctx, bool active = true) const; +}; + +class TextScreen : public AnimatedScreen { +protected: + const char *_title, *_body, *_prompt; + +public: + TextScreen(void); + virtual void draw(Context &ctx, bool active = true) const; +}; + +class ImageScreen : public AnimatedScreen { +protected: + gpu::Image _image; + int _imageScale, _imagePadding; + gpu::Color _backdropColor; + + const char *_title, *_prompt; + +public: + ImageScreen(void); + virtual void draw(Context &ctx, bool active = true) const; +}; + +class ListScreen : public AnimatedScreen { +private: + util::Tween _scrollAnim, _itemAnim; + + inline int _getItemWidth(Context &ctx) const { + return ctx.gpuCtx.width - (SCREEN_MARGIN_X + LIST_BOX_PADDING) * 2; + } + inline int _getListHeight(Context &ctx) const { + int screenHeight = ctx.gpuCtx.height - SCREEN_MARGIN_Y * 2; + return screenHeight - + (gpu::FONT_LINE_HEIGHT + SCREEN_PROMPT_HEIGHT + SCREEN_BLOCK_MARGIN * 2); + } + + void _drawItems(Context &ctx) const; + +protected: + int _listLength, _activeItem; + + const char *_title, *_prompt, *_itemPrompt; + + virtual const char *_getItemName(ui::Context &ctx, int index) const { + return nullptr; + } + +public: + ListScreen(void); + virtual void show(Context &ctx, bool goBack = false); + virtual void draw(Context &ctx, bool active = true) const; + virtual void update(Context &ctx); +}; + +class HexEntryScreen : public AnimatedScreen { +protected: + uint8_t _buffer[16]; + + const char *_title, *_prompt; + +public: + HexEntryScreen(void); + virtual void draw(Context &ctx, bool active = true) const; + virtual void update(Context &ctx); +}; + +} diff --git a/src/util.cpp b/src/util.cpp new file mode 100644 index 0000000..67fdca4 --- /dev/null +++ b/src/util.cpp @@ -0,0 +1,159 @@ + +#include +#include +#include +#include +#include +#include "ps1/registers.h" +#include "ps1/system.h" +#include "vendor/qrcodegen.h" +#include "util.hpp" + +namespace util { + +/* String hashing */ + +Hash hash(const char *str, char terminator) { + auto _str = reinterpret_cast(str); + Hash value = 0; + + while (*_str && (*_str != terminator)) + value = Hash(*(_str++)) + (value << 6) + (value << 16) - value; + + return value; +} + +Hash hash(const uint8_t *data, size_t length) { + Hash value = 0; + + for (; length; length--) + value = Hash(*(data++)) + (value << 6) + (value << 16) - value; + + return value; +} + +/* Logger */ + +// Global state, I know, but it's a necessary evil. +Logger logger; + +Logger::Logger(void) +: _tail(0), enableSyslog(false) { + clear(); +} + +void Logger::clear(void) { + for (int i = 0; i < MAX_LOG_LINES; i++) + _lines[i][0] = 0; +} + +void Logger::log(const char *format, ...) { + auto mask = setInterruptMask(0); + + size_t tail = _tail; + va_list ap; + + _tail = size_t(tail + 1) % MAX_LOG_LINES; + + va_start(ap, format); + vsnprintf(_lines[tail], MAX_LOG_LINE_LENGTH, format, ap); + va_end(ap); + + if (enableSyslog) + puts(_lines[tail]); + if (mask) + setInterruptMask(mask); +} + +/* CRC calculation */ + +static constexpr uint16_t _CRC8_POLY = 0x8c; +static constexpr uint16_t _CRC16_POLY = 0x1021; + +uint8_t dsCRC8(const uint8_t *data, size_t length) { + uint8_t crc = 0; + + for (; length; length--) { + uint8_t value = *(data++); + + for (int bit = 8; bit; bit--) { + uint8_t temp = crc ^ value; + + value >>= 1; + crc >>= 1; + if (temp & 1) + crc ^= _CRC8_POLY; + } + } + + return crc & 0xff; +} + +uint16_t zsCRC16(const uint8_t *data, size_t length) { + uint16_t crc = 0xffff; + + for (; length; length--) { + crc ^= *(data++) << 8; + + for (int bit = 8; bit; bit--) { + uint16_t temp = crc; + + crc <<= 1; + if (temp & 0x8000) + crc ^= _CRC16_POLY; + } + } + + return (crc ^ 0xffff) & 0xffff; +} + +/* String manipulation */ + +static const char HEX_CHARSET[] = "0123456789ABCDEF"; + +size_t hexToString(char *output, const uint8_t *input, size_t length, char sep) { + size_t outLength = 0; + + for (; length; length--) { + uint8_t value = *(input++); + + *(output++) = HEX_CHARSET[value >> 4]; + *(output++) = HEX_CHARSET[value & 0xf]; + + if (sep && (length > 1)) { + *(output++) = sep; + outLength += 3; + } else { + outLength += 2; + } + } + + *output = 0; + return outLength; +} + +size_t serialNumberToString(char *output, const uint8_t *input) { + uint32_t value = input[0] | (input[1] << 8) | (input[2] << 16) | (input[3] << 24); + + return sprintf(output, "%04d-%04d", (value / 10000) % 10000, value % 10000); +} + +// https://datatracker.ietf.org/doc/rfc9285 +size_t encodeBase45(char *output, const uint8_t *input, size_t length) { + size_t outLength = 0; + + for (int i = length + 1; i > 0; i -= 2) { + int value = *(input++) << 8; + value |= *(input++); + + *(output++) = qrcodegen_ALPHANUMERIC_CHARSET[value % 45]; + *(output++) = qrcodegen_ALPHANUMERIC_CHARSET[(value / 45) % 45]; + *(output++) = qrcodegen_ALPHANUMERIC_CHARSET[value / 2025]; + outLength += 3; + } + + *output = 0; + return outLength; +} + +} diff --git a/src/util.hpp b/src/util.hpp new file mode 100644 index 0000000..4136c92 --- /dev/null +++ b/src/util.hpp @@ -0,0 +1,229 @@ + +#pragma once + +#include +#include +#include "ps1/system.h" + +namespace util { + +/* Misc. template utilities */ + +template static inline T min(T a, T b) { + return (a < b) ? a : b; +} + +template static inline T max(T a, T b) { + return (a > b) ? a : b; +} + +template static inline T clamp(T value, T minValue, T maxValue) { + return (value < minValue) ? minValue : + ((value > maxValue) ? maxValue : value); +} + +// These shall only be used with unsigned types. +template static inline T truncateToMultiple(T value, T length) { + return value - (value % length); +} + +template static inline T roundUpToMultiple(T value, T length) { + T diff = value % length; + return diff ? (value - diff + length) : value; +} + +static inline uint16_t swapEndian(uint16_t value) { + value = ((value & 0x00ff) << 8) | ((value & 0xff00) >> 8); + + return value; +} + +static inline uint32_t swapEndian(uint32_t value) { + value = ((value & 0x0000ffff) << 16) | ((value & 0xffff0000) >> 16); + value = ((value & 0x00ff00ff) << 8) | ((value & 0xff00ff00) >> 8); + + return value; +} + +template static constexpr inline T forcedCast(X item) { + return reinterpret_cast(reinterpret_cast(item)); +} + +/* String hashing (http://www.cse.yorku.ca/~oz/hash.html) */ + +using Hash = uint32_t; + +template static constexpr inline Hash hash( + const T *const data, size_t length = -1, Hash value = 0 +) { + if (*data && length) + return hash( + &data[1], length - 1, + Hash(*data) + (value << 6) + (value << 16) - value + ); + + return value; +} + +Hash hash(const char *str, char terminator = 0); +Hash hash(const uint8_t *data, size_t length); + +/* Simple ring buffer */ + +template class RingBuffer { +private: + T _items[N]; + size_t _head, _tail; + +public: + size_t length; + + inline RingBuffer(void) + : _head(0), _tail(0), length(0) {} + + inline T *pushItem(void) volatile { + if (length >= N) + return nullptr; + + size_t i = _tail; + _tail = (i + 1) % N; + length++; + + return &_items[i]; + } + inline T *popItem(void) volatile { + if (!length) + return nullptr; + + size_t i = _head; + _head = (i + 1) % N; + length--; + + return &_items[i]; + } + inline T *peekItem(void) const { + if (!length) + return nullptr; + + return &_items[_head]; + } +}; + +/* Tween/animation classes */ + +static constexpr int TWEEN_UNIT = 1 << 12; + +class LinearEasing { +public: + template static inline T apply(T value) { + return value; + } +}; + +class QuadInEasing { +public: + template static inline T apply(T value) { + return (value * value) / TWEEN_UNIT; + } +}; + +class QuadOutEasing { +public: + template static inline T apply(T value) { + return (value * 2) - ((value * value) / TWEEN_UNIT); + } +}; + +template class Tween { +private: + T _base, _delta; + int _endTime, _timeScale; + +public: + inline Tween(void) { + setValue(static_cast(0)); + } + inline Tween(T start) { + setValue(start); + } + + inline T getValue(int time) const { + int remaining = time - _endTime; + if (remaining >= 0) + return _base + _delta; + + return _base + ( + _delta * E::apply(remaining * _timeScale + TWEEN_UNIT) + ) / TWEEN_UNIT; + } + inline T getTargetValue(void) const { + return _base + _delta; + } + inline bool isDone(int time) const { + return time >= _endTime; + } + + inline void setValue(int time, T start, T target, int duration) { + //assert(duration <= 0x800); + + _base = start; + _delta = target - start; + + _endTime = time + duration; + _timeScale = TWEEN_UNIT / duration; + } + inline void setValue(int time, T target, int duration) { + setValue(time, getValue(time), target, duration); + } + inline void setValue(T target) { + _base = target; + _delta = static_cast(0); + _endTime = 0; + } +}; + +/* Logger (basically a ring buffer of lines) */ + +static constexpr int MAX_LOG_LINE_LENGTH = 128; +static constexpr int MAX_LOG_LINES = 32; + +class Logger { +private: + char _lines[MAX_LOG_LINES][MAX_LOG_LINE_LENGTH]; + int _tail; + +public: + bool enableSyslog; + + // 0 = last line, 1 = second to last, etc. + inline const char *getLine(int line) const { + return _lines[size_t(_tail - (line + 1)) % MAX_LOG_LINES]; + } + + Logger(void); + void clear(void); + void log(const char *format, ...); +}; + +extern Logger logger; + +/* Other APIs */ + +uint8_t dsCRC8(const uint8_t *data, size_t length); +uint16_t zsCRC16(const uint8_t *data, size_t length); + +size_t hexToString(char *output, const uint8_t *input, size_t length, char sep = 0); +size_t serialNumberToString(char *output, const uint8_t *input); +size_t encodeBase45(char *output, const uint8_t *input, size_t length); + +} + +//#define LOG(...) util::logger.log(__VA_ARGS__) +#define LOG(fmt, ...) \ + util::logger.log("%s(%d): " fmt, __func__, __LINE__ __VA_OPT__(,) __VA_ARGS__) + +static constexpr inline util::Hash operator""_h( + const char *const literal, size_t length +) { + return util::hash(literal, length); +} diff --git a/src/vendor/miniz.c b/src/vendor/miniz.c new file mode 100644 index 0000000..db00f8c --- /dev/null +++ b/src/vendor/miniz.c @@ -0,0 +1,7833 @@ +#include "miniz.h" +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * 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. + * + **************************************************************************/ + + + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- zlib-style API's */ + +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) +{ + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); + size_t block_len = buf_len % 5552; + if (!ptr) + return MZ_ADLER32_INIT; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + return (s2 << 16) + s1; +} + +/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ +#if 0 + mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) + { + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) + return MZ_CRC32_INIT; + crcu32 = ~crcu32; + while (buf_len--) + { + mz_uint8 b = *ptr++; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; + } + return ~crcu32; + } +#elif defined(USE_EXTERNAL_MZCRC) +/* If USE_EXTERNAL_CRC is defined, an external module will export the + * mz_crc32() symbol for us to use, e.g. an SSE-accelerated version. + * Depending on the impl, it may be necessary to ~ the input/output crc values. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len); +#else +/* Faster, but larger CPU cache footprint. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) +{ + static const mz_uint32 s_crc_table[256] = + { + 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 + }; + + mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; + const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; + + while (buf_len >= 4) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; + pByte_buf += 4; + buf_len -= 4; + } + + while (buf_len) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + ++pByte_buf; + --buf_len; + } + + return ~crc32; +} +#endif + +void mz_free(void *p) +{ + MZ_FREE(p); +} + +MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) +{ + (void)opaque, (void)items, (void)size; + return MZ_MALLOC(items * size); +} +MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address) +{ + (void)opaque, (void)address; + MZ_FREE(address); +} +MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) +{ + (void)opaque, (void)address, (void)items, (void)size; + return MZ_REALLOC(address, items * size); +} + +const char *mz_version(void) +{ + return MZ_VERSION; +} + +#ifndef MINIZ_NO_ZLIB_APIS + +#ifndef MINIZ_NO_DEFLATE_APIS + +int mz_deflateInit(mz_streamp pStream, int level) +{ + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); +} + +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) +{ + tdefl_compressor *pComp; + mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) + return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; +} + +int mz_deflateReset(mz_streamp pStream) +{ + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) + return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); + return MZ_OK; +} + +int mz_deflate(mz_streamp pStream, int flush) +{ + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) + return MZ_STREAM_ERROR; + if (!pStream->avail_out) + return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; + orig_total_out = pStream->total_out; + for (;;) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; /* Can't make forward progress without some input. + */ + } + } + return mz_status; +} + +int mz_deflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) +{ + (void)pStream; + /* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */ + return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); +} + +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) +{ + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((mz_uint64)(source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) + return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); +} + +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); +} + +mz_ulong mz_compressBound(mz_ulong source_len) +{ + return mz_deflateBound(NULL, source_len); +} + +#endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ + +#ifndef MINIZ_NO_INFLATE_APIS + +typedef struct +{ + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; + int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; +} inflate_state; + +int mz_inflateInit2(mz_streamp pStream, int window_bits) +{ + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); + if (!pDecomp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; +} + +int mz_inflateInit(mz_streamp pStream) +{ + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +} + +int mz_inflateReset(mz_streamp pStream) +{ + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + + pDecomp = (inflate_state *)pStream->state; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + /* pDecomp->m_window_bits = window_bits */; + + return MZ_OK; +} + +int mz_inflate(mz_streamp pStream, int flush) +{ + inflate_state *pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) + return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + + pState = (inflate_state *)pStream->state; + if (pState->m_window_bits > 0) + decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; + pState->m_first_call = 0; + if (pState->m_last_status < 0) + return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + /* flush != MZ_FINISH then we must assume there's more input. */ + if (flush != MZ_FINISH) + decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for (;;) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ + else if (flush == MZ_FINISH) + { + /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; +} + +int mz_inflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} +int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong *pSource_len) +{ + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((mz_uint64)(*pSource_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)*pSource_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + *pSource_len = *pSource_len - stream.avail_in; + if (status != MZ_STREAM_END) + { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); +} + +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_uncompress2(pDest, pDest_len, pSource, &source_len); +} + +#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ + +const char *mz_error(int err) +{ + static struct + { + int m_err; + const char *m_pDesc; + } s_error_descs[] = + { + { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } + }; + mz_uint i; + for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) + if (s_error_descs[i].m_err == err) + return s_error_descs[i].m_pDesc; + return NULL; +} + +#endif /*MINIZ_NO_ZLIB_APIS */ + +#ifdef __cplusplus +} +#endif + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + 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 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. + + For more information, please refer to +*/ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * 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 MINIZ_NO_DEFLATE_APIS + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- Low-level Compression (independent from all decompression API's) */ + +/* Purposely making these tables static for faster init and thread safety. */ +static const mz_uint16 s_tdefl_len_sym[256] = + { + 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, + 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, + 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, + 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285 + }; + +static const mz_uint8 s_tdefl_len_extra[256] = + { + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 + }; + +static const mz_uint8 s_tdefl_small_dist_sym[512] = + { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 + }; + +static const mz_uint8 s_tdefl_small_dist_extra[512] = + { + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7 + }; + +static const mz_uint8 s_tdefl_large_dist_sym[128] = + { + 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 + }; + +static const mz_uint8 s_tdefl_large_dist_extra[128] = + { + 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 + }; + +/* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. */ +typedef struct +{ + mz_uint16 m_key, m_sym_index; +} tdefl_sym_freq; +static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) +{ + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; + tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; + MZ_CLEAR_ARR(hist); + for (i = 0; i < num_syms; i++) + { + mz_uint freq = pSyms0[i].m_key; + hist[freq & 0xFF]++; + hist[256 + ((freq >> 8) & 0xFF)]++; + } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) + total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + { + const mz_uint32 *pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) + { + offsets[i] = cur_ofs; + cur_ofs += pHist[i]; + } + for (i = 0; i < num_syms; i++) + pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; + { + tdefl_sym_freq *t = pCur_syms; + pCur_syms = pNew_syms; + pNew_syms = t; + } + } + return pCur_syms; +} + +/* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. */ +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) +{ + int root, leaf, next, avbl, used, dpth; + if (n == 0) + return; + else if (n == 1) + { + A[0].m_key = 1; + return; + } + A[0].m_key += A[1].m_key; + root = 0; + leaf = 2; + for (next = 1; next < n - 1; next++) + { + if (leaf >= n || A[root].m_key < A[leaf].m_key) + { + A[next].m_key = A[root].m_key; + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = A[leaf++].m_key; + if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) + { + A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); + } + A[n - 2].m_key = 0; + for (next = n - 3; next >= 0; next--) + A[next].m_key = A[A[next].m_key].m_key + 1; + avbl = 1; + used = dpth = 0; + root = n - 2; + next = n - 1; + while (avbl > 0) + { + while (root >= 0 && (int)A[root].m_key == dpth) + { + used++; + root--; + } + while (avbl > used) + { + A[next--].m_key = (mz_uint16)(dpth); + avbl--; + } + avbl = 2 * used; + dpth++; + used = 0; + } +} + +/* Limits canonical Huffman code table's max code size. */ +enum +{ + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 +}; +static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) +{ + int i; + mz_uint32 total = 0; + if (code_list_len <= 1) + return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) + pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) + total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) + if (pNum_codes[i]) + { + pNum_codes[i]--; + pNum_codes[i + 1] += 2; + break; + } + total--; + } +} + +static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) +{ + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; + mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; + MZ_CLEAR_ARR(num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) + num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) + if (pSym_count[i]) + { + syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; + syms0[num_used_syms++].m_sym_index = (mz_uint16)i; + } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); + tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) + num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + + MZ_CLEAR_ARR(d->m_huff_code_sizes[table_num]); + MZ_CLEAR_ARR(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) + d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; + for (j = 0, i = 2; i <= code_size_limit; i++) + next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; + if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) + continue; + code = next_code[code_size]++; + for (l = code_size; l > 0; l--, code >>= 1) + rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } +} + +#define TDEFL_PUT_BITS(b, l) \ + do \ + { \ + mz_uint bits = b; \ + mz_uint len = l; \ + MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); \ + d->m_bits_in += len; \ + while (d->m_bits_in >= 8) \ + { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ + } \ + MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() \ + { \ + if (rle_repeat_count) \ + { \ + if (rle_repeat_count < 3) \ + { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) \ + packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } \ + else \ + { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 16; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ + } \ + rle_repeat_count = 0; \ + } \ + } + +#define TDEFL_RLE_ZERO_CODE_SIZE() \ + { \ + if (rle_z_count) \ + { \ + if (rle_z_count < 3) \ + { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ + while (rle_z_count--) \ + packed_code_sizes[num_packed_code_sizes++] = 0; \ + } \ + else if (rle_z_count <= 10) \ + { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 17; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } \ + else \ + { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 18; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ + } \ + rle_z_count = 0; \ + } \ + } + +static const mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + +static void tdefl_start_dynamic_block(tdefl_compressor *d) +{ + int num_lit_codes, num_dist_codes, num_bit_lengths; + mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) + if (d->m_huff_code_sizes[0][num_lit_codes - 1]) + break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) + if (d->m_huff_code_sizes[1][num_dist_codes - 1]) + break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; + num_packed_code_sizes = 0; + rle_z_count = 0; + rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); + packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) + if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) + break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); + TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) + TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; + MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) + TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + } +} + +static void tdefl_start_static_block(tdefl_compressor *d) +{ + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); +} + +static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) \ + { \ + bit_buffer |= (((mz_uint64)(b)) << bits_in); \ + bits_in += (l); \ + } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0]; + mz_uint match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + /* This sequence coaxes MSVC into using cmov's vs. jmp's. */ + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + memcpy(pOutput_buf, &bit_buffer, sizeof(mz_uint64)); + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; + num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; + num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS */ + +static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) +{ + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); +} + +static const mz_uint s_tdefl_num_probes[11]; + +static int tdefl_flush_block(tdefl_compressor *d, int flush) +{ + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + const mz_uint8 cmf = 0x78; + mz_uint8 flg, flevel = 3; + mz_uint header, i, mz_un = sizeof(s_tdefl_num_probes) / sizeof(mz_uint); + + /* Determine compression level by reversing the process in tdefl_create_comp_flags_from_zip_params() */ + for (i = 0; i < mz_un; i++) + if (s_tdefl_num_probes[i] == (d->m_flags & 0xFFF)) break; + + if (i < 2) + flevel = 0; + else if (i < 6) + flevel = 1; + else if (i == 6) + flevel = 2; + + header = cmf << 8 | (flevel << 6); + header += 31 - (header % 31); + flg = header & 0xFF; + + TDEFL_PUT_BITS(cmf, 8); + TDEFL_PUT_BITS(flg, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; + saved_bit_buf = d->m_bit_buffer; + saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + + /* If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. */ + if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) + { + mz_uint i; + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + /* Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. */ + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) + { + mz_uint i, a = d->m_adler32; + for (i = 0; i < 4; i++) + { + TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); + a <<= 8; + } + } + } + else + { + mz_uint i, z = 0; + TDEFL_PUT_BITS(0, 3); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, z ^= 0xFFFF) + { + TDEFL_PUT_BITS(z & 0xFFFF, 16); + } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; + d->m_total_lz_bytes = 0; + d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; +} + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#ifdef MINIZ_UNALIGNED_USE_MEMCPY +static mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8* p) +{ + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; +} +static mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16* p) +{ + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; +} +#else +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) +#define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p) +#endif +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD2(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + q = (const mz_uint16 *)(d->m_dict + probe_pos); + if (TDEFL_READ_UNALIGNED_WORD2(q) != s01) + continue; + p = s; + probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); + if (!probe_len) + { + *pMatch_dist = dist; + *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); + break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) + break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } +} +#else +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) + if (*p++ != *q++) + break; + if (probe_len > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = probe_len) == max_match_len) + return; + c0 = d->m_dict[pos + match_len]; + c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */ + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#ifdef MINIZ_UNALIGNED_USE_MEMCPY +static mz_uint32 TDEFL_READ_UNALIGNED_WORD32(const mz_uint8* p) +{ + mz_uint32 ret; + memcpy(&ret, p, sizeof(mz_uint32)); + return ret; +} +#else +#define TDEFL_READ_UNALIGNED_WORD32(p) *(const mz_uint32 *)(p) +#endif +static mz_bool tdefl_compress_fast(tdefl_compressor *d) +{ + /* Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. */ + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) + break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = TDEFL_READ_UNALIGNED_WORD32(pCur_dict) & 0xFFFFFF; + mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((TDEFL_READ_UNALIGNED_WORD32(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *)pCur_dict; + const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + memcpy(&pLZ_code_buf[1], &cur_match_dist, sizeof(cur_match_dist)); +#else + *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; +#endif + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + return MZ_TRUE; +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) +{ + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + d->m_huff_count[0][lit]++; +} + +static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) +{ + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); + d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; +} + +static mz_bool tdefl_compress_normal(tdefl_compressor *d) +{ + const mz_uint8 *pSrc = d->m_pSrc; + size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + /* Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. */ + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc ? pSrc + num_bytes_to_process : NULL; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + ins_pos++; + } + } + else + { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + /* Simple lazy/greedy parsing state machine. */ + len_to_move = 1; + cur_match_dist = 0; + cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); + cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; + while (cur_match_len < d->m_lookahead_size) + { + if (d->m_dict[cur_pos + cur_match_len] != c) + break; + cur_match_len++; + } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) + cur_match_len = 0; + else + cur_match_dist = 1; + } + } + else + { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; + d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + /* Move the lookahead forward by len_to_move bytes. */ + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); + /* Check if it's time to flush the current LZ codes to the internal output buffer. */ + if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) + { + int n; + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + return MZ_TRUE; +} + +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) +{ + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) +{ + if (!d) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; + d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; + d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); + d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) + { + MZ_CLEAR_ARR(d->m_hash); + MZ_CLEAR_ARR(d->m_next); + d->m_dict_size = 0; + } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); +} + +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) +{ + MZ_ASSERT(d->m_pPut_buf_func); + return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +} + +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + d->m_pPut_buf_func = pPut_buf_func; + d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); + d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; + d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_ARR(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + *d->m_pLZ_flags = 0; + d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; + d->m_pOutput_buf_end = d->m_output_buf; + d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; + d->m_adler32 = 1; + d->m_pIn_buf = NULL; + d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; + d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; + d->m_pSrc = NULL; + d->m_src_buf_left = 0; + d->m_out_buf_ofs = 0; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_ARR(d->m_dict); + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) +{ + return d->m_prev_return_status; +} + +mz_uint32 tdefl_get_adler32(tdefl_compressor *d) +{ + return d->m_adler32; +} + +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + tdefl_compressor *pComp; + mz_bool succeeded; + if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) + return MZ_FALSE; + pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + if (!pComp) + return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); + succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); + MZ_FREE(pComp); + return succeeded; +} + +typedef struct +{ + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; +} tdefl_output_buffer; + +static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) +{ + tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; + mz_uint8 *pNew_buf; + if (!p->m_expandable) + return MZ_FALSE; + do + { + new_capacity = MZ_MAX(128U, new_capacity << 1U); + } while (new_size > new_capacity); + pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); + if (!pNew_buf) + return MZ_FALSE; + p->m_pBuf = pNew_buf; + p->m_capacity = new_capacity; + } + memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); + p->m_size = new_size; + return MZ_TRUE; +} + +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) + return MZ_FALSE; + else + *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return NULL; + *pOut_len = out_buf.m_size; + return out_buf.m_pBuf; +} + +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) + return 0; + out_buf.m_pBuf = (mz_uint8 *)pOut_buf; + out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return 0; + return out_buf.m_size; +} + +static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + +/* level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). */ +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) +{ + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) + comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) + comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) + comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) + comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) + comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) + comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; +} + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4204) /* nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) */ +#endif + +/* Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at + http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. + This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. */ +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) +{ + /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. */ + static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + tdefl_output_buffer out_buf; + int i, bpl = w * num_chans, y, z; + mz_uint32 c; + *pLen_out = 0; + if (!pComp) + return NULL; + MZ_CLEAR_OBJ(out_buf); + out_buf.m_expandable = MZ_TRUE; + out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); + if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) + { + MZ_FREE(pComp); + return NULL; + } + /* write dummy header */ + for (z = 41; z; --z) + tdefl_output_buffer_putter(&z, 1, &out_buf); + /* compress image data */ + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) + { + tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); + tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); + } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) + { + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + /* write real header */ + *pLen_out = out_buf.m_size - 41; + { + static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 }; + mz_uint8 pnghdr[41] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, + 0x0a, 0x1a, 0x0a, 0x00, 0x00, + 0x00, 0x0d, 0x49, 0x48, 0x44, + 0x52, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x49, 0x44, 0x41, + 0x54 }; + pnghdr[18] = (mz_uint8)(w >> 8); + pnghdr[19] = (mz_uint8)w; + pnghdr[22] = (mz_uint8)(h >> 8); + pnghdr[23] = (mz_uint8)h; + pnghdr[25] = chans[num_chans]; + pnghdr[33] = (mz_uint8)(*pLen_out >> 24); + pnghdr[34] = (mz_uint8)(*pLen_out >> 16); + pnghdr[35] = (mz_uint8)(*pLen_out >> 8); + pnghdr[36] = (mz_uint8)*pLen_out; + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); + for (i = 0; i < 4; ++i, c <<= 8) + ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + /* write footer (IDAT CRC-32, followed by IEND chunk) */ + if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) + { + *pLen_out = 0; + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); + for (i = 0; i < 4; ++i, c <<= 8) + (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); + /* compute final size of file, grab compressed data buffer and return */ + *pLen_out += 57; + MZ_FREE(pComp); + return out_buf.m_pBuf; +} +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) +{ + /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) */ + return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); +} + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that */ +/* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tdefl_compressor *tdefl_compressor_alloc(void) +{ + return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); +} + +void tdefl_compressor_free(tdefl_compressor *pComp) +{ + MZ_FREE(pComp); +} +#endif + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ + /************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * 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 MINIZ_NO_INFLATE_APIS + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- Low-level Decompression (completely independent from all compression API's) */ + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN \ + switch (r->m_state) \ + { \ + case 0: +#define TINFL_CR_RETURN(state_index, result) \ + do \ + { \ + status = result; \ + r->m_state = state_index; \ + goto common_exit; \ + case state_index:; \ + } \ + MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) \ + do \ + { \ + for (;;) \ + { \ + TINFL_CR_RETURN(state_index, result); \ + } \ + } \ + MZ_MACRO_END +#define TINFL_CR_FINISH } + +#define TINFL_GET_BYTE(state_index, c) \ + do \ + { \ + while (pIn_buf_cur >= pIn_buf_end) \ + { \ + TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ + } \ + c = *pIn_buf_cur++; \ + } \ + MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) \ + do \ + { \ + mz_uint c; \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + b = bit_buf & ((1 << (n)) - 1); \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END + +/* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */ +/* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */ +/* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */ +/* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ +#define TINFL_HUFF_BITBUF_FILL(state_index, pLookUp, pTree) \ + do \ + { \ + temp = pLookUp[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) \ + { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } \ + else if (num_bits > TINFL_FAST_LOOKUP_BITS) \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = pTree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); \ + if (temp >= 0) \ + break; \ + } \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < 15); + +/* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */ +/* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */ +/* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */ +/* The slow path is only executed at the very end of the input buffer. */ +/* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */ +/* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */ +#define TINFL_HUFF_DECODE(state_index, sym, pLookUp, pTree) \ + do \ + { \ + int temp; \ + mz_uint code_len, c; \ + if (num_bits < 15) \ + { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) \ + { \ + TINFL_HUFF_BITBUF_FILL(state_index, pLookUp, pTree); \ + } \ + else \ + { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ + pIn_buf_cur += 2; \ + num_bits += 16; \ + } \ + } \ + if ((temp = pLookUp[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = pTree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while (temp < 0); \ + } \ + sym = temp; \ + bit_buf >>= code_len; \ + num_bits -= code_len; \ + } \ + MZ_MACRO_END + +static void tinfl_clear_tree(tinfl_decompressor *r) +{ + if (r->m_type == 0) + MZ_CLEAR_ARR(r->m_tree_0); + else if (r->m_type == 1) + MZ_CLEAR_ARR(r->m_tree_1); + else + MZ_CLEAR_ARR(r->m_tree_2); +} + +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) +{ + static const mz_uint16 s_length_base[31] = { 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, 0, 0 }; + static const mz_uint8 s_length_extra[31] = { 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, 0, 0 }; + static const mz_uint16 s_dist_base[32] = { 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, 0, 0 }; + static const mz_uint8 s_dist_extra[32] = { 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 }; + static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + static const mz_uint16 s_min_table_sizes[3] = { 257, 1, 4 }; + + mz_int16 *pTrees[3]; + mz_uint8 *pCode_sizes[3]; + + tinfl_status status = TINFL_STATUS_FAILED; + mz_uint32 num_bits, dist, counter, num_extra; + tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next ? pOut_buf_next + *pOut_buf_size : NULL; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */ + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) + { + *pIn_buf_size = *pOut_buf_size = 0; + return TINFL_STATUS_BAD_PARAM; + } + + pTrees[0] = r->m_tree_0; + pTrees[1] = r->m_tree_1; + pTrees[2] = r->m_tree_2; + pCode_sizes[0] = r->m_code_size_0; + pCode_sizes[1] = r->m_code_size_1; + pCode_sizes[2] = r->m_code_size_2; + + num_bits = r->m_num_bits; + bit_buf = r->m_bit_buf; + dist = r->m_dist; + counter = r->m_counter; + num_extra = r->m_num_extra; + dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; + r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); + TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)((size_t)1 << (8U + (r->m_zhdr0 >> 4))))); + if (counter) + { + TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); + } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); + r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) + { + if (num_bits) + TINFL_GET_BITS(6, r->m_raw_header[counter], 8); + else + TINFL_GET_BYTE(7, r->m_raw_header[counter]); + } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) + { + TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); + } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); + } + while (pIn_buf_cur >= pIn_buf_end) + { + TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); + pIn_buf_cur += n; + pOut_buf_cur += n; + counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_code_size_0; + mz_uint i; + r->m_table_sizes[0] = 288; + r->m_table_sizes[1] = 32; + TINFL_MEMSET(r->m_code_size_1, 5, 32); + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) + { + TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); + r->m_table_sizes[counter] += s_min_table_sizes[counter]; + } + MZ_CLEAR_ARR(r->m_code_size_2); + for (counter = 0; counter < r->m_table_sizes[2]; counter++) + { + mz_uint s; + TINFL_GET_BITS(14, s, 3); + r->m_code_size_2[s_length_dezigzag[counter]] = (mz_uint8)s; + } + r->m_table_sizes[2] = 19; + } + for (; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; + mz_int16 *pLookUp; + mz_int16 *pTree; + mz_uint8 *pCode_size; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; + pLookUp = r->m_look_up[r->m_type]; + pTree = pTrees[r->m_type]; + pCode_size = pCode_sizes[r->m_type]; + MZ_CLEAR_ARR(total_syms); + TINFL_MEMSET(pLookUp, 0, sizeof(r->m_look_up[0])); + tinfl_clear_tree(r); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) + total_syms[pCode_size[i]]++; + used_syms = 0, total = 0; + next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) + { + used_syms += total_syms[i]; + next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); + } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pCode_size[sym_index]; + if (!code_size) + continue; + cur_code = next_code[code_size]++; + for (l = code_size; l > 0; l--, cur_code >>= 1) + rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) + { + mz_int16 k = (mz_int16)((code_size << 9) | sym_index); + while (rev_code < TINFL_FAST_LOOKUP_SIZE) + { + pLookUp[rev_code] = k; + rev_code += (1 << code_size); + } + continue; + } + if (0 == (tree_cur = pLookUp[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) + { + pLookUp[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTree[-tree_cur - 1]) + { + pTree[-tree_cur - 1] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + else + tree_cur = pTree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); + pTree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) + { + mz_uint s; + TINFL_HUFF_DECODE(16, dist, r->m_look_up[2], r->m_tree_2); + if (dist < 16) + { + r->m_len_codes[counter++] = (mz_uint8)dist; + continue; + } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; + TINFL_GET_BITS(18, s, num_extra); + s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); + counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_code_size_0, r->m_len_codes, r->m_table_sizes[0]); + TINFL_MEMCPY(r->m_code_size_1, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for (;;) + { + mz_uint8 *pSrc; + for (;;) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, r->m_look_up[0], r->m_tree_0); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; + mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 4; + num_bits += 32; + } +#else + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_look_up[0][bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tree_0[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + counter = sym2; + bit_buf >>= code_len; + num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_look_up[0][bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tree_0[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + bit_buf >>= code_len; + num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) + break; + + num_extra = s_length_extra[counter - 257]; + counter = s_length_base[counter - 257]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(25, extra_bits, num_extra); + counter += extra_bits; + } + + TINFL_HUFF_DECODE(26, dist, r->m_look_up[1], r->m_tree_1); + num_extra = s_dist_extra[dist]; + dist = s_dist_base[dist]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(27, extra_bits, num_extra); + dist += extra_bits; + } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist == 0 || dist > dist_from_out_buf_start || dist_from_out_buf_start == 0) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { +#ifdef MINIZ_UNALIGNED_USE_MEMCPY + memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32)*2); +#else + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; +#endif + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + while(counter>2) + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; + pSrc += 3; + counter -= 3; + } + if (counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + + /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */ + TINFL_SKIP_BITS(32, num_bits & 7); + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + bit_buf &= ~(~(tinfl_bit_buf_t)0 << num_bits); + MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */ + + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + for (counter = 0; counter < 4; ++counter) + { + mz_uint s; + if (num_bits) + TINFL_GET_BITS(41, s, 8); + else + TINFL_GET_BYTE(42, s); + r->m_z_adler32 = (r->m_z_adler32 << 8) | s; + } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + + TINFL_CR_FINISH + +common_exit: + /* As long as we aren't telling the caller that we NEED more input to make forward progress: */ + /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */ + if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) + { + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + } + r->m_num_bits = num_bits; + r->m_bit_buf = bit_buf & ~(~(tinfl_bit_buf_t)0 << num_bits); + r->m_dist = dist; + r->m_counter = counter; + r->m_num_extra = num_extra; + r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; + *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; + size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; + size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; + if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) + status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +/* Higher level helper functions. */ +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tinfl_decompressor decomp; + void *pBuf = NULL, *pNew_buf; + size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for (;;) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) + break; + new_out_buf_capacity = out_buf_capacity * 2; + if (new_out_buf_capacity < 128) + new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + pBuf = pNew_buf; + out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tinfl_decompressor decomp; + tinfl_status status; + tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +} + +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); + size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + memset(pDict,0,TINFL_LZ_DICT_SIZE); + tinfl_init(&decomp); + for (;;) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +#ifndef MINIZ_NO_MALLOC +tinfl_decompressor *tinfl_decompressor_alloc(void) +{ + tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); + if (pDecomp) + tinfl_init(pDecomp); + return pDecomp; +} + +void tinfl_decompressor_free(tinfl_decompressor *pDecomp) +{ + MZ_FREE(pDecomp); +} +#endif + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ + /************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * Copyright 2016 Martin Raiber + * All Rights Reserved. + * + * 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 MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- .ZIP archive reading */ + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include + +#if defined(_MSC_VER) || defined(__MINGW64__) + +#define WIN32_LEAN_AND_MEAN +#include + +static WCHAR* mz_utf8z_to_widechar(const char* str) +{ + int reqChars = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); + WCHAR* wStr = (WCHAR*)malloc(reqChars * sizeof(WCHAR)); + MultiByteToWideChar(CP_UTF8, 0, str, -1, wStr, sizeof(WCHAR) * reqChars); + return wStr; +} + +static FILE *mz_fopen(const char *pFilename, const char *pMode) +{ + WCHAR* wFilename = mz_utf8z_to_widechar(pFilename); + WCHAR* wMode = mz_utf8z_to_widechar(pMode); + FILE* pFile = NULL; + errno_t err = _wfopen_s(&pFile, wFilename, wMode); + free(wFilename); + free(wMode); + return err ? NULL : pFile; +} + +static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) +{ + WCHAR* wPath = mz_utf8z_to_widechar(pPath); + WCHAR* wMode = mz_utf8z_to_widechar(pMode); + FILE* pFile = NULL; + errno_t err = _wfreopen_s(&pFile, wPath, wMode, pStream); + free(wPath); + free(wMode); + return err ? NULL : pFile; +} + +static int mz_stat64(const char *path, struct __stat64 *buffer) +{ + WCHAR* wPath = mz_utf8z_to_widechar(path); + int res = _wstat64(wPath, buffer); + free(wPath); + return res; +} + +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN mz_fopen +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 _ftelli64 +#define MZ_FSEEK64 _fseeki64 +#define MZ_FILE_STAT_STRUCT _stat64 +#define MZ_FILE_STAT mz_stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN mz_freopen +#define MZ_DELETE_FILE remove + +#elif defined(__MINGW32__) || defined(__WATCOMC__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 _ftelli64 +#define MZ_FSEEK64 _fseeki64 +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove + +#elif defined(__TINYC__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove + +#elif defined(__USE_LARGEFILE64) /* gcc, clang */ +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen64(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT stat64 +#define MZ_FILE_STAT stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen64(p, m, s) +#define MZ_DELETE_FILE remove + +#elif defined(__APPLE__) || defined(__FreeBSD__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen(p, m, s) +#define MZ_DELETE_FILE remove + +#else +#pragma message("Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.") +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#ifdef __STRICT_ANSI__ +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#else +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#endif +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#endif /* #ifdef _MSC_VER */ +#endif /* #ifdef MINIZ_NO_STDIO */ + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +/* Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. */ +enum +{ + /* ZIP archive identifiers and record sizes */ + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, + MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + + /* ZIP64 archive identifier and record sizes */ + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, + MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, + MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, + MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, + MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, + + /* Central directory header record offsets */ + MZ_ZIP_CDH_SIG_OFS = 0, + MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, + MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, + MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, + MZ_ZIP_CDH_FILE_TIME_OFS = 12, + MZ_ZIP_CDH_FILE_DATE_OFS = 14, + MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, + MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, + MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, + MZ_ZIP_CDH_DISK_START_OFS = 34, + MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, + MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + + /* Local directory header offsets */ + MZ_ZIP_LDH_SIG_OFS = 0, + MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, + MZ_ZIP_LDH_BIT_FLAG_OFS = 6, + MZ_ZIP_LDH_METHOD_OFS = 8, + MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, + MZ_ZIP_LDH_CRC32_OFS = 14, + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, + MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, + + /* End of central directory offsets */ + MZ_ZIP_ECDH_SIG_OFS = 0, + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, + MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, + MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, + MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, + + /* ZIP64 End of central directory locator offsets */ + MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ + + /* ZIP64 End of central directory header offsets */ + MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ + MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, + MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 +}; + +typedef struct +{ + void *m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; +} mz_zip_array; + +struct mz_zip_internal_state_tag +{ + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + + /* The flags passed in when the archive is initially opened. */ + mz_uint32 m_init_flags; + + /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. */ + mz_bool m_zip64; + + /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 will also be slammed to true too, even if we didn't find a zip64 end of central dir header, etc.) */ + mz_bool m_zip64_has_extended_info_fields; + + /* These fields are used by the file, FILE, memory, and memory/heap read/write helpers. */ + MZ_FILE *m_pFile; + mz_uint64 m_file_archive_start_ofs; + + void *m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; +}; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size + +#if defined(DEBUG) || defined(_DEBUG) +static MZ_FORCEINLINE mz_uint mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) +{ + MZ_ASSERT(index < pArray->m_size); + return index; +} +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[mz_zip_array_range_check(array_ptr, index)] +#else +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] +#endif + +static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray, mz_uint32 element_size) +{ + memset(pArray, 0, sizeof(mz_zip_array)); + pArray->m_element_size = element_size; +} + +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) +{ + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); +} + +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) +{ + void *pNew_p; + size_t new_capacity = min_new_capacity; + MZ_ASSERT(pArray->m_element_size); + if (pArray->m_capacity >= min_new_capacity) + return MZ_TRUE; + if (growing) + { + new_capacity = MZ_MAX(1, pArray->m_capacity); + while (new_capacity < min_new_capacity) + new_capacity *= 2; + } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) + return MZ_FALSE; + pArray->m_p = pNew_p; + pArray->m_capacity = new_capacity; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) +{ + if (new_capacity > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) + return MZ_FALSE; + } + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) +{ + if (new_size > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) + return MZ_FALSE; + } + pArray->m_size = new_size; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) +{ + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) +{ + size_t orig_size = pArray->m_size; + if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) + return MZ_FALSE; + if (n > 0) + memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) +{ + struct tm tm; + memset(&tm, 0, sizeof(tm)); + tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((dos_date >> 5) & 15) - 1; + tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; + tm.tm_min = (dos_time >> 5) & 63; + tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); +} + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef _MSC_VER + struct tm tm_struct; + struct tm *tm = &tm_struct; + errno_t err = localtime_s(tm, &time); + if (err) + { + *pDOS_date = 0; + *pDOS_time = 0; + return; + } +#else + struct tm *tm = localtime(&time); +#endif /* #ifdef _MSC_VER */ + + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +} +#endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifndef MINIZ_NO_STDIO +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static mz_bool mz_zip_get_file_modified_time(const char *pFilename, MZ_TIME_T *pTime) +{ + struct MZ_FILE_STAT_STRUCT file_stat; + + /* On Linux with x86 glibc, this call will fail on large files (I think >= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ + if (MZ_FILE_STAT(pFilename, &file_stat) != 0) + return MZ_FALSE; + + *pTime = file_stat.st_mtime; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/ + +static mz_bool mz_zip_set_file_times(const char *pFilename, MZ_TIME_T access_time, MZ_TIME_T modified_time) +{ + struct utimbuf t; + + memset(&t, 0, sizeof(t)); + t.actime = access_time; + t.modtime = modified_time; + + return !utime(pFilename, &t); +} +#endif /* #ifndef MINIZ_NO_STDIO */ +#endif /* #ifndef MINIZ_NO_TIME */ + +static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num) +{ + if (pZip) + pZip->m_last_error = err_num; + return MZ_FALSE; +} + +static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) +{ + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + pZip->m_last_error = MZ_ZIP_NO_ERROR; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + pZip->m_pState->m_init_flags = flags; + pZip->m_pState->m_zip64 = MZ_FALSE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); +} + +#define MZ_SWAP_UINT32(a, b) \ + do \ + { \ + mz_uint32 t = a; \ + a = b; \ + b = t; \ + } \ + MZ_MACRO_END + +/* Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) */ +static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices; + mz_uint32 start, end; + const mz_uint32 size = pZip->m_total_files; + + if (size <= 1U) + return; + + pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + + start = (size - 2U) >> 1U; + for (;;) + { + mz_uint64 child, root = start; + for (;;) + { + if ((child = (root << 1U) + 1U) >= size) + break; + child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + if (!start) + break; + start--; + } + + end = size - 1; + while (end > 0) + { + mz_uint64 child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for (;;) + { + if ((child = (root << 1U) + 1U) >= end) + break; + child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + end--; + } +} + +static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 record_sig, mz_uint32 record_size, mz_int64 *pOfs) +{ + mz_int64 cur_file_ofs; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + + /* Basic sanity checks - reject files which are too small */ + if (pZip->m_archive_size < record_size) + return MZ_FALSE; + + /* Find the record by scanning the file from the end towards the beginning. */ + cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for (;;) + { + int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + + for (i = n - 4; i >= 0; --i) + { + mz_uint s = MZ_READ_LE32(pBuf + i); + if (s == record_sig) + { + if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) + break; + } + } + + if (i >= 0) + { + cur_file_ofs += i; + break; + } + + /* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */ + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size))) + return MZ_FALSE; + + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + + *pOfs = cur_file_ofs; + return MZ_TRUE; +} + +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flags) +{ + mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, cdir_disk_index = 0; + mz_uint64 cdir_ofs = 0; + mz_int64 cur_file_ofs = 0; + const mz_uint8 *p; + + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); + mz_uint32 zip64_end_of_central_dir_locator_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32; + + mz_uint32 zip64_end_of_central_dir_header_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_end_of_central_dir = (mz_uint8 *)zip64_end_of_central_dir_header_u32; + + mz_uint64 zip64_end_of_central_dir_ofs = 0; + + /* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */ + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) + return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); + + /* Read and verify the end of central directory record. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + { + if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) + { + zip64_end_of_central_dir_ofs = MZ_READ_LE64(pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); + if (zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) + { + pZip->m_pState->m_zip64 = MZ_TRUE; + } + } + } + } + } + + pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); + cdir_entries_on_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + + if (pZip->m_pState->m_zip64) + { + mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); + mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); + mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); + mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); + + if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (zip64_total_num_of_disks != 1U) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + /* Check for miniz's practical limits */ + if (zip64_cdir_total_entries > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; + + if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk; + + /* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */ + if (zip64_size_of_central_directory > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + cdir_size = (mz_uint32)zip64_size_of_central_directory; + + num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); + + cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); + + cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); + } + + if (pZip->m_total_files != cdir_entries_on_this_disk) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (cdir_size < (mz_uint64)pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + mz_uint i, n; + /* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */ + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (sort_central_dir) + { + if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + /* Now create an index into the central directory file records, do some basic sanity checking on each record */ + p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size; + mz_uint64 comp_size, decomp_size, local_header_ofs; + + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + + if (sort_central_dir) + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && + (ext_data_size) && + (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX)) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = ext_data_size; + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data; + void* buf = NULL; + + if (MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + ext_data_size > n) + { + buf = MZ_MALLOC(ext_data_size); + if(buf==NULL) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size, buf, ext_data_size) != ext_data_size) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (mz_uint8*)buf; + } + else + { + pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; + } + + do + { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + { + MZ_FREE(buf); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + /* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */ + pZip->m_pState->m_zip64 = MZ_TRUE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + + MZ_FREE(buf); + } + } + + /* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */ + if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) + { + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (comp_size != MZ_UINT32_MAX) + { + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + n -= total_header_size; + p += total_header_size; + } + } + + if (sort_central_dir) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; +} + +void mz_zip_zero_struct(mz_zip_archive *pZip) +{ + if (pZip) + MZ_CLEAR_PTR(pZip); +} + +static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) +{ + mz_bool status = MZ_TRUE; + + if (!pZip) + return MZ_FALSE; + + if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; + + return MZ_FALSE; + } + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; + pZip->m_pState = NULL; + + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; + status = MZ_FALSE; + } + } + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return status; +} + +mz_bool mz_zip_reader_end(mz_zip_archive *pZip) +{ + return mz_zip_reader_end_internal(pZip, MZ_TRUE); +} +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags) +{ + if ((!pZip) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_archive_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); + return s; +} + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags) +{ + if (!pMem) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pNeeds_keepalive = NULL; + +#ifdef __cplusplus + pZip->m_pState->m_pMem = const_cast(pMem); +#else + pZip->m_pState->m_pMem = (void *)pMem; +#endif + + pZip->m_pState->m_mem_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) +{ + return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0); +} + +mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size) +{ + mz_uint64 file_size; + MZ_FILE *pFile; + + if ((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pFile = MZ_FOPEN(pFilename, "rb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + file_size = archive_size; + if (!file_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + } + + file_size = MZ_FTELL64(pFile); + } + + /* TODO: Better sanity check archive_size and the # of actual remaining bytes */ + + if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags) +{ + mz_uint64 cur_file_ofs; + + if ((!pZip) || (!pFile)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + cur_file_ofs = MZ_FTELL64(pFile); + + if (!archive_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + + archive_size = MZ_FTELL64(pFile) - cur_file_ofs; + + if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = archive_size; + pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index) +{ + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); +} + +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; +} + +mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint bit_flag; + mz_uint method; + + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); + bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + + if ((method != 0) && (method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + return MZ_FALSE; + } + + if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + return MZ_FALSE; + } + + if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint filename_len, attribute_mapping_id, external_attr; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + /* Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. */ + /* Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. */ + /* FIXME: Remove this check? Is it necessary - we already check the filename. */ + attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; + (void)attribute_mapping_id; + + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) + { + return MZ_TRUE; + } + + return MZ_FALSE; +} + +static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_index, const mz_uint8 *pCentral_dir_header, mz_zip_archive_file_stat *pStat, mz_bool *pFound_zip64_extra_data) +{ + mz_uint n; + const mz_uint8 *p = pCentral_dir_header; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_FALSE; + + if ((!p) || (!pStat)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Extract fields from the central directory record. */ + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + /* Copy as much of the filename and comment as possible. */ + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); + pStat->m_comment[n] = '\0'; + + /* Set some flags for convienance */ + pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); + pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); + pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); + + /* See if we need to read any zip64 extended information fields. */ + /* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */ + if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + + do + { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; + mz_uint32 field_data_remaining = field_data_size; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_TRUE; + + if (pStat->m_uncomp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_uncomp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_comp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_comp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_local_header_ofs == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + } + } + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) +{ + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; +} + +static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); +} + +static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename, mz_uint32 *pIndex) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const mz_uint32 size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + + if (pIndex) + *pIndex = 0; + + if (size) + { + /* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */ + /* honestly the major expense here on 32-bit CPU's will still be the filename compare */ + mz_int64 l = 0, h = (mz_int64)size - 1; + + while (l <= h) + { + mz_int64 m = l + ((h - l) >> 1); + mz_uint32 file_index = pIndices[(mz_uint32)m]; + + int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + if (!comp) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) +{ + mz_uint32 index; + if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) + return -1; + else + return (int)index; +} + +mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex) +{ + mz_uint file_index; + size_t name_len, comment_len; + + if (pIndex) + *pIndex = 0; + + if ((!pZip) || (!pZip->m_pState) || (!pName)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* See if we can use a binary search */ + if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && + (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && + ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) + { + return mz_zip_locate_file_binary_search(pZip, pName, pIndex); + } + + /* Locate the entry by scanning the entire central directory */ + name_len = strlen(pName); + if (name_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + comment_len = pComment ? strlen(pComment) : 0; + if (comment_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; + filename_len -= ofs; + } + if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +static +mz_bool mz_zip_reader_extract_to_mem_no_alloc1(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size, const mz_zip_archive_file_stat *st) +{ + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + tinfl_decompressor inflator; + + if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (st) { + file_stat = *st; + } else + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Ensure supplied output buffer is large enough. */ + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); + + /* Read and parse the local directory entry. */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) + { + if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + } +#endif + + return MZ_TRUE; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) + { + /* Read directly from the archive in memory. */ + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + /* Use a user provided read buffer. */ + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + else + { + /* Temporarily allocate a read buffer. */ + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + /* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */ + size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + return mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size, NULL); +} + +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size, NULL); +} + +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, buf_size, flags, NULL, 0, NULL); +} + +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); +} + +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + mz_uint64 alloc_size; + void *pBuf; + + if (pSize) + *pSize = 0; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return NULL; + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + return NULL; + } + + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + if (!mz_zip_reader_extract_to_mem_no_alloc1(pZip, file_index, pBuf, (size_t)alloc_size, flags, NULL, 0, &file_stat)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) + *pSize = (size_t)alloc_size; + return pBuf; +} + +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + { + if (pSize) + *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); +} + +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int status = TINFL_STATUS_DONE; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + mz_uint file_crc32 = MZ_CRC32_INIT; +#endif + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; + void *pWrite_buf = NULL; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pState->m_pMem) + { + if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + } + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); +#endif + } + + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + } +#endif + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + status = TINFL_STATUS_FAILED; + } + else + { + do + { + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); +#endif + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (file_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); +} + +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) +{ + mz_zip_reader_extract_iter_state *pState; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + /* Argument sanity check */ + if ((!pZip) || (!pZip->m_pState)) + return NULL; + + /* Allocate an iterator status structure */ + pState = (mz_zip_reader_extract_iter_state*)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state)); + if (!pState) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + /* Fetch file details */ + if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Encryption and patch files are not supported. */ + if (pState->file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (pState->file_stat.m_method != 0) && (pState->file_stat.m_method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Init state - save args */ + pState->pZip = pZip; + pState->flags = flags; + + /* Init state - reset variables to defaults */ + pState->status = TINFL_STATUS_DONE; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + pState->file_crc32 = MZ_CRC32_INIT; +#endif + pState->read_buf_ofs = 0; + pState->out_buf_ofs = 0; + pState->pRead_buf = NULL; + pState->pWrite_buf = NULL; + pState->out_blk_remain = 0; + + /* Read and parse the local directory entry. */ + pState->cur_file_ofs = pState->file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + pState->cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) > pZip->m_archive_size) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pState->pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + pState->cur_file_ofs; + pState->read_buf_size = pState->read_buf_avail = pState->file_stat.m_comp_size; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + else + { + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) + { + /* Decompression required, therefore intermediate read buffer required */ + pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)pState->read_buf_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + else + { + /* Decompression not required - we will be reading directly into user buffer, no temp buf required */ + pState->read_buf_size = 0; + } + pState->read_buf_avail = 0; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) + { + /* Decompression required, init decompressor */ + tinfl_init( &pState->inflator ); + + /* Allocate write buffer */ + if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + if (pState->pRead_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + + return pState; +} + +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) +{ + mz_uint32 file_index; + + /* Locate file index by name */ + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return NULL; + + /* Construct iterator */ + return mz_zip_reader_extract_iter_new(pZip, file_index, flags); +} + +size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size) +{ + size_t copied_to_caller = 0; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf)) + return 0; + + if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data, calc amount to return. */ + copied_to_caller = (size_t)MZ_MIN( buf_size, pState->comp_remaining ); + + /* Zip is in memory....or requires reading from a file? */ + if (pState->pZip->m_pState->m_pMem) + { + /* Copy data to caller's buffer */ + memcpy( pvBuf, pState->pRead_buf, copied_to_caller ); + pState->pRead_buf = ((mz_uint8*)pState->pRead_buf) + copied_to_caller; + } + else + { + /* Read directly into caller's buffer */ + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pvBuf, copied_to_caller) != copied_to_caller) + { + /* Failed to read all that was asked for, flag failure and alert user */ + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + copied_to_caller = 0; + } + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Compute CRC if not returning compressed data only */ + if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, (const mz_uint8 *)pvBuf, copied_to_caller); +#endif + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += copied_to_caller; + pState->out_buf_ofs += copied_to_caller; + pState->comp_remaining -= copied_to_caller; + } + else + { + do + { + /* Calc ptr to write buffer - given current output pos and block size */ + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pState->pWrite_buf + (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + /* Calc max output size - given current output pos and block size */ + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + if (!pState->out_blk_remain) + { + /* Read more data from file if none available (and reading from file) */ + if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem)) + { + /* Calc read size */ + pState->read_buf_avail = MZ_MIN(pState->read_buf_size, pState->comp_remaining); + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pState->pRead_buf, (size_t)pState->read_buf_avail) != pState->read_buf_avail) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += pState->read_buf_avail; + pState->comp_remaining -= pState->read_buf_avail; + pState->read_buf_ofs = 0; + } + + /* Perform decompression */ + in_buf_size = (size_t)pState->read_buf_avail; + pState->status = tinfl_decompress(&pState->inflator, (const mz_uint8 *)pState->pRead_buf + pState->read_buf_ofs, &in_buf_size, (mz_uint8 *)pState->pWrite_buf, pWrite_buf_cur, &out_buf_size, pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + pState->read_buf_avail -= in_buf_size; + pState->read_buf_ofs += in_buf_size; + + /* Update current output block size remaining */ + pState->out_blk_remain = out_buf_size; + } + + if (pState->out_blk_remain) + { + /* Calc amount to return. */ + size_t to_copy = MZ_MIN( (buf_size - copied_to_caller), pState->out_blk_remain ); + + /* Copy data to caller's buffer */ + memcpy( (mz_uint8*)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy ); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Perform CRC */ + pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy); +#endif + + /* Decrement data consumed from block */ + pState->out_blk_remain -= to_copy; + + /* Inc output offset, while performing sanity check */ + if ((pState->out_buf_ofs += to_copy) > pState->file_stat.m_uncomp_size) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Increment counter of data copied to caller */ + copied_to_caller += to_copy; + } + } while ( (copied_to_caller < buf_size) && ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) || (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT)) ); + } + + /* Return how many bytes were copied into user buffer */ + return copied_to_caller; +} + +mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState) +{ + int status; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState)) + return MZ_FALSE; + + /* Was decompression completed and requested? */ + if ((pState->status == TINFL_STATUS_DONE) && (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + pState->status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (pState->file_crc32 != pState->file_stat.m_crc32) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + } +#endif + } + + /* Free buffers */ + if (!pState->pZip->m_pState->m_pMem) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf); + if (pState->pWrite_buf) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf); + + /* Save status */ + status = pState->status; + + /* Free context */ + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState); + + return status == TINFL_STATUS_DONE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) +{ + (void)ofs; + + return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); +} + +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) +{ + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + + if (MZ_FCLOSE(pFile) == EOF) + { + if (status) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + + status = MZ_FALSE; + } + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + + return status; +} + +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); +} + +mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *pFile, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + return mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); +} + +mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_uint32 *p = (mz_uint32 *)pOpaque; + (void)file_ofs; + *p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n); + return n; +} + +mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + mz_zip_internal_state *pState; + const mz_uint8 *pCentral_dir_header; + mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint64 local_header_ofs = 0; + mz_uint32 local_header_filename_len, local_header_extra_len, local_header_crc32; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_uint32 uncomp_crc32 = MZ_CRC32_INIT; + mz_bool has_data_descriptor; + mz_uint32 local_header_bit_flags; + + mz_zip_array file_data_array; + mz_zip_array_init(&file_data_array, 1); + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (file_index > pZip->m_total_files) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); + + if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_uncomp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_is_encrypted) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports stored and deflate. */ + if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + if (!file_stat.m_is_supported) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + /* Read and parse the local directory entry. */ + local_header_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + local_header_filename_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS); + local_header_bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + has_data_descriptor = (local_header_bit_flags & 8) != 0; + + if (local_header_filename_len != strlen(file_stat.m_filename)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE)) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + goto handle_failure; + } + + if (local_header_filename_len) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + /* I've seen 1 archive that had the same pathname, but used backslashes in the local dir and forward slashes in the central dir. Do we care about this? For now, this case will fail validation. */ + if (memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_uint32 extra_size_remaining = local_header_extra_len; + const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + /* TODO: parse local header extra data when local_header_comp_size is 0xFFFFFFFF! (big_descriptor.zip) */ + /* I've seen zips in the wild with the data descriptor bit set, but proper local header values and bogus data descriptors */ + if ((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32)) + { + mz_uint8 descriptor_buf[32]; + mz_bool has_id; + const mz_uint8 *pSrc; + mz_uint32 file_crc32; + mz_uint64 comp_size = 0, uncomp_size = 0; + + mz_uint32 num_descriptor_uint32s = ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf; + + file_crc32 = MZ_READ_LE32(pSrc); + + if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); + } + else + { + comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); + } + + if ((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + else + { + if ((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + mz_zip_array_clear(pZip, &file_data_array); + + if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) + { + if (!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) + return MZ_FALSE; + + /* 1 more check to be sure, although the extract checks too. */ + if (uncomp_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + return MZ_FALSE; + } + } + + return MZ_TRUE; + +handle_failure: + mz_zip_array_clear(pZip, &file_data_array); + return MZ_FALSE; +} + +mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) +{ + mz_zip_internal_state *pState; + mz_uint32 i; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Basic sanity checks */ + if (!pState->m_zip64) + { + if (pZip->m_total_files > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pZip->m_archive_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + else + { + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + for (i = 0; i < pZip->m_total_files; i++) + { + if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) + { + mz_uint32 found_index; + mz_zip_archive_file_stat stat; + + if (!mz_zip_reader_file_stat(pZip, i, &stat)) + return MZ_FALSE; + + if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index)) + return MZ_FALSE; + + /* This check can fail if there are duplicate filenames in the archive (which we don't check for when writing - that's up to the user) */ + if (found_index != i) + return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + } + + if (!mz_zip_validate_file(pZip, i, flags)) + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr) +{ + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if ((!pMem) || (!size)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr) +{ + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if (!pFilename) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +/* ------------------- .ZIP archive writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v) +{ + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); +} +static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v) +{ + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); + p[2] = (mz_uint8)(v >> 16); + p[3] = (mz_uint8)(v >> 24); +} +static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v) +{ + mz_write_le32(p, (mz_uint32)v); + mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32)); +} + +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) +#define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v)) + +static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); + + if (!n) + return 0; + + /* An allocation this big is likely to just fail on 32-bit systems, so don't even go there. */ + if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + return 0; + } + + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); + + while (new_capacity < new_size) + new_capacity *= 2; + + if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return 0; + } + + pState->m_pMem = pNew_block; + pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; +} + +static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) +{ + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + status = MZ_FALSE; + } + } + + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; +} + +mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags) +{ + mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; + + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + { + if (!pZip->m_pRead) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (pZip->m_file_offset_alignment) + { + /* Ensure user specified file offset alignment is a power of 2. */ + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + + pZip->m_pState->m_zip64 = zip64; + pZip->m_pState->m_zip64_has_extended_info_fields = zip64; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) +{ + return mz_zip_writer_init_v2(pZip, existing_size, 0); +} + +mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags) +{ + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_mem_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; + + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + { + mz_zip_writer_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) +{ + return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, initial_allocation_size, 0); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + return 0; + } + + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) +{ + return mz_zip_writer_init_file_v2(pZip, pFilename, size_to_reserve_at_beginning, 0); +} + +mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags) +{ + MZ_FILE *pFile; + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + if (NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + + pZip->m_pState->m_pFile = pFile; + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; + char buf[4096]; + + MZ_CLEAR_ARR(buf); + + do + { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_ofs += n; + size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags) +{ + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, 0, flags)) + return MZ_FALSE; + + pZip->m_pState->m_pFile = pFile; + pZip->m_pState->m_file_archive_start_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) +{ + mz_zip_internal_state *pState; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) + { + /* We don't support converting a non-zip64 file to zip64 - this seems like more trouble than it's worth. (What about the existing 32-bit data descriptors that could follow the compressed data?) */ + if (!pZip->m_pState->m_zip64) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* No sense in trying to write to an archive that's already at the support max size */ + if (pZip->m_pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + (void)pFilename; + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); +#else + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (!pFilename) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Archive is being read from stdio and was originally opened only for reading. Try to reopen as writable. */ + if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + { + /* The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. */ + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + } + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; +#endif /* #ifdef MINIZ_NO_STDIO */ + } + else if (pState->m_pMem) + { + /* Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. */ + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + } + /* Archive is being read via a user provided read function - make sure the user has specified a write function too. */ + else if (!pZip->m_pWrite) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Start writing new files at the archive's current central directory location. */ + /* TODO: We could add a flag that lets the user start writing immediately AFTER the existing central dir - this would be safer. */ + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_central_directory_file_ofs = 0; + + /* Clear the sorted central dir offsets, they aren't useful or maintained now. */ + /* Even though we're now in write mode, files can still be extracted and verified, but file locates will be slow. */ + /* TODO: We could easily maintain the sorted central directory offsets. */ + mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) +{ + return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0); +} + +/* TODO: pArchive_name is a terrible name here! */ +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) +{ + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); +} + +typedef struct +{ + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; +} mz_zip_writer_add_state; + +static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) +{ + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + return MZ_FALSE; + + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; +} + +#define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2) +#define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3) +static mz_uint32 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size, mz_uint64 *pComp_size, mz_uint64 *pLocal_header_ofs) +{ + mz_uint8 *pDst = pBuf; + mz_uint32 field_size = 0; + + MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + MZ_WRITE_LE16(pDst + 2, 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + MZ_WRITE_LE64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pComp_size) + { + MZ_WRITE_LE64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + MZ_WRITE_LE64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + MZ_WRITE_LE16(pBuf + 2, field_size); + + return (mz_uint32)(pDst - pBuf); +} + +static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, + mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_MIN(local_header_ofs, MZ_UINT32_MAX)); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, + const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes, + const char *user_extra_data, mz_uint user_extra_data_len) +{ + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + if (!pZip->m_pState->m_zip64) + { + if (local_header_ofs > 0xFFFFFFFF) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, (mz_uint16)(extra_size + user_extra_data_len), comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, user_extra_data_len)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + /* Try to resize the central directory array back into its original state. */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) +{ + /* Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. */ + if (*pArchive_name == '/') + return MZ_FALSE; + + /* Making sure the name does not contain drive letters or DOS style backward slashes is the responsibility of the program using miniz*/ + + return MZ_TRUE; +} + +static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) +{ + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (mz_uint)((pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1)); +} + +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) +{ + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_file_ofs += s; + n -= s; + } + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) +{ + return mz_zip_writer_add_mem_ex_v2(pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0); +} + +mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_uint16 bit_flags = 0; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if (uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + if (((mz_uint64)buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + +#ifndef MINIZ_NO_TIME + if (last_modified != NULL) + { + mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); + } + else + { + MZ_TIME_T cur_time; + time(&cur_time); + mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); + } +#endif /* #ifndef MINIZ_NO_TIME */ + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + user_extra_data_len + + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len + + MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + /* Set DOS Subdirectory attribute bit. */ + ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; + + /* Subdirectories cannot contain data. */ + if ((buf_size) || (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) */ + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + cur_archive_file_ofs += num_alignment_padding_bytes; + + MZ_CLEAR_ARR(local_dir_header); + + if (!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + method = MZ_DEFLATED; + } + + if (pState->m_zip64) + { + if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + + if (pExtra_data != NULL) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + if (uncomp_size) + { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, + comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 max_size, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + mz_uint16 gen_flags; + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_zip_internal_state *pState; + mz_uint64 file_ofs = 0, cur_archive_header_file_ofs; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + gen_flags = (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) ? 0 : MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if ((!pState->m_zip64) && (max_size > MZ_UINT32_MAX)) + { + /* Source file is too large for non-zip64 */ + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + pState->m_zip64 = MZ_TRUE; + } + + /* We could support this, but why? */ + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + archive_name_size + comment_size + user_extra_data_len + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024 + + MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + +#ifndef MINIZ_NO_TIME + if (pFile_time) + { + mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); + } +#endif + + if (max_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_archive_file_ofs; + + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + if (max_size && level) + { + method = MZ_DEFLATED; + } + + MZ_CLEAR_ARR(local_dir_header); + if (pState->m_zip64) + { + if (max_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + else + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, NULL, + NULL, + (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, (mz_uint16)user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (max_size) + { + void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!level) + { + while (1) + { + size_t n = read_callback(callback_opaque, file_ofs, pRead_buf, MZ_ZIP_MAX_IO_BUF_SIZE); + if (n == 0) + break; + + if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + file_ofs += n; + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + cur_archive_file_ofs += n; + } + uncomp_size = file_ofs; + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + } + + for (;;) + { + tdefl_status status; + tdefl_flush flush = TDEFL_NO_FLUSH; + + size_t n = read_callback(callback_opaque, file_ofs, pRead_buf, MZ_ZIP_MAX_IO_BUF_SIZE); + if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + break; + } + + file_ofs += n; + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + + if (pZip->m_pNeeds_keepalive != NULL && pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque)) + flush = TDEFL_FULL_FLUSH; + + if (n == 0) + flush = TDEFL_FINISH; + + status = tdefl_compress_buffer(pComp, pRead_buf, n, flush); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + { + mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + break; + } + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return MZ_FALSE; + } + + uncomp_size = file_ofs; + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + if (!(level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE)) + { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) + { + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, + (mz_uint16)archive_name_size, (mz_uint16)(extra_size + user_extra_data_len), + (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : uncomp_size, + (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : comp_size, + uncomp_crc32, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + cur_archive_header_file_ofs = local_dir_header_ofs; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + if (pExtra_data != NULL) + { + cur_archive_header_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_header_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_header_file_ofs += extra_size; + } + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, (mz_uint16)extra_size, pComment, comment_size, + uncomp_size, comp_size, uncomp_crc32, method, gen_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO + +static size_t mz_file_read_func_stdio(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + MZ_FILE *pSrc_file = (MZ_FILE *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pSrc_file); + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pSrc_file, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pSrc_file); +} + +mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 max_size, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + return mz_zip_writer_add_read_buf_callback(pZip, pArchive_name, mz_file_read_func_stdio, pSrc_file, max_size, pFile_time, pComment, comment_size, level_and_flags, + user_extra_data, user_extra_data_len, user_extra_data_central, user_extra_data_central_len); +} + +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + MZ_FILE *pSrc_file = NULL; + mz_uint64 uncomp_size = 0; + MZ_TIME_T file_modified_time; + MZ_TIME_T *pFile_time = NULL; + mz_bool status; + + memset(&file_modified_time, 0, sizeof(file_modified_time)); + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + pFile_time = &file_modified_time; + if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); +#endif + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + status = mz_zip_writer_add_cfile(pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, comment_size, level_and_flags, NULL, 0, NULL, 0); + + MZ_FCLOSE(pSrc_file); + + return status; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, mz_uint32 ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) +{ + /* + 64 should be enough for any new zip64 data */ + if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); + + if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) + { + mz_uint8 new_ext_block[64]; + mz_uint8 *pDst = new_ext_block; + mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + mz_write_le16(pDst + sizeof(mz_uint16), 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + mz_write_le64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + } + + if (pComp_size) + { + mz_write_le64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + mz_write_le64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + } + + if (pDisk_start) + { + mz_write_le32(pDst, *pDisk_start); + pDst += sizeof(mz_uint32); + } + + mz_write_le16(new_ext_block + sizeof(mz_uint16), (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); + + if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if ((pExt) && (ext_len)) + { + mz_uint32 extra_size_remaining = ext_len; + const mz_uint8 *pExtra_data = pExt; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + return MZ_TRUE; +} + +/* TODO: This func is now pretty freakin complex due to zip64, split it up? */ +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index) +{ + mz_uint n, bit_flags, num_alignment_padding_bytes, src_central_dir_following_data_size; + mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; + const mz_uint8 *pSrc_central_header; + mz_zip_archive_file_stat src_file_stat; + mz_uint32 src_filename_len, src_comment_len, src_ext_len; + mz_uint32 local_header_filename_size, local_header_extra_len; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Don't support copying files from zip64 archives to non-zip64, even though in some cases this is possible */ + if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Get pointer to the source central dir header and crack it */ + if (NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + src_filename_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); + src_comment_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS); + src_central_dir_following_data_size = src_filename_len + src_ext_len + src_comment_len; + + /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 fudge factor in case we need to add more extra data) */ + if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + if (!pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + /* TODO: Our zip64 support still has some 32-bit limits that may not be worth fixing. */ + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL)) + return MZ_FALSE; + + cur_src_file_ofs = src_file_stat.m_local_header_ofs; + cur_dst_file_ofs = pZip->m_archive_size; + + /* Read the source archive's local dir header */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Compute the total size we need to copy (filename+extra data+compressed data) */ + local_header_filename_size = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + src_archive_bytes_remaining = local_header_filename_size + local_header_extra_len + src_file_stat.m_comp_size; + + /* Try to find a zip64 extended information field */ + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_zip_array file_data_array; + const mz_uint8 *pExtra_data; + mz_uint32 extra_size_remaining = local_header_extra_len; + + mz_zip_array_init(&file_data_array, 1); + if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE)) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); /* may be 0 if there's a descriptor */ + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + + mz_zip_array_clear(pZip, &file_data_array); + } + + if (!pState->m_zip64) + { + /* Try to detect if the new archive will most likely wind up too big and bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which could be present, +64 is a fudge factor). */ + /* We also check when the archive is finalized so this doesn't need to be perfect. */ + mz_uint64 approx_new_archive_size = cur_dst_file_ofs + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + (sizeof(mz_uint32) * 4) + + pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; + + if (approx_new_archive_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + /* Write dest archive padding */ + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + + cur_dst_file_ofs += num_alignment_padding_bytes; + + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + /* The original zip's local header+ext block doesn't change, even with zip64, so we can just copy it over to the dest zip */ + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Copy over the source archive bytes to the dest archive, also ensure we have enough buf space to handle optional data descriptor */ + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining))))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + while (src_archive_bytes_remaining) + { + n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_dst_file_ofs += n; + + src_archive_bytes_remaining -= n; + } + + /* Now deal with the optional data descriptor */ + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + /* Copy data descriptor */ + if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + /* src is zip64, dest must be zip64 */ + + /* name uint32_t's */ + /* id 1 (optional in zip64?) */ + /* crc 1 */ + /* comp_size 2 */ + /* uncomp_size 2 */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5); + } + else + { + /* src is NOT zip64 */ + mz_bool has_id; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + + if (pZip->m_pState->m_zip64) + { + /* dest is zip64, so upgrade the data descriptor */ + const mz_uint8 *pSrc_descriptor = (const mz_uint8 *)pBuf + (has_id ? sizeof(mz_uint32) : 0); + const mz_uint32 src_crc32 = MZ_READ_LE32(pSrc_descriptor); + const mz_uint64 src_comp_size = MZ_READ_LE32(pSrc_descriptor + sizeof(mz_uint32)); + const mz_uint64 src_uncomp_size = MZ_READ_LE32(pSrc_descriptor + 2*sizeof(mz_uint32)); + + mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID); + mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4, src_uncomp_size); + + n = sizeof(mz_uint32) * 6; + } + else + { + /* dest is NOT zip64, just copy it as-is */ + n = sizeof(mz_uint32) * (has_id ? 4 : 3); + } + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + /* Finally, add the new central dir header */ + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(new_central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + + if (pState->m_zip64) + { + /* This is the painful part: We need to write a new central dir header + ext block with updated zip64 fields, and ensure the old fields (if any) are not included. */ + const mz_uint8 *pSrc_ext = pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; + mz_zip_array new_ext_block; + + mz_zip_array_init(&new_ext_block, sizeof(mz_uint8)); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_UINT32_MAX); + + if (!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return MZ_FALSE; + } + + MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, new_ext_block.m_size); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + mz_zip_array_clear(pZip, &new_ext_block); + } + else + { + /* sanity checks */ + if (cur_dst_file_ofs > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (local_dir_header_ofs >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + } + + /* This shouldn't trigger unless we screwed up during the initial sanity checks */ + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + { + /* TODO: Support central dirs >= 32-bits in size */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + } + + n = (mz_uint32)orig_central_dir_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[256]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if ((mz_uint64)pState->m_central_dir.m_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if ((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + /* Write central directory */ + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += central_dir_size; + } + + if (pState->m_zip64) + { + /* Write zip64 end of central directory header */ + mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; + + MZ_CLEAR_ARR(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - sizeof(mz_uint64)); + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, 0x031E); /* TODO: always Unix */ + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; + + /* Write zip64 end of central directory locator */ + MZ_CLEAR_ARR(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, rel_ofs_to_zip64_ecdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; + } + + /* Write end of central directory record */ + MZ_CLEAR_ARR(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_size)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize) +{ + if ((!ppBuf) || (!pSize)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + *ppBuf = NULL; + *pSize = 0; + + if ((!pZip) || (!pZip->m_pState)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_pWrite != mz_zip_heap_write_func) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *ppBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_end(mz_zip_archive *pZip) +{ + return mz_zip_writer_end_internal(pZip, MZ_TRUE); +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + return mz_zip_add_mem_to_archive_file_in_place_v2(pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, NULL); +} + +mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr) +{ + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + mz_zip_zero_struct(&zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_FILENAME; + return MZ_FALSE; + } + + /* Important: The regular non-64 bit version of stat() can fail here if the file is very large, which could cause the archive to be overwritten. */ + /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + { + /* Create a new archive. */ + if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + created_new_archive = MZ_TRUE; + } + else + { + /* Append to an existing archive. */ + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); + + return MZ_FALSE; + } + } + + status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); + actual_err = zip_archive.m_last_error; + + /* Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) */ + if (!mz_zip_writer_finalize_archive(&zip_archive)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if (!mz_zip_writer_end_internal(&zip_archive, status)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if ((!status) && (created_new_archive)) + { + /* It's a new archive and something went wrong, so just delete it. */ + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + + if (pErr) + *pErr = actual_err; + + return status; +} + +void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr) +{ + mz_uint32 file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + + return NULL; + } + + mz_zip_zero_struct(&zip_archive); + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + return NULL; + } + + if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index)) + { + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + } + + mz_zip_reader_end_internal(&zip_archive, p != NULL); + + if (pErr) + *pErr = zip_archive.m_last_error; + + return p; +} + +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) +{ + return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, NULL, pSize, flags, NULL); +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* ------------------- Misc utils */ + +mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID; +} + +mz_zip_type mz_zip_get_type(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID; +} + +mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) +{ + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = err_num; + return prev_err; +} + +mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) +{ + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + return pZip->m_last_error; +} + +mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip) +{ + return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR); +} + +mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) +{ + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = MZ_ZIP_NO_ERROR; + return prev_err; +} + +const char *mz_zip_get_error_string(mz_zip_error mz_err) +{ + switch (mz_err) + { + case MZ_ZIP_NO_ERROR: + return "no error"; + case MZ_ZIP_UNDEFINED_ERROR: + return "undefined error"; + case MZ_ZIP_TOO_MANY_FILES: + return "too many files"; + case MZ_ZIP_FILE_TOO_LARGE: + return "file too large"; + case MZ_ZIP_UNSUPPORTED_METHOD: + return "unsupported method"; + case MZ_ZIP_UNSUPPORTED_ENCRYPTION: + return "unsupported encryption"; + case MZ_ZIP_UNSUPPORTED_FEATURE: + return "unsupported feature"; + case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: + return "failed finding central directory"; + case MZ_ZIP_NOT_AN_ARCHIVE: + return "not a ZIP archive"; + case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: + return "invalid header or archive is corrupted"; + case MZ_ZIP_UNSUPPORTED_MULTIDISK: + return "unsupported multidisk archive"; + case MZ_ZIP_DECOMPRESSION_FAILED: + return "decompression failed or archive is corrupted"; + case MZ_ZIP_COMPRESSION_FAILED: + return "compression failed"; + case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: + return "unexpected decompressed size"; + case MZ_ZIP_CRC_CHECK_FAILED: + return "CRC-32 check failed"; + case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: + return "unsupported central directory size"; + case MZ_ZIP_ALLOC_FAILED: + return "allocation failed"; + case MZ_ZIP_FILE_OPEN_FAILED: + return "file open failed"; + case MZ_ZIP_FILE_CREATE_FAILED: + return "file create failed"; + case MZ_ZIP_FILE_WRITE_FAILED: + return "file write failed"; + case MZ_ZIP_FILE_READ_FAILED: + return "file read failed"; + case MZ_ZIP_FILE_CLOSE_FAILED: + return "file close failed"; + case MZ_ZIP_FILE_SEEK_FAILED: + return "file seek failed"; + case MZ_ZIP_FILE_STAT_FAILED: + return "file stat failed"; + case MZ_ZIP_INVALID_PARAMETER: + return "invalid parameter"; + case MZ_ZIP_INVALID_FILENAME: + return "invalid filename"; + case MZ_ZIP_BUF_TOO_SMALL: + return "buffer too small"; + case MZ_ZIP_INTERNAL_ERROR: + return "internal error"; + case MZ_ZIP_FILE_NOT_FOUND: + return "file not found"; + case MZ_ZIP_ARCHIVE_TOO_LARGE: + return "archive is too large"; + case MZ_ZIP_VALIDATION_FAILED: + return "validation failed"; + case MZ_ZIP_WRITE_CALLBACK_FAILED: + return "write callback failed"; + case MZ_ZIP_TOTAL_ERRORS: + return "total errors"; + default: + break; + } + + return "unknown error"; +} + +/* Note: Just because the archive is not zip64 doesn't necessarily mean it doesn't have Zip64 extended information extra field, argh. */ +mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return MZ_FALSE; + + return pZip->m_pState->m_zip64; +} + +size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + + return pZip->m_pState->m_central_dir.m_size; +} + +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_total_files : 0; +} + +mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) +{ + if (!pZip) + return 0; + return pZip->m_archive_size; +} + +mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_file_archive_start_ofs; +} + +MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_pFile; +} + +size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); +} + +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + if (filename_buf_size) + pFilename[0] = '\0'; + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return 0; + } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; +} + +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) +{ + return mz_zip_file_stat_internal(pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); +} + +mz_bool mz_zip_end(mz_zip_archive *pZip) +{ + if (!pZip) + return MZ_FALSE; + + if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) + return mz_zip_reader_end(pZip); +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) + return mz_zip_writer_end(pZip); +#endif + + return MZ_FALSE; +} + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/ diff --git a/src/vendor/miniz.h b/src/vendor/miniz.h new file mode 100644 index 0000000..35c740c --- /dev/null +++ b/src/vendor/miniz.h @@ -0,0 +1,1422 @@ +#ifndef MINIZ_EXPORT +#define MINIZ_EXPORT +#endif +/* miniz.c 3.0.0 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated Oct. 13, 2013 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateReset/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, + const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 + + * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz + uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files + (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). +*/ +#pragma once + + + +/* Defines to completely disable specific portions of miniz.c: + If all macros here are defined the only functionality remaining will be CRC-32 and adler-32. */ + +/* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ +/*#define MINIZ_NO_STDIO */ + +/* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ +/* get/set file times, and the C run-time funcs that get/set times won't be called. */ +/* The current downside is the times written to your archives will be from 1979. */ +/*#define MINIZ_NO_TIME */ + +/* Define MINIZ_NO_DEFLATE_APIS to disable all compression API's. */ +/*#define MINIZ_NO_DEFLATE_APIS */ + +/* Define MINIZ_NO_INFLATE_APIS to disable all decompression API's. */ +/*#define MINIZ_NO_INFLATE_APIS */ + +/* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_APIS */ + +/* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ +/*#define MINIZ_NO_ZLIB_APIS */ + +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ +/*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. + Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc + callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user + functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ +/*#define MINIZ_NO_MALLOC */ + +#ifdef MINIZ_NO_INFLATE_APIS +#define MINIZ_NO_ARCHIVE_APIS +#endif + +#ifdef MINIZ_NO_DEFLATE_APIS +#define MINIZ_NO_ARCHIVE_WRITING_APIS +#endif + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) +/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ +#define MINIZ_NO_TIME +#endif + +#include + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ +#define MINIZ_X86_OR_X64_CPU 1 +#else +#define MINIZ_X86_OR_X64_CPU 0 +#endif + +/* Set MINIZ_LITTLE_ENDIAN only if not set */ +#if !defined(MINIZ_LITTLE_ENDIAN) +#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) + +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) +/* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ +#define MINIZ_LITTLE_ENDIAN 1 +#else +#define MINIZ_LITTLE_ENDIAN 0 +#endif + +#else + +#if MINIZ_X86_OR_X64_CPU +#define MINIZ_LITTLE_ENDIAN 1 +#else +#define MINIZ_LITTLE_ENDIAN 0 +#endif + +#endif +#endif + +/* Using unaligned loads and stores causes errors when using UBSan */ +#if defined(__has_feature) +#if __has_feature(undefined_behavior_sanitizer) +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#endif +#endif + +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ +#if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) +#if MINIZ_X86_OR_X64_CPU +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#define MINIZ_UNALIGNED_USE_MEMCPY +#else +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#endif +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ +#define MINIZ_HAS_64BIT_REGISTERS 1 +#else +#define MINIZ_HAS_64BIT_REGISTERS 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- zlib-style API Definitions. */ + +/* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ +typedef unsigned long mz_ulong; + +/* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ +MINIZ_EXPORT void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +/* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ +MINIZ_EXPORT mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +/* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ +MINIZ_EXPORT mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +/* Compression strategies. */ +enum +{ + MZ_DEFAULT_STRATEGY = 0, + MZ_FILTERED = 1, + MZ_HUFFMAN_ONLY = 2, + MZ_RLE = 3, + MZ_FIXED = 4 +}; + +/* Method */ +#define MZ_DEFLATED 8 + +/* Heap allocation callbacks. +Note that mz_alloc_func parameter types purposely differ from zlib's: items/size is size_t, not unsigned long. */ +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ +enum +{ + MZ_NO_COMPRESSION = 0, + MZ_BEST_SPEED = 1, + MZ_BEST_COMPRESSION = 9, + MZ_UBER_COMPRESSION = 10, + MZ_DEFAULT_LEVEL = 6, + MZ_DEFAULT_COMPRESSION = -1 +}; + +#define MZ_VERSION "11.0.1" +#define MZ_VERNUM 0xB001 +#define MZ_VER_MAJOR 11 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 0 +#define MZ_VER_SUBREVISION 0 + +#ifndef MINIZ_NO_ZLIB_APIS + +/* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ +enum +{ + MZ_NO_FLUSH = 0, + MZ_PARTIAL_FLUSH = 1, + MZ_SYNC_FLUSH = 2, + MZ_FULL_FLUSH = 3, + MZ_FINISH = 4, + MZ_BLOCK = 5 +}; + +/* Return status codes. MZ_PARAM_ERROR is non-standard. */ +enum +{ + MZ_OK = 0, + MZ_STREAM_END = 1, + MZ_NEED_DICT = 2, + MZ_ERRNO = -1, + MZ_STREAM_ERROR = -2, + MZ_DATA_ERROR = -3, + MZ_MEM_ERROR = -4, + MZ_BUF_ERROR = -5, + MZ_VERSION_ERROR = -6, + MZ_PARAM_ERROR = -10000 +}; + +/* Window bits */ +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +/* Compression/decompression stream struct. */ +typedef struct mz_stream_s +{ + const unsigned char *next_in; /* pointer to next byte to read */ + unsigned int avail_in; /* number of bytes available at next_in */ + mz_ulong total_in; /* total number of bytes consumed so far */ + + unsigned char *next_out; /* pointer to next byte to write */ + unsigned int avail_out; /* number of bytes that can be written to next_out */ + mz_ulong total_out; /* total number of bytes produced so far */ + + char *msg; /* error msg (unused) */ + struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ + + mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ + mz_free_func zfree; /* optional heap free function (defaults to free) */ + void *opaque; /* heap alloc function user pointer */ + + int data_type; /* data_type (unused) */ + mz_ulong adler; /* adler32 of the source or uncompressed data */ + mz_ulong reserved; /* not used */ +} mz_stream; + +typedef mz_stream *mz_streamp; + +/* Returns the version string of miniz.c. */ +MINIZ_EXPORT const char *mz_version(void); + +#ifndef MINIZ_NO_DEFLATE_APIS + +/* mz_deflateInit() initializes a compressor with default options: */ +/* Parameters: */ +/* pStream must point to an initialized mz_stream struct. */ +/* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ +/* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ +/* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_PARAM_ERROR if the input parameters are bogus. */ +/* MZ_MEM_ERROR on out of memory. */ +MINIZ_EXPORT int mz_deflateInit(mz_streamp pStream, int level); + +/* mz_deflateInit2() is like mz_deflate(), except with more control: */ +/* Additional parameters: */ +/* method must be MZ_DEFLATED */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ +/* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ +MINIZ_EXPORT int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +/* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ +MINIZ_EXPORT int mz_deflateReset(mz_streamp pStream); + +/* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ +/* Parameters: */ +/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ +/* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ +/* Return values: */ +/* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ +/* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_PARAM_ERROR if one of the parameters is invalid. */ +/* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ +MINIZ_EXPORT int mz_deflate(mz_streamp pStream, int flush); + +/* mz_deflateEnd() deinitializes a compressor: */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +MINIZ_EXPORT int mz_deflateEnd(mz_streamp pStream); + +/* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ +MINIZ_EXPORT mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +/* Single-call compression functions mz_compress() and mz_compress2(): */ +/* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ +MINIZ_EXPORT int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +MINIZ_EXPORT int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +/* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ +MINIZ_EXPORT mz_ulong mz_compressBound(mz_ulong source_len); + +#endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ + +#ifndef MINIZ_NO_INFLATE_APIS + +/* Initializes a decompressor. */ +MINIZ_EXPORT int mz_inflateInit(mz_streamp pStream); + +/* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ +MINIZ_EXPORT int mz_inflateInit2(mz_streamp pStream, int window_bits); + +/* Quickly resets a compressor without having to reallocate anything. Same as calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */ +MINIZ_EXPORT int mz_inflateReset(mz_streamp pStream); + +/* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ +/* Parameters: */ +/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ +/* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ +/* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ +/* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ +/* Return values: */ +/* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ +/* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_DATA_ERROR if the deflate stream is invalid. */ +/* MZ_PARAM_ERROR if one of the parameters is invalid. */ +/* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ +/* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ +MINIZ_EXPORT int mz_inflate(mz_streamp pStream, int flush); + +/* Deinitializes a decompressor. */ +MINIZ_EXPORT int mz_inflateEnd(mz_streamp pStream); + +/* Single-call decompression. */ +/* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ +MINIZ_EXPORT int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +MINIZ_EXPORT int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong *pSource_len); +#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ + +/* Returns a string description of the specified error code, or NULL if the error code is invalid. */ +MINIZ_EXPORT const char *mz_error(int err); + +/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES +typedef unsigned char Byte; +typedef unsigned int uInt; +typedef mz_ulong uLong; +typedef Byte Bytef; +typedef uInt uIntf; +typedef char charf; +typedef int intf; +typedef void *voidpf; +typedef uLong uLongf; +typedef void *voidp; +typedef void *const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS +#define alloc_func mz_alloc_func +#define free_func mz_free_func +#define internal_state mz_internal_state +#define z_stream mz_stream + +#ifndef MINIZ_NO_DEFLATE_APIS +#define deflateInit mz_deflateInit +#define deflateInit2 mz_deflateInit2 +#define deflateReset mz_deflateReset +#define deflate mz_deflate +#define deflateEnd mz_deflateEnd +#define deflateBound mz_deflateBound +#define compress mz_compress +#define compress2 mz_compress2 +#define compressBound mz_compressBound +#endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ + +#ifndef MINIZ_NO_INFLATE_APIS +#define inflateInit mz_inflateInit +#define inflateInit2 mz_inflateInit2 +#define inflateReset mz_inflateReset +#define inflate mz_inflate +#define inflateEnd mz_inflateEnd +#define uncompress mz_uncompress +#define uncompress2 mz_uncompress2 +#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ + +#define crc32 mz_crc32 +#define adler32 mz_adler32 +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 +#define zError mz_error +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION +#define zlibVersion mz_version +#define zlib_version mz_version() +#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +#endif /* MINIZ_NO_ZLIB_APIS */ + +#ifdef __cplusplus +} +#endif + + + + + +#pragma once +#include +#include +#include +#include + + + +/* ------------------- Types and macros */ +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef int64_t mz_int64; +typedef uint64_t mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +/* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ +#ifdef _MSC_VER +#define MZ_MACRO_END while (0, 0) +#else +#define MZ_MACRO_END while (0) +#endif + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include +#define MZ_FILE FILE +#endif /* #ifdef MINIZ_NO_STDIO */ + +#ifdef MINIZ_NO_TIME +typedef struct mz_dummy_time_t_tag +{ + mz_uint32 m_dummy1; + mz_uint32 m_dummy2; +} mz_dummy_time_t; +#define MZ_TIME_T mz_dummy_time_t +#else +#define MZ_TIME_T time_t +#endif + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC +#define MZ_MALLOC(x) NULL +#define MZ_FREE(x) (void)x, ((void)0) +#define MZ_REALLOC(p, x) NULL +#else +#define MZ_MALLOC(x) malloc(x) +#define MZ_FREE(x) free(x) +#define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) +#define MZ_CLEAR_ARR(obj) memset((obj), 0, sizeof(obj)) +#define MZ_CLEAR_PTR(obj) memset((obj), 0, sizeof(*obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) +#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else +#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) +#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) + +#ifdef _MSC_VER +#define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) +#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) +#else +#define MZ_FORCEINLINE inline +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +extern MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); +extern MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address); +extern MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); + +#define MZ_UINT16_MAX (0xFFFFU) +#define MZ_UINT32_MAX (0xFFFFFFFFU) + +#ifdef __cplusplus +} +#endif + #pragma once + + +#ifndef MINIZ_NO_DEFLATE_APIS + +#ifdef __cplusplus +extern "C" { +#endif +/* ------------------- Low-level Compression API Definitions */ + +/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ +#define TDEFL_LESS_MEMORY 0 + +/* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ +/* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ +enum +{ + TDEFL_HUFFMAN_ONLY = 0, + TDEFL_DEFAULT_MAX_PROBES = 128, + TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +/* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ +/* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ +/* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ +/* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ +/* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ +/* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ +/* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ +/* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ +/* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ +enum +{ + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +/* High level compression functions: */ +/* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ +/* On entry: */ +/* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ +/* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ +/* On return: */ +/* Function returns a pointer to the compressed data, or NULL on failure. */ +/* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ +/* The caller must free() the returned block when it's no longer needed. */ +MINIZ_EXPORT void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ +/* Returns 0 on failure. */ +MINIZ_EXPORT size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +/* Compresses an image to a compressed PNG file in memory. */ +/* On entry: */ +/* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ +/* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ +/* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ +/* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ +/* On return: */ +/* Function returns a pointer to the compressed data, or NULL on failure. */ +/* *pLen_out will be set to the size of the PNG image file. */ +/* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ +MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); +MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +/* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); + +/* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ +MINIZ_EXPORT mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum +{ + TDEFL_MAX_HUFF_TABLES = 3, + TDEFL_MAX_HUFF_SYMBOLS_0 = 288, + TDEFL_MAX_HUFF_SYMBOLS_1 = 32, + TDEFL_MAX_HUFF_SYMBOLS_2 = 19, + TDEFL_LZ_DICT_SIZE = 32768, + TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, + TDEFL_MIN_MATCH_LEN = 3, + TDEFL_MAX_MATCH_LEN = 258 +}; + +/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ +#if TDEFL_LESS_MEMORY +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 12, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#else +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 15, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#endif + +/* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ +typedef enum { + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1 +} tdefl_status; + +/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ +typedef enum { + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +/* tdefl's compression state structure. */ +typedef struct +{ + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +/* Initializes the compressor. */ +/* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ +/* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ +/* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ +/* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ +MINIZ_EXPORT tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +/* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ +MINIZ_EXPORT tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +/* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ +/* tdefl_compress_buffer() always consumes the entire input buffer. */ +MINIZ_EXPORT tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +MINIZ_EXPORT tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +MINIZ_EXPORT mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +/* Create tdefl_compress() flags given zlib-style compression parameters. */ +/* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ +/* window_bits may be -15 (raw deflate) or 15 (zlib) */ +/* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ +MINIZ_EXPORT mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tdefl_compressor structure in C so that */ +/* non-C language bindings to tdefl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +MINIZ_EXPORT tdefl_compressor *tdefl_compressor_alloc(void); +MINIZ_EXPORT void tdefl_compressor_free(tdefl_compressor *pComp); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ + #pragma once + +/* ------------------- Low-level Decompression API Definitions */ + +#ifndef MINIZ_NO_INFLATE_APIS + +#ifdef __cplusplus +extern "C" { +#endif +/* Decompression flags used by tinfl_decompress(). */ +/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ +/* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ +/* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ +/* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +/* High level decompression functions: */ +/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ +/* On entry: */ +/* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ +/* On return: */ +/* Function returns a pointer to the decompressed data, or NULL on failure. */ +/* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ +/* The caller must call mz_free() on the returned block when it's no longer needed. */ +MINIZ_EXPORT void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ +/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +MINIZ_EXPORT size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ +/* Returns 1 on success or 0 on failure. */ +typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); +MINIZ_EXPORT int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; +typedef struct tinfl_decompressor_tag tinfl_decompressor; + +#ifndef MINIZ_NO_MALLOC +/* Allocate the tinfl_decompressor structure in C so that */ +/* non-C language bindings to tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +MINIZ_EXPORT tinfl_decompressor *tinfl_decompressor_alloc(void); +MINIZ_EXPORT void tinfl_decompressor_free(tinfl_decompressor *pDecomp); +#endif + +/* Max size of LZ dictionary. */ +#define TINFL_LZ_DICT_SIZE 32768 + +/* Return status. */ +typedef enum { + /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ + /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ + /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ + TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, + + /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ + TINFL_STATUS_BAD_PARAM = -3, + + /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ + TINFL_STATUS_ADLER32_MISMATCH = -2, + + /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ + TINFL_STATUS_FAILED = -1, + + /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ + + /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ + /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ + TINFL_STATUS_DONE = 0, + + /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ + /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ + /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + + /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ + /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ + /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ + /* so I may need to add some code to address this. */ + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +/* Initializes the decompressor to its initial state. */ +#define tinfl_init(r) \ + do \ + { \ + (r)->m_state = 0; \ + } \ + MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +/* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ +/* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ +MINIZ_EXPORT tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +/* Internal/private bits follow. */ +enum +{ + TINFL_MAX_HUFF_TABLES = 3, + TINFL_MAX_HUFF_SYMBOLS_0 = 288, + TINFL_MAX_HUFF_SYMBOLS_1 = 32, + TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, + TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +#if MINIZ_HAS_64BIT_REGISTERS +#define TINFL_USE_64BIT_BITBUF 1 +#else +#define TINFL_USE_64BIT_BITBUF 0 +#endif + +#if TINFL_USE_64BIT_BITBUF +typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) +#else +typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + mz_int16 m_look_up[TINFL_MAX_HUFF_TABLES][TINFL_FAST_LOOKUP_SIZE]; + mz_int16 m_tree_0[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; + mz_int16 m_tree_1[TINFL_MAX_HUFF_SYMBOLS_1 * 2]; + mz_int16 m_tree_2[TINFL_MAX_HUFF_SYMBOLS_2 * 2]; + mz_uint8 m_code_size_0[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_uint8 m_code_size_1[TINFL_MAX_HUFF_SYMBOLS_1]; + mz_uint8 m_code_size_2[TINFL_MAX_HUFF_SYMBOLS_2]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +#ifdef __cplusplus +} +#endif + +#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ + +#pragma once + + +/* ------------------- ZIP archive reading/writing */ + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +extern "C" { +#endif + +enum +{ + /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ + MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 +}; + +typedef struct +{ + /* Central directory file index. */ + mz_uint32 m_file_index; + + /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ + mz_uint64 m_central_dir_ofs; + + /* These fields are copied directly from the zip's central dir. */ + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; + + /* CRC-32 of uncompressed data. */ + mz_uint32 m_crc32; + + /* File's compressed size. */ + mz_uint64 m_comp_size; + + /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ + mz_uint64 m_uncomp_size; + + /* Zip internal and external file attributes. */ + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + + /* Entry's local header file offset in bytes. */ + mz_uint64 m_local_header_ofs; + + /* Size of comment in bytes. */ + mz_uint32 m_comment_size; + + /* MZ_TRUE if the entry appears to be a directory. */ + mz_bool m_is_directory; + + /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ + mz_bool m_is_encrypted; + + /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ + mz_bool m_is_supported; + + /* Filename. If string ends in '/' it's a subdirectory entry. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + + /* Comment field. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; + +#ifdef MINIZ_NO_TIME + MZ_TIME_T m_padding; +#else + MZ_TIME_T m_time; +#endif +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); +typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum { + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef enum { + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, + MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ + MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ + MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ + MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, + MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000, + /*After adding a compressed file, seek back + to local file header and set the correct sizes*/ + MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE = 0x20000 +} mz_zip_flags; + +typedef enum { + MZ_ZIP_TYPE_INVALID = 0, + MZ_ZIP_TYPE_USER, + MZ_ZIP_TYPE_MEMORY, + MZ_ZIP_TYPE_HEAP, + MZ_ZIP_TYPE_FILE, + MZ_ZIP_TYPE_CFILE, + MZ_ZIP_TOTAL_TYPES +} mz_zip_type; + +/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ +typedef enum { + MZ_ZIP_NO_ERROR = 0, + MZ_ZIP_UNDEFINED_ERROR, + MZ_ZIP_TOO_MANY_FILES, + MZ_ZIP_FILE_TOO_LARGE, + MZ_ZIP_UNSUPPORTED_METHOD, + MZ_ZIP_UNSUPPORTED_ENCRYPTION, + MZ_ZIP_UNSUPPORTED_FEATURE, + MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, + MZ_ZIP_NOT_AN_ARCHIVE, + MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, + MZ_ZIP_UNSUPPORTED_MULTIDISK, + MZ_ZIP_DECOMPRESSION_FAILED, + MZ_ZIP_COMPRESSION_FAILED, + MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, + MZ_ZIP_CRC_CHECK_FAILED, + MZ_ZIP_UNSUPPORTED_CDIR_SIZE, + MZ_ZIP_ALLOC_FAILED, + MZ_ZIP_FILE_OPEN_FAILED, + MZ_ZIP_FILE_CREATE_FAILED, + MZ_ZIP_FILE_WRITE_FAILED, + MZ_ZIP_FILE_READ_FAILED, + MZ_ZIP_FILE_CLOSE_FAILED, + MZ_ZIP_FILE_SEEK_FAILED, + MZ_ZIP_FILE_STAT_FAILED, + MZ_ZIP_INVALID_PARAMETER, + MZ_ZIP_INVALID_FILENAME, + MZ_ZIP_BUF_TOO_SMALL, + MZ_ZIP_INTERNAL_ERROR, + MZ_ZIP_FILE_NOT_FOUND, + MZ_ZIP_ARCHIVE_TOO_LARGE, + MZ_ZIP_VALIDATION_FAILED, + MZ_ZIP_WRITE_CALLBACK_FAILED, + MZ_ZIP_TOTAL_ERRORS +} mz_zip_error; + +typedef struct +{ + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + + /* We only support up to UINT32_MAX files in zip64 mode. */ + mz_uint32 m_total_files; + mz_zip_mode m_zip_mode; + mz_zip_type m_zip_type; + mz_zip_error m_last_error; + + mz_uint64 m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + mz_file_needs_keepalive m_pNeeds_keepalive; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef struct +{ + mz_zip_archive *pZip; + mz_uint flags; + + int status; + + mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + void *pWrite_buf; + + size_t out_blk_remain; + + tinfl_decompressor inflator; + +#ifdef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + mz_uint padding; +#else + mz_uint file_crc32; +#endif + +} mz_zip_reader_extract_iter_state; + +/* -------- ZIP reading */ + +/* Inits a ZIP archive reader. */ +/* These functions read and validate the archive's central directory. */ +MINIZ_EXPORT mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); + +MINIZ_EXPORT mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +/* Read a archive from a disk file. */ +/* file_start_ofs is the file offset where the archive actually begins, or 0. */ +/* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ +MINIZ_EXPORT mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +MINIZ_EXPORT mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); + +/* Read an archive from an already opened FILE, beginning at the current file position. */ +/* The archive is assumed to be archive_size bytes long. If archive_size is 0, then the entire rest of the file is assumed to contain the archive. */ +/* The FILE will NOT be closed when mz_zip_reader_end() is called. */ +MINIZ_EXPORT mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); +#endif + +/* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ +MINIZ_EXPORT mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +/* -------- ZIP reading or writing */ + +/* Clears a mz_zip_archive struct to all zeros. */ +/* Important: This must be done before passing the struct to any mz_zip functions. */ +MINIZ_EXPORT void mz_zip_zero_struct(mz_zip_archive *pZip); + +MINIZ_EXPORT mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); +MINIZ_EXPORT mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); + +/* Returns the total number of files in the archive. */ +MINIZ_EXPORT mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +MINIZ_EXPORT mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); +MINIZ_EXPORT mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); +MINIZ_EXPORT MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); + +/* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ +MINIZ_EXPORT size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); + +/* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ +/* Note that the m_last_error functionality is not thread safe. */ +MINIZ_EXPORT mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); +MINIZ_EXPORT mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); +MINIZ_EXPORT mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); +MINIZ_EXPORT mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); +MINIZ_EXPORT const char *mz_zip_get_error_string(mz_zip_error mz_err); + +/* MZ_TRUE if the archive file entry is a directory entry. */ +MINIZ_EXPORT mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); + +/* MZ_TRUE if the file is encrypted/strong encrypted. */ +MINIZ_EXPORT mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +/* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ +MINIZ_EXPORT mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); + +/* Retrieves the filename of an archive file entry. */ +/* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ +MINIZ_EXPORT mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +/* Attempts to locates a file in the archive's central directory. */ +/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ +/* Returns -1 if the file cannot be found. */ +MINIZ_EXPORT int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); + +/* Returns detailed information about an archive file entry. */ +MINIZ_EXPORT mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +/* MZ_TRUE if the file is in zip64 format. */ +/* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ +MINIZ_EXPORT mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); + +/* Returns the total central directory size in bytes. */ +/* The current max supported size is <= MZ_UINT32_MAX. */ +MINIZ_EXPORT size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); + +/* Extracts a archive file to a memory buffer using no memory allocation. */ +/* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ +MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +/* Extracts a archive file to a memory buffer. */ +MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +/* Extracts a archive file to a dynamically allocated heap buffer. */ +/* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ +/* Returns NULL and sets the last error on failure. */ +MINIZ_EXPORT void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +MINIZ_EXPORT void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +/* Extracts a archive file using a callback function to output the file's data. */ +MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +/* Extract a file iteratively */ +MINIZ_EXPORT mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); +MINIZ_EXPORT mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); +MINIZ_EXPORT size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState); + +#ifndef MINIZ_NO_STDIO +/* Extracts a archive file to a disk file and sets its last accessed and modified times. */ +/* This function only extracts files, not archive directory records. */ +MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); + +/* Extracts a archive file starting at the current position in the destination FILE stream. */ +MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); +#endif + +#if 0 +/* TODO */ + typedef void *mz_zip_streaming_extract_state_ptr; + mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + mz_uint64 mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + mz_uint64 mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, mz_uint64 new_ofs); + size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); + mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); +#endif + +/* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ +/* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ +MINIZ_EXPORT mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + +/* Validates an entire archive by calling mz_zip_validate_file() on each file. */ +MINIZ_EXPORT mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); + +/* Misc utils/helpers, valid for ZIP reading or writing */ +MINIZ_EXPORT mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); +#ifndef MINIZ_NO_STDIO +MINIZ_EXPORT mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); +#endif + +/* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ +MINIZ_EXPORT mz_bool mz_zip_end(mz_zip_archive *pZip); + +/* -------- ZIP writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +/* Inits a ZIP archive writer. */ +/*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/ +/*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/ +MINIZ_EXPORT mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +MINIZ_EXPORT mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); + +MINIZ_EXPORT mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); +MINIZ_EXPORT mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +MINIZ_EXPORT mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +MINIZ_EXPORT mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); +MINIZ_EXPORT mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); +#endif + +/* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ +/* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ +/* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ +/* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ +/* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ +/* the archive is finalized the file's central directory will be hosed. */ +MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); +MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); + +/* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ +/* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +MINIZ_EXPORT mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); + +/* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ +/* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ +MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); + +/* Adds the contents of a file to an archive. This function also records the disk file's modified time into the archive. */ +/* File data is supplied via a read callback function. User mz_zip_writer_add_(c)file to add a file directly.*/ +MINIZ_EXPORT mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 max_size, + const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); + + +#ifndef MINIZ_NO_STDIO +/* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +MINIZ_EXPORT mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +/* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ +MINIZ_EXPORT mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 max_size, + const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); +#endif + +/* Adds a file to an archive by fully cloning the data from another archive. */ +/* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ +MINIZ_EXPORT mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); + +/* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ +/* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ +/* An archive must be manually finalized by calling this function for it to be valid. */ +MINIZ_EXPORT mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); + +/* Finalizes a heap archive, returning a pointer to the heap block and its size. */ +/* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ +MINIZ_EXPORT mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); + +/* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ +/* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ +MINIZ_EXPORT mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +/* -------- Misc. high-level helper functions: */ + +/* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ +/* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +/* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ +MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); + +#ifndef MINIZ_NO_STDIO +/* Reads a single file from an archive into a heap block. */ +/* If pComment is not NULL, only the file with the specified comment will be extracted. */ +/* Returns NULL on failure. */ +MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); +MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); +#endif + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifdef __cplusplus +} +#endif + +#endif /* MINIZ_NO_ARCHIVE_APIS */ diff --git a/src/vendor/printf.c b/src/vendor/printf.c new file mode 100644 index 0000000..8a700ad --- /dev/null +++ b/src/vendor/printf.c @@ -0,0 +1,914 @@ +/////////////////////////////////////////////////////////////////////////////// +// \author (c) Marco Paland (info@paland.com) +// 2014-2019, PALANDesign Hannover, Germany +// +// \license The MIT License (MIT) +// +// 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. +// +// \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on +// embedded systems with a very limited resources. These routines are thread +// safe and reentrant! +// Use this instead of the bloated standard/newlib printf cause these use +// malloc for printf (and may not be thread safe). +// +/////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include "printf.h" + + +// define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the +// printf_config.h header file +// default: undefined +#ifdef PRINTF_INCLUDE_CONFIG_H +#include "printf_config.h" +#endif + + +// 'ntoa' conversion buffer size, this must be big enough to hold one converted +// numeric number including padded zeros (dynamically created on stack) +// default: 32 byte +#ifndef PRINTF_NTOA_BUFFER_SIZE +#define PRINTF_NTOA_BUFFER_SIZE 32U +#endif + +// 'ftoa' conversion buffer size, this must be big enough to hold one converted +// float number including padded zeros (dynamically created on stack) +// default: 32 byte +#ifndef PRINTF_FTOA_BUFFER_SIZE +#define PRINTF_FTOA_BUFFER_SIZE 32U +#endif + +// support for the floating point type (%f) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_FLOAT +#define PRINTF_SUPPORT_FLOAT +#endif + +// support for exponential floating point notation (%e/%g) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL +#define PRINTF_SUPPORT_EXPONENTIAL +#endif + +// define the default floating point precision +// default: 6 digits +#ifndef PRINTF_DEFAULT_FLOAT_PRECISION +#define PRINTF_DEFAULT_FLOAT_PRECISION 6U +#endif + +// define the largest float suitable to print with %f +// default: 1e9 +#ifndef PRINTF_MAX_FLOAT +#define PRINTF_MAX_FLOAT 1e9 +#endif + +// support for the long long types (%llu or %p) +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG +#define PRINTF_SUPPORT_LONG_LONG +#endif + +// support for the ptrdiff_t type (%t) +// ptrdiff_t is normally defined in as long or long long type +// default: activated +#ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T +#define PRINTF_SUPPORT_PTRDIFF_T +#endif + +/////////////////////////////////////////////////////////////////////////////// + +// internal flag definitions +#define FLAGS_ZEROPAD (1U << 0U) +#define FLAGS_LEFT (1U << 1U) +#define FLAGS_PLUS (1U << 2U) +#define FLAGS_SPACE (1U << 3U) +#define FLAGS_HASH (1U << 4U) +#define FLAGS_UPPERCASE (1U << 5U) +#define FLAGS_CHAR (1U << 6U) +#define FLAGS_SHORT (1U << 7U) +#define FLAGS_LONG (1U << 8U) +#define FLAGS_LONG_LONG (1U << 9U) +#define FLAGS_PRECISION (1U << 10U) +#define FLAGS_ADAPT_EXP (1U << 11U) + + +// import float.h for DBL_MAX +#if defined(PRINTF_SUPPORT_FLOAT) +#include +#endif + + +// output function type +typedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen); + + +// wrapper (used as buffer) for output function type +typedef struct { + void (*fct)(char character, void* arg); + void* arg; +} out_fct_wrap_type; + + +// internal buffer output +static inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen) +{ + if (idx < maxlen) { + ((char*)buffer)[idx] = character; + } +} + + +// internal null output +static inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)character; (void)buffer; (void)idx; (void)maxlen; +} + + +// internal _putchar wrapper +static inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)buffer; (void)idx; (void)maxlen; + if (character) { + _putchar(character); + } +} + + +// internal output function wrapper +static inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen) +{ + (void)idx; (void)maxlen; + if (character) { + // buffer is the output fct pointer + ((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg); + } +} + + +// internal secure strlen +// \return The length of the string (excluding the terminating 0) limited by 'maxsize' +static inline unsigned int _strnlen_s(const char* str, size_t maxsize) +{ + const char* s; + for (s = str; *s && maxsize--; ++s); + return (unsigned int)(s - str); +} + + +// internal test if char is a digit (0-9) +// \return true if char is a digit +static inline bool _is_digit(char ch) +{ + return (ch >= '0') && (ch <= '9'); +} + + +// internal ASCII string to unsigned int conversion +static unsigned int _atoi(const char** str) +{ + unsigned int i = 0U; + while (_is_digit(**str)) { + i = i * 10U + (unsigned int)(*((*str)++) - '0'); + } + return i; +} + + +// output the specified string in reverse, taking care of any zero-padding +static size_t _out_rev(out_fct_type out, char* buffer, size_t idx, size_t maxlen, const char* buf, size_t len, unsigned int width, unsigned int flags) +{ + const size_t start_idx = idx; + + // pad spaces up to given width + if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) { + for (size_t i = len; i < width; i++) { + out(' ', buffer, idx++, maxlen); + } + } + + // reverse string + while (len) { + out(buf[--len], buffer, idx++, maxlen); + } + + // append pad spaces up to given width + if (flags & FLAGS_LEFT) { + while (idx - start_idx < width) { + out(' ', buffer, idx++, maxlen); + } + } + + return idx; +} + + +// internal itoa format +static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags) +{ + // pad leading zeros + if (!(flags & FLAGS_LEFT)) { + if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { + width--; + } + while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + } + + // handle hash + if (flags & FLAGS_HASH) { + if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) { + len--; + if (len && (base == 16U)) { + len--; + } + } + if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'x'; + } + else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'X'; + } + else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) { + buf[len++] = 'b'; + } + if (len < PRINTF_NTOA_BUFFER_SIZE) { + buf[len++] = '0'; + } + } + + if (len < PRINTF_NTOA_BUFFER_SIZE) { + if (negative) { + buf[len++] = '-'; + } + else if (flags & FLAGS_PLUS) { + buf[len++] = '+'; // ignore the space if the '+' exists + } + else if (flags & FLAGS_SPACE) { + buf[len++] = ' '; + } + } + + return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); +} + + +// internal itoa for 'long' type +static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, unsigned long base, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_NTOA_BUFFER_SIZE]; + size_t len = 0U; + + // no hash for 0 values + if (!value) { + flags &= ~FLAGS_HASH; + } + + // write if precision != 0 and value is != 0 + if (!(flags & FLAGS_PRECISION) || value) { + do { + const char digit = (char)(value % base); + buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; + value /= base; + } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); + } + + return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); +} + + +// internal itoa for 'long long' type +#if defined(PRINTF_SUPPORT_LONG_LONG) +static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_NTOA_BUFFER_SIZE]; + size_t len = 0U; + + // no hash for 0 values + if (!value) { + flags &= ~FLAGS_HASH; + } + + // write if precision != 0 and value is != 0 + if (!(flags & FLAGS_PRECISION) || value) { + do { + const char digit = (char)(value % base); + buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10; + value /= base; + } while (value && (len < PRINTF_NTOA_BUFFER_SIZE)); + } + + return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags); +} +#endif // PRINTF_SUPPORT_LONG_LONG + + +#if defined(PRINTF_SUPPORT_FLOAT) + +#if defined(PRINTF_SUPPORT_EXPONENTIAL) +// forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT +static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags); +#endif + + +// internal ftoa for fixed decimal floating point +static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) +{ + char buf[PRINTF_FTOA_BUFFER_SIZE]; + size_t len = 0U; + double diff = 0.0; + + // powers of 10 + static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; + + // test for special values + if (value != value) + return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags); + if (value < -DBL_MAX) + return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags); + if (value > DBL_MAX) + return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags); + + // test for very large values + // standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad + if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) { +#if defined(PRINTF_SUPPORT_EXPONENTIAL) + return _etoa(out, buffer, idx, maxlen, value, prec, width, flags); +#else + return 0U; +#endif + } + + // test for negative + bool negative = false; + if (value < 0) { + negative = true; + value = 0 - value; + } + + // set default precision, if not set explicitly + if (!(flags & FLAGS_PRECISION)) { + prec = PRINTF_DEFAULT_FLOAT_PRECISION; + } + // limit precision to 9, cause a prec >= 10 can lead to overflow errors + while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) { + buf[len++] = '0'; + prec--; + } + + int whole = (int)value; + double tmp = (value - whole) * pow10[prec]; + unsigned long frac = (unsigned long)tmp; + diff = tmp - frac; + + if (diff > 0.5) { + ++frac; + // handle rollover, e.g. case 0.99 with prec 1 is 1.0 + if (frac >= pow10[prec]) { + frac = 0; + ++whole; + } + } + else if (diff < 0.5) { + } + else if ((frac == 0U) || (frac & 1U)) { + // if halfway, round up if odd OR if last digit is 0 + ++frac; + } + + if (prec == 0U) { + diff = value - (double)whole; + if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) { + // exactly 0.5 and ODD, then round up + // 1.5 -> 2, but 2.5 -> 2 + ++whole; + } + } + else { + unsigned int count = prec; + // now do fractional part, as an unsigned number + while (len < PRINTF_FTOA_BUFFER_SIZE) { + --count; + buf[len++] = (char)(48U + (frac % 10U)); + if (!(frac /= 10U)) { + break; + } + } + // add extra 0s + while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) { + buf[len++] = '0'; + } + if (len < PRINTF_FTOA_BUFFER_SIZE) { + // add decimal + buf[len++] = '.'; + } + } + + // do whole part, number is reversed + while (len < PRINTF_FTOA_BUFFER_SIZE) { + buf[len++] = (char)(48 + (whole % 10)); + if (!(whole /= 10)) { + break; + } + } + + // pad leading zeros + if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) { + if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) { + width--; + } + while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) { + buf[len++] = '0'; + } + } + + if (len < PRINTF_FTOA_BUFFER_SIZE) { + if (negative) { + buf[len++] = '-'; + } + else if (flags & FLAGS_PLUS) { + buf[len++] = '+'; // ignore the space if the '+' exists + } + else if (flags & FLAGS_SPACE) { + buf[len++] = ' '; + } + } + + return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags); +} + + +#if defined(PRINTF_SUPPORT_EXPONENTIAL) +// internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse +static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags) +{ + // check for NaN and special values + if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) { + return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags); + } + + // determine the sign + const bool negative = value < 0; + if (negative) { + value = -value; + } + + // default precision + if (!(flags & FLAGS_PRECISION)) { + prec = PRINTF_DEFAULT_FLOAT_PRECISION; + } + + // determine the decimal exponent + // based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c) + union { + uint64_t U; + double F; + } conv; + + conv.F = value; + int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2 + conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2) + // now approximate log10 from the log2 integer part and an expansion of ln around 1.5 + int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168); + // now we want to compute 10^expval but we want to be sure it won't overflow + exp2 = (int)(expval * 3.321928094887362 + 0.5); + const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453; + const double z2 = z * z; + conv.U = (uint64_t)(exp2 + 1023) << 52U; + // compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex + conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14))))); + // correct for rounding errors + if (value < conv.F) { + expval--; + conv.F /= 10; + } + + // the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters + unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U; + + // in "%g" mode, "prec" is the number of *significant figures* not decimals + if (flags & FLAGS_ADAPT_EXP) { + // do we want to fall-back to "%f" mode? + if ((value >= 1e-4) && (value < 1e6)) { + if ((int)prec > expval) { + prec = (unsigned)((int)prec - expval - 1); + } + else { + prec = 0; + } + flags |= FLAGS_PRECISION; // make sure _ftoa respects precision + // no characters in exponent + minwidth = 0U; + expval = 0; + } + else { + // we use one sigfig for the whole part + if ((prec > 0) && (flags & FLAGS_PRECISION)) { + --prec; + } + } + } + + // will everything fit? + unsigned int fwidth = width; + if (width > minwidth) { + // we didn't fall-back so subtract the characters required for the exponent + fwidth -= minwidth; + } else { + // not enough characters, so go back to default sizing + fwidth = 0U; + } + if ((flags & FLAGS_LEFT) && minwidth) { + // if we're padding on the right, DON'T pad the floating part + fwidth = 0U; + } + + // rescale the float value + if (expval) { + value /= conv.F; + } + + // output the floating part + const size_t start_idx = idx; + idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP); + + // output the exponent part + if (minwidth) { + // output the exponential symbol + out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen); + // output the exponent value + idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS); + // might need to right-pad spaces + if (flags & FLAGS_LEFT) { + while (idx - start_idx < width) out(' ', buffer, idx++, maxlen); + } + } + return idx; +} +#endif // PRINTF_SUPPORT_EXPONENTIAL +#endif // PRINTF_SUPPORT_FLOAT + + +// internal vsnprintf +static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va) +{ + unsigned int flags, width, precision, n; + size_t idx = 0U; + + if (!buffer) { + // use null output function + out = _out_null; + } + + while (*format) + { + // format specifier? %[flags][width][.precision][length] + if (*format != '%') { + // no + out(*format, buffer, idx++, maxlen); + format++; + continue; + } + else { + // yes, evaluate it + format++; + } + + // evaluate flags + flags = 0U; + do { + switch (*format) { + case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break; + case '-': flags |= FLAGS_LEFT; format++; n = 1U; break; + case '+': flags |= FLAGS_PLUS; format++; n = 1U; break; + case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break; + case '#': flags |= FLAGS_HASH; format++; n = 1U; break; + default : n = 0U; break; + } + } while (n); + + // evaluate width field + width = 0U; + if (_is_digit(*format)) { + width = _atoi(&format); + } + else if (*format == '*') { + const int w = va_arg(va, int); + if (w < 0) { + flags |= FLAGS_LEFT; // reverse padding + width = (unsigned int)-w; + } + else { + width = (unsigned int)w; + } + format++; + } + + // evaluate precision field + precision = 0U; + if (*format == '.') { + flags |= FLAGS_PRECISION; + format++; + if (_is_digit(*format)) { + precision = _atoi(&format); + } + else if (*format == '*') { + const int prec = (int)va_arg(va, int); + precision = prec > 0 ? (unsigned int)prec : 0U; + format++; + } + } + + // evaluate length field + switch (*format) { + case 'l' : + flags |= FLAGS_LONG; + format++; + if (*format == 'l') { + flags |= FLAGS_LONG_LONG; + format++; + } + break; + case 'h' : + flags |= FLAGS_SHORT; + format++; + if (*format == 'h') { + flags |= FLAGS_CHAR; + format++; + } + break; +#if defined(PRINTF_SUPPORT_PTRDIFF_T) + case 't' : + flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; +#endif + case 'j' : + flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + case 'z' : + flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG); + format++; + break; + default : + break; + } + + // evaluate specifier + switch (*format) { + case 'd' : + case 'i' : + case 'u' : + case 'x' : + case 'X' : + case 'o' : + case 'b' : { + // set the base + unsigned int base; + if (*format == 'x' || *format == 'X') { + base = 16U; + } + else if (*format == 'o') { + base = 8U; + } + else if (*format == 'b') { + base = 2U; + } + else { + base = 10U; + flags &= ~FLAGS_HASH; // no hash for dec format + } + // uppercase + if (*format == 'X') { + flags |= FLAGS_UPPERCASE; + } + + // no plus or space flag for u, x, X, o, b + if ((*format != 'i') && (*format != 'd')) { + flags &= ~(FLAGS_PLUS | FLAGS_SPACE); + } + + // ignore '0' flag when precision is given + if (flags & FLAGS_PRECISION) { + flags &= ~FLAGS_ZEROPAD; + } + + // convert the integer + if ((*format == 'i') || (*format == 'd')) { + // signed + if (flags & FLAGS_LONG_LONG) { +#if defined(PRINTF_SUPPORT_LONG_LONG) + const long long value = va_arg(va, long long); + idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); +#endif + } + else if (flags & FLAGS_LONG) { + const long value = va_arg(va, long); + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); + } + else { + const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int); + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags); + } + } + else { + // unsigned + if (flags & FLAGS_LONG_LONG) { +#if defined(PRINTF_SUPPORT_LONG_LONG) + idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags); +#endif + } + else if (flags & FLAGS_LONG) { + idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags); + } + else { + const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : va_arg(va, unsigned int); + idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags); + } + } + format++; + break; + } +#if defined(PRINTF_SUPPORT_FLOAT) + case 'f' : + case 'F' : + if (*format == 'F') flags |= FLAGS_UPPERCASE; + idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); + format++; + break; +#if defined(PRINTF_SUPPORT_EXPONENTIAL) + case 'e': + case 'E': + case 'g': + case 'G': + if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP; + if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE; + idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags); + format++; + break; +#endif // PRINTF_SUPPORT_EXPONENTIAL +#endif // PRINTF_SUPPORT_FLOAT + case 'c' : { + unsigned int l = 1U; + // pre padding + if (!(flags & FLAGS_LEFT)) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + // char output + out((char)va_arg(va, int), buffer, idx++, maxlen); + // post padding + if (flags & FLAGS_LEFT) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + format++; + break; + } + + case 's' : { + const char* p = va_arg(va, char*); + unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1); + // pre padding + if (flags & FLAGS_PRECISION) { + l = (l < precision ? l : precision); + } + if (!(flags & FLAGS_LEFT)) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + // string output + while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) { + out(*(p++), buffer, idx++, maxlen); + } + // post padding + if (flags & FLAGS_LEFT) { + while (l++ < width) { + out(' ', buffer, idx++, maxlen); + } + } + format++; + break; + } + + case 'p' : { + width = sizeof(void*) * 2U; + flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE; +#if defined(PRINTF_SUPPORT_LONG_LONG) + const bool is_ll = sizeof(uintptr_t) == sizeof(long long); + if (is_ll) { + idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags); + } + else { +#endif + idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags); +#if defined(PRINTF_SUPPORT_LONG_LONG) + } +#endif + format++; + break; + } + + case '%' : + out('%', buffer, idx++, maxlen); + format++; + break; + + default : + out(*format, buffer, idx++, maxlen); + format++; + break; + } + } + + // termination + out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen); + + // return written chars without terminating \0 + return (int)idx; +} + + +/////////////////////////////////////////////////////////////////////////////// + +int printf_(const char* format, ...) +{ + va_list va; + va_start(va, format); + char buffer[1]; + const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va); + va_end(va); + return ret; +} + + +int sprintf_(char* buffer, const char* format, ...) +{ + va_list va; + va_start(va, format); + const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va); + va_end(va); + return ret; +} + + +int snprintf_(char* buffer, size_t count, const char* format, ...) +{ + va_list va; + va_start(va, format); + const int ret = _vsnprintf(_out_buffer, buffer, count, format, va); + va_end(va); + return ret; +} + + +int vprintf_(const char* format, va_list va) +{ + char buffer[1]; + return _vsnprintf(_out_char, buffer, (size_t)-1, format, va); +} + + +int vsnprintf_(char* buffer, size_t count, const char* format, va_list va) +{ + return _vsnprintf(_out_buffer, buffer, count, format, va); +} + + +int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...) +{ + va_list va; + va_start(va, format); + const out_fct_wrap_type out_fct_wrap = { out, arg }; + const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va); + va_end(va); + return ret; +} diff --git a/src/vendor/printf.h b/src/vendor/printf.h new file mode 100644 index 0000000..6104ccf --- /dev/null +++ b/src/vendor/printf.h @@ -0,0 +1,117 @@ +/////////////////////////////////////////////////////////////////////////////// +// \author (c) Marco Paland (info@paland.com) +// 2014-2019, PALANDesign Hannover, Germany +// +// \license The MIT License (MIT) +// +// 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. +// +// \brief Tiny printf, sprintf and snprintf implementation, optimized for speed on +// embedded systems with a very limited resources. +// Use this instead of bloated standard/newlib printf. +// These routines are thread safe and reentrant. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef _PRINTF_H_ +#define _PRINTF_H_ + +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * Output a character to a custom device like UART, used by the printf() function + * This function is declared here only. You have to write your custom implementation somewhere + * \param character Character to output + */ +void _putchar(char character); + + +/** + * Tiny printf implementation + * You have to implement _putchar if you use printf() + * To avoid conflicts with the regular printf() API it is overridden by macro defines + * and internal underscore-appended functions like printf_() are used + * \param format A string that specifies the format of the output + * \return The number of characters that are written into the array, not counting the terminating null character + */ +#define printf printf_ +int printf_(const char* format, ...); + + +/** + * Tiny sprintf implementation + * Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD! + * \param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output! + * \param format A string that specifies the format of the output + * \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character + */ +#define sprintf sprintf_ +int sprintf_(char* buffer, const char* format, ...); + + +/** + * Tiny snprintf/vsnprintf implementation + * \param buffer A pointer to the buffer where to store the formatted string + * \param count The maximum number of characters to store in the buffer, including a terminating null character + * \param format A string that specifies the format of the output + * \param va A value identifying a variable arguments list + * \return The number of characters that COULD have been written into the buffer, not counting the terminating + * null character. A value equal or larger than count indicates truncation. Only when the returned value + * is non-negative and less than count, the string has been completely written. + */ +#define snprintf snprintf_ +#define vsnprintf vsnprintf_ +int snprintf_(char* buffer, size_t count, const char* format, ...); +int vsnprintf_(char* buffer, size_t count, const char* format, va_list va); + + +/** + * Tiny vprintf implementation + * \param format A string that specifies the format of the output + * \param va A value identifying a variable arguments list + * \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character + */ +#define vprintf vprintf_ +int vprintf_(const char* format, va_list va); + + +/** + * printf with output function + * You may use this as dynamic alternative to printf() with its fixed _putchar() output + * \param out An output function which takes one character and an argument pointer + * \param arg An argument pointer for user data passed to output function + * \param format A string that specifies the format of the output + * \return The number of characters that are sent to the output function, not counting the terminating null character + */ +int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...); + + +#ifdef __cplusplus +} +#endif + + +#endif // _PRINTF_H_ diff --git a/src/vendor/qrcodegen.c b/src/vendor/qrcodegen.c new file mode 100644 index 0000000..6fbb503 --- /dev/null +++ b/src/vendor/qrcodegen.c @@ -0,0 +1,1039 @@ +/* + * This library has been modified to output QR codes in a 4bpp format suitable + * for use as a texture without any additional conversion. The original license + * and copyright notice is below. + * ---------------------------------------------------------------------------- + * + * QR Code generator library (C) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * - The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * - The Software is provided "as is", without warranty of any kind, express or + * implied, including but not limited to the warranties of merchantability, + * fitness for a particular purpose and noninfringement. In no event shall the + * authors or copyright holders be liable for any claim, damages or other + * liability, whether in an action of contract, tort or otherwise, arising from, + * out of or in connection with the Software or the use or other dealings in the + * Software. + */ + +#include +#include +#include +#include +#include "qrcodegen.h" + +#ifndef QRCODEGEN_TEST + #define testable static // Keep functions private +#else + #define testable // Expose private functions +#endif + + +/*---- Forward declarations for private functions ----*/ + +// Regarding all public and private functions defined in this source file: +// - They require all pointer/array arguments to be not null unless the array length is zero. +// - They only read input scalar/array arguments, write to output pointer/array +// arguments, and return scalar values; they are "pure" functions. +// - They don't read mutable global variables or write to any global variables. +// - They don't perform I/O, read the clock, print to console, etc. +// - They allocate a small and constant amount of stack memory. +// - They don't allocate or free any memory on the heap. +// - They don't recurse or mutually recurse. All the code +// could be inlined into the top-level public functions. +// - They run in at most quadratic time with respect to input arguments. +// Most functions run in linear time, and some in constant time. +// There are no unbounded loops or non-obvious termination conditions. +// - They are completely thread-safe if the caller does not give the +// same writable buffer to concurrent calls to these functions. + +testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int *bitLen); + +testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[]); +testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl); +testable int getNumRawDataModules(int ver); + +testable void reedSolomonComputeDivisor(int degree, uint8_t result[]); +testable void reedSolomonComputeRemainder(const uint8_t data[], int dataLen, + const uint8_t generator[], int degree, uint8_t result[]); +testable uint8_t reedSolomonMultiply(uint8_t x, uint8_t y); + +testable void initializeFunctionModules(int version, uint32_t qrcode[]); +static void drawLightFunctionModules(uint32_t qrcode[], int version); +static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint32_t qrcode[]); +testable int getAlignmentPatternPositions(int version, uint8_t result[7]); +static void fillRectangle(int left, int top, int width, int height, uint32_t qrcode[]); + +static void drawCodewords(const uint8_t data[], int dataLen, uint32_t qrcode[]); +static void applyMask(const uint32_t functionModules[], uint32_t qrcode[], enum qrcodegen_Mask mask); +static long getPenaltyScore(const uint32_t qrcode[]); +static int finderPenaltyCountPatterns(const int runHistory[7], int qrsize); +static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, int runHistory[7], int qrsize); +static void finderPenaltyAddHistory(int currentRunLength, int runHistory[7], int qrsize); + +testable bool getModuleBounded(const uint32_t qrcode[], int x, int y); +testable void setModuleBounded(uint32_t qrcode[], int x, int y, bool isDark); +testable void setModuleUnbounded(uint32_t qrcode[], int x, int y, bool isDark); +static bool getBit(int x, int i); + +testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars); +testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version); +static int numCharCountBits(enum qrcodegen_Mode mode, int version); + + + +/*---- Private tables of constants ----*/ + +// The set of all legal characters in alphanumeric mode, where each character +// value maps to the index in the string. For checking text and encoding segments. +const char *qrcodegen_ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; + +// For generating error correction codes. +testable const int8_t ECC_CODEWORDS_PER_BLOCK[4][41] = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low + {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium + {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile + {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High +}; + +#define qrcodegen_REED_SOLOMON_DEGREE_MAX 30 // Based on the table above + +// For generating error correction codes. +testable const int8_t NUM_ERROR_CORRECTION_BLOCKS[4][41] = { + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low + {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium + {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile + {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High +}; + +// For automatic mask pattern selection. +static const int PENALTY_N1 = 3; +static const int PENALTY_N2 = 3; +static const int PENALTY_N3 = 40; +static const int PENALTY_N4 = 10; + + + +/*---- High-level QR Code encoding functions ----*/ + +// Public function - see documentation comment in header file. +bool qrcodegen_encodeText(const char *text, uint32_t tempBuffer[], uint32_t qrcode[], + enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl) { + + size_t textLen = strlen(text); + if (textLen == 0) + return qrcodegen_encodeSegmentsAdvanced(NULL, 0, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode); + size_t bufLen = (size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion); + + struct qrcodegen_Segment seg; + if (qrcodegen_isNumeric(text)) { + if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_NUMERIC, textLen) > bufLen) + goto fail; + seg = qrcodegen_makeNumeric(text, (uint8_t *)tempBuffer); + } else if (qrcodegen_isAlphanumeric(text)) { + if (qrcodegen_calcSegmentBufferSize(qrcodegen_Mode_ALPHANUMERIC, textLen) > bufLen) + goto fail; + seg = qrcodegen_makeAlphanumeric(text, (uint8_t *)tempBuffer); + } else { + if (textLen > bufLen) + goto fail; + for (size_t i = 0; i < textLen; i++) + tempBuffer[i] = (uint8_t)text[i]; + seg.mode = qrcodegen_Mode_BYTE; + seg.bitLength = calcSegmentBitLength(seg.mode, textLen); + if (seg.bitLength == -1) + goto fail; + seg.numChars = (int)textLen; + seg.data = (uint8_t *)tempBuffer; + } + return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, tempBuffer, qrcode); + +fail: + qrcode[0] = 0; // Set size to invalid value for safety + return false; +} + + +// Public function - see documentation comment in header file. +bool qrcodegen_encodeBinary(uint32_t dataAndTemp[], size_t dataLen, uint32_t qrcode[], + enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl) { + + struct qrcodegen_Segment seg; + seg.mode = qrcodegen_Mode_BYTE; + seg.bitLength = calcSegmentBitLength(seg.mode, dataLen); + if (seg.bitLength == -1) { + qrcode[0] = 0; // Set size to invalid value for safety + return false; + } + seg.numChars = (int)dataLen; + seg.data = (uint8_t *)dataAndTemp; + return qrcodegen_encodeSegmentsAdvanced(&seg, 1, ecl, minVersion, maxVersion, mask, boostEcl, dataAndTemp, qrcode); +} + + +// Appends the given number of low-order bits of the given value to the given byte-based +// bit buffer, increasing the bit length. Requires 0 <= numBits <= 16 and val < 2^numBits. +testable void appendBitsToBuffer(unsigned int val, int numBits, uint8_t buffer[], int *bitLen) { + assert(0 <= numBits && numBits <= 16 && (unsigned long)val >> numBits == 0); + for (int i = numBits - 1; i >= 0; i--, (*bitLen)++) + buffer[*bitLen >> 3] |= ((val >> i) & 1) << (7 - (*bitLen & 7)); +} + + + +/*---- Low-level QR Code encoding functions ----*/ + +// Public function - see documentation comment in header file. +bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len, + enum qrcodegen_Ecc ecl, uint32_t tempBuffer[], uint32_t qrcode[]) { + return qrcodegen_encodeSegmentsAdvanced(segs, len, ecl, + qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true, tempBuffer, qrcode); +} + + +// Public function - see documentation comment in header file. +bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl, + int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl, uint32_t tempBuffer[], uint32_t qrcode[]) { + assert(segs != NULL || len == 0); + assert(qrcodegen_VERSION_MIN <= minVersion && minVersion <= maxVersion && maxVersion <= qrcodegen_VERSION_MAX); + assert(0 <= (int)ecl && (int)ecl <= 3 && -1 <= (int)mask && (int)mask <= 7); + + // Find the minimal version number to use + int version, dataUsedBits; + for (version = minVersion; ; version++) { + int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available + dataUsedBits = getTotalBits(segs, len, version); + if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) + break; // This version number is found to be suitable + if (version >= maxVersion) { // All versions in the range could not fit the given data + qrcode[0] = 0; // Set size to invalid value for safety + return false; + } + } + assert(dataUsedBits != -1); + + // Increase the error correction level while the data still fits in the current version number + for (int i = (int)qrcodegen_Ecc_MEDIUM; i <= (int)qrcodegen_Ecc_HIGH; i++) { // From low to high + if (boostEcl && dataUsedBits <= getNumDataCodewords(version, (enum qrcodegen_Ecc)i) * 8) + ecl = (enum qrcodegen_Ecc)i; + } + + // Concatenate all segments to create the data bit string + memset(qrcode, 0, (size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(version) * sizeof(uint32_t)); + uint8_t *dataBuffer = (uint8_t *)qrcode; + int bitLen = 0; + for (size_t i = 0; i < len; i++) { + const struct qrcodegen_Segment *seg = &segs[i]; + appendBitsToBuffer((unsigned int)seg->mode, 4, dataBuffer, &bitLen); + appendBitsToBuffer((unsigned int)seg->numChars, numCharCountBits(seg->mode, version), dataBuffer, &bitLen); + for (int j = 0; j < seg->bitLength; j++) { + int bit = (seg->data[j >> 3] >> (7 - (j & 7))) & 1; + appendBitsToBuffer((unsigned int)bit, 1, dataBuffer, &bitLen); + } + } + assert(bitLen == dataUsedBits); + + // Add terminator and pad up to a byte if applicable + int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; + assert(bitLen <= dataCapacityBits); + int terminatorBits = dataCapacityBits - bitLen; + if (terminatorBits > 4) + terminatorBits = 4; + appendBitsToBuffer(0, terminatorBits, dataBuffer, &bitLen); + appendBitsToBuffer(0, (8 - bitLen % 8) % 8, dataBuffer, &bitLen); + assert(bitLen % 8 == 0); + + // Pad with alternating bytes until data capacity is reached + for (uint8_t padByte = 0xEC; bitLen < dataCapacityBits; padByte ^= 0xEC ^ 0x11) + appendBitsToBuffer(padByte, 8, dataBuffer, &bitLen); + + // Compute ECC, draw modules + uint8_t *interleavedBuffer = (uint8_t *)tempBuffer; + addEccAndInterleave(dataBuffer, version, ecl, interleavedBuffer); + initializeFunctionModules(version, qrcode); + drawCodewords(interleavedBuffer, getNumRawDataModules(version) / 8, qrcode); + drawLightFunctionModules(qrcode, version); + initializeFunctionModules(version, tempBuffer); + + // Do masking + if (mask == qrcodegen_Mask_AUTO) { // Automatically choose best mask + long minPenalty = LONG_MAX; + for (int i = 0; i < 8; i++) { + enum qrcodegen_Mask msk = (enum qrcodegen_Mask)i; + applyMask(tempBuffer, qrcode, msk); + drawFormatBits(ecl, msk, qrcode); + long penalty = getPenaltyScore(qrcode); + if (penalty < minPenalty) { + mask = msk; + minPenalty = penalty; + } + applyMask(tempBuffer, qrcode, msk); // Undoes the mask due to XOR + } + } + assert(0 <= (int)mask && (int)mask <= 7); + applyMask(tempBuffer, qrcode, mask); // Apply the final choice of mask + drawFormatBits(ecl, mask, qrcode); // Overwrite old format bits + return true; +} + + + +/*---- Error correction code generation functions ----*/ + +// Appends error correction bytes to each block of the given data array, then interleaves +// bytes from the blocks and stores them in the result array. data[0 : dataLen] contains +// the input data. data[dataLen : rawCodewords] is used as a temporary work area and will +// be clobbered by this function. The final answer is stored in result[0 : rawCodewords]. +testable void addEccAndInterleave(uint8_t data[], int version, enum qrcodegen_Ecc ecl, uint8_t result[]) { + // Calculate parameter numbers + assert(0 <= (int)ecl && (int)ecl < 4 && qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX); + int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[(int)ecl][version]; + int blockEccLen = ECC_CODEWORDS_PER_BLOCK [(int)ecl][version]; + int rawCodewords = getNumRawDataModules(version) / 8; + int dataLen = getNumDataCodewords(version, ecl); + int numShortBlocks = numBlocks - rawCodewords % numBlocks; + int shortBlockDataLen = rawCodewords / numBlocks - blockEccLen; + + // Split data into blocks, calculate ECC, and interleave + // (not concatenate) the bytes into a single sequence + uint8_t rsdiv[qrcodegen_REED_SOLOMON_DEGREE_MAX]; + reedSolomonComputeDivisor(blockEccLen, rsdiv); + const uint8_t *dat = data; + for (int i = 0; i < numBlocks; i++) { + int datLen = shortBlockDataLen + (i < numShortBlocks ? 0 : 1); + uint8_t *ecc = &data[dataLen]; // Temporary storage + reedSolomonComputeRemainder(dat, datLen, rsdiv, blockEccLen, ecc); + for (int j = 0, k = i; j < datLen; j++, k += numBlocks) { // Copy data + if (j == shortBlockDataLen) + k -= numShortBlocks; + result[k] = dat[j]; + } + for (int j = 0, k = dataLen + i; j < blockEccLen; j++, k += numBlocks) // Copy ECC + result[k] = ecc[j]; + dat += datLen; + } +} + + +// Returns the number of 8-bit codewords that can be used for storing data (not ECC), +// for the given version number and error correction level. The result is in the range [9, 2956]. +testable int getNumDataCodewords(int version, enum qrcodegen_Ecc ecl) { + int v = version, e = (int)ecl; + assert(0 <= e && e < 4); + return getNumRawDataModules(v) / 8 + - ECC_CODEWORDS_PER_BLOCK [e][v] + * NUM_ERROR_CORRECTION_BLOCKS[e][v]; +} + + +// Returns the number of data bits that can be stored in a QR Code of the given version number, after +// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. +// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. +testable int getNumRawDataModules(int ver) { + assert(qrcodegen_VERSION_MIN <= ver && ver <= qrcodegen_VERSION_MAX); + int result = (16 * ver + 128) * ver + 64; + if (ver >= 2) { + int numAlign = ver / 7 + 2; + result -= (25 * numAlign - 10) * numAlign - 55; + if (ver >= 7) + result -= 36; + } + assert(208 <= result && result <= 29648); + return result; +} + + + +/*---- Reed-Solomon ECC generator functions ----*/ + +// Computes a Reed-Solomon ECC generator polynomial for the given degree, storing in result[0 : degree]. +// This could be implemented as a lookup table over all possible parameter values, instead of as an algorithm. +testable void reedSolomonComputeDivisor(int degree, uint8_t result[]) { + assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX); + // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. + // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. + memset(result, 0, (size_t)degree * sizeof(result[0])); + result[degree - 1] = 1; // Start off with the monomial x^0 + + // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), + // drop the highest monomial term which is always 1x^degree. + // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). + uint8_t root = 1; + for (int i = 0; i < degree; i++) { + // Multiply the current product by (x - r^i) + for (int j = 0; j < degree; j++) { + result[j] = reedSolomonMultiply(result[j], root); + if (j + 1 < degree) + result[j] ^= result[j + 1]; + } + root = reedSolomonMultiply(root, 0x02); + } +} + + +// Computes the Reed-Solomon error correction codeword for the given data and divisor polynomials. +// The remainder when data[0 : dataLen] is divided by divisor[0 : degree] is stored in result[0 : degree]. +// All polynomials are in big endian, and the generator has an implicit leading 1 term. +testable void reedSolomonComputeRemainder(const uint8_t data[], int dataLen, + const uint8_t generator[], int degree, uint8_t result[]) { + assert(1 <= degree && degree <= qrcodegen_REED_SOLOMON_DEGREE_MAX); + memset(result, 0, (size_t)degree * sizeof(result[0])); + for (int i = 0; i < dataLen; i++) { // Polynomial division + uint8_t factor = data[i] ^ result[0]; + memmove(&result[0], &result[1], (size_t)(degree - 1) * sizeof(result[0])); + result[degree - 1] = 0; + for (int j = 0; j < degree; j++) + result[j] ^= reedSolomonMultiply(generator[j], factor); + } +} + +#undef qrcodegen_REED_SOLOMON_DEGREE_MAX + + +// Returns the product of the two given field elements modulo GF(2^8/0x11D). +// All inputs are valid. This could be implemented as a 256*256 lookup table. +testable uint8_t reedSolomonMultiply(uint8_t x, uint8_t y) { + // Russian peasant multiplication + uint8_t z = 0; + for (int i = 7; i >= 0; i--) { + z = (uint8_t)((z << 1) ^ ((z >> 7) * 0x11D)); + z ^= ((y >> i) & 1) * x; + } + return z; +} + + + +/*---- Drawing function modules ----*/ + +// Clears the given QR Code grid with light modules for the given +// version's size, then marks every function module as dark. +testable void initializeFunctionModules(int version, uint32_t qrcode[]) { + // Initialize QR Code + int qrsize = qrcodegen_SIZE_FOR_VERSION(version); + memset(qrcode, 0, (size_t)qrcodegen_BUFFER_LEN_FOR_VERSION(version) * sizeof(uint32_t)); + qrcode[0] = (uint32_t)qrsize | ((uint32_t)qrcodegen_STRIDE_FOR_VERSION(version) << 16); + + // Fill horizontal and vertical timing patterns + fillRectangle(6, 0, 1, qrsize, qrcode); + fillRectangle(0, 6, qrsize, 1, qrcode); + + // Fill 3 finder patterns (all corners except bottom right) and format bits + fillRectangle(0, 0, 9, 9, qrcode); + fillRectangle(qrsize - 8, 0, 8, 9, qrcode); + fillRectangle(0, qrsize - 8, 9, 8, qrcode); + + // Fill numerous alignment patterns + uint8_t alignPatPos[7]; + int numAlign = getAlignmentPatternPositions(version, alignPatPos); + for (int i = 0; i < numAlign; i++) { + for (int j = 0; j < numAlign; j++) { + // Don't draw on the three finder corners + if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))) + fillRectangle(alignPatPos[i] - 2, alignPatPos[j] - 2, 5, 5, qrcode); + } + } + + // Fill version blocks + if (version >= 7) { + fillRectangle(qrsize - 11, 0, 3, 6, qrcode); + fillRectangle(0, qrsize - 11, 6, 3, qrcode); + } +} + + +// Draws light function modules and possibly some dark modules onto the given QR Code, without changing +// non-function modules. This does not draw the format bits. This requires all function modules to be previously +// marked dark (namely by initializeFunctionModules()), because this may skip redrawing dark function modules. +static void drawLightFunctionModules(uint32_t qrcode[], int version) { + // Draw horizontal and vertical timing patterns + int qrsize = qrcodegen_getSize(qrcode); + for (int i = 7; i < qrsize - 7; i += 2) { + setModuleBounded(qrcode, 6, i, false); + setModuleBounded(qrcode, i, 6, false); + } + + // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) + for (int dy = -4; dy <= 4; dy++) { + for (int dx = -4; dx <= 4; dx++) { + int dist = abs(dx); + if (abs(dy) > dist) + dist = abs(dy); + if (dist == 2 || dist == 4) { + setModuleUnbounded(qrcode, 3 + dx, 3 + dy, false); + setModuleUnbounded(qrcode, qrsize - 4 + dx, 3 + dy, false); + setModuleUnbounded(qrcode, 3 + dx, qrsize - 4 + dy, false); + } + } + } + + // Draw numerous alignment patterns + uint8_t alignPatPos[7]; + int numAlign = getAlignmentPatternPositions(version, alignPatPos); + for (int i = 0; i < numAlign; i++) { + for (int j = 0; j < numAlign; j++) { + if ((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)) + continue; // Don't draw on the three finder corners + for (int dy = -1; dy <= 1; dy++) { + for (int dx = -1; dx <= 1; dx++) + setModuleBounded(qrcode, alignPatPos[i] + dx, alignPatPos[j] + dy, dx == 0 && dy == 0); + } + } + } + + // Draw version blocks + if (version >= 7) { + // Calculate error correction code and pack bits + int rem = version; // version is uint6, in the range [7, 40] + for (int i = 0; i < 12; i++) + rem = (rem << 1) ^ ((rem >> 11) * 0x1F25); + long bits = (long)version << 12 | rem; // uint18 + assert(bits >> 18 == 0); + + // Draw two copies + for (int i = 0; i < 6; i++) { + for (int j = 0; j < 3; j++) { + int k = qrsize - 11 + j; + setModuleBounded(qrcode, k, i, (bits & 1) != 0); + setModuleBounded(qrcode, i, k, (bits & 1) != 0); + bits >>= 1; + } + } + } +} + + +// Draws two copies of the format bits (with its own error correction code) based +// on the given mask and error correction level. This always draws all modules of +// the format bits, unlike drawLightFunctionModules() which might skip dark modules. +static void drawFormatBits(enum qrcodegen_Ecc ecl, enum qrcodegen_Mask mask, uint32_t qrcode[]) { + // Calculate error correction code and pack bits + assert(0 <= (int)mask && (int)mask <= 7); + static const int table[] = {1, 0, 3, 2}; + int data = table[(int)ecl] << 3 | (int)mask; // errCorrLvl is uint2, mask is uint3 + int rem = data; + for (int i = 0; i < 10; i++) + rem = (rem << 1) ^ ((rem >> 9) * 0x537); + int bits = (data << 10 | rem) ^ 0x5412; // uint15 + assert(bits >> 15 == 0); + + // Draw first copy + for (int i = 0; i <= 5; i++) + setModuleBounded(qrcode, 8, i, getBit(bits, i)); + setModuleBounded(qrcode, 8, 7, getBit(bits, 6)); + setModuleBounded(qrcode, 8, 8, getBit(bits, 7)); + setModuleBounded(qrcode, 7, 8, getBit(bits, 8)); + for (int i = 9; i < 15; i++) + setModuleBounded(qrcode, 14 - i, 8, getBit(bits, i)); + + // Draw second copy + int qrsize = qrcodegen_getSize(qrcode); + for (int i = 0; i < 8; i++) + setModuleBounded(qrcode, qrsize - 1 - i, 8, getBit(bits, i)); + for (int i = 8; i < 15; i++) + setModuleBounded(qrcode, 8, qrsize - 15 + i, getBit(bits, i)); + setModuleBounded(qrcode, 8, qrsize - 8, true); // Always dark +} + + +// Calculates and stores an ascending list of positions of alignment patterns +// for this version number, returning the length of the list (in the range [0,7]). +// Each position is in the range [0,177), and are used on both the x and y axes. +// This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. +testable int getAlignmentPatternPositions(int version, uint8_t result[7]) { + if (version == 1) + return 0; + int numAlign = version / 7 + 2; + int step = (version == 32) ? 26 : + (version * 4 + numAlign * 2 + 1) / (numAlign * 2 - 2) * 2; + for (int i = numAlign - 1, pos = version * 4 + 10; i >= 1; i--, pos -= step) + result[i] = (uint8_t)pos; + result[0] = 6; + return numAlign; +} + + +// Sets every module in the range [left : left + width] * [top : top + height] to dark. +static void fillRectangle(int left, int top, int width, int height, uint32_t qrcode[]) { + for (int dy = 0; dy < height; dy++) { + for (int dx = 0; dx < width; dx++) + setModuleBounded(qrcode, left + dx, top + dy, true); + } +} + + + +/*---- Drawing data modules and masking ----*/ + +// Draws the raw codewords (including data and ECC) onto the given QR Code. This requires the initial state of +// the QR Code to be dark at function modules and light at codeword modules (including unused remainder bits). +static void drawCodewords(const uint8_t data[], int dataLen, uint32_t qrcode[]) { + int qrsize = qrcodegen_getSize(qrcode); + int i = 0; // Bit index into the data + // Do the funny zigzag scan + for (int right = qrsize - 1; right >= 1; right -= 2) { // Index of right column in each column pair + if (right == 6) + right = 5; + for (int vert = 0; vert < qrsize; vert++) { // Vertical counter + for (int j = 0; j < 2; j++) { + int x = right - j; // Actual x coordinate + bool upward = ((right + 1) & 2) == 0; + int y = upward ? qrsize - 1 - vert : vert; // Actual y coordinate + if (!getModuleBounded(qrcode, x, y) && i < dataLen * 8) { + bool dark = getBit(data[i >> 3], 7 - (i & 7)); + setModuleBounded(qrcode, x, y, dark); + i++; + } + // If this QR Code has any remainder bits (0 to 7), they were assigned as + // 0/false/light by the constructor and are left unchanged by this method + } + } + } + assert(i == dataLen * 8); +} + + +// XORs the codeword modules in this QR Code with the given mask pattern +// and given pattern of function modules. The codeword bits must be drawn +// before masking. Due to the arithmetic of XOR, calling applyMask() with +// the same mask value a second time will undo the mask. A final well-formed +// QR Code needs exactly one (not zero, two, etc.) mask applied. +static void applyMask(const uint32_t functionModules[], uint32_t qrcode[], enum qrcodegen_Mask mask) { + assert(0 <= (int)mask && (int)mask <= 7); // Disallows qrcodegen_Mask_AUTO + int qrsize = qrcodegen_getSize(qrcode); + for (int y = 0; y < qrsize; y++) { + for (int x = 0; x < qrsize; x++) { + if (getModuleBounded(functionModules, x, y)) + continue; + bool invert; + switch ((int)mask) { + case 0: invert = (x + y) % 2 == 0; break; + case 1: invert = y % 2 == 0; break; + case 2: invert = x % 3 == 0; break; + case 3: invert = (x + y) % 3 == 0; break; + case 4: invert = (x / 3 + y / 2) % 2 == 0; break; + case 5: invert = x * y % 2 + x * y % 3 == 0; break; + case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; + case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; + default: assert(false); return; + } + bool val = getModuleBounded(qrcode, x, y); + setModuleBounded(qrcode, x, y, val ^ invert); + } + } +} + + +// Calculates and returns the penalty score based on state of the given QR Code's current modules. +// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. +static long getPenaltyScore(const uint32_t qrcode[]) { + int qrsize = qrcodegen_getSize(qrcode); + long result = 0; + + // Adjacent modules in row having same color, and finder-like patterns + for (int y = 0; y < qrsize; y++) { + bool runColor = false; + int runX = 0; + int runHistory[7] = {0}; + for (int x = 0; x < qrsize; x++) { + if (getModuleBounded(qrcode, x, y) == runColor) { + runX++; + if (runX == 5) + result += PENALTY_N1; + else if (runX > 5) + result++; + } else { + finderPenaltyAddHistory(runX, runHistory, qrsize); + if (!runColor) + result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3; + runColor = getModuleBounded(qrcode, x, y); + runX = 1; + } + } + result += finderPenaltyTerminateAndCount(runColor, runX, runHistory, qrsize) * PENALTY_N3; + } + // Adjacent modules in column having same color, and finder-like patterns + for (int x = 0; x < qrsize; x++) { + bool runColor = false; + int runY = 0; + int runHistory[7] = {0}; + for (int y = 0; y < qrsize; y++) { + if (getModuleBounded(qrcode, x, y) == runColor) { + runY++; + if (runY == 5) + result += PENALTY_N1; + else if (runY > 5) + result++; + } else { + finderPenaltyAddHistory(runY, runHistory, qrsize); + if (!runColor) + result += finderPenaltyCountPatterns(runHistory, qrsize) * PENALTY_N3; + runColor = getModuleBounded(qrcode, x, y); + runY = 1; + } + } + result += finderPenaltyTerminateAndCount(runColor, runY, runHistory, qrsize) * PENALTY_N3; + } + + // 2*2 blocks of modules having same color + for (int y = 0; y < qrsize - 1; y++) { + for (int x = 0; x < qrsize - 1; x++) { + bool color = getModuleBounded(qrcode, x, y); + if ( color == getModuleBounded(qrcode, x + 1, y) && + color == getModuleBounded(qrcode, x, y + 1) && + color == getModuleBounded(qrcode, x + 1, y + 1)) + result += PENALTY_N2; + } + } + + // Balance of dark and light modules + int dark = 0; + for (int y = 0; y < qrsize; y++) { + for (int x = 0; x < qrsize; x++) { + if (getModuleBounded(qrcode, x, y)) + dark++; + } + } + int total = qrsize * qrsize; // Note that size is odd, so dark/total != 1/2 + // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% + int k = (int)((labs(dark * 20L - total * 10L) + total - 1) / total) - 1; + assert(0 <= k && k <= 9); + result += k * PENALTY_N4; + assert(0 <= result && result <= 2568888L); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4 + return result; +} + + +// Can only be called immediately after a light run is added, and +// returns either 0, 1, or 2. A helper function for getPenaltyScore(). +static int finderPenaltyCountPatterns(const int runHistory[7], int qrsize) { + int n = runHistory[1]; + assert(n <= qrsize * 3); (void)qrsize; + bool core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n; + // The maximum QR Code size is 177, hence the dark run length n <= 177. + // Arithmetic is promoted to int, so n*4 will not overflow. + return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); +} + + +// Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). +static int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, int runHistory[7], int qrsize) { + if (currentRunColor) { // Terminate dark run + finderPenaltyAddHistory(currentRunLength, runHistory, qrsize); + currentRunLength = 0; + } + currentRunLength += qrsize; // Add light border to final run + finderPenaltyAddHistory(currentRunLength, runHistory, qrsize); + return finderPenaltyCountPatterns(runHistory, qrsize); +} + + +// Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). +static void finderPenaltyAddHistory(int currentRunLength, int runHistory[7], int qrsize) { + if (runHistory[0] == 0) + currentRunLength += qrsize; // Add light border to initial run + memmove(&runHistory[1], &runHistory[0], 6 * sizeof(runHistory[0])); + runHistory[0] = currentRunLength; +} + + + +/*---- Basic QR Code information ----*/ + +// Public function - see documentation comment in header file. +int qrcodegen_getSize(const uint32_t qrcode[]) { + assert(qrcode != NULL); + int result = qrcode[0] & 0xFFFF; + assert((qrcodegen_VERSION_MIN * 4 + 17) <= result + && result <= (qrcodegen_VERSION_MAX * 4 + 17)); + return result; +} + + +// Public function - see documentation comment in header file. +int qrcodegen_getStride(const uint32_t qrcode[]) { + assert(qrcode != NULL); + int result = qrcode[0] >> 16; + //assert((qrcodegen_VERSION_MIN * 4 + 17) <= result + //&& result <= (qrcodegen_VERSION_MAX * 4 + 17)); + return result; +} + + +// Public function - see documentation comment in header file. +bool qrcodegen_getModule(const uint32_t qrcode[], int x, int y) { + assert(qrcode != NULL); + int qrsize = qrcode[0] & 0xFFFF; + return (0 <= x && x < qrsize && 0 <= y && y < qrsize) && getModuleBounded(qrcode, x, y); +} + + +// Returns the color of the module at the given coordinates, which must be in bounds. +testable bool getModuleBounded(const uint32_t qrcode[], int x, int y) { + int qrsize = qrcode[0] & 0xFFFF, stride = qrcode[0] >> 16; + assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize); + int bitIndex = (x % 8) * 4; + int wordIndex = y * stride + x / 8; + return (qrcode[wordIndex + 1] >> bitIndex) & 1; +} + + +// Sets the color of the module at the given coordinates, which must be in bounds. +testable void setModuleBounded(uint32_t qrcode[], int x, int y, bool isDark) { + int qrsize = qrcode[0] & 0xFFFF, stride = qrcode[0] >> 16; + assert(21 <= qrsize && qrsize <= 177 && 0 <= x && x < qrsize && 0 <= y && y < qrsize); + int bitIndex = (x % 8) * 4; + int wordIndex = y * stride + x / 8; + if (isDark) + qrcode[wordIndex + 1] |= 1 << bitIndex; + else + qrcode[wordIndex + 1] &= ~(0xF << bitIndex); +} + + +// Sets the color of the module at the given coordinates, doing nothing if out of bounds. +testable void setModuleUnbounded(uint32_t qrcode[], int x, int y, bool isDark) { + int qrsize = qrcode[0] & 0xFFFF; + if (0 <= x && x < qrsize && 0 <= y && y < qrsize) + setModuleBounded(qrcode, x, y, isDark); +} + + +// Returns true iff the i'th bit of x is set to 1. Requires x >= 0 and 0 <= i <= 14. +static bool getBit(int x, int i) { + return ((x >> i) & 1) != 0; +} + + + +/*---- Segment handling ----*/ + +// Public function - see documentation comment in header file. +bool qrcodegen_isNumeric(const char *text) { + assert(text != NULL); + for (; *text != '\0'; text++) { + if (*text < '0' || *text > '9') + return false; + } + return true; +} + + +// Public function - see documentation comment in header file. +bool qrcodegen_isAlphanumeric(const char *text) { + assert(text != NULL); + for (; *text != '\0'; text++) { + if (strchr(qrcodegen_ALPHANUMERIC_CHARSET, *text) == NULL) + return false; + } + return true; +} + + +// Public function - see documentation comment in header file. +size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars) { + int temp = calcSegmentBitLength(mode, numChars); + if (temp == -1) + return SIZE_MAX; + assert(0 <= temp && temp <= INT16_MAX); + return ((size_t)temp + 7) / 8; +} + + +// Returns the number of data bits needed to represent a segment +// containing the given number of characters using the given mode. Notes: +// - Returns -1 on failure, i.e. numChars > INT16_MAX or +// the number of needed bits exceeds INT16_MAX (i.e. 32767). +// - Otherwise, all valid results are in the range [0, INT16_MAX]. +// - For byte mode, numChars measures the number of bytes, not Unicode code points. +// - For ECI mode, numChars must be 0, and the worst-case number of bits is returned. +// An actual ECI segment can have shorter data. For non-ECI modes, the result is exact. +testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars) { + // All calculations are designed to avoid overflow on all platforms + if (numChars > (unsigned int)INT16_MAX) + return -1; + long result = (long)numChars; + if (mode == qrcodegen_Mode_NUMERIC) + result = (result * 10 + 2) / 3; // ceil(10/3 * n) + else if (mode == qrcodegen_Mode_ALPHANUMERIC) + result = (result * 11 + 1) / 2; // ceil(11/2 * n) + else if (mode == qrcodegen_Mode_BYTE) + result *= 8; + else if (mode == qrcodegen_Mode_KANJI) + result *= 13; + else if (mode == qrcodegen_Mode_ECI && numChars == 0) + result = 3 * 8; + else { // Invalid argument + assert(false); + return -1; + } + assert(result >= 0); + if (result > INT16_MAX) + return -1; + return (int)result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]) { + assert(data != NULL || len == 0); + struct qrcodegen_Segment result; + result.mode = qrcodegen_Mode_BYTE; + result.bitLength = calcSegmentBitLength(result.mode, len); + assert(result.bitLength != -1); + result.numChars = (int)len; + if (len > 0) + memcpy(buf, data, len * sizeof(buf[0])); + result.data = buf; + return result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]) { + assert(digits != NULL); + struct qrcodegen_Segment result; + size_t len = strlen(digits); + result.mode = qrcodegen_Mode_NUMERIC; + int bitLen = calcSegmentBitLength(result.mode, len); + assert(bitLen != -1); + result.numChars = (int)len; + if (bitLen > 0) + memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0])); + result.bitLength = 0; + + unsigned int accumData = 0; + int accumCount = 0; + for (; *digits != '\0'; digits++) { + char c = *digits; + assert('0' <= c && c <= '9'); + accumData = accumData * 10 + (unsigned int)(c - '0'); + accumCount++; + if (accumCount == 3) { + appendBitsToBuffer(accumData, 10, buf, &result.bitLength); + accumData = 0; + accumCount = 0; + } + } + if (accumCount > 0) // 1 or 2 digits remaining + appendBitsToBuffer(accumData, accumCount * 3 + 1, buf, &result.bitLength); + assert(result.bitLength == bitLen); + result.data = buf; + return result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]) { + assert(text != NULL); + struct qrcodegen_Segment result; + size_t len = strlen(text); + result.mode = qrcodegen_Mode_ALPHANUMERIC; + int bitLen = calcSegmentBitLength(result.mode, len); + assert(bitLen != -1); + result.numChars = (int)len; + if (bitLen > 0) + memset(buf, 0, ((size_t)bitLen + 7) / 8 * sizeof(buf[0])); + result.bitLength = 0; + + unsigned int accumData = 0; + int accumCount = 0; + for (; *text != '\0'; text++) { + const char *temp = strchr(qrcodegen_ALPHANUMERIC_CHARSET, *text); + assert(temp != NULL); + accumData = accumData * 45 + (unsigned int)(temp - qrcodegen_ALPHANUMERIC_CHARSET); + accumCount++; + if (accumCount == 2) { + appendBitsToBuffer(accumData, 11, buf, &result.bitLength); + accumData = 0; + accumCount = 0; + } + } + if (accumCount > 0) // 1 character remaining + appendBitsToBuffer(accumData, 6, buf, &result.bitLength); + assert(result.bitLength == bitLen); + result.data = buf; + return result; +} + + +// Public function - see documentation comment in header file. +struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]) { + struct qrcodegen_Segment result; + result.mode = qrcodegen_Mode_ECI; + result.numChars = 0; + result.bitLength = 0; + if (assignVal < 0) + assert(false); + else if (assignVal < (1 << 7)) { + memset(buf, 0, 1 * sizeof(buf[0])); + appendBitsToBuffer((unsigned int)assignVal, 8, buf, &result.bitLength); + } else if (assignVal < (1 << 14)) { + memset(buf, 0, 2 * sizeof(buf[0])); + appendBitsToBuffer(2, 2, buf, &result.bitLength); + appendBitsToBuffer((unsigned int)assignVal, 14, buf, &result.bitLength); + } else if (assignVal < 1000000L) { + memset(buf, 0, 3 * sizeof(buf[0])); + appendBitsToBuffer(6, 3, buf, &result.bitLength); + appendBitsToBuffer((unsigned int)(assignVal >> 10), 11, buf, &result.bitLength); + appendBitsToBuffer((unsigned int)(assignVal & 0x3FF), 10, buf, &result.bitLength); + } else + assert(false); + result.data = buf; + return result; +} + + +// Calculates the number of bits needed to encode the given segments at the given version. +// Returns a non-negative number if successful. Otherwise returns -1 if a segment has too +// many characters to fit its length field, or the total bits exceeds INT16_MAX. +testable int getTotalBits(const struct qrcodegen_Segment segs[], size_t len, int version) { + assert(segs != NULL || len == 0); + long result = 0; + for (size_t i = 0; i < len; i++) { + int numChars = segs[i].numChars; + int bitLength = segs[i].bitLength; + assert(0 <= numChars && numChars <= INT16_MAX); + assert(0 <= bitLength && bitLength <= INT16_MAX); + int ccbits = numCharCountBits(segs[i].mode, version); + assert(0 <= ccbits && ccbits <= 16); + if (numChars >= (1L << ccbits)) + return -1; // The segment's length doesn't fit the field's bit width + result += 4L + ccbits + bitLength; + if (result > INT16_MAX) + return -1; // The sum might overflow an int type + } + assert(0 <= result && result <= INT16_MAX); + return (int)result; +} + + +// Returns the bit width of the character count field for a segment in the given mode +// in a QR Code at the given version number. The result is in the range [0, 16]. +static int numCharCountBits(enum qrcodegen_Mode mode, int version) { + assert(qrcodegen_VERSION_MIN <= version && version <= qrcodegen_VERSION_MAX); + int i = (version + 7) / 17; + switch (mode) { + case qrcodegen_Mode_NUMERIC : { static const int temp[] = {10, 12, 14}; return temp[i]; } + case qrcodegen_Mode_ALPHANUMERIC: { static const int temp[] = { 9, 11, 13}; return temp[i]; } + case qrcodegen_Mode_BYTE : { static const int temp[] = { 8, 16, 16}; return temp[i]; } + case qrcodegen_Mode_KANJI : { static const int temp[] = { 8, 10, 12}; return temp[i]; } + case qrcodegen_Mode_ECI : return 0; + default: assert(false); return -1; // Dummy value + } +} diff --git a/src/vendor/qrcodegen.h b/src/vendor/qrcodegen.h new file mode 100644 index 0000000..3ec072e --- /dev/null +++ b/src/vendor/qrcodegen.h @@ -0,0 +1,402 @@ +/* + * This library has been modified to output QR codes in a 4bpp format suitable + * for use as a texture without any additional conversion. The original license + * and copyright notice is below. + * ---------------------------------------------------------------------------- + * + * QR Code generator library (C) + * + * Copyright (c) Project Nayuki. (MIT License) + * https://www.nayuki.io/page/qr-code-generator-library + * + * 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. + */ + +#pragma once + +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/* + * This library creates QR Code symbols, which is a type of two-dimension barcode. + * Invented by Denso Wave and described in the ISO/IEC 18004 standard. + * A QR Code structure is an immutable square grid of dark and light cells. + * The library provides functions to create a QR Code from text or binary data. + * The library covers the QR Code Model 2 specification, supporting all versions (sizes) + * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. + * + * Ways to create a QR Code object: + * - High level: Take the payload data and call qrcodegen_encodeText() or qrcodegen_encodeBinary(). + * - Low level: Custom-make the list of segments and call + * qrcodegen_encodeSegments() or qrcodegen_encodeSegmentsAdvanced(). + * (Note that all ways require supplying the desired error correction level and various byte buffers.) + */ + + +/*---- Enum and struct types----*/ + +/* + * The error correction level in a QR Code symbol. + */ +enum qrcodegen_Ecc { + // Must be declared in ascending order of error protection + // so that an internal qrcodegen function works properly + qrcodegen_Ecc_LOW = 0 , // The QR Code can tolerate about 7% erroneous codewords + qrcodegen_Ecc_MEDIUM , // The QR Code can tolerate about 15% erroneous codewords + qrcodegen_Ecc_QUARTILE, // The QR Code can tolerate about 25% erroneous codewords + qrcodegen_Ecc_HIGH , // The QR Code can tolerate about 30% erroneous codewords +}; + + +/* + * The mask pattern used in a QR Code symbol. + */ +enum qrcodegen_Mask { + // A special value to tell the QR Code encoder to + // automatically select an appropriate mask pattern + qrcodegen_Mask_AUTO = -1, + // The eight actual mask patterns + qrcodegen_Mask_0 = 0, + qrcodegen_Mask_1, + qrcodegen_Mask_2, + qrcodegen_Mask_3, + qrcodegen_Mask_4, + qrcodegen_Mask_5, + qrcodegen_Mask_6, + qrcodegen_Mask_7, +}; + + +/* + * Describes how a segment's data bits are interpreted. + */ +enum qrcodegen_Mode { + qrcodegen_Mode_NUMERIC = 0x1, + qrcodegen_Mode_ALPHANUMERIC = 0x2, + qrcodegen_Mode_BYTE = 0x4, + qrcodegen_Mode_KANJI = 0x8, + qrcodegen_Mode_ECI = 0x7, +}; + + +/* + * A segment of character/binary/control data in a QR Code symbol. + * The mid-level way to create a segment is to take the payload data + * and call a factory function such as qrcodegen_makeNumeric(). + * The low-level way to create a segment is to custom-make the bit buffer + * and initialize a qrcodegen_Segment struct with appropriate values. + * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. + * Any segment longer than this is meaningless for the purpose of generating QR Codes. + * Moreover, the maximum allowed bit length is 32767 because + * the largest QR Code (version 40) has 31329 modules. + */ +struct qrcodegen_Segment { + // The mode indicator of this segment. + enum qrcodegen_Mode mode; + + // The length of this segment's unencoded data. Measured in characters for + // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. + // Always zero or positive. Not the same as the data's bit length. + int numChars; + + // The data bits of this segment, packed in bitwise big endian. + // Can be null if the bit length is zero. + uint8_t *data; + + // The number of valid data bits used in the buffer. Requires + // 0 <= bitLength <= 32767, and bitLength <= (capacity of data array) * 8. + // The character count (numChars) must agree with the mode and the bit buffer length. + int bitLength; +}; + + +extern const char *qrcodegen_ALPHANUMERIC_CHARSET; + + + +/*---- Macro constants and functions ----*/ + +#define qrcodegen_VERSION_MIN 1 // The minimum version number supported in the QR Code Model 2 standard +#define qrcodegen_VERSION_MAX 40 // The maximum version number supported in the QR Code Model 2 standard + +// Calculates the number of uint32s needed to store any QR Code up to and including the given version number, +// as a compile-time constant. For example, 'uint32_t buffer[qrcodegen_BUFFER_LEN_FOR_VERSION(25)];' +// can store any single QR Code from version 1 to 25 (inclusive). The result fits in an int (or int16). +// Requires qrcodegen_VERSION_MIN <= n <= qrcodegen_VERSION_MAX. +#define qrcodegen_SIZE_FOR_VERSION(n) ((n) * 4 + 17) +#define qrcodegen_STRIDE_FOR_VERSION(n) ((qrcodegen_SIZE_FOR_VERSION(n) + 7) / 8) +#define qrcodegen_BUFFER_LEN_FOR_VERSION(n) (qrcodegen_SIZE_FOR_VERSION(n) * qrcodegen_STRIDE_FOR_VERSION(n) + 1) + +// The worst-case number of bytes needed to store one QR Code, up to and including +// version 40. This value equals 3918, which is just under 4 kilobytes. +// Use this more convenient value to avoid calculating tighter memory bounds for buffers. +#define qrcodegen_TEMP_BUFFER_LEN_MAX qrcodegen_TEMP_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX) +#define qrcodegen_BUFFER_LEN_MAX qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX) + + + +/*---- Functions (high level) to generate QR Codes ----*/ + +/* + * Encodes the given text string to a QR Code, returning true if successful. + * If the data is too long to fit in any version in the given range + * at the given ECC level, then false is returned. + * + * The input text must be encoded in UTF-8 and contain no NULs. + * Requires 1 <= minVersion <= maxVersion <= 40. + * + * The smallest possible QR Code version within the given range is automatically + * chosen for the output. Iff boostEcl is true, then the ECC level of the result + * may be higher than the ecl argument if it can be done without increasing the + * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or + * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). + * + * About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion): + * - Before calling the function: + * - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow + * reading and writing; hence each array must have a length of at least len. + * - The two ranges must not overlap (aliasing). + * - The initial state of both ranges can be uninitialized + * because the function always writes before reading. + * - After the function returns: + * - Both ranges have no guarantee on which elements are initialized and what values are stored. + * - tempBuffer contains no useful data and should be treated as entirely uninitialized. + * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). + * + * If successful, the resulting QR Code may use numeric, + * alphanumeric, or byte mode to encode the text. + * + * In the most optimistic case, a QR Code at version 40 with low ECC + * can hold any UTF-8 string up to 2953 bytes, or any alphanumeric string + * up to 4296 characters, or any digit string up to 7089 characters. + * These numbers represent the hard upper limit of the QR Code standard. + * + * Please consult the QR Code specification for information on + * data capacities per version, ECC level, and text encoding mode. + */ +bool qrcodegen_encodeText(const char *text, uint32_t tempBuffer[], uint32_t qrcode[], + enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl); + + +/* + * Encodes the given binary data to a QR Code, returning true if successful. + * If the data is too long to fit in any version in the given range + * at the given ECC level, then false is returned. + * + * Requires 1 <= minVersion <= maxVersion <= 40. + * + * The smallest possible QR Code version within the given range is automatically + * chosen for the output. Iff boostEcl is true, then the ECC level of the result + * may be higher than the ecl argument if it can be done without increasing the + * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or + * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). + * + * About the arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(maxVersion): + * - Before calling the function: + * - The array ranges dataAndTemp[0 : len] and qrcode[0 : len] must allow + * reading and writing; hence each array must have a length of at least len. + * - The two ranges must not overlap (aliasing). + * - The input array range dataAndTemp[0 : dataLen] should normally be + * valid UTF-8 text, but is not required by the QR Code standard. + * - The initial state of dataAndTemp[dataLen : len] and qrcode[0 : len] + * can be uninitialized because the function always writes before reading. + * - After the function returns: + * - Both ranges have no guarantee on which elements are initialized and what values are stored. + * - dataAndTemp contains no useful data and should be treated as entirely uninitialized. + * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). + * + * If successful, the resulting QR Code will use byte mode to encode the data. + * + * In the most optimistic case, a QR Code at version 40 with low ECC can hold any byte + * sequence up to length 2953. This is the hard upper limit of the QR Code standard. + * + * Please consult the QR Code specification for information on + * data capacities per version, ECC level, and text encoding mode. + */ +bool qrcodegen_encodeBinary(uint32_t dataAndTemp[], size_t dataLen, uint32_t qrcode[], + enum qrcodegen_Ecc ecl, int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl); + + +/*---- Functions (low level) to generate QR Codes ----*/ + +/* + * Encodes the given segments to a QR Code, returning true if successful. + * If the data is too long to fit in any version at the given ECC level, + * then false is returned. + * + * The smallest possible QR Code version is automatically chosen for + * the output. The ECC level of the result may be higher than the + * ecl argument if it can be done without increasing the version. + * + * About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX): + * - Before calling the function: + * - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow + * reading and writing; hence each array must have a length of at least len. + * - The two ranges must not overlap (aliasing). + * - The initial state of both ranges can be uninitialized + * because the function always writes before reading. + * - The input array segs can contain segments whose data buffers overlap with tempBuffer. + * - After the function returns: + * - Both ranges have no guarantee on which elements are initialized and what values are stored. + * - tempBuffer contains no useful data and should be treated as entirely uninitialized. + * - Any segment whose data buffer overlaps with tempBuffer[0 : len] + * must be treated as having invalid values in that array. + * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). + * + * Please consult the QR Code specification for information on + * data capacities per version, ECC level, and text encoding mode. + * + * This function allows the user to create a custom sequence of segments that switches + * between modes (such as alphanumeric and byte) to encode text in less space. + * This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary(). + */ +bool qrcodegen_encodeSegments(const struct qrcodegen_Segment segs[], size_t len, + enum qrcodegen_Ecc ecl, uint32_t tempBuffer[], uint32_t qrcode[]); + + +/* + * Encodes the given segments to a QR Code, returning true if successful. + * If the data is too long to fit in any version in the given range + * at the given ECC level, then false is returned. + * + * Requires 1 <= minVersion <= maxVersion <= 40. + * + * The smallest possible QR Code version within the given range is automatically + * chosen for the output. Iff boostEcl is true, then the ECC level of the result + * may be higher than the ecl argument if it can be done without increasing the + * version. The mask is either between qrcodegen_Mask_0 to 7 to force that mask, or + * qrcodegen_Mask_AUTO to automatically choose an appropriate mask (which may be slow). + * + * About the byte arrays, letting len = qrcodegen_BUFFER_LEN_FOR_VERSION(qrcodegen_VERSION_MAX): + * - Before calling the function: + * - The array ranges tempBuffer[0 : len] and qrcode[0 : len] must allow + * reading and writing; hence each array must have a length of at least len. + * - The two ranges must not overlap (aliasing). + * - The initial state of both ranges can be uninitialized + * because the function always writes before reading. + * - The input array segs can contain segments whose data buffers overlap with tempBuffer. + * - After the function returns: + * - Both ranges have no guarantee on which elements are initialized and what values are stored. + * - tempBuffer contains no useful data and should be treated as entirely uninitialized. + * - Any segment whose data buffer overlaps with tempBuffer[0 : len] + * must be treated as having invalid values in that array. + * - If successful, qrcode can be passed into qrcodegen_getSize() and qrcodegen_getModule(). + * + * Please consult the QR Code specification for information on + * data capacities per version, ECC level, and text encoding mode. + * + * This function allows the user to create a custom sequence of segments that switches + * between modes (such as alphanumeric and byte) to encode text in less space. + * This is a low-level API; the high-level API is qrcodegen_encodeText() and qrcodegen_encodeBinary(). + */ +bool qrcodegen_encodeSegmentsAdvanced(const struct qrcodegen_Segment segs[], size_t len, enum qrcodegen_Ecc ecl, + int minVersion, int maxVersion, enum qrcodegen_Mask mask, bool boostEcl, uint32_t tempBuffer[], uint32_t qrcode[]); + + +/* + * Tests whether the given string can be encoded as a segment in numeric mode. + * A string is encodable iff each character is in the range 0 to 9. + */ +bool qrcodegen_isNumeric(const char *text); + + +/* + * Tests whether the given string can be encoded as a segment in alphanumeric mode. + * A string is encodable iff each character is in the following set: 0 to 9, A to Z + * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. + */ +bool qrcodegen_isAlphanumeric(const char *text); + + +/* + * Returns the number of bytes (uint8_t) needed for the data buffer of a segment + * containing the given number of characters using the given mode. Notes: + * - Returns SIZE_MAX on failure, i.e. numChars > INT16_MAX or the internal + * calculation of the number of needed bits exceeds INT16_MAX (i.e. 32767). + * - Otherwise, all valid results are in the range [0, ceil(INT16_MAX / 8)], i.e. at most 4096. + * - It is okay for the user to allocate more bytes for the buffer than needed. + * - For byte mode, numChars measures the number of bytes, not Unicode code points. + * - For ECI mode, numChars must be 0, and the worst-case number of bytes is returned. + * An actual ECI segment can have shorter data. For non-ECI modes, the result is exact. + */ +size_t qrcodegen_calcSegmentBufferSize(enum qrcodegen_Mode mode, size_t numChars); + + +/* + * Returns a segment representing the given binary data encoded in + * byte mode. All input byte arrays are acceptable. Any text string + * can be converted to UTF-8 bytes and encoded as a byte mode segment. + */ +struct qrcodegen_Segment qrcodegen_makeBytes(const uint8_t data[], size_t len, uint8_t buf[]); + + +/* + * Returns a segment representing the given string of decimal digits encoded in numeric mode. + */ +struct qrcodegen_Segment qrcodegen_makeNumeric(const char *digits, uint8_t buf[]); + + +/* + * Returns a segment representing the given text string encoded in alphanumeric mode. + * The characters allowed are: 0 to 9, A to Z (uppercase only), space, + * dollar, percent, asterisk, plus, hyphen, period, slash, colon. + */ +struct qrcodegen_Segment qrcodegen_makeAlphanumeric(const char *text, uint8_t buf[]); + + +/* + * Returns a segment representing an Extended Channel Interpretation + * (ECI) designator with the given assignment value. + */ +struct qrcodegen_Segment qrcodegen_makeEci(long assignVal, uint8_t buf[]); + + +/*---- Functions to extract raw data from QR Codes ----*/ + +/* + * Returns the side length of the given QR Code, assuming that encoding succeeded. + * The result is in the range [21, 177]. Note that the length of the array buffer + * is related to the side length - every 'uint32_t qrcode[]' must have length at least + * qrcodegen_BUFFER_LEN_FOR_VERSION(version), which equals ceil(size^2 / 8 + 1). + */ +int qrcodegen_getSize(const uint32_t qrcode[]); + + +/* + * Returns the horizontal stride (number of uint32s per row) of the given QR Code. + */ +int qrcodegen_getStride(const uint32_t qrcode[]); + + +/* + * Returns the color of the module (pixel) at the given coordinates, which is false + * for light or true for dark. The top left corner has the coordinates (x=0, y=0). + * If the given coordinates are out of bounds, then false (light) is returned. + */ +bool qrcodegen_getModule(const uint32_t qrcode[], int x, int y); + + +#ifdef __cplusplus +} +#endif diff --git a/src/zs01.cpp b/src/zs01.cpp new file mode 100644 index 0000000..9a7d63b --- /dev/null +++ b/src/zs01.cpp @@ -0,0 +1,155 @@ + +#include +#include +#include "util.hpp" +#include "zs01.hpp" + +namespace zs01 { + +/* Fixed keys */ + +// This key is identical across all ZS01 cartridges and seems to be hardcoded. +static const Key _COMMAND_KEY{ + .add = { 237, 8, 16, 11, 6, 4, 8, 30 }, + .shift = { 0, 3, 2, 2, 6, 2, 2, 1 } +}; + +// This key is provided by the 573 to the ZS01 and is used to encode responses. +// Konami's driver generates a pseudorandom key for each transaction, but it can +// be a fixed key as well. +static const Key _RESPONSE_KEY{ + .add = { 0, 0, 0, 0, 0, 0, 0, 0 }, + .shift = { 0, 0, 0, 0, 0, 0, 0, 0 } +}; + +/* Packet encoding/decoding */ + +void Key::unpackFrom(const uint8_t *key) { + add[0] = key[0]; + shift[0] = 0; + + for (int i = 1; i < 8; i++) { + add[i] = key[i] & 0x1f; + shift[i] = key[i] >> 5; + } +} + +void Key::packInto(uint8_t *key) const { + key[0] = add[0]; + + for (int i = 1; i < 8; i++) + key[i] = (add[i] & 0x1f) | (shift[i] << 5); +} + +void Key::encodePacket(uint8_t *data, size_t length, uint8_t state) const { + for (data += length; length; length--) { + uint8_t value = *(--data) ^ state; + value = (value + add[0]) & 0xff; + + for (int i = 1; i < 8; i++) { + int newValue; + newValue = static_cast(value) << shift[i]; + newValue |= static_cast(value) >> (8 - shift[i]); + newValue &= 0xff; + + value = (newValue + add[i]) & 0xff; + } + + state = value; + *data = value; + } +} + +void Key::decodePacket(uint8_t *data, size_t length, uint8_t state) const { + for (data += length; length; length--) { + uint8_t value = *(--data), prevState = state; + state = value; + + for (int i = 7; i; i--) { + int newValue = (value - add[i]) & 0xff; + value = static_cast(newValue) >> shift[i]; + value |= static_cast(newValue) << (8 - shift[i]); + value &= 0xff; + } + + value = (value - add[0]) & 0xff; + *data = value ^ prevState; + } +} + +void Key::encodePayload(uint8_t *data, size_t length, uint8_t state) const { + for (; length; length--) { + uint8_t value = *data ^ state; + value = (value + add[0]) & 0xff; + + for (int i = 1; i < 8; i++) { + int newValue; + newValue = static_cast(value) << shift[i]; + newValue |= static_cast(value) >> (8 - shift[i]); + newValue &= 0xff; + + value = (newValue + add[i]) & 0xff; + } + + state = value; + *(data++) = value; + } +} + +void Packet::updateCRC(void) { + uint16_t value = util::zsCRC16(&command, sizeof(Packet) - sizeof(crc)); + + crc[0] = value >> 8; + crc[1] = value & 0xff; +} + +bool Packet::validateCRC(void) const { + uint16_t _crc = (crc[0] << 8) | crc[1]; + uint16_t value = util::zsCRC16(&command, sizeof(Packet) - sizeof(crc)); + + if (value != _crc) { + LOG("CRC mismatch, exp=0x%04x, got=0x%04x", value, _crc); + return false; + } + + return true; +} + +void Packet::encodeReadRequest(void) { + command = REQ_READ; + _RESPONSE_KEY.packInto(data); + updateCRC(); + + _COMMAND_KEY.encodePacket(&command, sizeof(Packet)); +} + +void Packet::encodeReadRequest(Key &dataKey, uint8_t state) { + command = REQ_READ | REQ_USE_DATA_KEY; + _RESPONSE_KEY.packInto(data); + updateCRC(); + + dataKey.encodePayload(data, sizeof(data), state); + _COMMAND_KEY.encodePacket(&command, sizeof(Packet)); +} + +void Packet::encodeWriteRequest(Key &dataKey, uint8_t state) { + command = REQ_WRITE | REQ_USE_DATA_KEY; + updateCRC(); + + dataKey.encodePayload(data, sizeof(data), state); + _COMMAND_KEY.encodePacket(&command, sizeof(Packet)); +} + +bool Packet::decodeResponse(void) { + // NOTE: if a non-fixed response key is used, the ZS01 may encode the + // response to a read request with either the key provided in the request + // *or* the last key used (Konami's driver attempts decoding the response + // with both keys before giving up). When replying to a write request, the + // ZS01 always encodes the response with the same key it used when replying + // to the last read request. Confused yet? + _RESPONSE_KEY.decodePacket(&command, sizeof(Packet)); + + return validateCRC(); +} + +} diff --git a/src/zs01.hpp b/src/zs01.hpp new file mode 100644 index 0000000..926b044 --- /dev/null +++ b/src/zs01.hpp @@ -0,0 +1,81 @@ + +#pragma once + +#include +#include +#include + +namespace zs01 { + +/* Command definitions */ + +enum Address : uint8_t { + ADDR_PUBLIC = 0x00, + ADDR_PUBLIC_END = 0x04, + ADDR_PRIVATE = 0x04, + ADDR_PRIVATE_END = 0x0e, + ADDR_ZS01_ID = 0xfc, // Read-only (?) + ADDR_DS2401_ID = 0xfd, // Read-only + ADDR_ERASE = 0xfd, // Write-only + ADDR_CONFIG = 0xfe, + ADDR_DATA_KEY = 0xff // Write-only +}; + +enum RequestFlag : uint8_t { + REQ_WRITE = 0 << 0, + REQ_READ = 1 << 0, + REQ_BANK_SWITCH = 1 << 1, // Unused (should be bit 8 of block address) + REQ_USE_DATA_KEY = 1 << 2 +}; + +enum ResponseCode : uint8_t { + // The meaning of these codes is currently unknown. Presumably: + // - one of the "security errors" is a CRC validation failure, the other + // could be data key related + // - one of the unknown errors is for invalid commands or addresses + // - one or two of the unknown errors are for actual read/write failures + RESP_NO_ERROR = 0x00, + RESP_SECURITY_ERROR1 = 0x01, + RESP_UNKNOWN_ERROR1 = 0x02, + RESP_UNKNOWN_ERROR2 = 0x03, + RESP_SECURITY_ERROR2 = 0x04, + RESP_UNKNOWN_ERROR3 = 0x05 +}; + +/* Packet encoding/decoding */ + +class Key { +public: + uint8_t add[8], shift[8]; + + void unpackFrom(const uint8_t *key); + void packInto(uint8_t *key) const; + void encodePacket(uint8_t *data, size_t length, uint8_t state = 0xff) const; + void decodePacket(uint8_t *data, size_t length, uint8_t state = 0xff) const; + void encodePayload(uint8_t *data, size_t length, uint8_t state = 0xff) const; +}; + +class Packet { +public: + uint8_t command, address, data[8], crc[2]; + + inline void copyDataFrom(const uint8_t *source) { + memcpy(data, source, sizeof(data)); + } + inline void copyDataTo(uint8_t *dest) const { + memcpy(dest, data, sizeof(data)); + } + inline void clearData(void) { + memset(data, 0, sizeof(data)); + } + + void updateCRC(void); + bool validateCRC(void) const; + + void encodeReadRequest(void); + void encodeReadRequest(Key &dataKey, uint8_t state = 0xff); + void encodeWriteRequest(Key &dataKey, uint8_t state = 0xff); + bool decodeResponse(void); +}; + +} diff --git a/tools/buildResourceArchive.py b/tools/buildResourceArchive.py new file mode 100755 index 0000000..4c70e77 --- /dev/null +++ b/tools/buildResourceArchive.py @@ -0,0 +1,391 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +__version__ = "0.3.0" +__author__ = "spicyjpeg" + +import json, re +from argparse import ArgumentParser, FileType, Namespace +from collections import defaultdict +from itertools import chain +from pathlib import Path +from struct import Struct +from typing import Any, ByteString, Generator, Mapping +from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile + +import numpy +from numpy import ndarray +from PIL import Image + +## .TIM image converter + +TIM_HEADER_STRUCT: Struct = Struct("< 2I") +TIM_SECTION_STRUCT: Struct = Struct("< I 4H") +TIM_HEADER_VERSION: int = 0x10 + +LOWER_ALPHA_BOUND: int = 0x20 +UPPER_ALPHA_BOUND: int = 0xe0 + +# Color 0x0000 is interpreted by the PS1 GPU as fully transparent, so black +# pixels must be changed to dark gray to prevent them from becoming transparent. +TRANSPARENT_COLOR: int = 0x0000 +BLACK_COLOR: int = 0x0421 + +def convertRGBAto16(inputData: ndarray) -> ndarray: + source: ndarray = inputData.astype("> 11 + g: ndarray = ((source[:, :, 1] * 249) + 1014) >> 11 + b: ndarray = ((source[:, :, 2] * 249) + 1014) >> 11 + data: ndarray = r | (g << 5) | (b << 10) + + data = numpy.where(data != TRANSPARENT_COLOR, data, BLACK_COLOR) + + if source.shape[2] == 4: + alpha: ndarray = source[:, :, 3] + + data = numpy.select( + ( + alpha > UPPER_ALPHA_BOUND, # Leave as-is + alpha > LOWER_ALPHA_BOUND # Set semitransparency flag + ), ( + data, + data | (1 << 15) + ), + TRANSPARENT_COLOR + ) + + return data.reshape(source.shape[:-1]) + +def convertIndexedImage(imageObj: Image.Image) -> tuple[ndarray, ndarray]: + # PIL/Pillow doesn't provide a proper way to get the number of colors in a + # palette, so here's an extremely ugly hack. + colorDepth: int = { "RGB": 3, "RGBA": 4 }[imageObj.palette.mode] + clutData: bytes = imageObj.palette.tobytes() + numColors: int = len(clutData) // colorDepth + + clut: ndarray = convertRGBAto16( + numpy.frombuffer(clutData, "B").reshape(( 1, numColors, colorDepth )) + ) + + # Pad the palette to 16 or 256 colors. + padAmount: int = (16 if (numColors <= 16) else 256) - numColors + if padAmount: + clut = numpy.c_[ clut, numpy.zeros(padAmount, " bytearray: + if (ix < 0) or (ix > 1023) or (iy < 0) or (iy > 1023): + raise ValueError("image X/Y coordinates must be in 0-1023 range") + if (cx < 0) or (cx > 1023) or (cy < 0) or (cy > 1023): + raise ValueError("palette X/Y coordinates must be in 0-1023 range") + + image, clut = convertIndexedImage(imageObj) + + mode: int = 0x8 if (clut.size <= 16) else 0x9 + data: bytearray = bytearray(TIM_HEADER_STRUCT.pack(TIM_HEADER_VERSION, mode)) + + data.extend(TIM_SECTION_STRUCT.pack( + TIM_SECTION_STRUCT.size + clut.size * 2, + cx, cy, clut.shape[1], clut.shape[0] + )) + data.extend(clut) + + data.extend(TIM_SECTION_STRUCT.pack( + TIM_SECTION_STRUCT.size + image.size, + ix, iy, image.shape[1] // 2, image.shape[0] + )) + data.extend(image) + + return data + +## Font metrics generator + +FONT_CHAR_OFFSET: int = ord(" ") +FONT_CHAR_COUNT: int = 120 + +METRICS_ENTRY_STRUCT: Struct = Struct("< 2B H") + +def generateFontMetrics( + metrics: Mapping[str, Mapping[str, int | bool]] +) -> bytearray: + data: bytearray = bytearray(FONT_CHAR_COUNT * METRICS_ENTRY_STRUCT.size) + + for ch, entry in metrics.items(): + index: int = ord(ch) - FONT_CHAR_OFFSET + + if (index < 0) or (index > FONT_CHAR_COUNT): + raise ValueError(f"non-ASCII character {index} is not supported") + + x: int = int(entry["x"]) + y: int = int(entry["y"]) + w: int = int(entry["width"]) + h: int = int(entry["height"]) + i: bool = bool(entry.get("icon", False)) + + if (x < 0) or (x > 255) or (y < 0) or (y > 255): + raise ValueError("all X/Y coordinates must be in 0-255 range") + if (w < 0) or (w > 127) or (h < 0) or (h > 127): + raise ValueError("all characters must be <=127x127 pixels") + + data[ + METRICS_ENTRY_STRUCT.size * index: + METRICS_ENTRY_STRUCT.size * (index + 1) + ] = METRICS_ENTRY_STRUCT.pack(x, y, w | (h << 7) | (i << 14)) + + return data + +## String table generator + +TABLE_ENTRY_STRUCT: Struct = Struct("< I 2H") +TABLE_BUCKET_COUNT: int = 256 +TABLE_STRING_ALIGN: int = 4 + +TABLE_ESCAPE_REGEX: re.Pattern = re.compile(rb"\$?\{(.+?)\}") +TABLE_ESCAPE_REPL: Mapping[bytes, bytes] = { + b"UP_ARROW": b"\x80", + b"DOWN_ARROW": b"\x81", + b"LEFT_ARROW": b"\x82", + b"RIGHT_ARROW": b"\x83", + b"LEFT_BUTTON": b"\x84", + b"RIGHT_BUTTON": b"\x85", + b"START_BUTTON": b"\x86", + b"CLOSED_LOCK": b"\x87", + b"OPEN_LOCK": b"\x88", + b"CHIP_ICON": b"\x89", + b"CART_ICON": b"\x8a" +} + +def hashString(string: str) -> int: + value: int = 0 + + for byte in string.encode("ascii"): + value = ( + byte + \ + ((value << 6) & 0xffffffff) + \ + ((value << 16) & 0xffffffff) - \ + value + ) & 0xffffffff + + return value + +def convertString(string: str) -> bytes: + return TABLE_ESCAPE_REGEX.sub( + lambda match: TABLE_ESCAPE_REPL[match.group(1).strip().upper()], + string.encode("ascii") + ) + +def prepareStrings( + strings: Mapping[str, Any], prefix: str = "" +) -> Generator[tuple[int, bytes | None], None, None]: + for key, value in strings.items(): + fullKey: str = prefix + key + + if value is None: + yield hashString(fullKey), None + elif type(value) is str: + yield hashString(fullKey), convertString(value) + else: + yield from prepareStrings(value, f"{fullKey}.") + +def generateStringTable(strings: Mapping[str, Any]) -> bytearray: + offsets: dict[bytes, int] = {} + chains: defaultdict[int, list[tuple[int, int | None]]] = defaultdict(list) + + blob: bytearray = bytearray() + + for fullHash, string in prepareStrings(strings): + if string is None: + entry: tuple[int, int | None] = fullHash, 0 + else: + offset: int | None = offsets.get(string, None) + + if offset is None: + offset = len(blob) + offsets[string] = offset + + blob.extend(string) + blob.append(0) + + while len(blob) % TABLE_STRING_ALIGN: + blob.append(0) + + entry: tuple[int, int | None] = fullHash, offset + + chains[fullHash % TABLE_BUCKET_COUNT].append(entry) + + # Build the bucket array and all chains of entries. + buckets: list[tuple[int, int | None, int]] = [] + chained: list[tuple[int, int | None, int]] = [] + + for shortHash in range(TABLE_BUCKET_COUNT): + entries: list[tuple[int, int | None]] = chains[shortHash] + + if not entries: + buckets.append(( 0, None, 0 )) + continue + + for index, entry in enumerate(entries): + if index < (len(entries) - 1): + chainIndex: int = TABLE_BUCKET_COUNT + len(chained) + else: + chainIndex: int = 0 + + fullHash, offset = entry + + if index: + chained.append(( fullHash, offset, chainIndex )) + else: + buckets.append(( fullHash, offset, chainIndex )) + + # Relocate the offsets and serialize the table. + blobAddr: int = TABLE_ENTRY_STRUCT.size * (len(buckets) + len(chained)) + data: bytearray = bytearray() + + for fullHash, offset, chainIndex in chain(buckets, chained): + absOffset: int = 0 if (offset is None) else (blobAddr + offset) + + if absOffset > 0xffff: + raise RuntimeError("string table exceeds 64 KB size limit") + + data.extend(TABLE_ENTRY_STRUCT.pack( fullHash, absOffset, chainIndex )) + + data.extend(blob) + + return data + +## Main + +def createParser() -> ArgumentParser: + parser = ArgumentParser( + description = \ + "Parses a JSON file containing a list of resources to convert, " + "generates the respective files and packs them into a ZIP archive.", + add_help = False + ) + + group = parser.add_argument_group("Tool options") + group.add_argument( + "-h", "--help", + action = "help", + help = "Show this help message and exit" + ) + + group = parser.add_argument_group("ZIP compression options") + group.add_argument( + "-c", "--compress-level", + type = int, + default = 9, + help = "Set default gzip compression level (default 9)", + metavar = "0-9" + ) + group.add_argument( + "-n", "--no-compression", + action = "store_true", + help = "Forcefully disable gzip compression for all files" + ) + + group = parser.add_argument_group("File paths") + group.add_argument( + "-s", "--source-dir", + type = Path, + help = \ + "Set path to directory containing source files (same directory as " + "resource list by default)" + ) + group.add_argument( + "resourceList", + type = FileType("rt"), + help = "Path to JSON resource list", + ) + group.add_argument( + "output", + type = Path, + help = "Path to ZIP file to generate" + ) + + return parser + +def main(): + parser: ArgumentParser = createParser() + args: Namespace = parser.parse_args() + + with args.resourceList as _file: + assetList: list = json.load(_file) + sourceDir: Path = args.source_dir or Path(_file.name).parent + + with ZipFile(args.output, "w", allowZip64 = False) as _zip: + for asset in assetList: + match asset.get("type", "file").strip(): + case "empty": + data: ByteString = b"" + + case "text": + with open(sourceDir / asset["source"], "rt") as _file: + data: ByteString = _file.read().encode("ascii") + + case "binary": + with open(sourceDir / asset["source"], "rb") as _file: + data: ByteString = _file.read() + + case "tim": + ix: int = int(asset["imagePos"]["x"]) + iy: int = int(asset["imagePos"]["y"]) + cx: int = int(asset["clutPos"]["x"]) + cy: int = int(asset["clutPos"]["y"]) + + image: Image.Image = Image.open(sourceDir / asset["source"]) + image.load() + + if image.mode != "P": + image = image.quantize( + int(asset["quantize"]), dither = Image.Dither.NONE + ) + + data: ByteString = generateIndexedTIM(image, ix, iy, cx, cy) + + case "metrics": + if "metrics" in asset: + metrics: dict = asset["metrics"] + else: + with open(sourceDir / asset["source"], "rt") as _file: + metrics: dict = json.load(_file) + + data: ByteString = generateFontMetrics(metrics) + + case "strings": + if "strings" in asset: + strings: dict = asset["strings"] + else: + with open(sourceDir / asset["source"], "rt") as _file: + strings: dict = json.load(_file) + + data: ByteString = generateStringTable(strings) + + case _type: + raise KeyError(f"unsupported asset type '{_type}'") + + gzipLevel: int | None = asset.get("compress", args.compress_level) + disallow: bool = (gzipLevel is None) or args.no_compression + + _zip.writestr( + asset["name"], data, + ZIP_STORED if disallow else ZIP_DEFLATED, gzipLevel + ) + +if __name__ == "__main__": + main() diff --git a/tools/convertExecutable.py b/tools/convertExecutable.py new file mode 100755 index 0000000..9d7a2ff --- /dev/null +++ b/tools/convertExecutable.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +"""ELF executable to PlayStation 1 .EXE converter + +A very simple script to convert ELF files compiled for the PS1 to the executable +format used by the BIOS, with support for setting initial $sp/$gp values and +customizing the region string (used by some emulators to determine whether they +should start in PAL or NTSC mode by default). Requires no external dependencies. +""" + +__version__ = "0.1.0" +__author__ = "spicyjpeg" + +from argparse import ArgumentParser, FileType, Namespace +from enum import IntEnum, IntFlag +from struct import Struct +from typing import BinaryIO, ByteString, Generator + +## Utilities + +def alignToMultiple(data: bytearray, alignment: int): + padAmount: int = alignment - (len(data) % alignment) + + if padAmount < alignment: + data.extend(b"\0" * padAmount) + +def parseStructFromFile(_file: BinaryIO, _struct: Struct) -> tuple: + return _struct.unpack(_file.read(_struct.size)) + +def parseStructsFromFile( + _file: BinaryIO, _struct: Struct, count: int +) -> Generator[tuple, None, None]: + data: bytes = _file.read(_struct.size * count) + + for offset in range(0, len(data), _struct.size): + yield _struct.unpack(data[offset:offset + _struct.size]) + +## ELF file parser + +ELF_HEADER_STRUCT: Struct = Struct("< 4s 4B 8x 2H 5I 6H") +ELF_HEADER_MAGIC: bytes = b"\x7fELF" +PROG_HEADER_STRUCT: Struct = Struct("< 8I") + +class ELFType(IntEnum): + RELOCATABLE = 1 + EXECUTABLE = 2 + SHARED = 3 + CORE = 4 + +class ELFArchitecture(IntEnum): + MIPS = 8 + +class ELFEndianness(IntEnum): + LITTLE = 1 + BIG = 2 + +class ProgHeaderType(IntEnum): + NONE = 0 + LOAD = 1 + DYNAMIC = 2 + INTERPRETER = 3 + NOTE = 4 + +class ProgHeaderFlag(IntFlag): + EXECUTE = 1 << 0 + WRITE = 1 << 1 + READ = 1 << 2 + +class Segment: + def __init__(self, address: int, data: ByteString, flags: int): + self.address: int = address + self.data: ByteString = data + self.flags: ProgHeaderFlag = ProgHeaderFlag(flags) + + def isReadOnly(self) -> bool: + return not \ + (self.flags & (ProgHeaderFlag.WRITE | ProgHeaderFlag.EXECUTE)) + +class ELF: + def __init__(self, _file: BinaryIO): + self.type: ELFType | None = None + self.architecture: ELFArchitecture | None = None + + self.abi: int | None = None + self.entryPoint: int | None = None + self.flags: int | None = None + + self.segments: list[Segment] = [] + + self._parse(_file) + + def _parse(self, _file: BinaryIO): + # Parse the file header and perform some minimal validation. + _file.seek(0) + + magic, wordSize, endianness, _, self.abi, _type, architecture, _, \ + self.entryPoint, progHeaderOffset, secHeaderOffset, self.flags, \ + elfHeaderLength, progHeaderLength, progHeaderCount, secHeaderLength, \ + secHeaderCount, _ = \ + parseStructFromFile(_file, ELF_HEADER_STRUCT) + + self.type = ELFType(_type) + self.architecture = ELFArchitecture(architecture) + + if magic != ELF_HEADER_MAGIC: + raise RuntimeError("file is not a valid ELF") + if wordSize != 1 or endianness != ELFEndianness.LITTLE: + raise RuntimeError("ELF file must be 32-bit little-endian") + if ( + elfHeaderLength != ELF_HEADER_STRUCT.size or + progHeaderLength != PROG_HEADER_STRUCT.size + ): + raise RuntimeError("unsupported ELF format") + + # Parse the program headers and extract all loadable segments. + _file.seek(progHeaderOffset) + + for ( + headerType, fileOffset, address, _, fileLength, length, flags, _ + ) in parseStructsFromFile(_file, PROG_HEADER_STRUCT, progHeaderCount): + if headerType != ProgHeaderType.LOAD: + continue + + # Retrieve the segment and trim or pad it if necessary. + _file.seek(fileOffset) + data: bytes = _file.read(fileLength) + + if length > len(data): + data = data.ljust(length, b"\0") + else: + data = data[0:length] + + self.segments.append(Segment(address, data, flags)) + + #_file.close() + + def flatten(self, stripReadOnly: bool = False) -> tuple[int, bytearray]: + # Find the lower and upper boundaries of the segments' address space. + startAddress: int = min( + seg.address for seg in self.segments + ) + endAddress: int = max( + (seg.address + len(seg.data)) for seg in self.segments + ) + + # Copy all segments into a new byte array at their respective offsets. + data: bytearray = bytearray(endAddress - startAddress) + + for seg in self.segments: + if stripReadOnly and seg.isReadOnly(): + continue + + offset: int = seg.address - startAddress + data[offset:offset + len(seg.data)] = seg.data + + return startAddress, data + +## Main + +EXE_HEADER_STRUCT: Struct = Struct("< 16s 4I 16x 2I 20x 1972s") +EXE_HEADER_MAGIC: bytes = b"PS-X EXE" +EXE_ALIGNMENT: int = 2048 + +def createParser() -> ArgumentParser: + parser = ArgumentParser( + description = \ + "Converts an ELF executable into a PlayStation 1 .EXE file.", + add_help = False + ) + + group = parser.add_argument_group("Tool options") + group.add_argument( + "-h", "--help", + action = "help", + help = "Show this help message and exit" + ) + + group = parser.add_argument_group("Conversion options") + group.add_argument( + "-r", "--region-str", + type = str, + default = "", + help = "Add a custom region string to the header", + metavar = "string" + ) + group.add_argument( + "-s", "--set-sp", + type = lambda value: int(value, 0), + default = 0, + help = "Add an initial value for the stack pointer to the header", + metavar = "value" + ) + group.add_argument( + "-g", "--set-gp", + type = lambda value: int(value, 0), + default = 0, + help = "Add an initial value for the global pointer to the header", + metavar = "value" + ) + group.add_argument( + "-S", "--strip-read-only", + action = "store_true", + help = \ + "Remove all ELF segments not marked writable nor executable from " + "the output file" + ) + + group = parser.add_argument_group("File paths") + group.add_argument( + "input", + type = FileType("rb"), + help = "Path to ELF input executable", + ) + group.add_argument( + "output", + type = FileType("wb"), + help = "Path to PS1 executable to generate" + ) + + return parser + +def main(): + parser: ArgumentParser = createParser() + args: Namespace = parser.parse_args() + + with args.input as _file: + try: + elf: ELF = ELF(_file) + except RuntimeError as err: + parser.error(err.args[0]) + + if elf.type != ELFType.EXECUTABLE: + parser.error("ELF file must be an executable") + if elf.architecture != ELFArchitecture.MIPS: + parser.error("ELF architecture must be MIPS") + if not elf.segments: + parser.error("ELF file must contain at least one segment") + + startAddress, data = elf.flatten(args.strip_read_only) + alignToMultiple(data, EXE_ALIGNMENT) + + region: bytes = args.region_str.strip().encode("ascii") + header: bytes = EXE_HEADER_STRUCT.pack( + EXE_HEADER_MAGIC, # Magic + elf.entryPoint, # Entry point + args.set_gp, # Initial global pointer + startAddress, # Data load address + len(data), # Data size + args.set_sp, # Stack offset + 0, # Stack size + region # Region string + ) + + with args.output as _file: + _file.write(header) + _file.write(data) + +if __name__ == "__main__": + main() diff --git a/tools/decodeDump.py b/tools/decodeDump.py new file mode 100755 index 0000000..c156e50 --- /dev/null +++ b/tools/decodeDump.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +__version__ = "0.3.0" +__author__ = "spicyjpeg" + +import sys +from argparse import ArgumentParser, FileType, Namespace +from enum import IntEnum, IntFlag +from struct import Struct +from typing import BinaryIO, ByteString, Mapping, Sequence, TextIO +from zlib import decompress + +## Base45 decoder + +BASE45_CHARSET: str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:" + +def decodeBase45(data: str) -> bytearray: + mapped: map = map(BASE45_CHARSET.index, data) + output: bytearray = bytearray() + + for a, b, c in zip(mapped, mapped, mapped): + value: int = a + (b * 45) + (c * 2025) + + output.append(value >> 8) + output.append(value & 0xff) + + return output + +def serialNumberToString(_id: ByteString) -> str: + value: int = int.from_bytes(_id[1:7], "little") + + if value >= 100000000: + return "xxxx-xxxx" + + return f"{(value // 10000) % 10000:04d}-{value % 10000:04d}" + +## Dump parser + +DUMP_START: str = "573::" +DUMP_END: str = "::" +DUMP_STRUCT: Struct = Struct("< 3B x 8s 8s 8s 8s 8s 512s") +DUMP_VERSION: int = 1 + +class ChipType(IntEnum): + TYPE_NONE = 0 + TYPE_X76F041 = 1 + TYPE_X76F100 = 2 + TYPE_ZS01 = 3 + +class CartFlag(IntFlag): + HAS_DIGITAL_IO = 1 << 0 + HAS_DS2401 = 1 << 1 + CONFIG_OK = 1 << 2 + SYSTEM_ID_OK = 1 << 3 + CART_ID_OK = 1 << 4 + ZS_ID_OK = 1 << 5 + PUBLIC_DATA_OK = 1 << 6 + PRIVATE_DATA_OK = 1 << 7 + +CHIP_NAMES: Mapping[ChipType, str] = { + ChipType.TYPE_NONE: "None", + ChipType.TYPE_X76F041: "Xicor X76F041", + ChipType.TYPE_X76F100: "Xicor X76F100", + ChipType.TYPE_ZS01: "Konami ZS01 (PIC16CE625)" +} + +DATA_LENGTHS: Mapping[ChipType, int] = { + ChipType.TYPE_NONE: 0, + ChipType.TYPE_X76F041: 512, + ChipType.TYPE_X76F100: 112, + ChipType.TYPE_ZS01: 112 +} + +def toPrintableChar(value: int): + if (value < 0x20) or (value > 0x7e): + return "." + + return chr(value) + +def hexdump(data: ByteString | Sequence[int], output: TextIO, width: int = 16): + for i in range(0, len(data), width): + hexBytes: map = map(lambda value: f"{value:02x}", data[i:i + width]) + hexLine: str = " ".join(hexBytes).ljust(width * 3 - 1) + + asciiBytes: map = map(toPrintableChar, data[i:i + width]) + asciiLine: str = "".join(asciiBytes).ljust(width) + + output.write(f"{i:04x}: {hexLine} |{asciiLine}|\n") + +def parseDump( + dumpString: str, logOutput: TextIO | None = None, + exportOutput: BinaryIO | None = None +): + _dumpString: str = dumpString.strip().upper() + + if ( + not _dumpString.startswith(DUMP_START) or + not _dumpString.endswith(DUMP_END) + ): + raise ValueError(f"dump string does not begin with '{DUMP_START}' and end with '{DUMP_END}'") + + _dumpString = _dumpString[len(DUMP_START):-len(DUMP_END)] + dump: bytes = decompress(decodeBase45(_dumpString)) + + version, chipType, flags, dataKey, config, systemID, cartID, zsID, data = \ + DUMP_STRUCT.unpack(dump[0:DUMP_STRUCT.size]) + + if version != DUMP_VERSION: + raise ValueError(f"unsupported dump version {version}") + + chipType: ChipType = ChipType(chipType) + flags: CartFlag = CartFlag(flags) + data: bytes = data[0:DATA_LENGTHS[chipType]] + + if logOutput: + if flags & CartFlag.SYSTEM_ID_OK: + logOutput.write(f"Digital I/O ID: {systemID.hex('-')}\n") + logOutput.write(f"Serial number: {serialNumberToString(systemID)}\n") + + logOutput.write(f"Cartridge type: {CHIP_NAMES[chipType]}\n") + if flags & CartFlag.CART_ID_OK: + logOutput.write(f"DS2401 identifier: {cartID.hex('-')}\n") + if flags & CartFlag.ZS_ID_OK: + logOutput.write(f"ZS01 identifier: {zsID.hex('-')}\n") + if flags & CartFlag.CONFIG_OK: + logOutput.write(f"Configuration: {config.hex('-')}\n") + + logOutput.write("\nEEPROM dump:\n") + hexdump(data, logOutput) + logOutput.write("\n") + + if exportOutput: + pass # TODO: implement exporting + +## Main + +def createParser() -> ArgumentParser: + parser = ArgumentParser( + description = "Decodes the contents of a QR code generated by the tool.", + add_help = False + ) + + group = parser.add_argument_group("Tool options") + group.add_argument( + "-h", "--help", + action = "help", + help = "Show this help message and exit" + ) + + group = parser.add_argument_group("File paths") + group.add_argument( + "-i", "--input", + type = FileType("rt"), + help = "read dump from specified file", + metavar = "file" + ) + group.add_argument( + "-l", "--log", + type = FileType("at"), + default = sys.stdout, + help = "log cartridge info to specified file (stdout by default)", + metavar = "file" + ) + group.add_argument( + "-e", "--export", + type = FileType("wb"), + help = "export dump in MAME format to specified file", + metavar = "file" + ) + + group.add_argument( + "dump", + type = str, + nargs = "?", + help = "QR string to decode (if -i was not passed)" + ) + + return parser + +def main(): + parser: ArgumentParser = createParser() + args: Namespace = parser.parse_args() + + if args.input: + with args.input as _file: + dump: str = _file.read() + elif args.dump: + dump: str = args.dump + else: + parser.error("a dump must be passed on the command line or using -i") + + parseDump(dump, args.log, args.export) + +if __name__ == "__main__": + main() diff --git a/tools/requirements.txt b/tools/requirements.txt new file mode 100644 index 0000000..f75a8e6 --- /dev/null +++ b/tools/requirements.txt @@ -0,0 +1,6 @@ +# Install the dependencies required by the tools by running: +# py -m pip install -r tools/requirements.txt (Windows) +# sudo pip install -r tools/requirements.txt (Linux/macOS) + +numpy >= 1.19.4 +Pillow >= 8.2.0